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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
12f9c50368f3acf2ec9f0e23d4b3ec14afeef3cf | C++ | aleruirod/hpc | /Solution.h | UTF-8 | 2,307 | 3.4375 | 3 | [] | no_license | #ifndef SOLUTION_H
#define SOLUTION_H
#include <vector> // we will use the standard vector library provided by the C++ language.
#include <iostream>
/**
* The Solution class is the base for
* \n all other methods used as they all share
* \n some common characteristics.
*
*/
class Solution {
public:
// CONSTRUCTORS
/**
*Creates an empty Solution object
* @see Solution(Vector<Vector<double>> sols);
*/
Solution();
/**
* creates a Solution object from a vector of double vectors.
* @see Solution();
* @param sols Vector of double vectors that the new Solution will use.
*/
Solution(std::vector<std::vector<double>> sols /**< std::vector<std::vector<double>>. Vector of double vectors that the new Solution will use. */);
// GETTERS
/**
* Returns all solutions stored in the Solution object.
*/
std::vector<std::vector<double>> getAllSolutions();
/**
* Returns the current value for deltaX.
* @see getDeltaT();
*/
double getDeltaX();
/**
* Returns the current value for deltaT.
* @see getDeltaX();
*/
double getDeltaT();
// SETTERS
/**
* adds a new solution to allSolutions.
* @see setDeltaT();
* @param x new value for deltaX.
*/
void setDeltaX(double x /**double. new value for deltaX. */);
/**
* adds a new solution to allSolutions.
* @see setDeltaX();
* @param t new value for deltaT.
*/
void setDeltaT(double t /**double. new value for deltaT. */);
// STORING
/**
* adds a new solution to allSolutions.
* @param v double Vector to be added to allSolutions.
*/
void addToAllSolutions(std::vector<double> v /**std::vector<double>. double Vector to be added to allSolutions. */);
protected:
double deltaX = 0.5; //!< Space step. Can be changed for different problems.
double deltaT = 0.1;//!< Time step. Can be changed for different problems.
double D = 0.1;//!< Diffusivity of the material in the problem.
double L = 1.0;//!< Spatial size of the problem.
int n = L/deltaX;//!< The size of each solution should be: L / deltaX. This controls the size of the solution vectors for every single timestep.
std::vector<std::vector<double>> allSolutions; //!< We collect in a vector of vectors all solutions we think will be relevant.
int allSolPos = 0;//!< We control the number of elements inside the allSolutions vector.
};
#endif
| true |
6a8e54c3c775c4ac812347bb89e9f5e9d687e77f | C++ | mchoi0320/CSCE121H_IntroToProgram | /histogram.cpp | UTF-8 | 2,625 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <cmath>
#include <iomanip>
using namespace std;
int main(int argc, char** argv)
{
ifstream input;
input.open(argv[1]);
int numBins = atoi(argv[2]);
while (numBins <= 0) {
cout << "Please re-enter a positive value for the number of bins: ";
cin >> numBins; }
double val, sum=0, numVal=0;
vector<double> vals;
while (input >> val) {
vals.push_back(val);
numVal += 1;
sum += val; }
cout << "\nNumber of values: " << numVal << endl;
/* cout << sum << endl;
int a;
for (a=0; a<10; a++) {
cout << vals.at(a) << " "; }
cout << endl; */
// Mean Calculation
double mean = sum / numVal;
cout << "Mean = " << mean << endl;
// Standard Deviation Calculation
int i; double diffSq, sumDiffSq=0, stDev;
for (i=0; i<numVal; i++) {
diffSq = pow((vals.at(i)-mean),2);
sumDiffSq += diffSq;
stDev = sqrt(sumDiffSq / (numVal-1)); }
cout << "Standard Deviation = " << stDev << endl;
// Finding Min & Max
int j; double min=vals.at(0), max=vals.at(0);
for (j=0; j<numVal; j++) {
if (vals.at(j) < min) {
min = vals.at(j); }
if (vals.at(j) > max) {
max = vals.at(j); } }
cout << "Range: " << min << "-" << max << endl;
//// Histogram
// Finding the left bound of each bin
double range = max - min;
double binRange = range / numBins;
double lBound=min;
vector<double> bins;
while (bins.size() < numBins) {
bins.push_back(lBound);
lBound += binRange; }
/* cout << bins.size() << endl;
int b;
for (b=0; b<bins.size(); b++) {
cout << bins.at(b) << " "; }
cout << endl; */
// Finding the number of values in each bin
vector<int> numInBinTotal;
int numInBin;
int k, l, m;
for (k=0; k<bins.size()-1; k++) {
numInBin=0;
for (l=0; l<vals.size(); l++) {
if (vals.at(l) < (bins.at(k)+binRange) && vals.at(l) >= bins.at(k)) {
numInBin += 1; } }
numInBinTotal.push_back(numInBin); }
numInBin=0;
for (m=0; m<vals.size(); m++) {
if (vals.at(m) <= (bins.at(bins.size()-1)+binRange) && vals.at(m) >= bins.at(bins.size()-1)) {
numInBin += 1; } }
numInBinTotal.push_back(numInBin);
/* cout << numInBinTotal.size() << endl;
int c;
for (c=0; c<numInBinTotal.size(); c++) {
cout << numInBinTotal.at(c) << " "; }
cout << endl; */
// Printing the histogram
cout << "\n-------Histogram-------";
int n, o;
for (n=0; n<bins.size(); n++) {
cout << endl;
cout << fixed << setprecision(2) << bins.at(n) << '-' << bins.at(n)+binRange << "|";
for (o=0; o<numInBinTotal.at(n); o++) {
cout << '*'; } }
cout << endl;
cout << setfill('-') << setw(23) << '-' << endl;
return 0;
}
| true |
95961d2103739ca45b02fc983187337c31c6f85a | C++ | Kartikay123/Competitive-Programming-Question | /friend2.cpp | UTF-8 | 865 | 3.578125 | 4 | [] | no_license | #include"Kartikay.h"
class c2;
class c1{
int val1;
friend void exchange(c1 &,c2 &);
public:
void indata(int a){
val1 = a;
}
void display(){
cout<<val1<<endl;
}
};
class c2{
int val2;
friend void exchange(c1 &,c2 &);
public:
void indata(int a){
val2 =a;
}
void display(){
cout<<val2<<endl;
}
};
void exchange(c1 &x,c2 &y){
int temp = x.val1;
x.val1 = y.val2;
y.val2 = temp;
}
int main(int argc, char const *argv[])
{
c1 oc1;
c2 oc2;
oc1.indata(34);
oc2.indata(85);
exchange(oc1,oc2); /* here oc1 and oc2 are equal to x and y in exchange function*/
cout<<"THe value of c1 after exchanging becomes:";oc1.display();
cout<<"THe value of c2 after exchanging becomes:";oc2.display();
return 0;
}
/* since we are dealing with values here we are using the Reference Variable*/ | true |
366d1c3b96bb9519036d8d3b9a67d189a96a8206 | C++ | haileykim1/Algorithm-Problem | /백준/C++/2580_스도쿠.cpp | UTF-8 | 1,012 | 2.765625 | 3 | [] | no_license | #include<iostream>
#include<memory.h>
#include<queue>
using namespace std;
int map[9][9];
bool row[9][10];
bool col[9][10];
bool sqr[9][10];
void DFS(int cnt) {
int x = cnt / 9;
int y = cnt % 9;
if (cnt == 81) {
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
cout << map[i][j] << " ";
}
cout << '\n';
}
exit(0);
}
if (!map[x][y]) {
for (int i = 1; i <= 9; ++i) {
if ((!row[x][i]) && (!col[y][i]) && (!sqr[(x / 3) * 3 + y / 3][i])) {
row[x][i] = 1;
col[y][i] = 1;
sqr[(x / 3) * 3 + y / 3][i] = 1;
map[x][y] = i;
DFS(cnt + 1);
map[x][y] = 0;
row[x][i] = 0;
col[y][i] = 0;
sqr[(x / 3) * 3 + y / 3][i] = 0;
}
}
}
else
DFS(cnt + 1);
}
int main() {
cin.tie(NULL);
ios::sync_with_stdio(false);
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
cin >> map[i][j];
if (map[i][j]) {
row[i][map[i][j]] = 1;
col[j][map[i][j]] = 1;
sqr[(i / 3) * 3 + j / 3][map[i][j]] = 1;
}
}
}
DFS(0);
} | true |
4cc3070ce6e8f042c04dd7273bebe553b0a997c7 | C++ | lovesunmoonlight/leetcode-solutions | /leetcode2/leetcode2.cpp | GB18030 | 1,736 | 3.625 | 4 | [] | no_license | // leetcode2.cpp : ̨Ӧóڵ㡣
// ģ
#include "stdafx.h"
#include <iostream>
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *p1 = l1;
ListNode *p2 = l2;
ListNode *p = new ListNode(0);
ListNode *ans = p;
int flag = 0;
int temp = 0;
while (p1&&p2)
{
temp = p1->val + p2->val + flag;
flag = 0;
if (temp > 9)
{
temp -= 10;
flag = 1;
}
p->val = temp;
p1 = p1->next;
p2 = p2->next;
p->next = new ListNode(0);
p = p->next;
}
temp = 0;
while (p1)
{
temp = p1->val + flag;
flag = 0;
if (temp > 9)
{
temp -= 10;
flag = 1;
}
p->val = temp;
p->next = new ListNode(0);
p = p->next;
p1 = p1->next;
}
temp = 0;
while (p2)
{
temp = p2->val + flag;
flag = 0;
if (temp > 9)
{
temp -= 10;
flag = 1;
}
p->val = temp;
p->next = new ListNode(0);
p = p->next;
p2 = p2->next;
}
if (flag == 1)
{
p->val = 1;
return ans;
}
ListNode *pp = ans;
while (pp)
{
if (pp->next->next==nullptr)
{
pp->next = nullptr;
break;
}
pp = pp->next;
}
return ans;
}
};
int main()
{
Solution S;
ListNode *l1 = new ListNode(1);
l1->next = new ListNode(8);
l1->next->next = new ListNode(3);
ListNode *l2 = new ListNode(0);
l2->next = new ListNode(6);
l2->next->next = new ListNode(4);
ListNode *ans=S.addTwoNumbers(l1, l2);
while (ans)
{
cout << ans->val << endl;
ans = ans->next;
}
system("pause");
return 0;
}
| true |
5594b1d9c8033555dc23bb4c2f06007ee7763068 | C++ | anr6921/ggp-game-engine | /ggp-engine/LightManager.cpp | UTF-8 | 5,475 | 2.921875 | 3 | [] | no_license | #include "stdafx.h"
#include "LightManager.h"
using namespace DirectX;
LightManager* LightManager::instance = nullptr;
LightManager* LightManager::GetInstance() {
if (instance == nullptr) {
instance = new LightManager();
}
return instance;
}
void LightManager::ReleaseInstance() {
if (instance != nullptr) {
delete instance;
instance = nullptr;
}
}
void LightManager::UploadAllLights(SimplePixelShader* _pixelShader) {
//TODO: Only upload lights close to objects
UINT dirLightCount = 0;
UINT pointLightCount = 0;
UINT spotLightCount = 0;
//Loop through and get every directional light
std::map<UINT, DirLight*>::iterator dlIt;
for (dlIt = dirLightUIDMap.begin(); dlIt != dirLightUIDMap.end();) {
if (dlIt->second == nullptr) {
dirLightUIDMap.erase(dlIt++);
continue;
}
//Add the directional light to the array
dirLights[dirLightCount] = dlIt->second->buildLightStruct();
dirLightCount += 1;
//Break out of loop if we've hit the max number of lights
if (dirLightCount >= maxDirLights) { break; }
dlIt++;
}
_pixelShader->SetData("dirLights", &dirLights, sizeof(DirLightStruct) * maxDirLights);
_pixelShader->SetData("dirLightCount", &dirLightCount, sizeof(UINT));
//Loop through and get every point light
std::map<UINT, PointLight*>::iterator plIt;
for (plIt = pointLightUIDMap.begin(); plIt != pointLightUIDMap.end();) {
if (plIt->second == nullptr) {
pointLightUIDMap.erase(plIt++);
continue;
}
pointLights[pointLightCount] = plIt->second->buildLightStruct();
pointLightCount += 1;
if (pointLightCount >= maxPointLights) { break; }
plIt++;
}
_pixelShader->SetData("pointLights", &pointLights, sizeof(PointLightStruct) * maxPointLights);
_pixelShader->SetData("pointLightCount", &pointLightCount, sizeof(UINT));
//Loop through and get every spot light
std::map<UINT, SpotLight*>::iterator slIt;
for (slIt = spotLightUIDMap.begin(); slIt != spotLightUIDMap.end();) {
if (slIt->second == nullptr) {
spotLightUIDMap.erase(slIt++);
continue;
}
spotLights[spotLightCount] = slIt->second->buildLightStruct();
spotLightCount += 1;
if (spotLightCount >= maxSpotLights) { break; }
slIt++;
}
_pixelShader->SetData("spotLights", &spotLights, sizeof(SpotLightStruct) * maxSpotLights);
_pixelShader->SetData("spotLightCount", &spotLightCount, sizeof(UINT));
}
#pragma region Directional Lights
DirLightID LightManager::AddDirLight(DirLight* _dirLight) {
dirLightUIDMap[dlCount] = _dirLight;
dlCount++;
return dlCount - 1;
}
DirLight* LightManager::GetDirLight(DirLightID _uniqueID) {
auto thisDL = dirLightUIDMap.find(_uniqueID);
//If found, return it. Else, return nullptr
if (thisDL != dirLightUIDMap.end()) {
return thisDL->second;
}
return nullptr;
}
void LightManager::RemoveDirLight(DirLight * _dirLight) {
auto dlIt = dirLightUIDMap.begin();
for (; dlIt != dirLightUIDMap.end(); ++dlIt) {
if (dlIt->second == _dirLight) {
dirLightUIDMap[dlIt->first] = nullptr;
}
}
}
DirLightStruct LightManager::GetDirLightStruct(DirLightID _uniqueID) {
DirLight* tempDL = GetDirLight(_uniqueID);
if (tempDL != nullptr) {
return tempDL->buildLightStruct();
}
return {};
}
#pragma endregion
#pragma region Point Lights
PointLightID LightManager::AddPointLight(PointLight* _pointLight) {
pointLightUIDMap[plCount] = _pointLight;
plCount++;
return plCount - 1;
}
PointLight* LightManager::GetPointLight(PointLightID _uniqueID) {
auto thisPL = pointLightUIDMap.find(_uniqueID);
//If found, return it. Else, return nullptr
if (thisPL != pointLightUIDMap.end()) {
return thisPL->second;
}
return nullptr;
}
void LightManager::RemovePointLight(PointLight * _pointLight) {
auto plIt = pointLightUIDMap.begin();
for (; plIt != pointLightUIDMap.end(); ++plIt) {
if (plIt->second == _pointLight) {
pointLightUIDMap[plIt->first] = nullptr;
}
}
}
PointLightStruct LightManager::GetPointLightStruct(PointLightID _uniqueID) {
PointLight* tempPL = GetPointLight(_uniqueID);
if (tempPL != nullptr) {
return tempPL->buildLightStruct();
}
return {};
}
#pragma endregion
#pragma region Spot Lights
SpotLightID LightManager::AddSpotLight(SpotLight* _spotLight) {
spotLightUIDMap[slCount] = _spotLight;
slCount++;
return slCount - 1;
}
void LightManager::RemoveSpotLight(SpotLight * _spotLight) {
auto slIt = spotLightUIDMap.begin();
for (; slIt != spotLightUIDMap.end(); ++slIt) {
if (slIt->second == _spotLight) {
spotLightUIDMap[slIt->first] = nullptr;
}
}
}
SpotLight* LightManager::GetSpotLight(PointLightID _uniqueID) {
auto thisSL = spotLightUIDMap.find(_uniqueID);
//If found, return it. Else, return nullptr
if (thisSL != spotLightUIDMap.end()) {
return thisSL->second;
}
return nullptr;
}
SpotLightStruct LightManager::GetSpotLightStruct(PointLightID _uniqueID) {
SpotLight* tempSpotL = GetSpotLight(_uniqueID);
if (tempSpotL != nullptr) {
return tempSpotL->buildLightStruct();
}
return {};
}
#pragma endregion
LightManager::LightManager() {}
LightManager::~LightManager() {
Release();
}
void LightManager::Release() {
//Reset directional light unique ID values
dlCount = 0;
//Clear the map so the singleton can be reused.
dirLightUIDMap.clear();
//Reset point light unique ID values
plCount = 0;
//Clear the map so the singleton can be reused.
pointLightUIDMap.clear();
//Reset spot light unique ID values
slCount = 0;
//Clear the map so the singleton can be reused.
spotLightUIDMap.clear();
}
| true |
b5a45e089b7d3c92028910aac08dfbe7d27c646d | C++ | HossamAshraf10/Battle | /CIE205Project_Code_S2021/Castle/SuperSoliders.cpp | UTF-8 | 4,859 | 2.765625 | 3 | [] | no_license | #include "SuperSoliders.h"
#include <iostream>
using namespace std;
//Constructor
superSoliders::superSoliders()
{
this->distance = 0; this->power = 0; this->arrTime = 0; this->reloadTime = 0; this->speed = 0; this->health = maxHealth; this->ID = 0;
}
superSoliders::superSoliders(int ID, int power, int arrTime, int reloadTime, int speed, double maxHealth)
{
this->ID = ID; this->power = power; this->arrTime = arrTime; this->reloadTime = reloadTime; this->speed = speed; this->maxHealth = maxHealth;
health = maxHealth;
this->distance = 0;
}
//Getters
int superSoliders::getID() const { return ID;}
int superSoliders::getArrTime() const { return arrTime;}
int superSoliders::getPower() const { return power;}
double superSoliders::getHealth() const { return health;}
int superSoliders::getReload() const { return reloadTime;}
int superSoliders::getSpeed() const { return speed;}
double superSoliders::getMaxHealth() const { return maxHealth;}
int superSoliders::getDistnce() const { return distance; }
//Setters
void superSoliders::setID(int ID) { this->ID = ID; }
void superSoliders::setArrTime(int arrTime) { this->arrTime = arrTime; }
void superSoliders::setPower(int power) { this->power = power; }
void superSoliders::setReload(int reloadTime) { this->reloadTime = reloadTime; }
void superSoliders::setSpeed(int speed) { this->speed = speed; }
void superSoliders::setHealth(double health) { this->health = health; }
void superSoliders::setDistance(int distance) { this->distance = distance; }
//Functions
/*
void superSoliders::Move()
{
}
void superSoliders::Act()
{
}
*/
void superSoliders::Fight(Battle* battle, int curntTime)
{
int numAttacked = 0;
numAttacked += attackFighters(battle->getActvFighters(), battle->getKilledEnimies(), 3,curntTime);
numAttacked += attackHealers(battle->getActvHealers(), battle->getKilledEnimies(), 3, curntTime);
numAttacked += attackFreezers(battle->getActvFreezers(), battle->getKilledEnimies(), 3, curntTime);
}
int superSoliders::attackFighters(PriorityQueue<Fighter*>* actvFighters, Queue<Enemy*>* kld_enms, int max, int crntTime)
{
PriorityQueue<Fighter*>* tmpQ = new PriorityQueue<Fighter*>();
int totalAttacked = 0;
while (!actvFighters->isEmpty())
{
Fighter* tmpFighter = actvFighters->dequeue();
if (IsWorthFighterAttack(tmpFighter, ACTV) && totalAttacked <= max)
{
totalAttacked++;
tmpFighter->SetHealth(0);
//setFirstShotTime(tmpFighter, crntTime);
cout << "Kld: " << tmpFighter->GetID() << endl;
kld_enms->enqueue(tmpFighter);
tmpFighter->SetStatus(KILD);
}
}
//putting them back:
while (!tmpQ->isEmpty())
{
Fighter* tmpFighter = tmpQ->dequeue();
actvFighters->enqueue(tmpFighter);
}
return totalAttacked;
}
bool superSoliders::IsWorthFighterAttack(Fighter* fighter, ENMY_STATUS status)
{
if ((fighter->GetDistance() - getDistnce() >= 3 && fighter->GetDistance() - getDistnce() <= 0) || (fighter->GetDistance() - getDistnce() >= -3 && fighter->GetDistance() - getDistnce() <= 0) )
{
double totalPercentage = 0;
if (status == ACTV) totalPercentage += 30;
if (status == FRST) totalPercentage += 15;
if ((fighter->GetHealth() / fighter->GetMaxHealth()) * 100 >= 50) totalPercentage += 30;
//if (fighter->GetHealth() < 50) totalPercentage += 15;
totalPercentage = totalPercentage + ((60 - fighter->GetDistance()) / 60.0) * 25;
totalPercentage = totalPercentage + (fighter->GetPower() / 100.0) * 15;
if (totalPercentage > 40) return true;
}
return false;
}
int superSoliders::attackHealers(ArrayStack<Healer*>* healers, Queue<Enemy*>* kld_enms, int max, int crntTime)
{
ArrayStack<Healer*>* tmpH = new ArrayStack<Healer*>(healers->getSize());
int totalAttacked = 0;
while (!healers->isEmpty())
{
Healer* tmpHealer;
healers->pop(tmpHealer);
if (totalAttacked < max)
{
totalAttacked++;
tmpHealer->SetHealth(0);
//setFirstShotTime(tmpHealer, crntTime);
}
cout << "Kld: " << tmpHealer->GetID() << endl;
kld_enms->enqueue(tmpHealer);
tmpHealer->SetStatus(KILD);
}
//reverse
while (!tmpH->isEmpty())
{
Healer* tmpHealer;
tmpH->pop(tmpHealer);
healers->push(tmpHealer);
}
return totalAttacked;
}
int superSoliders::attackFreezers(Queue<Freezer*>* actv_freezers, Queue<Enemy*>* kld_enms, int max, int crntTime)
{
Queue<Freezer*>* tmpF = new Queue<Freezer*>();
int totalAttacked = 0;
while (!actv_freezers->isEmpty())
{
Freezer* tmpFreezer;
actv_freezers->dequeue(tmpFreezer);
if (totalAttacked < max)
{
totalAttacked++;
tmpFreezer->SetHealth(0);
//setFirstShotTime(tmpFreezer, crntTime);
}
kld_enms->enqueue(tmpFreezer);
//kld_enms->enqueue(tmpFreezer);
tmpFreezer->SetStatus(KILD);
}
//reverse
while (!tmpF->isEmpty())
{
Freezer* tmpFreezer;
tmpF->dequeue(tmpFreezer);
actv_freezers->enqueue(tmpFreezer);
}
return totalAttacked;
} | true |
ad90ba5d4919c72babc9b9d86fa7c9fbbac9bff8 | C++ | yellowzunzhi/PAT | /Advance/1011.cpp | UTF-8 | 456 | 2.84375 | 3 | [] | no_license | #include<stdio.h>
int main (void)
{
float MAX[5]={0.0},temp[5];
char SELECT[5],SELECTS[4] = {' ','W','T','L'};
float total;
for (int i = 1;i <= 3 ;i++)
{
scanf("%f%f%f",&temp[1],&temp[2],&temp[3]);
for (int j = 1;j <= 3 ;j++)
{
if (MAX[i] < temp[j])
{
MAX[i] = temp[j];
SELECT[i] = SELECTS[j];
}
}
}
total = (MAX[1]*MAX[2]*MAX[3]*0.65 - 1)*2;
printf("%c %c %c %.2f",SELECT[1],SELECT[2],SELECT[3],total );
return 0;
}//
| true |
3ae16646b85e32f2fce6653acd08d7e3283915bf | C++ | RaoKarter/microbenches | /threads.cpp | UTF-8 | 2,898 | 2.640625 | 3 | [] | no_license | #include "threads.h"
using namespace std;
int main(int argc, char * argv[])
{
int NUM_THREADS;
if(argc < 2)
{
cout << "Usage: threads NUM_THREADS " << endl;
exit(0);
}
NUM_THREADS = atoi(argv[1]);
int i, j, k;
vector<int> iter;
s_var **p_str;
p_str = new s_var* [NUM_THREADS];
iter.resize(NUM_THREADS);
for(i = 0; i < NUM_THREADS; i++)
{
p_str[i] = (s_var*) calloc(L2BANKMUL, sizeof(s_var));
}
for(i = 0; i < NUM_THREADS; i++)
{
for(j = 0; j < L2BANKMUL; j++)
{
for(k = 0; k < L1MUL; k++)
{
p_str[i][j].var1[k] = 12 + k;
p_str[i][j].var2[k] = double (3.1415 + k);
}
}
}
omp_set_num_threads(NUM_THREADS);
qsim_magic_enable();
#pragma omp parallel for private(j, k)
for (i = 0; i < NUM_THREADS; i++)
{
// cout << "Thread" << omp_get_thread_num() << endl << flush;
// For each thread / core, access one element of the structure
// element number in the range 0 - L2BANKMUL
j = 0;
while (j < L2BANKMUL)
{
// cout << "Element number: " << j << endl << flush;
// Integer Ops
for(k = 0; k < L1MUL - 3; k++)
{
while (iter[i] < NUM_CPU_OPS)
{
p_str[i][j].var1[k] = p_str[i][j].var1[k] + 15;
p_str[i][j].var1[k+1] = p_str[i][j].var1[k+1] * 25;
p_str[i][j].var1[k+2] = p_str[i][j].var1[k+2] / 23;
iter[i] += 1;
}
iter[i] = 0;
//cout << endl << flush;
}
iter[i] = 0;
// Floating point Ops
for(k = 0; k < L1MUL - 3; k++)
{
while (iter[i] < NUM_CPU_OPS)
{
p_str[i][j].var2[k] = p_str[i][j].var2[k] + 15.5567;
p_str[i][j].var2[k+1] = p_str[i][j].var2[k+1] * 25.3346;
p_str[i][j].var2[k+2] = p_str[i][j].var2[k+2] / 27.5678;
iter[i] += 1;
}
iter[i] = 0;
//cout << endl << flush;
}
iter[i] = 0;
j = j + MEM_FETCH_INTERVAL;
}
}
qsim_magic_disable();
for(i = 0; i < NUM_THREADS; i++)
free(p_str[i]);
delete [] p_str;
return 0;
}
/*
int p[NUM_THREADS][NUM_ITER1], i, j;
int inum1, inum2, iresult[NUM_THREADS];
inum1 = 0x15;
inum2 = 0x44;
double dnum1, dnum2, dresult[NUM_THREADS];
dnum1 = 123.4567;
dnum2 = 987.6543;
for(i = 0; i < NUM_THREADS; i++)
{
iresult[i] = 0;
dresult[i] = 0;
}
omp_set_num_threads(NUM_THREADS);
qsim_magic_enable();
#pragma omp parallel for private(j)
for (i = 0; i < NUM_THREADS; i++)
{
cout << "Thread" << omp_get_thread_num() << endl << flush;
// Integer Ops
for(j = 0; j < NUM_ITER1;j++)
{
iresult[i] = inum1 + 0x25;
iresult[i] = inum2 + 0x59;
iresult[i] = inum1 + 0x51;
iresult[i] = inum1 * 0x19;
iresult[i] = inum2 / 0x2;
cout << iresult[i] << endl << flush;
}
// Floating point Ops
for(j = 0; j < NUM_ITER1;j++)
{
dresult[i] = dnum1 + 12.3456;
dresult[i] = dnum2 + 98.7654;
dresult[i] = dnum1 + 23.4567;
dresult[i] = dnum1 * 87.6543;
dresult[i] = dnum2 / 65.4321;
cout << dresult[i] << endl << flush;
}
}
qsim_magic_disable();
*/
| true |
d39826aff76e9578028285768d05ba97c7d94857 | C++ | jasonCarruthers/De-Casteljau-Algorithm-And-Bezier-Curves | /Curves.cpp | UTF-8 | 29,333 | 2.53125 | 3 | [] | no_license | #include <vector>
#include "Main.h"
#include "MyMath.h"
#include "Line.h"
#include "Curves.h"
#include "GUI.h"
#include "Graph.h"
#include "Tree.h"
/*
*Global variables
*/
int curveIndex;
std::vector<Curve*> curveVec;
unsigned int curveResolution;
float splitT;
bool isUsingBernstein;
bool controlPointsVisible; /*True if the controlPointCheckbox is checked*/
bool controlPolygonVisible; /*True if the controlPolygonCheckbox is checked*/
bool MBBVisible; /*True if the MBBCheckbox is checked*/
std::vector<Vector2I*> intersectionsVec;
/*
* -------------------------------------------------------------------------------------------------------
* Implementation of class ControlPoints
* -------------------------------------------------------------------------------------------------------
*/
/*
* Constructor(s)
*/
ControlPoints::ControlPoints(const Color3 &newColor)
{
mColor.Set(newColor);
}
/*
* Accessors
*/
std::vector<Vector2I*>* ControlPoints::GetControlPointVec()
{
return &mCPVec;
}
Color3 ControlPoints::GetColor() const
{
return mColor;
}
MyRectangle ControlPoints::GetMBB() const
{
if (mCPVec.size() == 0)
return MyRectangle();
int leftMostX;
int rightMostX;
int bottomMostY;
int topMostY;
/*Find the MBB x and y values.*/
for (unsigned int i = 0; i < mCPVec.size(); i++)
{
if (i == 0)
{
leftMostX = mCPVec[i]->GetX();
rightMostX = mCPVec[i]->GetX();
bottomMostY = mCPVec[i]->GetY();
topMostY = mCPVec[i]->GetY();
}
else
{
if (mCPVec[i]->GetX() < leftMostX)
leftMostX = mCPVec[i]->GetX();
else if (mCPVec[i]->GetX() > rightMostX)
rightMostX = mCPVec[i]->GetX();
if (mCPVec[i]->GetY() < bottomMostY)
bottomMostY = mCPVec[i]->GetY();
else if (mCPVec[i]->GetY() > topMostY)
topMostY = mCPVec[i]->GetY();
}
}
/*Create the MBB, then return it.*/
MyRectangle *mbb = new MyRectangle(Vector2I(leftMostX, topMostY), Vector2I(rightMostX - leftMostX, topMostY - bottomMostY), mColor);
return *mbb;
}
void ControlPoints::Draw() const
{
for (unsigned int controlPoint = 0; controlPoint < mCPVec.size(); controlPoint++)
{
for (int relativeY = -5; relativeY <= 5; relativeY++)
for (int relativeX = -5; relativeX <= 5; relativeX++)
SetPixel(mCPVec[controlPoint]->GetX() + relativeX, mCPVec[controlPoint]->GetY() + relativeY, mColor);
}
}
/*Connect all adjacent control points*/
void ControlPoints::DrawControlPolygon() const
{
for (unsigned int controlPoint = 1; controlPoint < mCPVec.size(); controlPoint++)
{
Line *tempLine = new Line(*mCPVec[controlPoint - 1], *mCPVec[controlPoint], Color3(1.0f, 1.0f, 1.0f));
tempLine->Draw();
}
}
/*Draw convex hull*/
void ControlPoints::DrawConvexHull() const
{
}
/*Draw Minimum Bounding Box*/
void ControlPoints::DrawMBB() const
{
GetMBB().DrawOutline();
}
/*Erase all control point pixels from pixel buffer*/
void ControlPoints::Clear() const
{
for (unsigned int controlPoint = 0; controlPoint < mCPVec.size(); controlPoint++)
{
for (int relativeY = -5; relativeY <= 5; relativeY++)
for (int relativeX = -5; relativeX <= 5; relativeX++)
SetPixel(mCPVec[controlPoint]->GetX() + relativeX, mCPVec[controlPoint]->GetY() + relativeY, Color3(0.0f, 0.0f, 0.0f));
}
}
/*Erase the given control point's pixels from pixel buffer.*/
void ControlPoints::ClearControlPoint(int index) const
{
for (int relativeY = -5; relativeY <= 5; relativeY++)
for (int relativeX = -5; relativeX <= 5; relativeX++)
SetPixel(mCPVec[index]->GetX() + relativeX, mCPVec[index]->GetY() + relativeY, Color3(0.0f, 0.0f, 0.0f));
}
/*Erase control polygon pixels from pixel buffer*/
void ControlPoints::ClearControlPolygon() const
{
for (unsigned int controlPoint = 1; controlPoint < mCPVec.size(); controlPoint++)
{
Line *tempLine = new Line(*mCPVec[controlPoint - 1], *mCPVec[controlPoint], Color3(0.0f, 0.0f, 0.0f));
tempLine->Draw();
}
}
/*Erase convex hull pixels from pixel buffer*/
void ControlPoints::ClearConvexHull() const
{
}
/*Erase MBB pixels from pixel buffer*/
void ControlPoints::ClearMBB() const
{
GetMBB().DrawOutline(Color3(0.0f, 0.0f, 0.0f));
}
/*
* Mutators
*/
void ControlPoints::SetColor(const Color3 &newColor)
{
mColor.Set(newColor);
}
void ControlPoints::PushBack(const Vector2I &newControlPoint)
{
Vector2I *cpPtr = new Vector2I(newControlPoint);
mCPVec.push_back(cpPtr);
}
void ControlPoints::EraseAll()
{
Clear();
mCPVec.clear();
}
void ControlPoints::Erase(int index)
{
if (index < 0 || (unsigned int)index >= mCPVec.size())
return;
ClearControlPoint(index);
mCPVec.erase(mCPVec.begin() + index);
}
/*
* Overloaded operators
*/
Vector2I& ControlPoints::operator[](int index)
{
if (index < 0 || index >= (int)mCPVec.size())
return *mCPVec[0]; /*If index is out of bounds, return the first element by default.*/
return *mCPVec[index];
}
const Vector2I& ControlPoints::operator[](int index) const
{
if (index < 0 || index >= (int)mCPVec.size())
return *mCPVec[0]; /*If index is out of bounds, return the first element by default.*/
return *mCPVec[index];
}
/*
* -------------------------------------------------------------------------------------------------------
* Implementation of class Curve
* -------------------------------------------------------------------------------------------------------
*/
/*
* Constructor(s)
*/
Curve::Curve(const Color3 &newColor)
{
mColor.Set(newColor);
mControlPoints.SetColor(mColor);
mControlPointVisible = false;
mControlPolygonVisible = false;
mMBBVisible = false;
}
/*
* Accessors
*/
std::vector<Vector2I*>* Curve::GetControlPointVec()
{
return mControlPoints.GetControlPointVec();
}
std::vector<Vector2I*>* Curve::GetPlottedPointsVec()
{
return &mPlotVec;
}
Color3 Curve::GetColor() const
{
return mColor;
}
bool Curve::GetControlPointVisibility() const
{
return mControlPointVisible;
}
bool Curve::GetControlPolygonVisibility() const
{
return mControlPolygonVisible;
}
bool Curve::GetMBBVisibility() const
{
return mMBBVisible;
}
MyRectangle Curve::GetMBB()
{
MyRectangle *returnRect = new MyRectangle();
returnRect->Set(mControlPoints.GetMBB());
return *returnRect;
}
void Curve::Draw() const
{
Draw(mColor);
}
void Curve::Draw(const Color3 &drawColor) const
{
Line tempLine;
for (unsigned int i = 0; i < mPlotVec.size(); i++)
{
/*Draw a point within the vec holding the points of the curve*/
SetPixel(mPlotVec[i]->GetX(), mPlotVec[i]->GetY(), drawColor);
/*Draw lines connecting two adjecent points in mPlotVec, in case the resolution
of the parametric range isn't sufficiently large to draw a continuous curve by
plotting individual points alone*/
if (i > 0)
{
tempLine = Line(*mPlotVec[i - 1], *mPlotVec[i], drawColor);
tempLine.Draw();
}
/*Draw intermediate lines*/
//if (mGenerationLines.size() > 0)
//{
// if (i > 0)
// {
// /*Erase previous generation's itermediate lines*/
// for (unsigned int gen = 0; gen < mGenerationLines[i - 1].size(); gen++)
// mGenerationLines[i - 1][gen]->Draw(Color3(0.0f, 0.0f, 0.0f));
// }
// /*Draw current generation's intermediate lines*/
// for (unsigned int gen = 0; gen < mGenerationLines[i].size(); gen++)
// mGenerationLines[i][gen]->Draw();
//}
}
if (mControlPointVisible)
mControlPoints.Draw();
if (mControlPolygonVisible)
mControlPoints.DrawControlPolygon();
if (mMBBVisible)
mControlPoints.DrawMBB();
}
void Curve::DrawIntermediateLines() const
{
for (unsigned int i = 0; i < mIntermediateLines.size(); i++)
mIntermediateLines[i]->Draw();
}
/*
* Mutators
*/
/*Whenever a new control point is inserted, (re)calculate all the plot points of the curve*/
void Curve::InsertControlPoint(const Vector2I &newControlPoint)
{
/*First, clear previously drawn curve*/
Clear();
/*Also clear any intermediate lines that may be in the pixelBuffer*/
ClearIntermediateLines();
/*Make a copy of the newControlPoint*/
Vector2I *temp = new Vector2I(newControlPoint.GetX(), newControlPoint.GetY());
/*Insert the new control point and recalculate the curve*/
mControlPoints.PushBack(*temp);
CalcPlotVec();
/*
* NOTE: I don't like how this is implemented. It would be better if none of the curve functions
* depended on the graphModeIsOn flag, or any other global flags for that matter, so that
* this file stays very portable to other projects.
*/
//if (!graphModeIsOn)
//{
// int index = MAGIC_GARBAGE;
// for (unsigned int i = 0; i < curveVec.size(); i++)
// {
// if (&(*this) == &(*(curveVec[i])))
// {
// index = i;
// break;
// }
// }
// HandleCurveDraw(index);
//}
}
void Curve::EraseAllControlPoints()
{
mControlPoints.EraseAll();
}
void Curve::EraseControlPoint(int index)
{
mControlPoints.Erase(index);
}
void Curve::SetIntermediateLines(float t)
{
/*If there are no control points, return*/
if (mControlPoints.GetControlPointVec()->size() < 1)
return;
/*Ensure that t is normalized*/
t = (t < 0.0f) ? 0.0f : t;
t = (t > 1.0f) ? 1.0f : t;
/*Allocate space for the 2D array generation table,
used for keeping track of children in generations from
zero to n*/
const unsigned int n = mControlPoints.GetControlPointVec()->size() - 1;
Vector2I *generationTable = new Vector2I[(n + 1)*(n + 1)]; /*Each row represents a generation,
starting with generation 0 at the top.
Each column within a row represents
a child of that generation, in
increasing order from left to right.*/
/*Populate the generation table*/
for (unsigned int j = 0; j <= n; j++)
{
for (unsigned int i = 0; i <= n - j; i++)
{
if (j == 0)
{
generationTable[i].SetX(mControlPoints[i].GetX());
generationTable[i].SetY(mControlPoints[i].GetY());
}
else
{
Vector2I temp = Vector2I((1.0f - t) * generationTable[(j - 1) * (n + 1) + i] +
t * generationTable[(j - 1) * (n + 1) + i + 1]);
generationTable[j * (n + 1) + i].SetX(temp.GetX());
generationTable[j * (n + 1) + i].SetY(temp.GetY());
}
/*Calculate intermediate lines*/
if (i > 0)
{
/*
* Store line connecting two adjacent children of the same generation
*/
/*Calculate which point on the curve this is*/
float tStep = 1.0f / curveResolution;
int s = (int)(t / tStep); /*Counter of which pixel is being calculated in the curve*/
/*Store a generation line*/
Line* tempLine = new Line(generationTable[j * (n + 1) + i - 1],
generationTable[j * (n + 1) + i],
Color3(mColor.GetR() / 2.0f, mColor.GetG() / 2.0f, mColor.GetB() / 2.0f));
mIntermediateLines.push_back(tempLine);
}
}
}
}
void Curve::Clear()
{
/*Clear pixels from pixelBuffer*/
Line tempLine;
for (unsigned int i = 0; i < mPlotVec.size(); i++)
{
SetPixel(mPlotVec[i]->GetX(), mPlotVec[i]->GetY(), Color3(0.0f, 0.0f, 0.0f));
if (i > 0)
{
tempLine = Line(*mPlotVec[i - 1], *mPlotVec[i], Color3(0.0f, 0.0f, 0.0f));
tempLine.Draw();
}
}
/*Clear stored pixel locations within mPlotVec and mGenerationLines*/
mPlotVec.clear();
//mGenerationLines.clear();
}
void Curve::ClearIntermediateLines()
{
/*Clear pixels from pixelBuffer*/
Line tempLine;
for (unsigned int i = 0; i < mIntermediateLines.size(); i++)
mIntermediateLines[i]->Draw(Color3(0.0f, 0.0f, 0.0f));
/*Clear stored pixel locations within mIntermediateLines*/
mIntermediateLines.clear();
}
/*Clear the MBB lines from the pixelBuffer.*/
void Curve::ClearMBB()
{
mControlPoints.ClearMBB();
}
/*Clear curve, intermediate lines, control points, control polygon, MBB*/
void Curve::ClearEverything()
{
Clear();
ClearIntermediateLines();
mControlPoints.Clear();
mControlPoints.ClearControlPolygon();
/*mControlPoints.ClearConvexHull();*/
mControlPoints.ClearMBB();
}
void Curve::SetColor(const Color3 &newColor)
{
mColor.Set(newColor);
mControlPoints.SetColor(newColor);
}
/*Splits this curve at t. This curve becomes the left child and the right child is returned.*/
Curve* Curve::Split(float t)
{
/*If there are no control points, return*/
if (mControlPoints.GetControlPointVec()->size() < 1)
return NULL;
/*Ensure that t is normalized*/
t = (t < 0.0f) ? 0.0f : t;
t = (t > 1.0f) ? 1.0f : t;
/*Allocate space for the 2D array generation table,
used for keeping track of children in generations from
zero to n*/
const unsigned int n = mControlPoints.GetControlPointVec()->size() - 1;
Vector2I *generationTable = new Vector2I[(n + 1)*(n + 1)]; /*Each row represents a generation,
starting with generation 0 at the top.
Each column within a row represents
a child of that generation, in
increasing order from left to right.*/
/*Populate the generation table*/
for (unsigned int j = 0; j <= n; j++)
{
for (unsigned int i = 0; i <= n - j; i++)
{
if (j == 0)
{
generationTable[i].SetX(mControlPoints[i].GetX());
generationTable[i].SetY(mControlPoints[i].GetY());
}
else
{
Vector2I temp = Vector2I((1.0f - t) * generationTable[(j - 1) * (n + 1) + i] +
t * generationTable[(j - 1) * (n + 1) + i + 1]);
generationTable[j * (n + 1) + i].SetX(temp.GetX());
generationTable[j * (n + 1) + i].SetY(temp.GetY());
}
}
}
/*Clear this curve's control points, then set its new control points to be those
of the left child*/
EraseAllControlPoints();
for (unsigned int i = 0; i < n + 1; i++)
InsertControlPoint(generationTable[i * (n + 1)]);
/*Create a pointer to a curve with the right child's control points.*/
Curve *rightChild;
if(isUsingBernstein)
rightChild = new BernsteinCurve(GetRandomCurveColor().GetColor3());
else /*if(!isUsingBernstein)*/
rightChild = new DeCasteljauCurve(GetRandomCurveColor().GetColor3());
for (unsigned int i = 0; i < n + 1; i++)
rightChild->InsertControlPoint(generationTable[i * (n + 1) + n - i]);
/*Handle flags for right child*/
rightChild->SetControlPointVisibility(controlPointsVisible);
rightChild->SetControlPolygonVisibility(controlPolygonVisible);
rightChild->SetMBBVisibility(MBBVisible);
/*return right child curve*/
return rightChild;
}
void Curve::SetControlPointVisibility(bool newVisibility)
{
mControlPointVisible = newVisibility;
/*If control point visibility has just been turned off, clear all control points that may
be onscreen.*/
if (newVisibility == false)
mControlPoints.Clear();
/*If control point visibility has just been turned on, draw control points*/
else
if ( !graphModeIsOn )
mControlPoints.Draw();
}
void Curve::SetControlPolygonVisibility(bool newVisibility)
{
mControlPolygonVisible = newVisibility;
/*If control polygon visibility has just been turned off, clear all lines from the
control polygon that may be onscreen.*/
if (newVisibility == false)
mControlPoints.ClearControlPolygon();
/*If control polygon visibility has just been turned on, draw lines that make up
the control polygon*/
else
if (!graphModeIsOn)
mControlPoints.DrawControlPolygon();
}
void Curve::SetMBBVisibility(bool newVisibility)
{
mMBBVisible = newVisibility;
/*If MBB visibility has just been turned off, clear all lines from the
MBB that may be onscreen.*/
if (newVisibility == false)
mControlPoints.ClearMBB();
/*If control polygon visibility has just been turned on, draw lines that make up
the control polygon*/
else
if (!graphModeIsOn)
mControlPoints.DrawMBB();
}
/*
* -------------------------------------------------------------------------------------------------------
* Implementation of class DeCasteljauCurve
* -------------------------------------------------------------------------------------------------------
*/
/*
* Constructor(s)
*/
DeCasteljauCurve::DeCasteljauCurve(const Color3 &newColor) : Curve(newColor)
{
}
/*
* Accessors
*/
Vector2I DeCasteljauCurve::GetPlotPoint(float t)
{
/*If there are no control points, return some arbitrary coordinate*/
if (mControlPoints.GetControlPointVec()->size() < 1)
return Vector2I(0, 0);
/*Ensure that t is normalized*/
t = (t < 0.0f) ? 0.0f : t;
t = (t > 1.0f) ? 1.0f : t;
/*Allocate space for the 2D array generation table,
used for keeping track of children in generations from
zero to n*/
const unsigned int n = mControlPoints.GetControlPointVec()->size() - 1;
Vector2F *generationTable = new Vector2F[(n + 1)*(n + 1)]; /*Each row represents a generation,
starting with generation 0 at the top.
Each column within a row represents
a child of that generation, in
increasing order from left to right.*/
/*Populate the generation table, then return the single child of the last generation*/
for (unsigned int j = 0; j <= n; j++)
{
for (unsigned int i = 0; i <= n - j; i++)
{
if (j == 0)
{
generationTable[i].SetX((float)mControlPoints[i].GetX());
generationTable[i].SetY((float)mControlPoints[i].GetY());
}
else
{
Vector2F temp = Vector2F((1.0f - t) * generationTable[(j - 1) * (n + 1) + i] +
t * generationTable[(j - 1) * (n + 1) + i + 1]);
generationTable[j * (n + 1) + i].SetX(temp.GetX());
generationTable[j * (n + 1) + i].SetY(temp.GetY());
}
/*Calculate intermediate lines*/
//if (i > 0)
//{
// /*
// * Store line connecting two adjacent children of the same generation
// */
// /*Calculate which point on the curve this is*/
// float tStep = 1.0f / curveResolution;
// int s = (int)(t / tStep); /*Counter of which pixel is being calculated in the curve*/
// /*Store a generation line*/
// Line* tempLine = new Line(generationTable[j * (n + 1) + i - 1],
// generationTable[j * (n + 1) + i], mColor);
// std::vector<Line*> tempGenLine;
// tempGenLine.push_back(tempLine);
// if (j == 0)
// mGenerationLines.push_back(tempGenLine);
// else
// mGenerationLines[s].push_back(tempLine);
//}
}
}
Vector2I roundedPlotPoint = Vector2I(MyRound(generationTable[n * (n + 1)].GetX()), MyRound(generationTable[n * (n + 1)].GetY()));
return roundedPlotPoint; /*Return the first (and only) child of the last generation.*/
}
/*
* Mutators
*/
void DeCasteljauCurve::CalcPlotVec()
{
/*Since this function will calculate every point on the curve, we can clear any previous
contents in the mPlotVec and mGenerationLines*/
mPlotVec.clear();
//mGenerationLines.clear();
/*Populate the mPlotVec (and, implicitly, mGenerationLines)*/
Vector2I *temp;
float tStep = 1.0f / curveResolution;
for (float t = 0.0f; t <= 1.0f; t += tStep)
{
temp = new Vector2I(GetPlotPoint(t));
mPlotVec.push_back(temp);
}
/*Ensure that the point when t=1.0f is drawn*/
mPlotVec.push_back(new Vector2I(GetPlotPoint(1.0f)));
}
/*
* -------------------------------------------------------------------------------------------------------
* Implementation of class Bernstein
* -------------------------------------------------------------------------------------------------------
*/
/*
* Constructor(s)
*/
BernsteinCurve::BernsteinCurve(const Color3 &newColor) : Curve(newColor)
{
}
/*
* Accessors
*/
/*
* This function has odd behavior when the number of control points is greater than
* or equal to 22, i.e. when nPlusOne >= 22
*/
Vector2I BernsteinCurve::GetPlotPoint(float t)
{
/*If there are no control points, return some arbitrary coordinate*/
if (mControlPoints.GetControlPointVec()->size() < 1)
return Vector2I(0, 0);
/*Ensure that t is normalized*/
t = (t < 0.0f) ? 0.0f : t;
t = (t > 1.0f) ? 1.0f : t;
/*Use the Bernstein algorithm to get the plot point determined by t*/
float x = 0;
float y = 0;
float coeff = 0;
unsigned int nPlusOne = mControlPoints.GetControlPointVec()->size();
for (unsigned int i = 0; i < nPlusOne; i++)
{
coeff = (float)(pascalsTriangle[nPlusOne - 1][i] * MyPow(1.0f - t, (float)(nPlusOne - 1 - i)) * MyPow(t, (float)i));
x += coeff * (*mControlPoints.GetControlPointVec())[i]->GetX();
y += coeff * (*mControlPoints.GetControlPointVec())[i]->GetY();
}
Vector2I roundedPlotPoint = Vector2I(MyRound(x), MyRound(y));
return roundedPlotPoint; /*Return the first (and only) child of the last generation.*/
}
/*
* Mutators
*/
void BernsteinCurve::CalcPlotVec()
{
/*Since this function will calculate every point on the curve, we can clear any previous
contents in the mPlotVec and mGenerationLines*/
mPlotVec.clear();
//mGenerationLines.clear();
/*Populate the mPlotVec (and, implicitly, mGenerationLines)*/
Vector2I *temp;
float tStep = 1.0f / curveResolution;
for (float t = 0.0f; t <= 1.0f; t += tStep)
{
temp = new Vector2I(GetPlotPoint(t));
mPlotVec.push_back(temp);
}
/*Ensure that the point when t=1.0f is drawn*/
mPlotVec.push_back(new Vector2I(GetPlotPoint(1.0f)));
}
/*
* Global functions
*/
/*Takes a float param because all functions linked to a slider must have the form:
* void funcName(float paramName)
*/
void SetCurveResolution(float newCurveResolution)
{
/*Set new curve resolution*/
curveResolution = (unsigned int)newCurveResolution;
/*Move the other slider bar slightly so that the intermediate lines are cleared,
recalculated, and redrawn to fit the new curve*/
if (intermediateLinesSlider != NULL)
{
Vector2I sliderPos = intermediateLinesSlider->GetSliderPosition();
if (intermediateLinesSlider->GetSliderOrientation() == Slider::Vertical)
{
sliderPos = (sliderPos.GetY() < intermediateLinesSlider->GetRect().GetTopLeft().GetY()) ?
Vector2I(sliderPos.GetX(), sliderPos.GetY() + 1) :
Vector2I(sliderPos.GetX(), sliderPos.GetY() - 1);
}
else /*if (intermediateLinesSlider->GetSliderOrientation() == Slider::Horizontal)*/
{
sliderPos = (sliderPos.GetX() > intermediateLinesSlider->GetRect().GetTopLeft().GetX()) ?
Vector2I(sliderPos.GetX() - 1, sliderPos.GetY()) :
Vector2I(sliderPos.GetX() + 1, sliderPos.GetY());
}
intermediateLinesSlider->SetSliderPosition(sliderPos);
}
/*Set new resolution for curves and redraw them.*/
for (unsigned int i = 0; i < curveVec.size(); i++)
{
/*Clear all curves onscreen, as they are about to have a new resolution*/
curveVec[i]->Clear();
/*Recalculate all the points for the curves based on the new curve resolution*/
curveVec[i]->CalcPlotVec();
HandleCurveDraw(i);
}
}
void SetAndDrawIntermediateLines(float t)
{
for (unsigned int i = 0; i < curveVec.size(); i++)
{
/*Clear old intermediate lines*/
curveVec[i]->ClearIntermediateLines();
/*Set new intermediate lines*/
curveVec[i]->SetIntermediateLines(t);
/*Draw intermediate lines*/
curveVec[i]->DrawIntermediateLines();
/*Since clearing the old intermediate lines might have cleared some pixels representing the
actual curve in the pixelBuffer, redraw the curve. Since intermediate lines are only drawn
for the line described by the deCasteljau algorithm, that is the line to redraw*/
HandleCurveDraw(i);
}
}
void SetSplitValue(float t)
{
if (t > 1.0f)
splitT = 1.0f;
else if (t < 0.0f)
splitT = 0.0f;
else
splitT = t;
}
void HandleNewControlPoint(const Vector2I &temp)
{
/*If curveIndex is out of bounds, set it to MAGIC_GARBAGE so that the new control point
will go towards making a new curve.*/
if (curveIndex < 0 || (unsigned int)curveIndex >= curveVec.size())
curveIndex = MAGIC_GARBAGE;
/*When the user places a new control point, clear any intermediate lines that may have
been onscreen.*/
for (unsigned int i = 0; i < curveVec.size(); i++)
curveVec[i]->ClearIntermediateLines();
/*Clear the MBB of the curve in focus that may have been onscreen, as placing a new control point
may change the MBB of the curve in focus. In any case, after forcing a redraw, the MBB of the
curve in focsu will be redisplayed if the MBBCheckbox is checked.*/
if (curveIndex >= 0 && (unsigned int)curveIndex < curveVec.size())
curveVec[curveIndex]->ClearMBB();
/*Make a deep copy of the new control point's position*/
Vector2I *newControlPointPos = new Vector2I();
newControlPointPos->SetX(temp.GetX());
newControlPointPos->SetY(temp.GetY());
/*If no curve is in focus, then create a new curve (using the Bernstein algorithm
if the respective checkbox is checked, or the deCasteljau otherwise).*/
if (curveIndex == MAGIC_GARBAGE)
{
Curve *newCurve = NULL;
/*Create a curve using with the underlying algorithm either being the deCasteljau
or the Bernstein.*/
if (isUsingBernstein)
newCurve = new BernsteinCurve();
else /*(!isUsingBernstein)*/
newCurve = new DeCasteljauCurve();
/*Give curve a random, non-yellow color, non-dark color.*/
do
{
newCurve->SetColor(GetRandomCurveColor().GetColor3());
} while (newCurve->GetColor().GetR() >= 0.8f && newCurve->GetColor().GetG() >= 0.8f);
/*Handle flags for new curve*/
newCurve->SetControlPointVisibility(controlPointsVisible);
newCurve->SetControlPolygonVisibility(controlPolygonVisible);
newCurve->SetMBBVisibility(MBBVisible);
/*Change curveIndex and insert curve into curveVec*/
curveIndex = curveVec.size();
newCurve->InsertControlPoint(*newControlPointPos);
curveVec.push_back(newCurve);
}
else
{
if ((curveVec[curveIndex]->GetControlPointVec())->size() < pascalsTriangle.size())
curveVec[curveIndex]->InsertControlPoint(*newControlPointPos);
}
/*Force redraw of curve that just had a new control point inserted into it.*/
HandleCurveDraw(curveIndex);
}
void HandleCurveDraw(int index)
{
if (index < 0 || (unsigned int)index >= curveVec.size())
return;
if (index == curveIndex)
curveVec[index]->Draw(Color3(1.0f, 1.0f, 0.0f));
else
curveVec[index]->Draw();
}
void GetIntersections(Curve *firstCurve, Curve *secondCurve)
{
const unsigned int EPSILON = 1;
MyRectangle firstCurveMBB = firstCurve->GetMBB();
MyRectangle secondCurveMBB = secondCurve->GetMBB();
Curve *firstCurveFirstChild = NULL;
Curve *firstCurveSecondChild = NULL;
Curve *secondCurveFirstChild = NULL;
Curve *secondCurveSecondChild = NULL;
/*The MBBs of the two curves overlap. Check to see if the MBBs of both curves are small enough.
If they are, then update intersectionsVec. If not, split both curves and make a recursive
call to this function to check if the children MBBs overlap.*/
if (firstCurveMBB.ContainsRect(secondCurveMBB))
{
/*Create a copy of firstCurve*/
firstCurveFirstChild = new BernsteinCurve();
for (unsigned int controlPoint = 0; controlPoint < firstCurve->GetControlPointVec()->size(); controlPoint++)
firstCurveFirstChild->InsertControlPoint(*((*(firstCurve->GetControlPointVec()))[controlPoint]));
/*Create a copy of secondCurve.*/
secondCurveFirstChild = new BernsteinCurve();
for (unsigned int controlPoint = 0; controlPoint < secondCurve->GetControlPointVec()->size(); controlPoint++)
secondCurveFirstChild->InsertControlPoint(*((*(secondCurve->GetControlPointVec()))[controlPoint]));
/*Split firstCurve.*/
firstCurveSecondChild = firstCurveFirstChild->Split(0.5f);
/*Split secondCurve.*/
secondCurveSecondChild = secondCurveFirstChild->Split(0.5f);
/*If both MBBs are small enough, update intersectionsVec and return.*/
if ((firstCurveMBB.GetDimensions().GetX() < EPSILON && firstCurveMBB.GetDimensions().GetY() < EPSILON) ||
(secondCurveMBB.GetDimensions().GetX() < EPSILON && secondCurveMBB.GetDimensions().GetY() < EPSILON) ||
(firstCurveMBB.GetDimensions() == firstCurveFirstChild->GetMBB().GetDimensions() || firstCurveMBB.GetDimensions() == firstCurveSecondChild->GetMBB().GetDimensions()) &&
(secondCurveMBB.GetDimensions() == secondCurveFirstChild->GetMBB().GetDimensions() || secondCurveMBB.GetDimensions() == secondCurveSecondChild->GetMBB().GetDimensions()))
{
Vector2I *newIntersection = new Vector2I(firstCurveMBB.GetCenter());
intersectionsVec.push_back(newIntersection);
return;
}
/*Force a redisplay of the pixel buffer, to display any MBBs of children curves created.*/
for (unsigned int i = 0; i < curveVec.size(); i++)
HandleCurveDraw(i);
Display();
/*Check for intersections between children curves belonging to different parent curves.*/
GetIntersections(firstCurveFirstChild, secondCurveFirstChild);
GetIntersections(firstCurveFirstChild, secondCurveSecondChild);
GetIntersections(firstCurveSecondChild, secondCurveFirstChild);
GetIntersections(firstCurveSecondChild, secondCurveSecondChild);
}
} | true |
3a2d70e784351204fa17624129010d44781204ac | C++ | Muneebdw/DSproject | /Keystree.h | UTF-8 | 4,706 | 3.0625 | 3 | [] | no_license | #include<iostream>
#include<cmath>
#include<cstdio>
#include <string>
#include<cstdlib>
#include <sys/stat.h>
#include <iomanip>
#include <fstream>
#include <time.h>
using namespace std;
string char_arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
short int system_bits=4;
short int number_of_Ports=1;
short int number_of_Hubs=1;
string hashfunc(int i){
string r="";
for(int i=0;i<3;i++){
r += char_arr[rand( ) % 27];}
r+= to_string(i);
r+= to_string(i%number_of_Ports);
for(int i=0;i<2;i++){
r += char_arr[rand( ) % 27];}
return r;
}
int convertDecimal_to_Binary(int n)
{
int binaryNumber = 0;
int remainder, i = 1, step = 1;
while (n != 0)
{
remainder = n % 2;
n /= 2;
binaryNumber += remainder* i;
i *= 10;
}
return binaryNumber;
}
struct key_Node
{
short int key;
string hkey;
bool status;
string data_in;
int key_in_binary;
key_Node* Left;
key_Node* Right;
};
class keys_tree
{
private:
key_Node* head=NULL;
public:
keys_tree()
{
for (int i = 0; i<number_of_Ports; i++)
{
if (i == 0)
{
key_Node* temp;
temp = new key_Node;
temp->key = i;
temp->key_in_binary = convertDecimal_to_Binary(i);
temp->Left = NULL;
temp->status = false;
temp->hkey = hashfunc(i);
temp->data_in="";
head = temp;
}
else
{
key_Node* temp;
temp = new key_Node;
temp->key = i;
temp->key_in_binary = convertDecimal_to_Binary(i);
temp->Left = NULL;
temp->status = false;
temp->hkey = hashfunc(i);
temp->data_in="";
key_Node* temp2 = head;
while (temp2->Left != NULL)
{
temp2 = temp2->Left;
}
temp2->Left = temp;
}
}
}
bool get_Port_status(short int key_argument)
{
if (key_argument>= number_of_Ports)
{
cout << "such key does not exist\n";
return false;
}
key_Node* temp2 = head;
while (temp2 != NULL)
{
if (temp2->key == key_argument)
{
return temp2->status;
}
temp2 = temp2->Left;
}
}
string get(int key){
//cout << "such key does not exist\n";
key_Node* temp2 = head;
while (temp2 != NULL)
{
if (temp2->key == key)
{
return temp2->data_in;
}
temp2 = temp2->Left;
}
return "";
}
bool deletekey(int key){
key_Node* temp2 = head;
while (temp2 != NULL)
{
if (temp2->key == key)
{
temp2->status=false;
temp2->data_in="";
return true;
}
temp2 = temp2->Left;
}
return false;
}
bool insertin(short int key_argument,string data)
{bool status_argument = true;
if (key_argument >= number_of_Ports)
{
key_Node* temp;
temp = new key_Node;
temp->key = key_argument;
temp->key_in_binary = convertDecimal_to_Binary(key_argument);
temp->Left = NULL;
temp->status = true;
temp->data_in = data;
temp->hkey = hashfunc(key_argument);
key_Node* temp2 = head;
while (temp2->Left != NULL)
{
temp2 = temp2->Left;
}
temp2->Left = temp;
return false;
}
key_Node* temp2 = head;
while (temp2 != NULL)
{
if (temp2->key == key_argument)
{
temp2->status= status_argument;
temp2->data_in = data;
return true;
temp2->data_in = data;
}
temp2 = temp2->Left;
}
}
void Extend_the_Ports_keys_array()
{
key_Node* temp2 = head;
while (temp2->Left!= NULL)
{
temp2 = temp2->Left;
}
short int tempreory_port_numbers = temp2->key;
for (int i = tempreory_port_numbers + 1; i < number_of_Ports; i++)
{
key_Node* temp;
temp = new key_Node;
temp->key = i;
temp->key_in_binary = convertDecimal_to_Binary(i);
temp->Left = NULL;
temp->status = false;
temp2->Left = temp;
temp2=temp;
}
}
void Displayall()
{
cout << "Key"<<setw(10)<<"Hash key" << setw(20)<< "status" << setw(10) << "Binary"<<setw(10) << "Data"<<endl;
key_Node* temp2=head;
while (temp2!= NULL)
{
cout << temp2->key << setw(20)<<temp2->hkey<<setw(10) << temp2->status <<setw(10) << temp2->key_in_binary<< setw(10)<< temp2->data_in<<endl;
temp2 = temp2->Left;
}
}
void Displayactive(){
cout << "Key"<<setw(10)<<"Hash key" << setw(20)<< "status" << setw(10) << "Binary"<<setw(10) << "Data"<<endl;
key_Node* temp2=head;
while (temp2!= NULL)
{
if(temp2->status==true) {
cout << temp2->key << setw(20)<<temp2->hkey<<setw(10) << temp2->status <<setw(10) << temp2->key_in_binary<< setw(10)<< temp2->data_in<<endl;
}
temp2 = temp2->Left;}
}
void writetofile(string filepath,int key , string data_in){
std::ofstream outfile (filepath);
outfile << key;
key_Node* t = this->head;
while(t->key==key || t->Left == NULL){
t= t->Left;
}
outfile << setw(10) << t->hkey<< setw(10)<< data_in <<"\n";
outfile.close();
}
};
| true |
3d34242ad92983ffd9bc68a9f5be0bdb6abebf1f | C++ | PTReturns/Source | /Server/FieldTable.cpp | UTF-8 | 2,091 | 2.53125 | 3 | [] | no_license | #include "stdafx.h"
#include "FieldTable.h"
#include "SQLApi.h"
void CFieldTable::BuildFields( )
{
int nMaps = 0;
SQLBuffer Maps;
SecureZeroMemory( ( void* )0x0075B038, 0x3AA00 );
if( SQL->Select( Maps, "SELECT * FROM ServerDB.dbo.Maps" ) )
{
nMaps = Maps.size( ) - 1;
if( nMaps > MAX_TOTAL_FIELD )
nMaps = MAX_TOTAL_FIELD;
int Address = 0x0075B038;
int nFieldAddr = 0x0075BE94;
#ifdef _DEBUG_MODE_
std::cout << "Reading Maps[ " << nMaps << " ]..." << std::endl;
#endif
for( int i = 0; i < nMaps; i++ )
{
*( int* )( nFieldAddr ) = atoi( Maps[ i ][ 0 ].c_str( ) );
strcpy_s( ( char* )( Address + 0x4 ), 0x40, Maps[ i ][ 2 ].c_str( ) );
*( int* )( Address + 0xC4 ) = GetEnvironmentFromString( Maps[ i ][ 3 ].c_str( ) );
*( int* )( Address + 0xCB8 ) = atoi( Maps[ i ][ 4 ].c_str( ) );
Address += 0xEA8;
nFieldAddr += 0xEA8;
#ifdef _DEBUG_MODE_
std::cout << "Map read[ " << Maps[ i ][ 2 ].c_str( ) << " ]..." << std::endl;
#endif
};
};
#ifdef _DEBUG_MODE_
std::cout << "All found maps are read." << std::endl;
#endif
}
int CFieldTable::GetEnvironmentFromString( const char* String )
{
if( lstrcmpiA( String, "City" ) == 0 )
return FieldEnvironment::City;
else if( lstrcmpiA( String, "Forest" ) == 0 )
return FieldEnvironment::Forest;
else if( lstrcmpiA( String, "Desert" ) == 0 )
return FieldEnvironment::Desert;
else if( lstrcmpiA( String, "Ruins" ) == 0 )
return FieldEnvironment::Ruins;
else if( lstrcmpiA( String, "Dungeon" ) == 0 )
return FieldEnvironment::Dungeon;
else if( lstrcmpiA( String, "Iron" ) == 0 )
return FieldEnvironment::Iron;
else if( lstrcmpiA( String, "Office" ) == 0 )
return FieldEnvironment::Office;
else if( lstrcmpiA( String, "Ice" ) == 0 )
return FieldEnvironment::Ice;
else if( lstrcmpiA( String, "Castle" ) == 0 )
return FieldEnvironment::Castle;
else if( lstrcmpiA( String, "Mini-Game" ) == 0 )
return FieldEnvironment::MiniGame;
return FieldEnvironment::Invalid;
}
void Initialize_Maps( )
{
CFieldTable* pField = new CFieldTable( );
pField->BuildFields( );
delete pField;
} | true |
0674e1e035814f5809639ab0602a8d46f429de4b | C++ | ngangwar962/C_and_Cpp_Programs | /june_27_string_dp/delete_consecutive_vowels.cpp | UTF-8 | 606 | 2.5625 | 3 | [] | no_license | #include<iostream>
#include<bits/stdc++.h>
#include<unordered_set>
using namespace std;
int main()
{
unordered_set<char> s;
s.insert('a');
s.insert('e');
s.insert('i');
s.insert('o');
s.insert('u');
int i,j,k,l;
string str;
getline(cin,str);
//cout<<str<<"\n";
int len=str.length();
//cout<<len<<"\n";
if(len==1)
{
cout<<str;
return 0;
}
i=1;
cout<<str[0];
while(str[i]!='\0')
{
if(s.find(str[i])==s.end())
{
cout<<str[i];
i++;
}
else
{
if(s.find(str[i-1])!=s.end())
{
i++;
}
else
{
cout<<str[i];
i++;
}
}
}
cout<<"\n";
return 0;
}
| true |
b13df053ee7144cee7b3370b212399f98086b788 | C++ | fabiohsm2008/3er-Semestre | /Algebra Abstracta/RSA/main.cpp | UTF-8 | 1,769 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include "RSA.h"
using namespace std;
int rdtsc() ///rand de ciclos utilizados por procesador desde el inicio
{
__asm__ __volatile__("rdtsc");
}
int main()
{
srand(rdtsc());
cout << "RSA Cifrado y Descifrado" << endl;
cout << "1: Imprimir claves" << endl;
cout << "2: Cifrar un Texto" << endl;
cout << "3: Descifrar un Texto" << endl;
cout << "0: Salir" << endl;
int x;
cin >> x;
RSA Receptor(1024);
while(x != 0){
switch (x){
case 1:{
Receptor.impr_claves();}
break;
case 2:{
string a, b;
cout << "Ingrese clave publica: ";
cin >> a;
cout << "Ingrese N: ";
cin >> b;
RSA emisor(stringTozz(a), stringTozz(b));
ifstream ficheroEntrada;
string mensaje;
ficheroEntrada.open ("temp.txt");
getline(ficheroEntrada,mensaje);
ficheroEntrada.close();
ofstream ficheroSalida;
ficheroSalida.open("mensaje.txt");
ficheroSalida << emisor.cifrar(mensaje);
ficheroSalida.close();}
break;
case 3:{
string mess, desci;
cout << "Ingrese el mensaje cifrado: ";
cin >> mess;
desci = Receptor.descifrar(mess);
cout << desci << endl;
ofstream salida;
salida.open("ofset.txt");
salida << desci;
salida.close();}
break;
}
cin >> x;
}
ZZ e = des(1024);
cout << e << endl;
if(ProbPrime(e,10))
cout << "ES PRIMO" << endl;
return 0;
}
| true |
fb39e5bd2834e8149bb39aa4ce9bf1e03a2d9ece | C++ | KamalAfiqMN/MCTE4342-Embedded-System-Design | /Week 4 GPIO/Example 8/Exercise_8.ino | UTF-8 | 550 | 2.703125 | 3 | [] | no_license | #include <ezButton.h>
int total_A, total_B;
ezButton A(7);
ezButton B(8);
void setup()
{
Serial.begin(9600);
A.setDebounceTime(100);
B.setDebounceTime(100);
}
void loop()
{
A.loop();
B.loop();
if (A.isPressed())
{
total_A++;
print();
}
else if (B.isPressed())
{
total_B++;
print();
}
else
{
}
}
void print()
{
Serial.print("A = ");
Serial.print(total_A);
Serial.print(" B = ");
Serial.print(total_B);
Serial.print('\n');
}
| true |
47a61250d353b701972d8d4805a6893eaa405528 | C++ | intelfx/pulse-dispatcher | /sources/soundfile.cpp | UTF-8 | 2,026 | 2.5625 | 3 | [] | no_license | #include "soundfile.h"
#include <common.h>
#include <limits>
namespace {
const double DEFAULT_THRESHOLD_LOW = 0.4,
DEFAULT_THRESHOLD_HIGH = 1;
const long DEFAULT_PULSE_MSEC = 30;
} // anonymous namespace
SoundFileSource::SoundFileSource (const options_map_t& options)
: FrequencySource (options)
, filename_ (options.get_string ("file"))
, handle_ (filename_)
, threshold_low_ (std::numeric_limits<sample_t>::max() * options.get_float ("th_low", DEFAULT_THRESHOLD_LOW))
, threshold_high_ (std::numeric_limits<sample_t>::max() * options.get_float ("th_high", DEFAULT_THRESHOLD_HIGH))
, pulse_width_ (options.get_int ("pulse", DEFAULT_PULSE_MSEC))
, play_file_ (options.get_bool ("play"))
{
assert (!handle_.error(), "sndfile failed to open file '%s': %d (%s)",
filename_.c_str(), handle_.error(), handle_.strError());
dbg ("reading%s file '%s' with threshold levels [%.2f; %.2f] and pulse width %d ms",
play_file_ ? " and playing" : "",
filename_.c_str(),
options.get_float ("th_low", DEFAULT_THRESHOLD_LOW),
options.get_float ("th_high", DEFAULT_THRESHOLD_HIGH),
options.get_int ("pulse", DEFAULT_PULSE_MSEC));
set_frequency (handle_.samplerate());
}
bool SoundFileSource::check_sample (sample_t sample)
{
return ((sample >= threshold_low_) && (sample <= threshold_high_));
}
void SoundFileSource::loop()
{
if (play_file_) {
char* call_string = nullptr;
asprintf (&call_string, "aplay -q \"%s\" &", filename_.c_str());
system (call_string);
free (call_string);
}
FrequencySource::loop();
}
bool SoundFileSource::single_iteration()
{
sample_t *sample = (sample_t*)alloca (sizeof (sample_t) * handle_.channels()),
max_value = 0;
sf_count_t count = handle_.readf (sample, 1);
for (size_t i = 0; i < handle_.channels(); ++i) {
if (abs (sample[i]) > max_value) {
max_value = abs (sample[i]);
}
}
if (count < 1) {
return false;
} else {
if (check_sample (max_value)) {
pulse (pulse_width_);
}
return true;
}
} | true |
222f0a572346f258819eef48a64811a22d728cce | C++ | hyfung/Arduino_Libaries | /HS420391/HS420391.h | UTF-8 | 1,143 | 3 | 3 | [] | no_license | #ifndef HS422391_h
#define HS422391_h
#include "Arduino.h"
/*
Library used to drive 4-digit seven segment
Common Anode
HS420391 sevenSeg;
*/
class HS420391{
public:
void setDigit(int x[]);
void setSegment(int x[]);
void writeNumber(int Number);
private:
unsigned char _Segment[7];
unsigned char _Digit[4];
void WriteNumberToSegment(int x, int number);
};
void HS420391::writeNumber(int Number){
WriteNumberToSegment(0 , Number / 1000);
WriteNumberToSegment(1 , (Number / 100) % 10);
WriteNumberToSegment(2 , (Number / 10) % 10);
WriteNumberToSegment(3 , Number % 10);
}
void HS420391::WriteNumberToSegment(int x, int number){
//Pull selected LOW
digitalWrite(_Digit[x], LOW);
}
/*
Set 4 pin of Anode (Digit places)
sevenSeg.setDigit(1,2,3,4)
*/
void HS420391::setDigit(int x[4]){
for(int i=0;i<4;i++){
pinMode(x[i], OUTPUT);
digitalWrite(x[i], HIGH);
}
}
/*
Set 7 pin of Cathode (Segments)
sevenSeg.setSegment(1,2,3,4,5,6,7)
*/
void HS420391::setSegment(int x[7]){
for(int i=0;i<8;i++){
pinMode(x[i], OUTPUT);
digitalWrite(x[i], LOW);
}
}
#endif
| true |
bded901694cfc25f85bd3dd58172e727805bc451 | C++ | jacekzema/Sterownik | /src/Sypialnia.cpp | UTF-8 | 681 | 2.828125 | 3 | [] | no_license | #include "Sypialnia.h"
Sypialnia::Sypialnia(string n, float t, float c, float w)
{
cout << "Podaj nazwe sypialni: " << endl;
cin >> n;
name = n;
temperatura = t;
cisnienie = c;
wilgotnosc = w;
cout << "Stworzono sypialnie: " << name << endl;
obiekty.push_back(new Czujnik(name,temperatura,cisnienie,wilgotnosc));
//Czujnik *czujnik = new Czujnik(name,temperatura,cisnienie,wilgotnosc);
//obiekty.at(0)->pokaz_parametry();
//temperatura = 15;
//obiekty.at(0)->pokaz_parametry();
return;
//ctor
}
Sypialnia::~Sypialnia()
{
cout<<"Usunieto sypialnie w: "<<name<<endl;
}
void Sypialnia::przedstaw_sie()
{
cout<<"Sypialnia o nazwie: "<<name<<endl;
}
| true |
205999cf271d5244872739b4458e4ab1447bbac4 | C++ | RogueProfile/RogueProject | /src/gl/BoundBufferObject.h | UTF-8 | 4,037 | 2.921875 | 3 | [] | no_license | #ifndef GL_BOUNDBUFFEROBJECT_H__
#define GL_BOUNDBUFFEROBJECT_H__
#include <vector>
#include <array>
#include <cstdint>
#include "Flags.h"
#include "TargetLock.h"
#include "BufferObject.h"
#include "MappedBufferObject.h"
#include "Enums.h"
namespace gl
{
class GlContext;
class BoundBufferObject
{
public:
BoundBufferObject(BufferObject* buffer, GlContext* context,
TargetLock lock);
virtual ~BoundBufferObject() = default;
BoundBufferObject(const BoundBufferObject& other) = delete;
BoundBufferObject(BoundBufferObject&& other) noexcept;
BoundBufferObject& operator =(const BoundBufferObject& other) = delete;
BoundBufferObject& operator =(BoundBufferObject&& other) noexcept;
void set_data(const void* data);
template<typename T>
void set_data(const std::vector<T>& data)
{set_data(data.data());}
void set_data(const void* data, intptr_t offset, size_t length);
template<typename T>
void set_data(const std::vector<T>& data, intptr_t offset)
{set_data(data.data(), offset, data.size() * sizeof(T));}
template<typename T, size_t N>
void set_data(const std::array<T, N>& data, intptr_t offset)
{set_data(data.data(), offset, N * sizeof(T));}
void get_data(intptr_t offset, size_t size, char* out) const;
template<typename T>
std::vector<T> get_data(intptr_t offset, size_t count) const;
template<typename T, size_t N>
std::array<T, N> get_data(intptr_t offset);
template<typename T>
MappedBufferObject<T> map(bool can_read)
{return map<T>(0, m_buffer->size() / sizeof(T), Flags<BufferObject::MappingOptions>(), can_read);}
template<typename T>
MappedBufferObject<T> map(const Flags<BufferObject::MappingOptions>& options,
bool can_read)
{return map<T>(0, m_buffer->size() / sizeof(T), options, can_read);}
template<typename T>
MappedBufferObject<T> map(intptr_t offset, size_t count,
const Flags<BufferObject::MappingOptions>& options,
bool can_read);
template<typename T>
MappedBufferObject<const T> map_const(intptr_t offset, size_t count,
const Flags<BufferObject::MappingOptions>& options);
void* map_raw(intptr_t offset, size_t size,
const Flags<BufferObject::MappingOptions>& options,
const Flags<BufferObject::MappingAccess>& access);
void flush_mapped_buffer_range(intptr_t offset, size_t length);
void invalidate();
void release();
protected:
GLenum raw_target() const {return GL_COPY_WRITE_BUFFER;}
BufferObject* m_buffer;
GlContext* m_context;
TargetLock m_lock;
private:
};
template<typename T>
std::vector<T> BoundBufferObject::get_data(intptr_t offset, size_t count) const
{
auto data = std::vector<T>(count);
get_data(offset, count * sizeof(T), data.data());
return data;
}
template<typename T, size_t N>
std::array<T, N> BoundBufferObject::get_data(intptr_t offset)
{
auto data = std::array<T, N>();
get_data(offset, N * sizeof(T), data.data());
return data;
}
template<typename T>
MappedBufferObject<T> BoundBufferObject::map(intptr_t offset, size_t count,
const Flags<BufferObject::MappingOptions>& options, bool can_read)
{
auto access = Flags<BufferObject::MappingAccess>(BufferObject::MappingAccess::Write);
auto size = count * sizeof(T);
if(can_read)
{
access |= BufferObject::MappingAccess::Read;
}
void* buffer = map_raw(offset, size, options, access);
auto ret = MappedBufferObject<T>(m_context, m_buffer, reinterpret_cast<T*>(buffer), size);
return ret;
}
template<typename T>
MappedBufferObject<const T> BoundBufferObject::map_const(intptr_t offset, size_t count,
const Flags<BufferObject::MappingOptions>& options)
{
auto size = count * sizeof(T);
void* buffer = map_raw(offset, size, options, BufferObject::MappingAccess::Read);
auto ret = MappedBufferObject<const T>(m_context, m_buffer, buffer, size);
return ret;
}
}
#endif
| true |
e90428431243d18a5714d0da9e8e462ba0c1ebc8 | C++ | ljianhui/TaskManager | /core/systeminfo.h | UTF-8 | 1,387 | 2.765625 | 3 | [] | no_license | #ifndef _SYSTEMINFO_H
#define _SYSTEMINFO_H
#include <string>
#include <vector>
class SystemInfo
{
public:
virtual void update() = 0;
virtual std::string toString()const = 0;
virtual std::string toString(const std::vector<char> &filter)const = 0;
virtual ~SystemInfo();
protected: // data
const static std::string INVALID_NAME;
protected: // function
void initFilterFlags(bool *filterFlags, int size,
const std::vector<char> &filter)const;
std::string concatNameValue(
const std::string &name, const std::string &valeu)const;
std::string concatNameValue(
const std::string &name, short value)const;
std::string concatNameValue(
const std::string &name, unsigned short value)const;
std::string concatNameValue(
const std::string &name, int value)const;
std::string concatNameValue(
const std::string &name, unsigned int value)const;
std::string concatNameValue(
const std::string &name, long value)const;
std::string concatNameValue(
const std::string &name, unsigned long value)const;
std::string concatNameValue(
const std::string &name, long long value)const;
std::string concatNameValue(
const std::string &name, unsigned long long value)const;
std::string concatNameValue(
const std::string &name, float value)const;
std::string concatNameValue(
const std::string &name, double value)const;
};
#endif
| true |
74bcb230ed991a7eecb24c6bdf0b7a5c5840d6df | C++ | TheWorldOfCode/Introduction-to-robotics-exercise-1 | /src/position.cpp | UTF-8 | 602 | 3.1875 | 3 | [] | no_license | #include "../includes/position.hpp"
position::position(int position_x, int position_y, cv::Vec3b Color)
{
x = position_x;
y = position_y;
color = Color;
}
bool position::at_position(int x_r, int y_r)
{
return x == x_r && y == y_r;
}
void position::draw_position_on_map(map2D & map)
{
map.draw_circle(x,y,color);
}
void position::draw_line_between_position_on_map(position p, map2D & map, cv::Vec3b color)
{
map.draw_line(x,y,p.get_x() , p.get_y(), color);
}
int position::get_x()
{
return x;
}
int position::get_y()
{
return y;
}
position::~position(){}
| true |
9ad07c94f695a48349f8b50d03eb161562f734f7 | C++ | TheMarsupialMole/Laboration3 | /Laboration3/fiterator.cpp | UTF-8 | 1,241 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include "String.h"
//constructor that takes a char pointer
fiterator::fiterator(char* string) {
currentposition = string;
}
//constructor that takes an iterator
fiterator::fiterator(const fiterator& ptrin) {
*this = ptrin;
}
fiterator::~fiterator(){
}
//increase pointer by onePOST
fiterator fiterator::operator++(){
return ++currentposition;
}
//increase pointer by one PRE
fiterator fiterator::operator++(const int i) {
fiterator tmp = currentposition;
++currentposition;
return tmp;
}
//return the value that the pointer is at
char& fiterator::operator*() {
return *currentposition;
}
//check equality
bool fiterator::operator==(fiterator& pin) {
return currentposition == pin.currentposition;
}
//check for inequality
bool fiterator::operator!=(fiterator& pin) {
return currentposition != pin.currentposition;
}
//ger ny iterators position by int(parameter) steps
fiterator fiterator::operator+(int i) {
return fiterator(currentposition+i);
}
//places the iterator at int(parameter) steps in
char& fiterator::operator[](int i) {
return currentposition[i];
}
//sets the "this" pointer equal to the parameter
fiterator& fiterator::operator=(char* ptr) {
currentposition = ptr;
return *this;
}
| true |
6f3c43cedf5f5c08ef59dd60ac5631f5b62b1e40 | C++ | samcragg/Autocrat | /src/Autocrat.Bootstrap/include/locks.h | UTF-8 | 1,405 | 3.5625 | 4 | [
"MIT"
] | permissive | #ifndef LOCKS_H
#define LOCKS_H
#include <atomic>
#include <cstdint>
namespace autocrat
{
/**
* Represents a light-weight lock over a resource.
* @remarks This class provides mutual exclusion facility and can be locked
* recursively by the same thread.
*/
class exclusive_lock
{
public:
/**
* Initializes a new instance of the `exclusive_lock` class.
*/
exclusive_lock();
/**
* Tries to acquire the lock, without blocking.
* @returns `true` on successful lock acquisition; otherwise, `false`.
*/
bool try_lock();
/**
* Releases the lock.
*/
void unlock();
private:
std::atomic_uint32_t _owner_id;
std::uint32_t _lock_count = 0;
};
/**
* Represents a light-weight shareable lock.
* @remarks This class provides allows shared and exclusive locking of a
* resource but does not allow recursive locking by the same
* thread in exclusive mode.
*/
class shared_spin_lock
{
public:
/**
* Locks the instance for exclusive ownership.
*/
void lock();
/**
* Locks the instance for shared ownership.
*/
void lock_shared();
/**
* Unlocks the instance from exclusive ownership.
*/
void unlock();
/**
* Unlocks the instance from shared ownership.
*/
void unlock_shared();
private:
std::atomic_uint32_t _counter = 0;
};
}
#endif
| true |
3c7039d34dabb1fa4755baa61bc2f37c700220f4 | C++ | eglide/bdlib | /src/Array.h | UTF-8 | 10,545 | 2.6875 | 3 | [
"BSD-2-Clause"
] | permissive | /*
* Copyright (c) 2006-2014, Bryan Drewery <bryan@shatow.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTIRBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Array.h
*/
#ifndef _BD_ARRAY_H
#define _BD_ARRAY_H 1
#include "bdlib.h"
#include "ReferenceCountedArray.h"
#include "String.h"
#include <functional>
#ifdef CPPUNIT_VERSION
#include <cppunit/SourceLine.h>
#include <cppunit/TestAssert.h>
#define CPPUNIT_ASSERT_ARRAY_EQUAL(expected, actual) expected.CPPUNIT_checkArrayEqual(actual, CPPUNIT_SOURCELINE())
#endif /* CPPUNIT_VERSION */
BDLIB_NS_BEGIN
template <class T>
/**
* @class Array
* @brief Dynamic Array
*/
class Array : public ReferenceCountedArray<T> {
public:
typedef T value_type;
typedef size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
/* Constructors */
Array() : ReferenceCountedArray<value_type>() {};
Array(const Array<value_type>& array) : ReferenceCountedArray<value_type>(array) {};
Array(Array<value_type>&& array) : ReferenceCountedArray<value_type>(std::move(array)) {};
/**
* @brief Create an array from an initializer list
* @param list An initializer_list
*/
Array(std::initializer_list<value_type> list) : ReferenceCountedArray<value_type>() {
*this = list;
}
/**
* @brief Create a Array from a given carray.
* @param carray The null-terminated array to create the object from.
* @param len How big is the carray?
* @post A ArrayBuf has been initialized.
* @post The buffer has been filled with the array.
* @test Array test("Some array");
*/
Array(const_pointer carray, size_t len) : ReferenceCountedArray<value_type>() {
this->Reserve(len);
for (size_t i = 0; i < len; ++i)
push(carray[i]);
};
/**
* @brief Create an empty Array container with at least the specified elements in size.
* @param newSize Reserve at least this many buckets for this Array.
* @post This array's memory will also never be shrunk.
* @post A buffer has been created.
*/
explicit Array(const size_type newSize) : ReferenceCountedArray<value_type>(newSize) {};
Array(const size_type newSize, const value_type value) : ReferenceCountedArray<value_type>(newSize, value) {};
virtual ~Array() {};
/**
* @brief Create an array from an initializer list
* @param list An initializer_list
*/
Array& operator=(std::initializer_list<value_type> list) {
this->clear();
this->Reserve(list.size());
for (value_type item : list) {
push(std::move(item));
}
return *this;
}
Array& operator=(const Array<value_type>& array) {
ReferenceCountedArray<value_type>::operator=(array);
return *this;
}
Array& operator=(Array<value_type>&& array) {
ReferenceCountedArray<value_type>::operator=(std::move(array));
return *this;
}
/**
* @brief Add an item to the end of the array
*/
inline void push(const value_type item) {
this->AboutToModify(this->length() + 1);
*(this->Buf(this->length())) = item;
this->addLength(1);
}
/**
* @sa push
*/
inline friend Array<value_type>& operator<<(Array<value_type>& array, const_reference item) {
array.push(item);
return array;
}
/**
* @brief Shift the array left, removing the first element.
* @return The first element.
*/
inline value_type shift() {
if (this->isEmpty()) return value_type();
value_type temp(*(this->Buf(0)));
++(this->offset);
this->subLength(1);
return temp;
}
/**
* @brief Pop a value off the end of the array
* @return The last element.
*/
inline value_type pop() {
if (this->isEmpty()) return value_type();
value_type temp(*(this->Buf(this->length() - 1)));
this->subLength(1);
return temp;
}
/**
* @sa pop
*/
inline friend Array<value_type>& operator>>(Array<value_type>& array, reference item) {
item = array.pop();
return array;
}
/**
* @brief Join an array by a delimiter into a string
*/
String join(const String& delim, bool quoted = false) const {
if (!this->length()) return String();
size_t str_size = 0, i;
// Preallocate a fully sized String to avoid frequent resizing
str_size += (this->length() * delim.length()) - 1;
if (quoted)
str_size += this->length() * 2;
for (i = 0; i < this->length(); ++i)
str_size += this->Buf(i)->length();
String str(str_size);
for (i = 0; i < this->length(); ++i) {
if (i)
str += delim;
if (quoted) {
str += '"' + *(this->Buf(i)) + '"';
} else {
str += *(this->Buf(i));
}
}
return str;
}
inline bool equals(const Array& array) const { return equals(array, array.length()); };
/**
* @brief Compare our Array object with another Array object, but only n elements
* @param array The Array object to equals to.
* @param n The number of items to equals.
* @return True if the number of elements are the same, and they all are equal.
*/
bool equals(const Array& array, size_t n) const
{
size_t my_len = this->length();
bool same_length = (my_len == array.length());
/* Same array? */
if (this->data() == array.data() && same_length)
return true;
if (!same_length)
return false;
size_t slen = std::min(array.length(), n);
size_t len = std::min(my_len, slen);
for (size_t i = 0; i < len; ++i) {
if ((*this)[i] != array[i])
return false;
}
return true;
}
inline friend bool operator==(const Array& lhs, const Array& rhs) {
return lhs.size() == rhs.size() && lhs.equals(rhs);
};
inline friend bool operator!=(const Array& lhs, const Array& rhs) { return !(lhs == rhs); };
// Subarrays
/**
* @sa ReferenceCountedArray::slice()
*/
inline Array subarray(int start, int len = -1) const {
Array newArray(*this);
newArray.slice(start, len);
return newArray;
};
/**
* @sa subarray
*/
inline Array operator()(int start, int len = -1) const { return subarray(start, len); };
/**
* @brief Returns a 'Slice' class for safe (cow) writing into the array
* @sa Slice
* @param start Starting position
* @param len How many items to use
*/
inline Slice<Array> operator()(int start, int len = -1) { return Slice<Array>(*this, start, len); };
#ifdef CPPUNIT_VERSION
void CPPUNIT_checkArrayEqual(Array actual, CPPUNIT_NS::SourceLine sourceLine) {
if ((*this) == actual) return;
::CPPUNIT_NS::Asserter::failNotEqual(this->join("|").c_str(), actual.join("|").c_str(), sourceLine);
}
#endif /* CPPUNIT_VERSION */
/* Operators */
/**
* @relates Array
* @brief Concatenates two array objects together.
* @param array1 The LHS array.
* @param array2 The RHS array.
* @post A new array is allocated, reference copied and returned.
* @return Returns a new array that can be reference copied by the lvalue.
*/
inline friend Array operator+(Array array1, const Array& array2) {
array1 += array2;
return array1;
}
/**
* @brief Prefix increment
*/
inline const Array& operator++() {
return (*this) += 1;
}
/**
* @brief Postfix increment
*/
inline const Array operator++(int) {
Array tmp((*this)(0, 1));
++(this->offset);
this->subLength(1);
return tmp;
}
/**
* @brief Prefix decrement
*/
inline const Array& operator--() {
return (*this) -= 1;
}
/**
* @brief Postfix decrement
*/
inline const Array operator--(int) {
Array tmp((*this)(this->length() - 1, 1));
this->subLength(1);
return tmp;
}
/**
* \sa append(const char)
*/
inline Array& operator+=(const_reference item) {
this->append(item);
return *this;
}
/**
* \sa append(const Array&)
*/
inline Array& operator+=(const Array& array) {
this->append(array);
return *this;
}
inline Array& operator+=(const int n) {
if (!this->length())
return *this;
if (int(this->length()) - n < 0) {
this->offset = this->length();
this->setLength(0);
} else {
this->offset += n;
this->subLength(n);
}
return *this;
}
inline Array& operator-=(const int n) {
if (!this->length())
return *this;
if (int(this->length()) - n < 0) {
this->offset = this->length();
this->setLength(0);
} else
this->subLength(n);
return *this;
}
};
BDLIB_NS_END
namespace std {
template<typename T>
struct hash<BDLIB_NS::Array<T>> {
inline size_t operator()(const BDLIB_NS::Array<T>& val) const {
return val.hash();
}
};
}
#endif /* _BD_ARRAY_H */
/* vim: set sts=2 sw=2 ts=8 et: */
| true |
c659a2f1635c2383db1eb69dcbec5043b7a79407 | C++ | kursatyurt/HS_Panel_Solver | /src/Point.cpp | UTF-8 | 280 | 3.0625 | 3 | [] | no_license | #include "Point.hpp"
Point::Point() : x(0.0), y(0.0) {}
Point::Point(double a, double b) : x(a), y(b) {}
void Point::changeDelta(double dx, double dy)
{
this->x += dx;
this->y += dy;
}
void Point::setValues(double xn, double yn)
{
this->x = xn;
this->y = yn;
}
| true |
7900e11c1bb99a0d3f9428edea760068dc41e1bf | C++ | Gustice/ESP32Tutorial | /SimpleTemplate/components/CppModule/include/cppModule.h | UTF-8 | 156 | 2.609375 | 3 | [
"MIT"
] | permissive |
#pragma once
class Module
{
public:
Module(int init = 0);
~Module(){};
void AddValue(int v);
int GetValue();
private:
int value;
};
| true |
9cf2d144daa84e02d96086e7ea27026065dcd247 | C++ | denniskb/merge_fusion | /KinectFission/kifi/cuda/device_allocator.h | UTF-8 | 980 | 2.65625 | 3 | [] | no_license | #pragma once
#include <cstddef>
#include <memory>
namespace kifi {
namespace cuda {
template< typename T >
class device_allocator : public std::allocator< T >
{
public:
pointer allocate( std::size_t n, const_pointer hint = 0 );
void deallocate( pointer p, std::size_t n );
};
}} // namespace
#pragma region Implementation
#include <cuda_runtime.h>
namespace kifi {
namespace cuda {
// unreferenced parameters 'n' and 'hint'
#pragma warning( push )
#pragma warning( disable : 4100 )
template< typename T >
typename device_allocator< T >::pointer device_allocator< T >::allocate( std::size_t n, const_pointer hint )
{
if( 0 == n )
return nullptr;
pointer result;
cudaMalloc( & result, n * sizeof( T ) );
return result;
}
template< typename T >
void device_allocator< T >::deallocate( pointer p, std::size_t n )
{
if( p )
cudaFree( p );
}
#pragma warning( pop )
}} // namespace
#pragma endregion | true |
f5a8e12c305a7768e9d5e93b52f50df9b80ec672 | C++ | anvv5/httpServ | /core/FileRead.cpp | UTF-8 | 979 | 2.5625 | 3 | [] | no_license | //
// Created by Talla Chicken on 5/21/21.
//
#include "FileRead.h"
#include "SendFile.h"
FileRead::FileRead(int fd, char *buf, size_t buf_capacity, const ClientSocket &clientSocket)
:
_fd(fd),
buf(buf),
buf_size(0),
buf_capacity(buf_capacity),
_isDeleted(false),
_clientSocket(clientSocket)
{}
void FileRead::readEvent(EventLoop &eventLoop) {
ssize_t cnt = read(_fd, buf + buf_size, buf_capacity - buf_size);
if (cnt == -1)
throw SocketException(strerror(errno));
if (cnt == 0)
{
eventLoop.addWriteSubscriber(new SendFile(_clientSocket, _fd, buf, buf_size, buf_capacity, true));
_isDeleted = true;
}
buf_size += cnt;
if (buf_size == buf_capacity)
{
eventLoop.addWriteSubscriber(new SendFile(_clientSocket, _fd, buf, buf_size, buf_capacity, false));
_isDeleted = true;
}
}
bool FileRead::isDeleted() const {
return _isDeleted;
}
int FileRead::getFd() const {
return _fd;
}
| true |
3c372018c8e2a3522b7b8c8501b8c1fb04a1d28d | C++ | lkrizan/ECF_deep_learning | /DeepModelTraining/ConfigParser.h | UTF-8 | 2,046 | 2.578125 | 3 | [
"MIT"
] | permissive | #include <vector>
#include <fstream>
#include <boost/tokenizer.hpp>
#include <common/Shape.h>
class ConfigParser
{
private:
std::vector<std::pair<std::string, std::vector<std::vector<int>>>> m_LayerConfiguration;
std::vector<unsigned int> m_InputShape;
std::vector<unsigned int> m_OutputShape;
std::vector<std::string> m_InputFiles;
std::vector<std::string> m_LabelFiles;
std::vector<double> m_InitializerParams;
unsigned int m_BatchSize = 0;
std::string m_DatasetLoaderType;
std::string m_LossFunctionName;
std::string m_InitializerName = "TruncatedNormalDistributionRNG";
float m_WeightDecay = 0;
// used for checking if all required parameters are configured
bool inputsConfigured = false;
bool outputsConfigured = false;
bool datasetPathConfigured = false;
bool layerConfigurationConfigured = false;
bool lossFunctionConfigured = false;
bool datasetLoaderTypeConfigured = false;
enum State {eStart, eDataset, eLayers, eLoss, eLossFinished, eInitializer};
State m_State = eStart;
void parseLine(const std::string line);
bool isHeaderLine(const std::string line) const { return (line.size() > 2 && line.front() == '[' && line.back() == ']'); }
public:
ConfigParser(const std::string pathToFile);
std::vector<std::pair<std::string, std::vector<std::vector<int>>>> & LayerConfiguration() { return m_LayerConfiguration; }
const std::vector<unsigned int>& InputShape() { return m_InputShape; }
const std::vector<unsigned int>& OutputShape() { return m_OutputShape; }
const std::vector<std::string> & InputFiles() { return m_InputFiles; }
const std::vector<std::string> & LabelFiles() { return m_LabelFiles; }
const std::vector<double> & InitializerParams() { return m_InitializerParams; }
std::string InitializerName() { return m_InitializerName; }
std::string LossFunctionName() { return m_LossFunctionName; }
std::string DatasetLoaderType() { return m_DatasetLoaderType; }
unsigned int BatchSize() { return m_BatchSize; }
float WeightDecay() { return m_WeightDecay; }
};
| true |
765052ed10b6d62b9cb8c62fc3554e9949150bc3 | C++ | fishybell/ATIatm | /open_embedded_stable_ati/oe_at91sam/recipes/ati/files/modules/fasit/process.h | UTF-8 | 1,239 | 3.03125 | 3 | [
"MIT"
] | permissive | #ifndef _PROCESS_H_
#define _PROCESS_H_
#include <stdio.h>
#include "connection.h"
using namespace std;
// a minimal wrapper around Connection to allow for handling a process pipe rather than a socket
class Process : public Connection {
public:
Process(FILE *pipe); // a new process always starts with a file stream
virtual ~Process(); // closes, cleans up, etc.
template <class Proc> static Proc *newProc(const char *cmd, bool readonly); // creates a new Process object (of the given class type) using the given command string
private :
FILE *pipe; // file stream of process pipe
protected:
virtual int handleWrite(const epoll_event *ev); // could be overwritten
virtual int handleRead(const epoll_event *ev); // could be overwritten
};
// start a process that has no interaction and can not be cancelled
// will automatically delete on end of data
class BackgroundProcess : public Process {
public:
BackgroundProcess(FILE *pipe); // create using BackgroundProcess::newProc()
static void newProc(const char *cmd); // automatically sets the & in the correct place and starts the process
protected:
int parseData(int rsize, const char *rbuf); // do nothing with the data, when finished, delete
};
#endif
| true |
60bb47b9a99dfa50dcb727f9f7233b554c430ec5 | C++ | fassad1001/triples- | /Ontology.h | UTF-8 | 1,934 | 2.546875 | 3 | [] | no_license | #ifndef ONTOLOGY_H
#define ONTOLOGY_H
#include <QtCore>
#include "TripleStorage.h"
#include "Class.h"
class MyHash : public QHash< QString, QString >
{
public:
MyHash& insertInc(const QString key, const QString value)
{
insert(key, value);
return *this;
}
MyHash& insertIncMulti(const QString key, const QString value)
{
insertMulti(key, value);
return *this;
}
};
Q_DECLARE_METATYPE(MyHash)
class Ontology : public TripleStorage
{
public:
static const QString IS;
static const QString CONTAINS;
static const QString CLASS;
static const QString HAS_PROPERTY;
enum DIRECTION
{
UP,
DOWN
};
Ontology();
Ontology(const QSet<Triple> &triples);
QSet<QString> classInstances(const QString &className) const;
QSet<QString> classProperties(const QString &className) const;
QSet<QString> anyClassInstances(const QStringList &classNames) const;
QSet<QString> propertyValues(const QString &propertyName) const;
MyHash instanceProperties(const QString &instanceName) const;
QSet<QString> allClassInstances(const QStringList &classNames) const;
QSet<QString> allClasses() const;
QSet<QString> allInstances() const;
QSet<QString> traverse(const DIRECTION &look, const QString &className) const;
QSet<QString> classesForInstance(const QString &instanceName) const;
QSet<QString> instancesForProperties(const MyHash &values) const;
QSet<QString> instancesForNonProperties(const MyHash &hashValues) const;
QSet<QString> subClasses(const QString &className) const;
QSet<QString> superClasses(const QString &className) const;
QSet<QString> mainSuperClass(const QString &instanceName1, const QString &instanceName2) const;
bool isValid() const;
bool isMinimal(QSet<Pair> &redundantPairs) const;
void minimalize();
};
Q_DECLARE_METATYPE(Ontology)
#endif // ONTOLOGY_H
| true |
8e3bd9f87876e6bdeb156f58d5a2c2c643a36018 | C++ | jrubix/Pub-ProjectsCPP131 | /EPP-Practice/Header2.h | UTF-8 | 1,695 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
class Booking {
private:
string firstname;
string lastname;
string pclass;
vector<Booking> myvec;
vector<Booking> boardingorder;
public:
void checkin(string _firstname, string _lastname, string _pclass);
void printorder();
Booking();
Booking(string _firstname, string _lastname, string _pclass);
void sortorder();
};
Booking::Booking(string _firstname, string _lastname, string _pclass){
firstname = _firstname;
lastname = _lastname;
pclass = _pclass;
}
Booking::Booking(){
firstname = "";
lastname = "";
pclass = "";
}
void Booking::checkin(string _firstname, string _lastname, string _pclass){
myvec.push_back(Booking(_firstname, _lastname, _pclass));
//where I had the sortoder that caused the bug.
}
void Booking::printorder(){
sortorder();
for (int i=0; i<boardingorder.size(); i++){
cout << boardingorder.at(i).firstname << " " << boardingorder.at(i).lastname
<< " " << "(" << boardingorder.at(i).pclass << ")" << "\n";
}
}
void Booking::sortorder(){
for (int i = 0; i<myvec.size(); i++){
if(myvec.at(i).pclass == "First"){
boardingorder.push_back(Booking(myvec.at(i).firstname,
myvec.at(i).lastname,myvec.at(i).pclass));
}
}
for (int i = 0; i<myvec.size(); i++){
if(myvec.at(i).pclass == "Business"){
boardingorder.push_back(Booking(myvec.at(i).firstname,
myvec.at(i).lastname,myvec.at(i).pclass));
}
}
for (int i = 0; i<myvec.size(); i++){
if(myvec.at(i).pclass == "Economy"){
boardingorder.push_back(Booking(myvec.at(i).firstname,
myvec.at(i).lastname,myvec.at(i).pclass));
}
}
}
| true |
dab0cc746ef6773019c41ed746f4350c14880b91 | C++ | madcato/StreamLib | /include/ProtectedFIFO.h | UTF-8 | 2,696 | 3.046875 | 3 | [] | no_license | // ProtectedFIFO.h: interface for the ProtectedFIFO class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_PROTECTEDFIFO_H__52F473E7_EBAD_4612_AFF2_853A8F55CAA9__INCLUDED_)
#define AFX_PROTECTEDFIFO_H__52F473E7_EBAD_4612_AFF2_853A8F55CAA9__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/// namespace stream
namespace stream
{
/// namespace sync
namespace sync
{
/**
Protected FIFO dequeue ready to be used in multithreading applications.
Must be specified the maximun number of elements that could be stored in the dequeue.
*/
template<class T>
class ProtectedFIFO
{
public:
ProtectedFIFO(int max_number_of_elements);
virtual ~ProtectedFIFO();
/**
Pop an element from the top of the dequeue.
This function is thread-safe. If there isn't any element in the dequeue, the calling thread is blocked until any other thread calls Push function.
@return an element.
*/
T Pop();
/**
Push an element to the back of the dequeue.
This function is thread-safe. If the dequeue is full, the calling thread is blocked until any other thread calls Pop function..
*/
void Push(T data);
/**
Return the number of elements in the dequeue. This function is thread-safe.
@return The number of elements in the dequeue.
*/
size_t Size();
protected:
CriticalSection m_criSec;
HANDLE m_semaphoreReaders;
HANDLE m_semaphoreWriters;
std::list<T> m_pila;
};
template<class T>
ProtectedFIFO<T>::ProtectedFIFO(int max_number_of_elements)
{
m_semaphoreReaders = CreateSemaphore(NULL,0,max_number_of_elements,0);
m_semaphoreWriters = CreateSemaphore(NULL,max_number_of_elements,max_number_of_elements,0);
}
template<class T>
ProtectedFIFO<T>::~ProtectedFIFO()
{
CloseHandle(m_semaphoreReaders);
CloseHandle(m_semaphoreWriters);
}
template<class T>
T ProtectedFIFO<T>::Pop()
{
WaitForSingleObject(m_semaphoreReaders,INFINITE);
m_criSec.Lock();
T data = *(m_pila.begin());
m_pila.pop_front();
m_criSec.Unlock();
ReleaseSemaphore(m_semaphoreWriters,1,0);
return data;
}
template<class T>
void ProtectedFIFO<T>::Push(T data)
{
WaitForSingleObject(m_semaphoreWriters,INFINITE);
m_criSec.Lock();
m_pila.push_back(data);
m_criSec.Unlock();
ReleaseSemaphore(m_semaphoreReaders,1,0);
}
template<class T>
size_t ProtectedFIFO<T>::Size()
{
m_criSec.Lock();
size_t tam = m_pila.size();
m_criSec.Unlock();
return tam;
}
} // namespace sync
} // namespace stream
#endif // !defined(AFX_PROTECTEDFIFO_H__52F473E7_EBAD_4612_AFF2_853A8F55CAA9__INCLUDED_)
| true |
3fe6dc7f06cbaa5788a4dd72b29750394f99af1a | C++ | en30/online-judge | /atcoder/past201912_k.cpp | UTF-8 | 584 | 2.71875 | 3 | [] | no_license | #include <bits/stdc++.h>
#include "../include/template"
#include "../include/lca.hpp"
int N, Q;
vector<int> p;
vector<vector<int>> G;
int main() {
cin >> N;
p.resize(N);
G.resize(N);
int root;
rep(i, N) {
cin >> p[i];
if (p[i] == -1) {
root = i;
continue;
}
--p[i];
G[i].push_back(p[i]);
G[p[i]].push_back(i);
}
LCA lca(G, root);
cin >> Q;
rep(i, Q) {
int a, b;
cin >> a >> b;
--a, --b;
if (lca.find(a, b) == b) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
return 0;
}
| true |
28499a844f8704694f3ae15fd4c4005e8e7babe8 | C++ | y-shindoh/coding_interview | /c_02/q_02.03.cpp | UTF-8 | 1,617 | 3.4375 | 3 | [] | no_license | /* -*- coding: utf-8; tab-width: 4 -*- */
/**
* @file q_02.03.cpp
* @brief 「世界で闘うプログラミング力を鍛える150問」の問題2.3の回答
* @author Yasutaka SHINDOH / 新堂 安孝
* @note see http://www.amazon.co.jp/dp/4839942390 .
*/
/*
問題:
単方向連結リストにおいて、中央の要素のみアクセス可能であるとします。
その要素を削除するアルゴリズムを実装してください。
*/
#include <cstddef>
#include <cassert>
#include "list.hpp"
/**
* 末尾以外のノードをリストから削除
* @param[in,out] node 削除対象のノード
* @note 実際に削除されるのは、引数 @a node の次のノード。
* @note 計算量は O(1)。
* @note この方法では末尾ノードを処理できない。
この方法のまま末尾ノードを処理したい場合は、
番兵ノードを利用する形にするなどの対処が必要となる。
*/
template<typename TYPE>
void
DeleteNotTailNode(Node<TYPE>* node)
{
assert(node);
assert(node->get_next());
Node<TYPE>* next = node->get_next();
node->set_next(next->get_next());
node->set_data(next->get_data());
delete next;
}
/**
* 動作確認用コマンド
*/
int main()
{
int data[] = {1, 3, 5, 7, 9, 5, 0, 2, 4, 4, 6, 8, 1};
Node<int>* list = Node<int>::MakeLinkedList(data, sizeof(data)/sizeof(data[0]));
Node<int>::PrintLinkedList(list);
Node<int>* node(list);
for (size_t i(0); i < 5; ++i) {
node = node->get_next();
}
DeleteNotTailNode<int>(node);
Node<int>::PrintLinkedList(list);
Node<int>::DeleteLinkedList(list);
return 0;
}
| true |
595fd564436d5d1df0683e0478915d6d0c3cb0dd | C++ | Hearen/AlgorithmHackers | /SheYi/2015-12-11-week2/Longest-Substring-Without-Repeating-Characters.cpp | UTF-8 | 1,055 | 3.390625 | 3 | [] | no_license | #include<iostream>
#include<set>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.length()==0) return 0;
int head=0; //count start point
int maxLength=1; //the current max lenght of substring
int count=1; //cout for a certain substring
set<char> charSet; //set store identical elements
charSet.insert(s[0]) ;
for(int i=1;i<s.length();){
if(charSet.count(s[i])==0){ //if not contains
charSet.insert(s[i]); //add to set
count++;
if(count>maxLength) maxLength=count; //update maxLength
i++;
}else{ //if contains
if(count>maxLength) maxLength=count;
charSet.erase(s[head]); //erase the head element
head++; //move start point
count=count-1;
if(count<1) {charSet.insert(s[i]);count=1;i++;} //for two same elements are neighbour
}
}
return maxLength;
}
};
int main(){
Solution s;
string str="abcbbcdeafcf";
int result=s.lengthOfLongestSubstring(s);
cout<<"result:"<<result<<endl;
}
| true |
f698c788ada9831a85116899593e1008f5941466 | C++ | carrardt/Fleye | /plugins/PanTiltFollowerAdHoc.cc | UTF-8 | 3,671 | 2.5625 | 3 | [] | no_license | #include "fleye/plugin.h"
#include "fleye/FleyeContext.h"
#include "fleye/vec2f.h"
#include "services/PanTiltService.h"
#include "services/TrackingService.h"
#include "services/TextService.h"
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <assert.h>
#define _USE_MATH_DEFINES
#include <cmath>
// TODO: need a service to configure head tracking :
// target position, object to track, etc.
struct PanTiltFollowerAdHoc : public FleyePlugin
{
inline PanTiltFollowerAdHoc()
: m_ptsvc(0)
, m_txt(0)
, m_obj1(0)
, m_obj2(0)
, m_panMin(0.1)
, m_panMax(0.9)
, m_tiltMin(0.1)
, m_tiltMax(0.9)
, m_targetOffsetX(0.0f)
, m_targetOffsetY(0.0f)
, m_start(true)
{
}
void setup(FleyeContext* ctx)
{
std::string targetOffsetXStr = ctx->vars["TARGET_OFFX"];
if( ! targetOffsetXStr.empty() ) { m_targetOffsetX = atoi(targetOffsetXStr.c_str()); }
std::string targetOffsetYStr = ctx->vars["TARGET_OFFY"];
if( ! targetOffsetYStr.empty() ) { m_targetOffsetY = atoi(targetOffsetYStr.c_str()); }
m_ptsvc = PanTiltService_instance();
m_ptsvc->setPan( 0.5f );
m_ptsvc->setTilt( 0.5f );
m_obj1 = TrackingService_instance()->getTrackedObject(0);
m_obj2 = TrackingService_instance()->getTrackedObject(1);
m_txt = TextService_instance()->addPositionnedText(0.1,0.2);
m_txt->out()<<"Initializing...";
// TODO: tracked object have drawing style and color attributes
auto cobj = TrackingService_instance()->getTrackedObject(99);
cobj->posX = 0.5;
cobj->posY = 0.5;
std::cout<<"PanTiltFollower ready : PanTiltService @"<<m_ptsvc<<", obj1 @"<<m_obj1<<", obj2 @"<<m_obj2<< "\n";
}
void run(FleyeContext* ctx,int threadId)
{
// what is the target position of the tracked point
const Vec2f target( 0.5f+m_targetOffsetX, 0.5f+m_targetOffsetY );
float W1 = m_obj1->weight;
float A1 = m_obj1->area;
float S1 = (W1>=1.0f) ? 1.0f/W1 : 0.0f;
float W2 = m_obj2->weight;
float A2 = m_obj2->area;
float S2 = (W2>=1.0f) ? 1.0f/W2 : 0.0f;
Vec2f P1( m_obj1->posX * S1 , m_obj1->posY * S1 );
Vec2f P2( m_obj2->posX * S2 , m_obj2->posY * S2 );
bool bigEnough = ( A2 > 32.0f );
// this will be the position to track
Vec2f P = P2; //P1; //(P1+P2)*0.5f;
Vec2f dP = target - P;
// wait to have an object in the center before starting
if( dP.norm() < 0.1 )
{
//if( ! m_start ) { m_txt->out()<<"Target locked :-)"; }
//std::cout<<"target locked\n";
m_start=true;
}
if( ! m_start ) return;
if( ! bigEnough )
{
m_txt->out()<<"Target lost :(";
return;
}
if( dP.norm2() < 0.0004 )
{
//std::cout<<"target centered\n";
m_ptsvc->setLaser( ! m_ptsvc->laser() );
return;
}
m_ptsvc->setLaser( false );
float cx = m_ptsvc->pan();
float cy = m_ptsvc->tilt();
//std::cout<<"cx="<<cx<<", dP.x"<<dP.x*0.04f;
cx += dP.x * 0.04f;
cx = std::max( std::min( cx , m_panMax ) , m_panMin );
//std::cout<<", final cx="<<cx<<"\n";
float tiltAmpMax = 0.5f - std::abs( 0.5f - ( cx - m_panMin ) / ( m_panMax - m_panMin ) );
float tiltMax = (m_tiltMin+m_tiltMax)*0.5f + (m_tiltMax-m_tiltMin)*tiltAmpMax;
float tiltMin = (m_tiltMin+m_tiltMax)*0.5f - (m_tiltMax-m_tiltMin)*tiltAmpMax;
cy += dP.y * 0.04f;
cy = std::max( std::min( cy , tiltMax ) , tiltMin );
m_txt->out()<<"A1="<<A1<<"\nA2="<<A2<<"\ncx="<<cx<<"\ncy="<<cy;
m_ptsvc->setPan( cx );
m_ptsvc->setTilt( cy );
}
PanTiltService* m_ptsvc;
PositionnedText* m_txt;
TrackedObject* m_obj1;
TrackedObject* m_obj2;
float m_panMin,m_panMax,m_tiltMin,m_tiltMax, m_targetOffsetX, m_targetOffsetY;
bool m_start;
};
FLEYE_REGISTER_PLUGIN(PanTiltFollowerAdHoc);
| true |
55fc6ad102f7e779ba730908d633f05ef4c0af85 | C++ | ChaeLinYeo/BAEKJOON | /11441.cpp | UTF-8 | 814 | 3.015625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main (){
cin.tie(NULL);
int N; //첫째 줄에 수의 개수 N이 주어진다. (1 ≤ N ≤ 100,000)
int A[100000]; //둘째 줄에는 A1, A2, ..., AN이 주어진다. (-1,000 ≤ Ai ≤ 1,000)
int M; //셋째 줄에는 구간의 개수 M이 주어진다. (1 ≤ M ≤ 100,000)
int i, j; //넷째 줄부터 M개의 줄에는 각 구간을 나타내는 i와 j가 주어진다. (1 ≤ i ≤ j ≤ N)
int sum=0; //총 M개의 줄에 걸쳐 입력으로 주어진 구간의 합
cin >> N;
for(int i=0; i<N; i++) cin >> A[i];
cin >> M;
for(int i=0; i<M; i++) {
cin >> i >> j;
for(int k = i-1; k<j; k++){
sum = sum + A[k];
}
cout << sum << "\n";
sum = 0;
}
return 0;
} | true |
12a446ce654f72b9b4405545f2a07456fea75cd2 | C++ | LukeLookS/All-sortings-algorithm | /Sorting/Counting.h | UTF-8 | 1,133 | 3.0625 | 3 | [] | no_license | /////////////////////////////////////////////////////////////////////
// Counting.h //
// //
// Mengjie Shi, CSE674 //
// SUID: 457056896 //
/////////////////////////////////////////////////////////////////////
#pragma once
#include"ISort.h"
#include<vector>
class Counting :public ISort {
public:
void sort(std::vector<int>& data)
{
int i;
int s = data.size();
int largest = data[0];
std::vector<int> temp(data.size());
for (i = 1; i < s; i++)
if (largest < data[i])
largest = data[i];//Find the largest the value
std::vector<int> count(largest + 1);
for (i = 0; i <= largest; i++)
count[i] = 0;
for (i = 0; i < s; i++)
count[data[i]]++;//Count the frequence of value
for (i = 1; i <= largest; i++)
count[i] = count[i - 1] + count[i];
for (i = s - 1; i >= 0; i--)
{
temp[count[data[i]] - 1] = data[i];
count[data[i]]--;
}
data = temp;
}
}; | true |
9d54f9ae6d6756fbc6dc74b8a7f7425d3af623ce | C++ | WheretIB/nullc | /NULLC/includes/error.cpp | UTF-8 | 1,657 | 2.6875 | 3 | [
"MIT"
] | permissive | #include "error.h"
#include "../../NULLC/nullc.h"
#include "../../NULLC/nullbind.h"
#include "../../NULLC/nullc_debug.h"
namespace NULLCError
{
void throw_0(NULLCArray message)
{
nullcThrowError("%.*s", message.len, message.ptr);
}
void throw_1(NULLCRef exception)
{
nullcThrowErrorObject(exception);
}
bool try_0(NULLCRef function, NULLCArray* message, NULLCRef* exception, NULLCRef* result)
{
if(!function.ptr)
{
nullcThrowError("ERROR: null pointer access");
return false;
}
ExternTypeInfo *exTypes = nullcDebugTypeInfo(NULL);
if(exTypes[function.typeID].subCat != ExternTypeInfo::CAT_FUNCTION)
{
nullcThrowError("ERROR: argument is not a function");
return false;
}
if(exTypes[function.typeID].memberCount > 1)
{
nullcThrowError("ERROR: can't call function with arguments");
return false;
}
NULLCFuncPtr functionValue = *(NULLCFuncPtr*)function.ptr;
if(!nullcCallFunction(functionValue))
{
if(message)
{
const char *rawMessage = nullcGetLastError();
unsigned rawLength = unsigned(strlen(rawMessage));
*message = nullcAllocateArrayTyped(NULLC_TYPE_CHAR, rawLength + 1);
strcpy(message->ptr, rawMessage);
}
*exception = nullcGetLastErrorObject();
nullcClearError();
return false;
}
if(result)
*result = nullcGetResultObject();
return true;
}
}
#define REGISTER_FUNC(funcPtr, name, index) if(!nullcBindModuleFunctionHelper("std.error", NULLCError::funcPtr, name, index)) return false;
bool nullcInitErrorModule()
{
REGISTER_FUNC(throw_0, "throw", 0);
REGISTER_FUNC(throw_1, "throw", 1);
REGISTER_FUNC(try_0, "try", 0);
return true;
}
| true |
f41be52407f918af653f3066ed0e4a9f5a37537f | C++ | vodelerk/locha-mesh-app | /Turpial/general_utils.cpp | UTF-8 | 9,225 | 3.296875 | 3 | [
"MIT"
] | permissive | /**
* @file general_utils.cpp
* @author locha.io project developers (dev@locha.io)
* @brief
* @version 0.1
* @date 2019-04-24
*
* @copyright Copyright (c) 2019 locha.io project developers
* @license MIT license, see LICENSE file for details
*
*/
#include <Arduino.h>
#include "general_utils.h"
// compare char
bool compare_char(char *src, char *dst)
{
if (strcmp(src, dst) == 0)
{
return true;
}
else
{
return false;
}
}
void eraseAllSubStr(std::string &mainStr, const std::string &toErase)
{
size_t pos = std::string::npos;
// Search for the substring in string in a loop untill nothing is found
while ((pos = mainStr.find(toErase)) != std::string::npos)
{
// If found then erase it from string
mainStr.erase(pos, toErase.length());
}
}
// funcion para convertir un std::string en un char*
char *std_string_to_char(std::string cadena)
{
char *cstr = new char[cadena.length() + 1];
strcpy(cstr, cadena.c_str());
return cstr;
}
// Funcion de conversion de tipo de datos: Char* a long long
// usada para convertir timestamps que vienen en cadenas de caracteres a un numero tipo long long
long long char2LL(char *str)
{
long long result = 0; // Initialize result
// Iterate through all characters of input string and update result
for (int i = 0; str[i] != '\0'; ++i)
result = result * 10 + str[i] - '0';
return result;
}
/**
* @brief Funcion de conversion de tipo de datos: std::string a uint8_t
*
* @param texto
* @return uint8_t
*/
uint8_t convert_str_to_uint8(std::string texto)
{
unsigned long long y = 0;
for (int i = 0; i < texto.length(); i++)
{
char c = texto[i];
if (c < '0' || c > '9')
break;
y *= 10;
y += (c - '0');
}
return y;
}
// Funcion de conversion de tipo de datos: std::string a char*
char *string2char(std::string command)
{
if (command.length() != 0)
{
char *p = const_cast<char *>(command.c_str());
return p;
}
}
// Copia arreglos de char (src->dst) dado un largo determinado len
void copy_array(char *src, char *dst, int len)
{
for (int i = 0; i < len; i++)
{
*dst++ = *src++;
}
}
// obtiene la macaddress del ESP32 una vez conectado a Wifi
std::string getMacAddress()
{
uint8_t baseMac[6];
// Get MAC address for WiFi station
esp_read_mac(baseMac, ESP_MAC_WIFI_STA);
char baseMacChr[18] = {0};
sprintf(baseMacChr, "%02X:%02X:%02X:%02X:%02X:%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
return (baseMacChr);
}
// funcion para convertir un valor en un tipo std::string
template <typename T>
std::string ToString(T val)
{
std::stringstream stream;
stream << val;
return stream.str();
}
// funcion para convertir un numero en un std::string
std::string number_to_str(unsigned long long i)
{
std::string str = ToString(i);
return str;
}
// convierte un string en un numero tipo long
unsigned long convert_str_to_long(char *time_in_char)
{
unsigned long uil;
uil = strtoul(time_in_char, NULL, 10);
return uil;
}
// https://stackoverflow.com/questions/9072320/split-string-into-string-array
std::string getValue(std::string data, char separator, int index)
{
uint8_t found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++)
{
if (data[i] == separator || i == maxIndex)
{
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i + 1 : i;
}
}
return found > index ? data.substr(strIndex[0], strIndex[1]) : "";
}
/*
* Erase First Occurrence of given substring from main string.
*/
void eraseSubStr(std::string & mainStr, const std::string & toErase)
{
// Search for the substring in string
size_t pos = mainStr.find(toErase);
if (pos != std::string::npos)
{
// If found then erase it from string
mainStr.erase(pos, toErase.length());
}
}
/**
* @brief verify if a nstd::string is a number
*
* @param str
* @return true
* @return false
*/
bool isNumeric(std::string str)
{
unsigned int stringLength = str.length();
if (stringLength == 0)
{
return false;
}
bool seenDecimal = false;
for (unsigned int i = 0; i < stringLength; ++i)
{
if (isDigit(str[i]))
{
continue;
}
if (str[i] == '.')
{
if (seenDecimal)
{
return false;
}
seenDecimal = true;
continue;
}
return false;
}
return true;
}
// use cJson integrated into espressif esp32 sdk
/* The cJSON structure: */
//typedef struct cJSON {
// struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
// struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
//int type; /* The type of the item, as above. */
//char *valuestring; /* The item's string, if type==cJSON_String */
//int valueint; /* The item's number, if type==cJSON_Number */
//double valuedouble; /* The item's number, if type==cJSON_Number */
//char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
//} cJSON;
void json_receive(std::string message, char *&uid_intern, char *&msg_intern, char *&timemsg_intern_str, char *&hash_msg_intern)
{
// this function receives data message in format: "{'uid':'xxxxx','msg':'yyyy','time':#############}"
double time_in_number = 0;
int tipo_dato_time_int;
int tipo_dato_time_dbl;
int tipo_dato_time_type;
char *nombre_del_dato;
const char *TAG = "JSON_RECEIVE";
std::replace(message.begin(), message.end(), '\'', '\"');
// message.replace("'","\"");
// message=message.c_str();
char *mensaje3;
//message.toCharArray(mensaje3,message.length()+1);
mensaje3 = string2char(message);
ESP_LOGD(TAG, "%s mensaje completo Json recibido:", mensaje3);
cJSON *el_arreglo = cJSON_Parse(mensaje3);
uid_intern = cJSON_GetObjectItem(el_arreglo, "uid")->valuestring;
msg_intern = cJSON_GetObjectItem(el_arreglo, "msg")->valuestring;
timemsg_intern_str = cJSON_GetObjectItem(el_arreglo, "time")->valuestring;
hash_msg_intern = cJSON_GetObjectItem(el_arreglo, "hash")->valuestring;
// TODO: verificar si se recibe en lugar de msg un ERR
// deletes cJSON from memory, ESTA OPCION ESTA PENDIENTE DE PRUEBA
// cJSON_Delete(el_arreglo);
}
// procedimiento inverso a Json_receive para devolver valores al BLE (toma un packet y lo transforma en un json)
std::string packet_into_json(packet_t packet_to_convert, std::string BLE_type)
{
// this function convert [acket data in format: "{'uid':'xxxxx','BLE_type':'yyyy','time':#############,'hash':'XXXXXXXXXX'}"
char *rpta;
char *tipo_packet = convertir_packet_type_e_str(packet_to_convert.header.packet_type);
char *subtipo_packet = convertir_packet_type_e_str(packet_to_convert.header.packet_type);
if (packet_to_convert.header.packet_type != EMPTY)
{
strcpy(rpta, "{'uid':'");
strcat(rpta, packet_to_convert.header.from);
strcat(rpta, "','");
strcat(rpta, string2char(BLE_type));
strcat(rpta, "':'");
if (packet_to_convert.header.packet_type == DATA)
{
strcat(rpta, packet_to_convert.body.body_data_splitted.payload);
}
else
{
strcat(rpta, packet_to_convert.body.body_data.payload);
}
strcat(rpta, "','type':");
strcat(rpta, string2char(tipo_packet));
strcat(rpta, "','subtype':");
strcat(rpta, string2char(tipo_packet));
strcat(rpta, "','time':");
strcat(rpta, string2char(number_to_str(packet_to_convert.header.timestamp)));
strcat(rpta, "','hash':");
strcat(rpta, packet_to_convert.header.checksum_data);
strcat(rpta, "'}");
}
return ToString(rpta);
}
/**
* @brief Get devuelve la mac address del ESP32
*
* @return std::string
*/
std::string get_id_mac()
{
std::string result = getMacAddress();
result.erase(std::remove(result.begin(), result.end(), ':'), result.end());
return result;
}
// funcion usada para imprimir valores hexadecimales (tipo hash160)
void printHex(byte *data, int len)
{
const char *TAG = "printHex";
ESP_LOGD(TAG, "%04X", data);
}
// se genera un unique id basado en la mac address original de fabrica del equipo
void create_unique_id(char *&unique_id_created)
{
// se adiciona el random porque puede que un mcu no tenga RTC integrado y de esa forma se evitan duplicados
//TODO: armar el unique id como un compuesto donde el user pueda colocar una parte del uniqueid y el resto sea el chipid (completo o una parte) y algun caracter de validacion
char uniqueid3[SIZE_IDNODE];
uint32_t uChipId;
uChipId = ESP.getEfuseMac(); //The chip ID is essentially its MAC address(length: 6 bytes).
snprintf(uniqueid3, 25, "%08X", uChipId);
copy_array(uniqueid3, unique_id_created, SIZE_IDNODE);
}
// verifica si existe un archivo en el FS
bool Fileexists(const char *path)
{
File f = SPIFFS.open(path, "r");
return (f == true) && !f.isDirectory();
}
// verifica la cantidad de memoria disponible libre
std::string freeRam()
{
return number_to_str(ESP.getFreeHeap());
}
| true |
d19d14ec06a088bca2bf162477f8def038ef5a0d | C++ | ldiez/GWNSyM | /modules/utilities/Distance.cpp | UTF-8 | 449 | 2.640625 | 3 | [] | no_license | #include "Distance.h"
Distance::Distance(units::m d) : m_km(units::To<units::km>::Do(d))
{
}
Distance::Distance(units::km d) : m_km(d)
{
}
double
Distance::GetM(void) const
{
return units::To<units::m>::Do(m_km).RawVal();
}
double
Distance::GetKm(void) const
{
return m_km.RawVal();
}
units::m
Distance::GetUnitsM(void) const
{
return units::To<units::m>::Do(m_km);
}
units::km
Distance::GetUnitsKm(void) const
{
return m_km;
} | true |
215f0a5499ca2bed5e2becff90f2a5c373e0ef62 | C++ | Ckins/c-sicily | /07cs_2015-12-18/6.cpp | UTF-8 | 1,982 | 2.734375 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
int n, m, ans;
int g[7][7];
int MAX(int a, int b)
{
if(a > b)
return a;
return b;
}
void dfs(int x, int y, int cnt)
{
if(x >= n)//表示已经搜索完毕
{
ans = MAX(ans,cnt);
return;
}
if(y >= m)//列出界,表示当前行已经搜索完毕
{
dfs(x+1,0,cnt);//重新从下一行的0开始
return;
}
if(g[x][y] == 1)//若当前位置已经有棋子
{
dfs(x,y+1,cnt);//则从下一个重新开始搜索
return;
}
dfs(x,y+1,cnt);
int t, flag = 0;
for(t = x-1; t >= 0; t--)//下面的两个for是查找同一列是否存在
{ //前面已经有炮和炮架
if(g[t][y])
{
break;
}
}
for(int i = t-1; i >= 0; i--)
{
if(g[i][y])
{
if(g[i][y] == 2)
{
flag = 1;
}
break;
}
}
if(flag)
{
return;//如果存在上面说得情况,就返回上一层
}
for(t = y-1; t >= 0; t--)//下面的两个for是查找同一行是否存在
{ //前面已经有炮和炮架
if(g[x][t])
break;
}
for(int j = t-1; j >= 0 ; j--)
{
if(g[x][j])
{
if(g[x][j] == 2)
{
flag = 1;
}
break;
}
}
if(flag)
{
return;//如果存在上面说得情况,就返回上一层
}
g[x][y] = 2;//表示此处暂放一个炮
dfs(x,y+1,cnt+1);
g[x][y] = 0;//回溯
}
int main()
{
int Q, u, v, i;
while(~scanf("%d%d%d",&n,&m,&Q))
{
memset(g,0,sizeof(g));
for(i = 0; i < Q; i++)
{
scanf("%d%d",&u,&v);
g[u][v] = 1; //表示开始此处已经有棋子
}
ans = 0;
dfs(0, 0, 0);
printf("%d\n",ans);
}
return 0;
}
| true |
7db144807a28d4c7abc47b87958a85ca005ef066 | C++ | RoiTanGene/mrustc | /tools/backend_c/codegen.cpp | UTF-8 | 8,274 | 2.6875 | 3 | [
"MIT"
] | permissive | /*
*/
#include "codegen.hpp"
Codegen_C::Codegen_C(const char* outfile):
m_of(outfile)
{
}
Codegen_C::~Codegen_C()
{
}
void Codegen_C::emit_type_proto(const HIR::TypeRef& ty)
{
TRACE_FUNCTION_R(ty, ty);
}
void Codegen_C::emit_static_proto(const RcString& name, const Static& s)
{
TRACE_FUNCTION_R(name, name);
}
void Codegen_C::emit_function_proto(const RcString& name, const Function& s)
{
TRACE_FUNCTION_R(name, name);
this->emit_ctype(s.ret_ty);
m_of << " " << name;
m_of << "(";
for(const auto& ty : s.args)
{
if(&ty != &s.args.front())
m_of << ", ";
this->emit_ctype(ty);
}
m_of << ");\n";
}
void Codegen_C::emit_composite(const RcString& name, const DataType& s)
{
TRACE_FUNCTION_R(name, name);
}
void Codegen_C::emit_static(const RcString& name, const Static& s)
{
TRACE_FUNCTION_R(name, name);
}
void Codegen_C::emit_function(const RcString& name, const Function& s)
{
TRACE_FUNCTION_R(name, name);
this->emit_ctype(s.ret_ty);
m_of << " " << name;
m_of << "(";
for(const auto& ty : s.args)
{
size_t idx = &ty - &s.args.front();
if(&ty != &s.args.front())
m_of << ", ";
this->emit_ctype(ty);
m_of << " a" << idx;
}
m_of << ")\n";
m_of << "{\n";
for(const auto& b : s.m_mir.blocks)
{
m_of << "bb" << (&b - &s.m_mir.blocks.front()) << ":\n";
for(const auto& stmt : b.statements)
{
}
}
m_of << "}\n";
}
struct FmtMangledTy {
const HIR::TypeRef& t;
unsigned depth;
FmtMangledTy(const HIR::TypeRef& t, unsigned depth):
t(t), depth(depth)
{
}
void fmt(std::ostream& os) const
{
if(t.wrappers.size() == depth)
{
switch(t.inner_type)
{
case RawType::Unreachable:
os << 'C' << 'z';
break;
case RawType::Unit:
os << "T0";
break;
case RawType::U8 : os << 'C' << 'a'; break;
case RawType::I8 : os << 'C' << 'b'; break;
case RawType::U16 : os << 'C' << 'c'; break;
case RawType::I16 : os << 'C' << 'd'; break;
case RawType::U32 : os << 'C' << 'e'; break;
case RawType::I32 : os << 'C' << 'f'; break;
case RawType::U64 : os << 'C' << 'g'; break;
case RawType::I64 : os << 'C' << 'h'; break;
case RawType::U128: os << 'C' << 'i'; break;
case RawType::I128: os << 'C' << 'j'; break;
case RawType::F32 : os << 'C' << 'n'; break;
case RawType::F64 : os << 'C' << 'o'; break;
case RawType::USize: os << 'C' << 'u'; break;
case RawType::ISize: os << 'C' << 'v'; break;
case RawType::Bool: os << 'C' << 'w'; break;
case RawType::Char: os << 'C' << 'x'; break;
case RawType::Str : os << 'C' << 'y'; break;
case RawType::Composite:
os << t.ptr.composite_type->my_path;
break;
case RawType::TraitObject:
LOG_TODO(t);
break;
case RawType::Function: {
const auto& e = *t.ptr.function_type;;
// - Function: 'F' <abi:RcString> <nargs> [args: <TypeRef> ...] <ret:TypeRef>
os << "F";
//os << (e.is_unsafe ? "u" : ""); // Optional allowed, next is a number
if( e.abi != "Rust" )
{
os << "e";
os << e.abi.size();
os << e.abi;
}
os << e.args.size();
for(const auto& t : e.args)
os << FmtMangledTy(t, 0);
os << FmtMangledTy(e.ret, 0);
} break;
}
}
else
{
const auto& w = t.wrappers.at(depth);
switch(w.type)
{
case TypeWrapper::Ty::Array:
os << "A" << w.size;
os << FmtMangledTy(t, depth+1);
break;
case TypeWrapper::Ty::Slice:
os << "S";
break;
case TypeWrapper::Ty::Pointer:
os << "P"; if(0)
case TypeWrapper::Ty::Borrow:
os << "B";
switch(static_cast<::HIR::BorrowType>(w.size))
{
case ::HIR::BorrowType::Shared: os << "s"; break;
case ::HIR::BorrowType::Unique: os << "u"; break;
case ::HIR::BorrowType::Move: os << "o"; break;
}
break;
}
os << FmtMangledTy(t, depth+1);
}
}
friend std::ostream& operator<<(std::ostream& os, const FmtMangledTy& x)
{
x.fmt(os);
return os;
}
};
void Codegen_C::emit_ctype(const HIR::TypeRef& t, unsigned depth/*=0*/)
{
if(t.wrappers.size() == depth)
{
switch(t.inner_type)
{
case RawType::Unreachable:
m_of << "tBANG";
break;
case RawType::Bool:
m_of << "bool";
break;
case RawType::Unit:
m_of << "ZRT" << "T0";
break;
case RawType::U8: m_of << "uint8_t"; break;
case RawType::U16: m_of << "uint16_t"; break;
case RawType::U32: m_of << "uint32_t"; break;
case RawType::U64: m_of << "uint64_t"; break;
case RawType::I8: m_of << "int8_t"; break;
case RawType::I16: m_of << "int16_t"; break;
case RawType::I32: m_of << "int32_t"; break;
case RawType::I64: m_of << "int64_t"; break;
case RawType::U128: m_of << "uint128_t"; break;
case RawType::I128: m_of << "int128_t"; break;
case RawType::USize: m_of << "uintptr_t"; break;
case RawType::ISize: m_of << "intptr_t"; break;
case RawType::F32: m_of << "float"; break;
case RawType::F64: m_of << "double"; break;
case RawType::Char:
m_of << "uint32_t";
break;
case RawType::Str:
LOG_ERROR("Hit a str - " << t);
break;
case RawType::Composite:
m_of << t.ptr.composite_type->my_path;
break;
case RawType::TraitObject:
LOG_TODO(t);
break;
case RawType::Function:
// Should be pre-defined, just emit the type name for it
m_of << "ZRT" << FmtMangledTy(t, depth);
break;
}
}
else
{
const auto& w = t.wrappers.at(depth);
switch(w.type)
{
case TypeWrapper::Ty::Array:
// Arrays should be pre-defined, just emit the type name for it
m_of << "ZRT" << FmtMangledTy(t, depth);
break;
case TypeWrapper::Ty::Slice:
// Invalid, must be behind a pointer
LOG_ERROR("Hit a slice - " << t);
break;
case TypeWrapper::Ty::Pointer:
case TypeWrapper::Ty::Borrow:
// Check for unsized inner, otherwise recurse with a trailing *
if( depth+1 == t.wrappers.size() && t.inner_type == RawType::Str )
{
m_of << "SLICE_PTR";
}
else if( depth+1 < t.wrappers.size() && t.wrappers[depth+1].type == TypeWrapper::Ty::Slice )
{
m_of << "SLICE_PTR";
}
else if( depth+1 == t.wrappers.size() && t.inner_type == RawType::TraitObject )
{
m_of << "TRAITOBJ_PTR";
}
else if( depth+1 == t.wrappers.size() && t.inner_type == RawType::Composite && t.ptr.composite_type->dst_meta != HIR::TypeRef() )
{
if( t.ptr.composite_type->dst_meta == RawType::USize )
{
m_of << "SLICE_PTR";
}
else
{
m_of << "TRAITOBJ_PTR";
}
}
else
{
this->emit_ctype(t, depth+1);
m_of << "*";
}
break;
}
}
} | true |
67a955c78d626021a57cb7a7a38756dcc5676ec2 | C++ | ShareTheWorld/algorithms | /LeetCode/letter_combinations_phone_number.cpp | UTF-8 | 1,860 | 3.5 | 4 | [] | no_license | /*
* author: luo feng
* date: 2013/11/20
* source: LeetCode OJ
* title: Letter Combinations of a Phone Number
* language: C++
*/
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iterator>
using namespace std;
class Solution {
public:
vector<string> letterCombinations(string digits)
{
map<char, string> phone;
phone.insert(make_pair('2', "abc"));
phone.insert(make_pair('3', "def"));
phone.insert(make_pair('4', "ghi"));
phone.insert(make_pair('5', "jkl"));
phone.insert(make_pair('6', "mno"));
phone.insert(make_pair('7', "pqrs"));
phone.insert(make_pair('8', "tuv"));
phone.insert(make_pair('9', "wxyz"));
phone.insert(make_pair('0', " "));
if(digits.size() == 0)
return vector<string>(1, "");
char ch = *(digits.end() - 1);
digits.erase(digits.end() - 1);
vector<string> svec = letterCombinations(digits);
vector<string>::size_type svec_size = svec.size();
vector<string>::size_type i = 0;
for(i = 0; i != svec_size; ++i) {
string str = svec[i];
string tmp = svec[i];
for(string::iterator siter = phone[ch].begin();
siter != phone[ch].end(); ++siter) {
tmp = str;
svec.push_back(tmp + *siter);
}
}
for(i = 0; i != svec_size; ++i) {
svec.erase(svec.begin());
}
return svec;
}
};
int main(int argc, char *argv[])
{
Solution sol;
string str("23");
vector<string> vec = sol.letterCombinations(str);
for(vector<string>::iterator iter = vec.begin();
iter != vec.end(); ++iter) {
cout << *iter << endl;
}
cout << endl;
return 0;
}
| true |
82d67504fda1fa8a8ba2b18d114926c2764111ea | C++ | gdmsl/bwsl | /templates/template.test.cpp | UTF-8 | 2,467 | 3.09375 | 3 | [] | no_license | //===-- FooTest.cpp --------------------------------------------*- C++ -*-===//
//
// BeagleWarlord's Support Library
//
// Copyright 2016-2022 Guido Masella. All Rights Reserved.
// See LICENSE file for details
//
//===---------------------------------------------------------------------===//
///
/// @file
/// @author Guido Masella (guido.masella@gmail.com)
/// @brief Tests for the Foo Class
///
//===---------------------------------------------------------------------===//
// bwsl
#include <bwsl/Foo.hpp>
// std
#include <vector>
// catch
#include <catch2/catch_approx.hpp>
#include <catch2/catch_test_macros.hpp>
using namespace bwsl;
// TDD example
TEST_CASE("vectors can be sized and resized", "[vector]")
{
std::vector<int> v(5);
REQUIRE(v.size() == 5);
REQUIRE(v.capacity() >= 5);
SECTION("resizing bigger changes size and capacity")
{
v.resize(10);
REQUIRE(v.size() == 10);
REQUIRE(v.capacity() >= 10);
}
SECTION("resizing smaller changes size but not capacity")
{
v.resize(0);
REQUIRE(v.size() == 0);
REQUIRE(v.capacity() >= 5);
}
SECTION("reserving bigger changes capacity but not size")
{
v.reserve(10);
REQUIRE(v.size() == 5);
REQUIRE(v.capacity() >= 10);
}
SECTION("reserving smaller does not change size or capacity")
{
v.reserve(0);
REQUIRE(v.size() == 5);
REQUIRE(v.capacity() >= 5);
}
}
// BDD Example
SCENARIO("vectors can be sized and resized", "[vector]")
{
GIVEN("A vector with some items")
{
std::vector<int> v(5);
REQUIRE(v.size() == 5);
REQUIRE(v.capacity() >= 5);
WHEN("the size is increased")
{
v.resize(10);
THEN("the size and capacity change")
{
REQUIRE(v.size() == 10);
REQUIRE(v.capacity() >= 10);
}
}
WHEN("the size is reduced")
{
v.resize(0);
THEN("the size changes but not capacity")
{
REQUIRE(v.size() == 0);
REQUIRE(v.capacity() >= 5);
}
}
WHEN("more capacity is reserved")
{
v.reserve(10);
THEN("the capacity changes but not the size")
{
REQUIRE(v.size() == 5);
REQUIRE(v.capacity() >= 10);
}
}
WHEN("less capacity is reserved")
{
v.reserve(0);
THEN("neither size nor capacity are changed")
{
REQUIRE(v.size() == 5);
REQUIRE(v.capacity() >= 5);
}
}
}
}
// vim: set ft=cpp ts=2 sts=2 et sw=2 tw=80: //
| true |
0323f01d2dbe3e04def78944d0bd278eff5ba313 | C++ | ewodac/PortaDrop | /include/StatusLed.h | UTF-8 | 2,318 | 3.078125 | 3 | [] | no_license | #pragma once
/**
* @file StatusLed.h
*
* @class StatusLed
* @author Nils Bosbach
* @date 04.08.2019
* @brief used to control the status LED, which are connected to a shift register via the atmega32
*/
#include "Uc_Connection.h"
#include <memory>
#include <chrono>
#include <bitset>
class StatusLed{
public:
/// smart pointer to a StatusLed object
typedef std::shared_ptr<StatusLed> StatusLed_ptr;
/**
* @brief constructor - opens the i2c connenction to the atmega32
*/
StatusLed();
/**
* @brief create a StatusLed object
* @return smart pointer to the created object
*/
static StatusLed_ptr create();
/**
* @brief virtual destructor
*/
virtual ~StatusLed();
/**
* @brief sets the running LED in the internal variable. The value can be transfered to the atmega32 by calling the write_reg_val function
* @param bool status of the LED
*/
void running(bool on);
/**
* @brief sets the impedance meausurement running LED in the internal variable. The value can be transfered to the atmega32 by calling the write_reg_val function
* @param bool status of the LED
*/
void impMeasRunning(bool on);
/**
* @brief sets the recipe running LED in the internal variable. The value can be transfered to the atmega32 by calling the write_reg_val function
* @param bool status of the LED
*/
void recipeRunning(bool on);
/**
* @brief sets all LEDs in the internal variable. The value can be transfered to the atmega32 by calling the write_reg_val function
* @param bool status of all LEDs
*/
void all(bool on);
/**
* @brief sets the Pad LED in the internal variable. The value can be transfered to the atmega32 by calling the write_reg_val function
* @param bool status of the Pad LED
*/
void pad(bool on);
/**
* @brief reads the current status of the LEDs from the atmega32 and stores it in the internal variable
*/
void read_reg_val();
/**
* @brief writes the value of the internal variable to the atmega32
*/
void write_reg_val();
private:
typedef std::chrono::system_clock::time_point TimePoint;
Uc_Connection::Uc_Connection_ptr uc_connection;
TimePoint lastWrite;
std::bitset<16> reg_val;
inline void setLED(bool on, int led_id);
inline TimePoint getCurrentTime() const;
inline void delay_to_last_write() const;
};
| true |
43be623f47bf6888b5fdb56b0d421ad5972736d8 | C++ | ferconde87/Programming-contests | /guide-to-competitive-programming/02 programming-techniques/bit-manipulation/representing-sets.cpp | UTF-8 | 3,807 | 3.71875 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define cn(x) cout << #x << " = " << x << endl;
#define xn(x) cout << #x << " = ";
//prints 10 less significative bits
void printBits(int num){
for(int i = 6; i >= 0; i--){
cout << ((num & (1 << i))!=0);
}
cout << endl;
}
int set_union(int x, int y){
return x | y;
}
int set_intersection(int x, int y){
return x & y;
}
int set_complement(int x){
return ~x;
}
int set_difference(int x, int y){
return x & (~y);
}
int main(){
//INTRO
// The following code declares an int variable x that can contain a subset of
// {0, 1, 2, . . . , 31}. After this, the code adds the elements 1, 3, 4, and 8 to the set
// and prints the size of the set
int x = 0;
x |= (1<<1);//this add 1 to the set x ... x = {1}
x |= (1<<3);// x = {1,3}
x |= (1<<4);// x = {1,3,4}
x |= (1<<8);// x = {1,3,4,8}
// __builtin_popcount(x) counts the 1's in x ... ie, the amount of element in the set x
cout << __builtin_popcount(x) << "\n"; // 4
// Then, the following code prints all elements that belong to the set:
for (int i = 0; i < 32; i++) {
if (x&(1<<i)) cout << i << " ";
}
cout << "\n";// output: 1 3 4 8
/////////////////////////////////////////////////////////////////////////
//SET OPERATIONS
// x = {1,3,4,8}
xn(x)printBits(x);
int y = (1<<3)|(1<<6)|(1<<8)|(1<<9);// y = {1,6,8,9}
xn(y)printBits(y);
int z = x|y;// z = y = {1,3,4,6,8,9}
xn(z)printBits(z);
cout << __builtin_popcount(z) << "\n"; // 6
int a = 0;
a |= (1<<1);
a |= (1<<2);
int b = 0;
b |= (1<<1);
b |= (1<<3);
xn(a)printBits(a);
xn(b)printBits(b);
int a_union_b = set_union(a,b);
xn(a_union_b)printBits(a_union_b);
int a_intersection_b = set_intersection(a,b);
xn(a_intersection_b)printBits(a_intersection_b);
int a_complement = set_complement(a);
xn(a_complement)printBits(a_complement);
int a_difference_b = set_difference(a,b);
xn(a_difference_b)printBits(a_difference_b);
cout << endl;
// The following code goes through the subsets of {0, 1, . . . , n − 1}:
int n = 4;
for (int b = 0; b < (1<<n); b++) {
// process subset b
printBits(b);
}
cout << endl;
// Then, the following code goes through the subsets with exactly k elements:
n = 6;
int k = 4;
for (int b = 0; b < (1<<n); b++) {
if (__builtin_popcount(b) == k) {
// process subset b
printBits(b);
}
}
cout << endl;
// (!)
//(!!!)
//Finally, the following code goes through the subsets of a set x:
x = 0;
x |= (1 << 2);
x |= (1 << 4);
xn(x)printBits(x);
b = 0;
do {
// process subset b
printBits(b);cout << b << endl;
cout << "next value:" << endl;
int b_minus_x = b-x;
xn(b)printBits(b);cout << b << endl;
xn(x)printBits(x);cout << x << endl;
xn(b_minus_x)printBits(b_minus_x);cout << b_minus_x << endl;
int b_minus_x_and_x = b_minus_x & x;
int b = b_minus_x_and_x;
} while (b=(b-x)&x);
cout << endl;
/////////////////////////////////////////////////////////////////////////
//C++ Bitsets
cout << "C++ Bitsets" << endl;
bitset<10> s;
s[1] = 1;
s[3] = 1;
s[4] = 1;
s[7] = 1;
cout << s[4] << "\n"; // 1
cout << s[5] << "\n"; // 0
cout << s.count() << "\n"; // 4
bitset<8> A = 12;
bitset<8> B = 10;
cout << A.to_string() << endl;
cout << B.to_string() << endl;
bitset<8> C = A&B;
bitset<8> D = A|B;
bitset<8> E = A^B;
cout << C.to_string() << endl;
cout << D.to_string() << endl;
cout << E.to_string() << endl;
return 0;
} | true |
8c854a5d6c9e361ceaf6e05cff4cd0936d499974 | C++ | yoongoing/Algorithm | /~2019/1247_c++.cpp | UTF-8 | 636 | 2.75 | 3 | [] | no_license | #include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
for(int i=0; i<3; i++){
long long int data[1000000] = {0};
int a;
scanf("%d",&a);
long long int sum = 0;
for(int j=0; j<a; j++){
scanf("%lld",&data[j]);
}
sort(data,data+a);
if(data[0] > 0){
printf("+\n");
continue;
}
else if(data[a-1] < 0){
printf("-\n");
continue;
}
else{
for(int j=0; j<a/2; j++){
sum += (data[j]+data[a-j-1]);
}
if(a%2 != 0){
sum += data[(a/2)];
}
if(sum > 0){
printf("+\n");
}
else if(sum == 0){
printf("0\n");
}
else{
printf("-\n");
}
}
}
} | true |
31cd4daf0bf10d457dcddbf6faa5f290a5a1a2f2 | C++ | comradesurendra/cpp-ds-algo | /tree/BFStrav.cpp | UTF-8 | 711 | 3.40625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
Node(int data){
this->data = data;
left=right=NULL;
}
};
//Levelorder
void Levelorder(Node *root){
if(root==NULL){
return;
}
queue<Node *> q;
q.push(root);
while (q.empty() == false){
Node *a = q.front();
q.pop();
cout<<a->data<<" ";
if(a->left!=NULL){
q.push(root->left);
}
if(a->right!=NULL){
q.push(root->right);
}
}
}
int main(){
Node *root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
Levelorder(root);
return 0;
} | true |
65dc73dfca54f0a0bb6cbf785c12acc36e5b25da | C++ | k-a-z-u/KLib | /math/filter/particles/estimation/ParticleFilterEstimationRegionalWeightedAverage.h | UTF-8 | 1,914 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | #ifndef K_MATH_FILTER_PARTICLES_PARTICLEFILTERESTIMATIONREGIONALWEIGHTEDAVERAGE_H
#define K_MATH_FILTER_PARTICLES_PARTICLEFILTERESTIMATIONREGIONALWEIGHTEDAVERAGE_H
#include "ParticleFilterEstimation.h"
#include "../Particle.h"
#include "../ParticleAssertions.h"
#include <algorithm>
namespace K {
/**
* this implementation estimates the current state
* by using the most probable particle and some near particles
* combining them by their weight (weighted average)
*
* the checker, whether a particle is near or not, uses a special,
* user-defined metric "belongsToRegion()". This user-method must
* return a boolean, whether to include the provided particle
* within the region around the maximum particle, or not.
*/
template <typename State>
class ParticleFilterEstimationRegionalWeightedAverage : public ParticleFilterEstimation<State> {
public:
State estimate(const std::vector<Particle<State>>& particles) override {
// compile-time sanity checks
static_assert( HasOperatorPlusEq<State>::value, "your state needs a += operator!" );
static_assert( HasOperatorDivEq<State>::value, "your state needs a /= operator!" );
static_assert( HasOperatorMul<State>::value, "your state needs a * operator!" );
//1) get the most probable particle
const auto comp = [] (const Particle<State>& p1, const Particle<State>& p2) {return p1.weight < p2.weight;};
const Particle<State>& max = *std::max_element(particles.begin(), particles.end(), comp);
//2) calculate the regional weighted average
double cumWeight = 0;
State res;
for (const Particle<State>& p : particles) {
if (!p.state.belongsToRegion(max.state)) {continue;}
cumWeight += p.weight;
res += p.state * p.weight;
}
// 3) normalize
res /= cumWeight;
// done
return res;
}
};
}
#endif // K_MATH_FILTER_PARTICLES_PARTICLEFILTERESTIMATIONREGIONALWEIGHTEDAVERAGE_H
| true |
909e476cd17c4543b9ace0342dac399feaf92d77 | C++ | paercebal/Kizuko | /paercebal/KizukoLib/clusters/AltitudeLine.cpp | UTF-8 | 5,346 | 2.828125 | 3 | [
"MIT"
] | permissive | #include <paercebal/KizukoLib/clusters/AltitudeLine.hpp>
#include <paercebal/KizukoLib/utilities.hpp>
#include <SFML/Graphics.hpp>
#include <memory>
#include <string>
#include <cmath>
namespace paercebal::KizukoLib::clusters
{
namespace {
const sf::Color PositiveAltitudeColor{ 0, 128, 0, 255 };
const sf::Color NegativeAltitudeColor{ 128, 0, 0, 255 };
sf::Color defineColor(sf::Vector3f starCenter)
{
if (starCenter.z >= 0)
{
return PositiveAltitudeColor;
}
return NegativeAltitudeColor;
}
bool calcultateAltitudePositivity(sf::Vector3f starCenter)
{
return (starCenter.z >= 0);
}
AltitudeLine::Positions createBaseShape(sf::Vector3f center_, float radius)
{
AltitudeLine::Positions positions;
const float count = 16.f;
positions.push_back({ center_.x, center_.y, 0 }); // the center of the shape
for (float i = 0.f; i < count; i += 1.f)
{
const float angle = 2 * Graphics::maths::utilities::pi<float> * i / count;
const float x = std::cos(angle) * radius;
const float y = std::sin(angle) * radius;
positions.push_back({ center_.x + x, center_.y + y, 0 });
}
return positions;
}
float findRatio(const AltitudeLine::Positions & positions, int baseShapePositionsOnlySize, float starSize)
{
auto findMaxDistance = [](const AltitudeLine::Positions & positions, int baseShapePositionsOnlySize)->float
{
auto findDistance = [](const sf::Vector3f & origin, const sf::Vector3f & position)->float
{
return static_cast<float>(std::pow(std::pow(origin.x - position.x, 2) + std::pow(origin.y - position.y, 2), .5));
};
float maxDistance = 0.f;
// Note: As we are looking at distances from a circle, we don't need to go all around 2 PI.
// Going up to 1/2 PI is enough, as long as the number of points is a multiple of 4.
for (size_t i = 0, iMax = (baseShapePositionsOnlySize - 1) / 4; i < iMax; ++i)
{
auto currentDistance = findDistance(positions[1], positions[2 + i]);
if (maxDistance < currentDistance)
{
maxDistance = currentDistance;
}
}
return maxDistance;
};
const auto maxDistance = findMaxDistance(positions, baseShapePositionsOnlySize);
return starSize / maxDistance;
};
void calculateBaseShapePositions(sf::ConvexShape & baseShape, const AltitudeLine::Positions & allRelativePositions, int allBaseShapePositionsSize, float starSize)
{
auto to2D = [](float ratio, sf::Vector3f origin, sf::Vector3f position)->sf::Vector2f
{
return { (position.x - origin.x) * ratio + origin.x, (position.y - origin.y) * ratio + origin.y };
};
const auto ratio = 1 * findRatio(allRelativePositions, allBaseShapePositionsSize, starSize);
baseShape.setPointCount(allBaseShapePositionsSize - 1);
for (size_t i = 0, iMax = allBaseShapePositionsSize - 1; i < iMax; ++i)
{
auto point = to2D(ratio, allRelativePositions[1], allRelativePositions[2 + i]);
baseShape.setPoint(i, point);
}
};
} // namespace
AltitudeLine::AltitudeLine(const GlobalResources & globalResources, sf::Vector3f starCenter)
: super(globalResources)
, color{ defineColor(starCenter) }
, isAltitudePositive{ calcultateAltitudePositivity(starCenter) }
{
AltitudeLine::Positions relativePositions;
relativePositions.push_back({ starCenter }); // the star itself
// Now, we append the points of the base shape
auto basePositions = createBaseShape(starCenter, 10.f);
this->baseShapePointCount = static_cast<int>(basePositions.size());
relativePositions.insert(relativePositions.end(), basePositions.begin(), basePositions.end());
this->setRelativePositions(relativePositions);
}
void AltitudeLine::createShapes2D()
{
AltitudeLine::Positions & positions = this->getAbsolutePositions();
if (positions.size() > 0)
{
this->line2D[0].color = this->color;
this->line2D[1].color = this->color;
this->line2D[0].position.x = positions[0].x;
this->line2D[0].position.y = positions[0].y;
this->line2D[1].position.x = positions[1].x;
this->line2D[1].position.y = positions[1].y;
this->baseShape.setFillColor(sf::Color::Transparent);
this->baseShape.setOutlineColor(this->color);
this->baseShape.setOutlineThickness(1.f);
calculateBaseShapePositions(this->baseShape, positions, this->baseShapePointCount - 1, 5.f);
}
}
void AltitudeLine::drawInto(sf::RenderTarget & renderTarget) const
{
if (isAltitudePositive)
{
renderTarget.draw(this->baseShape);
renderTarget.draw(this->line2D.data(), this->line2D.size(), sf::Lines);
}
else
{
renderTarget.draw(this->line2D.data(), this->line2D.size(), sf::Lines);
renderTarget.draw(this->baseShape);
}
}
std::unique_ptr<AltitudeLine> AltitudeLine::clone() const
{
return std::unique_ptr<AltitudeLine>(this->cloneImpl());
}
AltitudeLine * AltitudeLine::cloneImpl() const
{
return new AltitudeLine(*this);
}
sf::Vector3f AltitudeLine::getBegin3D() const noexcept
{
return this->getRelativePositions().at(0);
}
sf::Vector3f AltitudeLine::getEnd3D() const noexcept
{
return this->getRelativePositions().at(1);
}
sf::Color AltitudeLine::getColor() const noexcept
{
return this->color;
}
} // namespace paercebal::KizukoLib::clusters
| true |
fc40cc68227ce8f1ced8433aec0b4de61ffaeb72 | C++ | HenriqueIII/learning-cpp | /Capitulo 2/exercicios/ex2714.cpp | UTF-8 | 553 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main(){
float x1, x2;
int a, b, c;
cout << "Insira os coeficientes da equacao de 2 grau(a b c): " << endl;
cin >> a >> b >> c;
x1 = (-b+(sqrt((b*b)-4*a*c)))/(2*a);
x2 = (-b-(sqrt((b*b)-4*a*c)))/(2*a);
if (x2>x1){
float tmp = x1;
x1 = x2;
x2 = tmp;
}
if (!(isnanf(x1)))
cout << "Conjunto de solução: {" << x1 << " ; " << x2 << "}" << endl;
else
cout << "Nao existe raizes reais" << endl;
return 0;
}
| true |
a0e2aae2064519aef621e4b00395a852d668a4ac | C++ | famo7/music_program | /include/Queue.h | UTF-8 | 997 | 3.21875 | 3 | [] | no_license | // Filename: Queue.h
// Written by: Farhan Mohamed
// Created date: 03/01/2020
// Last modified: 03/08/2020
/* Description: Header file containing the class definition for Queue class
* class that handles queue of songs.
*/
#include "Song.h"
#include <cstddef>
#include <iostream>
#include <iomanip>
using std::cout; using std::setw; using std::endl;
#ifndef DT019G_QUEUE_H
#define DT019G_QUEUE_H
class Queue {
private:
// song pointer.
Song *ptr;
// size of queue.
size_t size;
// first and last elements of queue
size_t last, first;
public:
// default constructor and destructor.
Queue();
// copy constructor
Queue(const Queue &q);
// destructor.
~Queue();
// public methods for the queue.
bool isEmpty();
bool isFull();
void enQueue(const Song& s);
bool deQueue();
size_t getFirst() const{return first;}
size_t getLast() const {return last;}
Song* getSongs() const { return ptr;}
};
#endif //DT019G_QUEUE_H
| true |
0ca42e5bec543ddb8f9b0284a0f5c7968764b6f8 | C++ | zhangweiooy/C-Language-learning | /FF的肉饼.cpp | UTF-8 | 833 | 2.71875 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define PI 3.14159265
long long r[10005];
long long s[10005];
long long ans=0;
int m,n;
int judge(long long k)
{
int count=0;
for (int i=0;i<n;i++)
count+=s[i]/k;
if (count>=m) return 1;
return 0;
}
void binsearch(long long left,long long right)
{
long long mid=(left+right)/2;
if (left>right)
return;
if (judge(mid))
{
ans=mid;
binsearch(mid+1,right);
}
else binsearch(left,mid-1);
}
int main()
{
int i,j,flag=0;
long long max;
scanf("%d%d",&n,&m);
m+=1;
for (i=0;i<n;i++)
{
scanf("%ld",&r[i]);
s[i]=PI*r[i]*r[i]*1000000;
if(s[i]>0)
flag=1;
}
if (flag=0)
{
printf("0.0000\n");
return 0;
}
for(max=s[0],i=1;i<n;i++)
{
if(s[i]>max)
max=s[i];
}
binsearch(0,max+1);
printf("%.4f\n",ans/1000000.0);
return 0;
}
| true |
9f13f1488854455283dbe0a19659408f120b4fc0 | C++ | Hi10086/CR22-2 | /MFC/20160405课堂代码和作业/ChatClient2/ChatServer/SSocket.cpp | GB18030 | 2,817 | 2.953125 | 3 | [] | no_license | #include "stdafx.h"
#include "SSocket.h"
int TEMPSIZE = 255;
CSSocket::CSSocket(void)
{
m_socket = -1;
m_sock_type = 0;
}
CSSocket::~CSSocket(void)
{
if (m_socket != -1)
{
closesocket(m_socket);
}
}
int CSSocket::TcpSocket(sockaddr addr)
{
//
m_socket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (m_socket != -1)
{
//
if (::bind(m_socket, &addr, sizeof(addr)) == -1)
{
::closesocket(m_socket);
m_socket = -1;
return -1;
}
m_sock_type = SOCK_STREAM;
m_addr = addr;
}
return m_socket;
}
int CSSocket::UdpSocket(sockaddr addr)
{
//
m_socket = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (m_socket != -1)
{
//
if (::bind(m_socket, &addr, sizeof(addr)) == -1)
{
::closesocket(m_socket);
m_socket = -1;
return -1;
}
m_sock_type = SOCK_DGRAM;
m_addr = addr;
}
return m_socket;
}
bool CSSocket::SendData(const char *msg, int to_socket, sockaddr *to_addr /*= NULL*/)
{
// δʼ
if (msg == NULL || m_sock_type == 0 || to_socket == -1)
{
return false;
}
else if (m_sock_type == SOCK_STREAM)
{
return SendTcpData(msg, to_socket);
}
else if (m_sock_type == SOCK_DGRAM && to_addr != NULL)
{
return SendUdpData(msg, to_socket, to_addr);
}
return false;
}
int CSSocket::RecvData(int from_socket, char *buf, int flags, sockaddr* from /*= NULL*/, int *from_len /*= NULL*/)
{
if (m_sock_type == 0)
{
return NULL;
}
else if (m_sock_type == SOCK_STREAM && from_socket != -1)
{
return RecvTcpData(from_socket, buf, flags);
}
else if (m_sock_type == SOCK_DGRAM && from != NULL && from_len > 0)
{
return RecvUdpData(buf, flags, from, from_len);
}
return NULL;
}
bool CSSocket::SendTcpData(const char *msg, int to_socket)
{
size_t len = ::strlen(msg);
if (::send(to_socket, msg, len, 0) != len)
return false;
return true;
}
bool CSSocket::SendUdpData(const char *msg, int to_socket, sockaddr *to_addr)
{
size_t len = ::strlen(msg);
if (::sendto(to_socket, msg, len, 0, to_addr, sizeof(to_addr)) != len)
return false;
return true;
}
int CSSocket::RecvTcpData(int to_socket, char *buf, int flags)
{
buf = new char[TEMPSIZE];
if (buf == NULL)
return 0;
return ::recv(to_socket, buf, TEMPSIZE, flags);
}
int CSSocket::RecvUdpData(char *buf, int flags, sockaddr* from, int *from_len)
{
buf = new char[TEMPSIZE];
if (buf == NULL)
return 0;
return ::recvfrom(m_socket, buf, TEMPSIZE, flags, from, from_len);
}
| true |
2e5eeb2adf7102d01d3e3fc02ac9a947d24d582e | C++ | MicekP/Biblioteka | /Biblioteka/Aktorzy.h | UTF-8 | 1,374 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include "Karta.h"
#ifndef Aktorzyh
#define Aktorzyh
using namespace std;
class Osoba
{
private:
public:
string Imie;
string Nazwisko;
string GetImie()
{
return Imie;
}
string GetNazwisko()
{
return Nazwisko;
}
};
class Czytelnik : public Osoba
{
private:
static int licznik;
public:
Karta* Karta_czytelnika = NULL;
static void Licznik_add()
{
licznik++;
}
Czytelnik()
{
Imie = "X";
Nazwisko = "Y";
}
Czytelnik(string i, string n)
{
Imie = i;
Nazwisko = n;
}
~Czytelnik() {};
static void Dodaj_czytelnik();
static void Dodaj_czytelnik(string, string); //od razu podajemy imie i nazwisko
static Czytelnik* Zwroc(int);
static void Wypisz();
static bool Czy_istnieje(int);
};
class Obsluga : public Osoba
{
private:
static int licznik;
public:
static void Licznik_add()
{
licznik++;
}
Obsluga()
{
Imie = "X";
Nazwisko = "Y";
}
Obsluga(string i, string n)
{
Imie = i;
Nazwisko = n;
}
~Obsluga() {};
static void Dodaj_obsluga();
static void Dodaj_obsluga(string, string);
static bool Czy_istnieje(int);
static void Wypisz();
static Obsluga* Zwroc(int);
};
#endif // !Aktorzyh | true |
a75b832bd0185f9fe9fa7a6064ffee7185b9f6b8 | C++ | nackata/ss_ecs | /entity.h | UTF-8 | 680 | 2.609375 | 3 | [] | no_license | #ifndef ENTITY_H
#define ENTITY_H
#include "component.h"
#include "componentmanager.h"
#include "TypeCounter.h"
#include <array>
template<class T, size_t type_count>
class Entity
{
protected:
// replace method to entityManager
bool validateEntity() const
{
for (const auto & a : types)
{
// TODO: check if appropriate components exist in component manager
//
}
return true;
}
public:
static const size_t TypeID;
static const std::array<size_t, type_count> types;
};
template <class T, size_t type_count>
const size_t Entity<T, type_count>::TypeID = TypeCounter::get<T>();
#endif // ENTITY_H
| true |
9c06c87512d0e9ac56d8e18b96b0b0d2b477dd67 | C++ | kunalpratapsingh13/C-CPP-Programs---2 | /ch-1(5).cpp | UTF-8 | 548 | 2.984375 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
//clrscr();
int main()
{
int l,b,rad,ar,pr;
float pi=3.14,ac,cc;
printf("\nENTER THE LENGTH OF RECTANGLE:");
scanf("%d",&l);
printf("\nENTER THE BREADTH OF RECTANGLE:");
scanf("%d",&b);
printf("\nENTER RADIUS OF CIRCLE:");
scanf("%d",&rad);
ar=l*b;
pr=2*(l+b);
ac=pi*rad*rad;
cc=4*pi*rad;
printf("\nAREA OF THE RECTANGLE:%d",ar);
printf("\nPERIMETER OF THE RECTANGLE:%d",pr);
printf("\nAREA OF CIRCLE:%0.3f",ac);
printf("\nCIRCUMFERENCE OF CIRCLE:%0.3f",cc);
getch();
}
| true |
1f34fa1e94efcd83b79d008b9d19be15d388c2ff | C++ | Scoder15/CS-note | /code/75. Sort Colors.cpp | UTF-8 | 413 | 2.546875 | 3 | [] | no_license | class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size();
int a[3] = {0};
for(int i = 0; i < n ; i++)
{
a[nums[i]]++;
}
int j;
for(j = 0; j < a[0]; j++)
nums[j] = 0;
for(j = a[0]; j < a[1] + a[0]; j++)
nums[j] = 1;
for(j = a[0]+a[1]; j < n;j++)
nums[j] = 2;
}
}; | true |
38a38a5d08ded37fde6e9bdeb67bb442bda8d9c1 | C++ | ZigorSK/Technology_of_prog2 | /Stack.cpp | WINDOWS-1251 | 4,158 | 3.734375 | 4 | [] | no_license | #include "Stack.h"
Stack::Stack()
{
hight_stack_ptr = nullptr;
}
Stack::Stack(int d = 0)
{
float dat;
hight_stack_ptr = nullptr;
for (int i = 0; i < d; i++)
{
cout << " , " << endl;
cin >> dat;
this->push(dat);
}
}
Stack::Stack(const Stack &obg)
{
hight_stack_ptr = nullptr;
Node *ptr = obg.hight_stack_ptr;
int count = 0;
double *arr = nullptr;
while (ptr)
{
count++;
ptr = ptr->get_next_ptr();
}
arr = new double[count];
ptr = obg.hight_stack_ptr;// 1 - -
for (int i = 0; i < (count); i++)
{
*(arr + count - i - 1) = ptr->get_data();
ptr = ptr->get_next_ptr();
}
for (int i = 0; i < count; i++)
{
push(*(arr + i));
}
delete arr;
}
inline Node *Stack::get_hight_stack_ptr()
{
return hight_stack_ptr;
}
void Stack::push(float d = 10 )//
{
if (hight_stack_ptr != nullptr)//
{
Node *ptr = nullptr;
ptr = new Node;
ptr->set_next_ptr(hight_stack_ptr);
ptr->set_data(d);
hight_stack_ptr = ptr;
}
else//
{
hight_stack_ptr = new Node;
hight_stack_ptr->set_next_ptr(nullptr);
hight_stack_ptr->set_data(d);
}
}
float Stack::pop()//
{
float d = 0;
if (hight_stack_ptr != nullptr)//
{
d = hight_stack_ptr->get_data();
cout << " " << d << " " << endl;
Node *ptr = hight_stack_ptr->get_next_ptr();
delete hight_stack_ptr;
hight_stack_ptr = ptr;
}
else
{
cout << " " << endl;
}
return d;
}
void Stack::show()//
{
Node *ptr = hight_stack_ptr;
cout << setw(20) << "Top of stack:"<<endl;
while (ptr)
{
cout << setw(20) << ptr-> get_data()<<endl;
ptr = ptr->get_next_ptr();
}
cout << setw(20) << "Bottom of stack:" << endl;
}
Stack & Stack::operator!()//
{
Node *ptr = hight_stack_ptr;
while (ptr)
{
ptr->set_data(-ptr->get_data());
ptr = ptr->get_next_ptr();
}
return *this;
}
Stack & Stack::operator--()// 1
{
Node *ptr = hight_stack_ptr;
while (ptr)
{
ptr->set_data(ptr->get_data() - 1);
ptr = ptr->get_next_ptr();
}
return *this;
}
Stack & Stack::operator++()// 1
{
Node *ptr = hight_stack_ptr;
while (ptr)
{
ptr->set_data((double)(ptr->get_data() + 0.5));
ptr = ptr->get_next_ptr();
}
return *this;
}
Stack &Stack::operator=(Stack &obg)
{
Node *ptr = obg.get_hight_stack_ptr();
int count = 0;
double *arr = nullptr;
while(ptr)
{
count++;
ptr = ptr->get_next_ptr();
}
arr = new double[count];
ptr = obg.get_hight_stack_ptr();// 1 - -
for(int i = 0; i < (count);i++)
{
*(arr + count - i - 1 ) = ptr->get_data();
ptr = ptr->get_next_ptr();
}
for (int i = 0; i < count; i++)
{
push(*(arr + i));
}
delete arr;
return *this;
}
Stack &operator++(Stack &op, int notused)// ( - )
{
static Stack res = op;
float d = 0;
cout << " , : " << endl;
cin >> d;
op.push(d);
return res;
}
Stack &operator--(Stack & op, int a)//
{
static Stack res = op;
op.pop();
return res;
} | true |
7f231492f83a8c33399a2ece6e76a797ed3271ec | C++ | goku321/code | /cc/shknum.cpp | UTF-8 | 1,272 | 2.796875 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
typedef unsigned long ul;
typedef long long ll;
int countSetBits(ul num) {
int count = 0;
while(num) {
count += num & 1;
num >>= 1;
}
return count;
}
int main() {
int t;
cin >> t;
while(t--) {
ul num;
cin >> num;
if(num == 1) {
cout << 2 << endl;
continue;
}
if(countSetBits(num) == 2) {
cout << 0 << endl;
continue;
}
if(countSetBits(num) == 1) {
cout << 1 << endl;
continue;
}
int pos = (int)(log2(num));
//cout << pos << " " << countSetBits(num) << endl;
ul x = 2147483648UL;
//cout << countSetBits(x) << endl;
ul y = x;
//y >>= 1;
ul minSteps = 9999999999UL;
while(x) {
y = x;
y >>= 1;
while(y) {
ul z = x | y;
if(z > num)
minSteps = min((ul)abs(z-num), minSteps);
else
minSteps = min((ul)abs(num-z), minSteps);
y >>= 1;
}
x >>= 1;
}
cout << minSteps << endl;
}
} | true |
69fa60ce663924d7b42664c897f7e4e3c142d703 | C++ | AnikDas-Stack/Codeforces-Problem-Solution | /519B. A and B and Compilation Errors.cpp | UTF-8 | 532 | 2.671875 | 3 | [] | no_license | #include <stdio.h>
int main()
{
long long int n, sum1=0, sum2=0, sum3=0;
scanf("%lld", &n);
long long int ara1[n], ara2[n-1], ara3[n-2];
for(int i=0; i<n; i++)
{
scanf("%lld", &ara1[i]);
sum1+=ara1[i];
}
for(int i=0; i<n-1; i++)
{
scanf("%lld", &ara2[i]);
sum2+=ara2[i];
}
for(int i=0; i<n-2; i++)
{
scanf("%lld", &ara3[i]);
sum3+=ara3[i];
}
printf("%lld\n%lld\n", sum1-sum2, sum2-sum3);
return 0;
}
| true |
f0efa8cc6a049351853791baabcb560dd53ddd0c | C++ | SheSnake/code-jamp-solution | /code-jam-2018/round_a/edgy_baking.cpp | UTF-8 | 2,467 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <vector>
using namespace std;
// view analysis: try each interval and for each new interval cut off the invalid
struct Interval
{
double l;
double r;
Interval(double l = 0, double r = 0): l(l), r(r) {}
};
int compare(const void* a, const void* b)
{
return ((Interval*)a)->l - ((Interval*)b)->l;
}
vector<Interval> merge(vector<Interval>& s)
{
if (s.size() == 0) return s;
vector<Interval> res;
Interval cur = s[0];
for (int i = 1; i < s.size(); ++i)
{
if (s[i].l <= cur.r)
{
if (s[i].r > cur.r)
{
cur.r = s[i].r;
}
}
else
{
res.push_back(cur);
cur = s[i];
}
}
res.push_back(cur);
return res;
}
int main()
{
int T;
cin >> T;
for (int t = 1; t <= T; ++t)
{
int N; double P;
cin >> N >> P;
Interval LR[100];
double cur_P = 0.0;
for (int i = 0; i < N; ++i)
{
int H, W;
cin >> H >> W;
double l = H > W ? W : H;
double r = sqrt(H * H + W * W);
LR[i].l = l * 2;
LR[i].r = r * 2;
cur_P += (H + W) * 2;
}
vector<Interval> s;
s.push_back(Interval(0, 0));
double most_add_P = P - cur_P;
for (int i = 0; i < N; ++i)
{
int size = s.size();
for (int j = 0; j < size; ++j)
{
if (s[j].l + LR[i].l > most_add_P) continue;
s.push_back(Interval(s[j].l + LR[i].l, s[j].r + LR[i].r));
}
qsort(s.data(), s.size(), sizeof(Interval), compare);
//for (int j = 0; j < s.size(); ++j)
//{
// cout << "after sort inter: "<<s[j].l << " "<< s[j].r << endl;
//}
s = merge(s);
//for (int j = 0; j < s.size(); ++j)
//{
// cout << "inter: "<<s[j].l << " "<< s[j].r << endl;
//}
}
double res = cur_P;
if (s.size() > 0)
{
if (s[s.size() - 1].r + res >= P)
{
printf("Case #%d: %.6f\n", t, P);
}
else
{
res += s[s.size() - 1].r;
printf("Case #%d: %.6f\n", t, res);
}
}
}
}
| true |
7c57ef882eabe791869b3495c1c7547f97c7e6cb | C++ | mwthinker/CppSdl2 | /src/sdl/texture.h | UTF-8 | 2,328 | 2.640625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #ifndef CPPSDL2_SDL_TEXTURE_H
#define CPPSDL2_SDL_TEXTURE_H
#include "opengl.h"
#include "rect.h"
#include "surface.h"
#include <spdlog/spdlog.h>
#include <type_traits>
namespace sdl {
class Texture {
public:
friend class TextureAtlas;
Texture() = default;
~Texture();
Texture(const Texture& texture) = delete;
Texture& operator=(const Texture& texture) = delete;
Texture(Texture&& texture) noexcept;
Texture& operator=(Texture&& texture) noexcept;
void bind();
void texImage(const Surface& surface);
void texImage(const Surface& surface, std::invocable auto&& filter);
void texSubImage(const Surface& surface, const Rect& dst);
void generate();
bool isValid() const noexcept;
friend bool operator==(const Texture& left, const Texture& right) noexcept;
friend bool operator!=(const Texture& left, const Texture& right) noexcept;
operator gl::GLuint() const noexcept {
return texture_;
}
private:
static gl::GLenum surfaceFormat(SDL_Surface* surface);
gl::GLuint texture_{};
};
inline bool operator==(const Texture& left, const Texture& right) noexcept {
return left.texture_ == right.texture_;
}
inline bool operator!=(const Texture& left, const Texture& right) noexcept {
return left.texture_ != right.texture_;
}
inline void Texture::texImage(const Surface& surface) {
texImage(surface, []() {
gl::glTexParameteri(gl::GL_TEXTURE_2D, gl::GL_TEXTURE_MIN_FILTER, gl::GL_LINEAR);
gl::glTexParameteri(gl::GL_TEXTURE_2D, gl::GL_TEXTURE_MAG_FILTER, gl::GL_LINEAR);
});
}
void Texture::texImage(const Surface& surface, std::invocable auto&& filter) {
if (!surface.isLoaded()) {
spdlog::debug("[sdl::Texture] Failed to bind, must be loaded first");
return;
}
if (!isValid()) {
spdlog::debug("[sdl::Texture] Failed to bind, must be generated first");
return;
}
auto format = surfaceFormat(surface.surface_);
if (format == 0) {
spdlog::debug("[sdl::Texture] Failed BytesPerPixel, must be 1, 3 or 4. Is: {}", surface.surface_->format->BytesPerPixel);
return;
}
gl::glBindTexture(gl::GL_TEXTURE_2D, texture_);
filter();
gl::glTexImage2D(gl::GL_TEXTURE_2D, 0, format,
surface.surface_->w, surface.surface_->h,
0,
format,
gl::GL_UNSIGNED_BYTE,
surface.surface_->pixels
);
}
}
#endif
| true |
5ed00ee37e6dc0a87a6bdb9f7a9565fca1b7c518 | C++ | ankushgarg1998/Competitive_Coding | /college-labs/Information Security Lab/caesar_cipher.cpp | UTF-8 | 609 | 3.359375 | 3 | [] | no_license | #include<bits/stdc++.h>
#define loop(i, a, b) for(int i=a; i<b; i++)
using namespace std;
string caesar_cipher(string text, int shift) {
string cipher = "";
loop(i, 0, text.size()) {
int ch = text[i] - 'A';
ch = (ch + shift) % 26;
if(ch < 0)
ch += 26;
cipher += char(ch + 'A');
}
return cipher;
}
int main() {
string text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int shift = 23, textlen = text.size();
string cipher = caesar_cipher(text, shift);
cout<<cipher<<"\n";
string ret = caesar_cipher(cipher, shift*-1);
cout<<ret<<"\n";
} | true |
01961f05c300eb6c7fdaed08a942a0e1e5abdb3f | C++ | LuhMoonShy/Lista-07-Algoritmos-e-programacao | /Lista 07/Exercicio 09 Lista 10.cpp | ISO-8859-1 | 917 | 3.234375 | 3 | [] | no_license | //Faa um algoritmo que leia a idade de at 100 pessoas e apresente a mdia entre todas, alm de
//identificar a mais velha e a posio em que ela se encontra no vetor. A idade mais velha pode aparecer em
//mais de uma posio.
#include <stdio.h>
#include <locale.h>
int main(){
setlocale(LC_ALL, "Portuguese");
int i, idade[100], maiorIdade = 0;
float quantPessoas, somaIdades = 0.0, mediaIdades = 0.0;
printf("Informe a quantidade de pessoas: ");
scanf("%f", &quantPessoas);
for(i = 0; i < quantPessoas;i++){
printf("Informe a idade da pessoa %d: ",i+1);
scanf("%d",&idade[i]);
somaIdades+=idade[i];
if(maiorIdade<idade[i])
maiorIdade=idade[i];
}
mediaIdades=somaIdades/quantPessoas;
printf("\nA mdia das idades apresentadas foi de: %.2f.\n",mediaIdades);
printf("A pessoa mais velha tem %d anos,identificado na posio %d.",maiorIdade, i);
return 0;
}
| true |
d21e62ddbabda38e90dd00b209bf432279738123 | C++ | HDarko/CPP-Projects | /BlackJack/Headers/Card.h | UTF-8 | 1,091 | 3.640625 | 4 | [] | no_license | #pragma once
#include <iostream>
//Declaration of the Card class
enum class Suit
//Hearts, Clubs, Spades, Diamonds in that order
{
HEARTS,
CLUBS,
SPADES,
DIAMONDS
};
enum class Rank
{
//Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten
//| Jack | Queen | King | Ace
//We treat ACE as 1 value in class for easier implementation
ACE=1,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING,
};
class Card
{
//The card should know its value and rank, wheter it is flipped down or not,
//and should be able to output its value
public:
Rank getRank() const { return m_rank; };
Suit getSuit() const { return m_suit; };
bool isFacingDown() const { return m_isDown; };
//if the Card is FaceDown then the value should be 0 else return the value
int getValue() const;
Card(Rank r = Rank::TWO, Suit s = Suit::CLUBS, bool down = false);
void flipCard();
friend std::ostream& operator<<(std::ostream& os, const Card& card);
private:
Rank m_rank;
Suit m_suit;
bool m_isDown;
};
| true |
1e8c5c44bf8584c7bd40f6536d30807dfc81247c | C++ | 15831944/Fdo_SuperMap | /源代码/Thirdparty/UGC/inc/Geometry/UGGeoRect.h | GB18030 | 12,664 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | #ifndef INCLUDE_GEOMETRY_UGGEORECT_H_HEADER_INCLUDED_BE220BE3
#define INCLUDE_GEOMETRY_UGGEORECT_H_HEADER_INCLUDED_BE220BE3
#include "UGGeoRect.h"
#include "UGGeometry.h"
namespace UGC {
//! \brief (б)
//! \remarks ڲݽṹĵ/θ߶/ο/תǶȹ
//! ·ʽε״: һηŵʵλ(ĵ/߶/),
//! ȻʱתεĽǶ, õ״
class GEOMETRY_API UGGeoRect : public UGGeometry
{
public:
//! \brief 캯
UGGeoRect();
//! \brief
virtual ~UGGeoRect();
public: //pure virtual
//! \brief յ
virtual void Clear();
//! \brief õά, ̶Ϊ2
//! \return õά,̶Ϊ2
virtual UGint GetDimension() const;
//! \brief õ, ̶Ϊ GeoRect
virtual Type GetType() const;
//! \brief õڵ㣨Geometryڲĵ㣩,Ϊĵ
virtual UGPoint2D GetInnerPoint() const;
//! \brief õ
//! \attention DimensionΪ1or2Ķ֧
//! \return س
virtual UGdouble GetLength() const;
//! \brief õ
//! \return
virtual UGdouble GetArea() const;
//! \brief , ڶѡ
//! \param pntHitTest ѡеĵ
//! \param dTolerance
//! \return ѡзtrue, false
virtual UGbool HitTest( const UGPoint2D &pntHitTest, UGdouble dTolerance) const;
//! \brief õռ, ҪҪάͬʱ
//! ͳһʱ, һЩռжϺͲ㷨
//! \param pPoints ĵ[out]
//! \param pPolyCount ÿӶ[out]
//! \param nSubCount Ӷ[out]
//! \param nSegmentCount Բ, ÿηָĸ[in]
//! \remarks ָļ,߲ͷڴռ
//! \return ɹtrue,false
virtual UGbool GetSpatialData(UGAutoPtr<UGPoint2D>& pPoints,
UGAutoPtr<UGint>& pPolyCount, UGint& nSubCount, UGint nSegmentCount=0) const;
//! \brief ζǷЧ
//! \return Чtrue,Чfalse
virtual UGbool IsValid()const;
//! \brief
//! \param dRatioX Xű
//! \param dRatioY Yű
virtual void Inflate( UGdouble dRatioX, UGdouble dRatioY);
//! \brief
//! \param dRatio ű(X,Yͬ)
virtual void Inflate( UGdouble dRatio);
//! \brief ƽ
//! \param dX ƽƵXƫ
//! \param dY ƽƵYƫ
virtual void Offset( UGdouble dX, UGdouble dY);
//! \brief ƽ
//! \param ƫ(X,Yͬ)
virtual void Offset( UGdouble dOffset);
//! \brief ƽ
//! \param ƽƵƫ(ֱUGSize2Dеx,yX,Yƫ)
virtual void Offset( const UGSize2D &szOffset);
//! \brief ת
//! \param pntOrigin תĵ(ê,)
//! \param dAngle תǶ
virtual void Rotate(const UGPoint2D& pntOrigin, UGdouble dAngle);
//! \brief ת,һЩ,ԱڲԲýcos,sin, ʱЧ
//! \remarks dAngleƶ,GeoTextҪ,Ҫ
//! \param pntOrigin תĵ(ê,)
//! \param dCosAngle תcosֵ
//! \param dSinAngle תsinֵ
//! \param dAngle תǶ
virtual void Rotate( const UGPoint2D& pntOrigin, UGdouble dCosAngle, UGdouble dSinAngle, double dAngle = 0);
//! \brief ,µBounds
//! \param rcNewBounds µ,ΧBounds
//! \return ɹtrue,ʧܷfalse
virtual UGbool Resize(const UGRect2D& rcNewBounds);
//! \brief 㾵
//! \param pntMirror1 ɾĵһ
//! \param pntMirror2 ɾĵڶ
//! \return ɹtrue,ʧܷfalse
virtual UGbool Mirror(const UGPoint2D &pntMirror1, const UGPoint2D &pntMirror2);
public:
//! \brief ͶӰתúתҪ, ͶӰת
//! \param pPJTranslator ͶӰת
//! \param bForward ת, trueUGRefTranslatorԴ(Src)תĿ(Des), false෴
virtual void PJConvert( UGRefTranslator *pPJTranslator, UGbool bForward = true);
//! \brief ӾγϵͳתΪͶӰϵͳ
//! \param pCoordSys ͶӰϵͳ
virtual void PJForward( UGPrjCoordSys *pCoordSys );
//! \brief ͶӰϵͳתΪγ
//! \param pCoordSys ͶӰϵͳ
virtual void PJInverse( UGPrjCoordSys *pCoordSys );
public:
//! \brief ζ
//! \param geoRect [in] оζ
//! \return true
UGbool Make(const UGGeoRect& geoRect);
//! \brief ĵ/Size/תǶȹζ
//! \param pntCenter [in] ĵ㡣
//! \param szSize [in] sizexΪ,yΪ߶ȡ
//! \param dAngle [in] תǶȡ
//! \return true
UGbool Make( const UGPoint2D &pntCenter, const UGSize2D& szSize, UGdouble dAngle = 0);
//! \brief þνṹתǶȹζ
//! \param rcRect [in] νṹ
//! \param dAngle [in] תǶȡ
//! \return true
UGbool Make( const UGRect2D& rcRect, UGdouble dAngle = 0);
//! \brief õĵ㡣
//! \return ĵ㡣
UGPoint2D GetCenterPoint() const;
//! \brief ĵ㡣
//! \param pntCenter [in] ĵ㡣
void SetCenterPoint( const UGPoint2D& pntCenter );
//! \brief õ߶ȡ
//! \return ظ߶ȡ
//! \remarks ø߶Ȳǿȥĸ߶,ûнת֮ǰĸ߶ȡ
UGdouble GetHeight() const;
//! \brief ø߶ȡ
//! \param dHeight [in] Ҫõĸ߶ȡ
//! \return dHeightСڵ0, false
UGbool SetHeight( UGdouble dHeight );
//! \brief õȡ
//! \return ؿȡ
//! \remarks ÿȲǿȥĿ,ûнת֮ǰĿȡ
UGdouble GetWidth() const;
//! \brief ÿȡ
//! \param dWidth [in] ҪõĿȡ
//! \return dWidthСڵ0,false
UGbool SetWidth( UGdouble dWidth );
//! \brief õתǶȡ
//! \return תǶȡ
UGdouble GetAngle() const;
//! \brief תǶȡ
//! \param dAngle [in] ҪõתǶȡ
void SetAngle( UGdouble dAngle );
//! \brief תΪ߶
//! \param geoLine[out] õ߶
//! \param nSegmentCount תΪʱ,ÿһöٸģ; в
//! \return ɹtrue,ʧܷfalse
virtual UGbool ConvertToLine( UGGeoLine &geoLine, UGint nSegmentCount = 0 ) const;
//! \brief תΪ
//! \param geoRegion[out] õ
//! \param nSegmentCount תΪʱ,ÿһöٸģ; в
//! \return ɹtrue,ʧܷfalse
virtual UGbool ConvertToRegion( UGGeoRegion &geoRegion, UGint nSegmentCount = 0 ) const;
#if PACKAGE_TYPE==PACKAGE_UGC
public:
//! \brief XMLʽϢ
//! \param versionType GMLİ汾
//! \param nPace ĿոĿ,ʹxmlַ˹Ķ;
//! Ҫصxmlַһǩеһ, ָͨոĿ,ʹ
//! \return ָGML汾xmlַ
virtual UGString ToXML(GMLVersionType versionType, UGint nPace = 0) const;
//! \brief XMLַGeometry
//! \param strXML xmlʽַ
//! \param versionType xmlַGML汾
//! \return ָGML汾xmlַ
virtual UGbool FromXML(const UGString& strXML, GMLVersionType versionType);
#endif // end declare ugc sdk
public:
//added by xielin ^_^ ༭غ,ѱ༭geometryͳһ
//! \brief ñ༭ľĿ
//! \remarks ڹ̶Ϊ9˸ıС8ƵһתƵ
virtual UGint GetHandleCount();
//nHandle:ֵƵĹϵͼ
// 1---+ +--2 +----3
// | | |
// | | |
// x---------x---------x 9
// | ____________ | |
// | / \ | x---+
// 4---x | | x-----5
// | \____________/ |
// | |
// x---------x---------x
// | | |
// | | |
// 6---+ +-----7 +-----8
//! \brief ݾӦƵֵ
//! \param nHandle Ƶ
//! \param point ӦĿƵֵ
//! \return ظ
virtual UGint GetHandle( UGint nHandle, UGPoint2D& point);
//! \brief ƶƵ㵽ָ,ҪڻƶĶڵȲ
//! \param nHandle Ƶ
//! \param point Ƶ
virtual void MoveHandle( UGint nHandle, const UGPoint2D& pnt2D,UGEditType::EditToolShape nEditType=UGEditType::ET_None);
//! \brief ڵ༭ʱһƵ,Ҳڻƶʱڵ
//! \param nHandle λ
//! \param pnt2D ĵ
virtual void AddHandle( UGint nHandle, const UGPoint2D& pnt2D,UGEditType::EditToolShape nEditType=UGEditType::ET_None);
//! \brief ɾ༭ָڵ
//! \param nHandle ڵ
virtual UGuint DelNode( UGint nHandle );
//! \brief ʱĸߣصһ϶
//! \param pPoints 㴮
//! \param nPntCount ĸ
//! \param nEditType ƶͣοUGEditType
//! \param pStyle ߵķΪNULLĬϵķ
virtual UGGeometry* CalAssistantLine(const UGPoint2D* pPoints,UGint nPntCount,UGEditType::EditToolShape nEditType,UGStyle* pStyle=NULL);
//! \brief ݴĵ㴮ɶҪڱ༭еIJûڲ鱣㴮Ķ
//ҲԶ,ڲ鱣㴮ĶúֱreturnȿɣGeoLine
//GeoLineȶֱAddHandleɣЧʱȽϸ
//! \param pPoints 㴮
//! \param nPntCount ĸ
virtual void MakeWithPoints(UGPoint2D* pPoints,UGint nPntCount,UGEditType::EditToolShape nEditType=UGEditType::ET_None);
//! \brief ȡҪĵ㴮
//! \param aryPnts 㴮ȥҪĵ㴮
//! \return trueʾҪĵ㴮falseʾöûҪĵ㴮
virtual UGbool GetSnapPoints(UGArray<UGPoint2D>& aryPnts);
//! \brief ȡҪ߶
//! \param aryLines Ҫ飨жpartôaryLinesӦжٸcount
//! \return trueʾҪߣfalseʾöûҪ
virtual UGbool GetSnapLines(UGLineArray& aryLines);
//added by xielin ^_^ ༭غ,ѱ༭geometryͳһ end
protected:
virtual UGRect2D ComputeBounds() const;
/*virtual UGRect2D GetBoundsInside() const;
virtual void SetBoundsInside( const UGRect2D & rcBounds );*/
virtual UGbool SaveGeoData(UGStream& stream, UGDataCodec::CodecType eCodecType,UGbool bSDBPlus = FALSE) const;
virtual UGbool LoadGeoData( UGStream& stream , UGDataCodec::CodecType eCodecType = UGDataCodec::encNONE,UGbool bSDBPlus = FALSE );
// added by zengzm 2007-5-10 õڲĶ
//! \brief õĸ꣬Զա
//! \param pPoints ڷصָ롣
//! \attention ߱뱣֤pPointsĿռ㡣
void GetVertexes(UGPoint2D* pPoints) const;
private:
//! \brief ĵ
UGPoint2D m_pntCenter;
//! \brief
UGdouble m_dWidth;
//! \brief ߶
UGdouble m_dHeight;
// modified by zengzm 2007-4-27
//UGint m_nAngle;
//! \brief תǶ
//! \remarks ڴиΪdouble,Ƕȵλ,洢ʱSFCּ
UGdouble m_dAngle;
};
} // namespace UGC
#endif /* INCLUDE_GEOMETRY_UGGEORECTOBLIQUE_H_HEADER_INCLUDED_BE220BE3 */
| true |
a3ebdba5318147b4b929fec3d8dfa22295d79a25 | C++ | 9hack/net-sandbox | /trash/game_server.cpp | UTF-8 | 3,754 | 2.953125 | 3 | [] | no_license | #include "threadsafe_queue.h"
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/bimap.hpp>
#include <boost/thread.hpp>
#include <string>
#include <array>
#define PORT 9000
using boost::asio::ip::tcp;
typedef boost::bimap<int, tcp::endpoint> ClientList;
typedef ClientList::value_type Client;
typedef std::pair<std::string, int> ClientMessage;
class NetworkServer {
public:
NetworkServer(unsigned short port) :
socket(io_service, tcp::endpoint(tcp::v4(), port)),
service_thread(std::bind(&NetworkServer::run_service, this)),
nextClientID(0)
{
std::cerr << "Starting server on port " << port << "\n";
}
~NetworkServer()
{
io_service.stop();
service_thread.join();
}
// bool HasMessages();
// ClientMessage PopMessage();
//
// void SendToClient(std::string message, unsigned __int64 clientID, bool guaranteed = false);
// void SendToAllExcept(std::string message, unsigned __int64 clientID, bool guaranteed = false);
// void SendToAll(std::string message, bool guaranteed = false);
private:
// Network send/receive stuff
boost::asio::io_service io_service;
tcp::socket socket;
// tcp::endpoint server_endpoint;
// tcp::endpoint remote_endpoint;
std::array<char, BUFSIZ> recv_buffer;
boost::thread service_thread;
void start_receive()
{
socket.async_receive(boost::asio::buffer(recv_buffer),
boost::bind(&NetworkServer::handle_receive, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void handle_receive(const boost::system::error_code& error, std::size_t bytes_transferred)
{
if (!error)
{
try {
auto message = ClientMessage(
std::string(recv_buffer.data(), recv_buffer.data() + bytes_transferred),
1); //get_client_id(remote_endpoint));
if (!message.first.empty())
message_queue.push(message);
}
catch (std::exception ex) {
std::cerr << "handle_receive: Error parsing incoming message:" << ex.what();
}
catch (...) {
std::cerr << "handle_receive: Unknown error while parsing incoming message";
}
}
else
{
std::cerr << "handle_receive: error: " << error.message();
}
start_receive();
}
// void handle_send(std::string /*message*/, const boost::system::error_code& /*error*/, std::size_t /*bytes_transferred*/) {}
void run_service()
{
start_receive();
while (!io_service.stopped()){
try {
io_service.run();
} catch( const std::exception& e ) {
std::cerr << "Server network exception: " << e.what();
}
catch(...) {
std::cerr << "Unknown exception in server network thread";
}
}
std::cerr << "Server network thread stopped";
}
// unsigned int get_client_id(tcp::endpoint endpoint)
// {
// auto cit = clients.right.find(endpoint);
// if (cit != clients.right.end())
// return (*cit).second;
//
// nextClientID++;
// clients.insert(Client(nextClientID, endpoint));
// return nextClientID;
// }
// void send(std::string pmessage, tcp::endpoint target_endpoint);
// Incoming messages queue
// locked_queue<ClientMessage> incomingMessages;
ThreadSafeQueue<ClientMessage> message_queue;
// Clients of the server
ClientList clients;
unsigned int nextClientID;
};
int main(int argc, char* argv[]) {
NetworkServer server(PORT);
for (;;) {
sleep(1);
}
}
| true |
0cf24a9e49774b553af398a3a02e5bb2c40aa448 | C++ | apatank2/Algorithms | /Algorithms in C++/OBST/obst.cpp | UTF-8 | 3,910 | 2.890625 | 3 | [] | no_license | // Name of program obst.cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
float mat[100][100];
int index2[100][100];
int v[100];
int count = 0;
int t,tmax = -1;
//creates an array of obst tree values
int printObst(int i, int j, int k){
//cout << endl << "i-j-k" << i <<"," << j << "," << k;
if (i > j)
return 0;
else {
v[k] = index2[i][j];
t = (2 * k) + 1;
printObst (i, index2[i][j] - 1, t);
t = (2 * k) + 2;
printObst (index2[i][j] + 1, j, t);
}
}
int main (int nkey, char** prob) {
int level = 0;
float ans1 = 0.0, result=0.0;
if(nkey==1) {
cout << "Enter more parameters" << endl;
return 0;
}
cout << endl << "You have entered " << nkey-1 << " arguments:" << "\n";
int key = atoi(prob[1]);
if (nkey-2 > key || nkey-2 < key) {
cout << "Incorrect number of probabilities !" << endl;
return 0;
}
if(key==1) {
cout << "Enter more than 1 probability" << endl;
return 0;
}
char* p[key];
cout << endl << "Keys--" << key;
for(int i = 2; i <= nkey-1; i++) {
p[i-2] = (char*)prob[i];
}
float val[key+1];
val[0] = -1;
for(int i = 0; i < key; i++) {
val[i+1]=(atof(p[i]));
}
cout << "\nProbabilities--" << endl;
for(int i = 1; i <= key; i++)
cout << val[i] << "\n";
for(int i = 0; i <= key; i++) {
mat[0][i] = 0.0;
index2[0][i] = 0.0;
mat[i][0] = 0.0;
index2[i][0] = 0.0;
mat[key+1][i] = 0.0;
index2[key+1][i] = 0.0;
}
for(int i = 0; i <= key+1; i++) { //rows
for(int j = 0; j <= key; j++) { //columns
index2[i][j] = 0.0;
}
}
for(int i = 1; i <= key+1; i++) {
for(int j = 1; j <= key; j++) {
if(i==j) {
mat[i][j] = val[i];
index2[i][j] = i;
}
else
mat[i][j] = 0;
}
}
int j;
//create cost matrix and corresponding index matrix
for (level = 1; level < key; level++) {
for(int i = 1; i <= (key - level); i++) {
j = i + level;
for(int k = i; k <= j; k++) {
ans1 = ans1 + val[k];
}
float min = 999.99;
for(int k = i; k <= j; k++) {
if (min > (mat[i][k-1] + mat[k+1][j] + ans1)) {
min = mat[i][k-1] + mat[k+1][j] + ans1;
mat[i][j] = min;
index2[i][j] = k;
}
}
ans1 = 0.0;
//cout << "ans1 = " << ans1 << endl;
}
}
cout << "\nFinal Matrix--" << endl;
for(int i = 0; i <= key+1; i++) {
for (int j = 0; j <= key; j++) {
cout << mat[i][j] <<"\t\t";
}
cout << endl;
}
cout << "\nFinal index--" << endl;
for(int i = 0; i <= key+1; i++) {
for (int j = 0; j <= key; j++) {
cout << index2[i][j] <<"\t\t";
}
cout << endl;
}
//for printing the tree depth-wise
int c = 1;
printObst (1, key, 0);
cout << endl << "Tree --";
cout << endl << "depth 0 : " << index2[1][key];
int vLen=1, depLen = 1;
for(int i=0;i<100;i++) {
if(v[i] > 0) {
vLen++;
}
}
vLen--;
int depth = 1;
while(vLen>depLen) {
int k=1;
cout << endl << "depth " << depth << " : ";
while(k <= pow(2,depth)) {
cout << v[c] << "\t";
if(v[c] > 0) {
depLen++;
}
c++;
k++;
}
if(vLen==depLen) {
break;
}
depth++;
}
cout << endl;
return 0;
}
| true |
3215db48c932cee849daba636acc9e396c11f50a | C++ | DMHACYJ/work1 | /gcd,lcm.cpp | UTF-8 | 566 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include<cstring>
using namespace std;
const int maxn=100;
long long int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
long long int lcm(int a,int b)
{
return (a/gcd(a,b))*b;
}
int a[maxn];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(a,0,sizeof a);
int n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int x=gcd(a[0],a[1]);
int y=lcm(a[0],a[1]);
for(int i=2;i<n;i++)
{
x=gcd(a[i],x);
y=lcm(a[i],y);
}
cout<<x<<" "<<y<<endl;
}
return 0;
}
| true |
acd568af31292d0e09f6e676980f4bc93f329506 | C++ | jihoonn/Alt | /JMH/숙제1.cpp | UHC | 472 | 3.359375 | 3 | [] | no_license | #include <stdio.h>
int main(void)
{
int num;
printf("90 ̻ 40 ̸ Է: ");
scanf("%d", &num);
switch(num)
{
case (80.0<90.0):
printf("A \n");
break;
case 80:
printf("B \n");
break;
case 70:
printf("C \n");
break;
case 60:
printf("D \n");
break;
case 5:
printf("E \n");
break;
case 6:
printf("40 F \n");
break;
defaukt:
printf("I don't know! \n");
}
return 0;
}
| true |
360138c8bc017fa91ed822cf8591ddf576840324 | C++ | mohansella/simple-kvstore | /source/lib/src/mohansella/kvstore/StoreValue.cpp | UTF-8 | 3,220 | 3.21875 | 3 | [
"MIT"
] | permissive | #include <mohansella/kvstore/StoreValue.hpp>
#include <memory>
namespace mohansella::kvstore
{
StoreValue::StoreValue()
{
this->valueType = StoreValue::Type::Unknown;
}
StoreValue::StoreValue(std::int64_t value)
{
this->valueType = StoreValue::Type::Integer;
this->sizeVal = sizeof(value);
this->pointer.integer = value;
}
StoreValue::StoreValue(std::string & value)
{
this->valueType = StoreValue::Type::String;
this->sizeVal = value.length();
auto ptr = std::make_unique<std::string>();
*ptr = std::move(value);
this->pointer.string = ptr.release();
}
StoreValue::StoreValue(StoreValue && value)
{
this->valueType = StoreValue::Type::Unknown;
this->operator=(std::move(value));
}
StoreValue & StoreValue::operator=(StoreValue && other)
{
this->~StoreValue();
//copy from other
this->pointer = other.pointer;
this->valueType = other.valueType;
this->sizeVal = other.sizeVal;
//reset other
other.pointer = {0};
other.valueType = StoreValue::Type::Unknown;
other.sizeVal = 0;
return *this;
}
StoreValue::~StoreValue()
{
switch (this->valueType)
{
case StoreValue::Type::Unknown:
{
break; //nop
}
case StoreValue::Type::Integer:
{
break; //nop
}
case StoreValue::Type::String:
{
std::unique_ptr<std::string>(this->pointer.string);
break;
}
default:
break;
}
}
StoreValue::Type StoreValue::getType() const
{
return this->valueType;
}
std::int32_t StoreValue::size() const
{
return this->sizeVal;
}
bool StoreValue::isInteger() const
{
return this->getType() == StoreValue::Type::Integer;
}
bool StoreValue::isString() const
{
return this->getType() == StoreValue::Type::String;
}
const std::int64_t * StoreValue::asInteger() const
{
return this->isInteger() ? &this->pointer.integer : nullptr;
}
const std::string * StoreValue::asString() const
{
return this->isString() ? this->pointer.string : nullptr;
}
void StoreValue::copyTo(StoreValue & other) const
{
other.~StoreValue();
other.valueType = this->valueType;
other.sizeVal = this->sizeVal;
other.pointer = {0};
switch (this->valueType)
{
case StoreValue::Type::Integer:
{
other.pointer.integer = this->pointer.integer;
break; //nop
}
case StoreValue::Type::String:
{
auto ptr = std::make_unique<std::string>();
*ptr = *this->pointer.string;
other.pointer.string = ptr.release();
break;
}
default:
break;
}
}
} | true |
2aa9490eb7f3be725f1c07257e1f3fc8ee09e12c | C++ | rock4on/Atm | /Atm.h | UTF-8 | 663 | 2.9375 | 3 | [] | no_license | #pragma once
#include <map>
#include "Bill.h"
using std::map;
class Atm
{
public:
Atm() = default;
Atm(map<Bill::bill, int> bills) : num_of_Bills(bills) { recalculate_ballance(); };
int recalculate_ballance();
Atm* add_Bill(Bill::bill b, int quantity);
float get_balance();
float extract(float sum);
static Atm* valueOf(Atm& v);
private:
//0-10 l
Atm(const Atm& at) = default;
map<Bill::bill, int> num_of_Bills
{
{ Bill::bill::Lei_10,0 },
{ Bill::bill::Lei_100,0 },
{ Bill::bill::Lei_200,0 },
{ Bill::bill::Lei_500,0 },
{ Bill::bill::Lei_5,0 },
{ Bill::bill::Lei_50,0 },
};
float balance=0;
};
| true |
91b6b38d5dd4a0f7e70c793843b8050ba8a210db | C++ | bfMendonca/SFND_Lidar_Obstacle_Detection | /src/quiz/cluster/kdtree.h | UTF-8 | 2,740 | 3.71875 | 4 | [] | no_license | /* \author Aaron Brown */
// Quiz on implementing kd tree
#include "../../render/render.h"
// Structure to represent node of kd tree
struct Node
{
std::vector<float> point;
int id;
Node* left;
Node* right;
int depth;
Node(std::vector<float> arr, int setId, int _depth = 0 )
: point(arr), id(setId), left(NULL), right(NULL), depth( _depth )
{}
void insert( std::vector<float> p, int setId ) {
Node** n;
if( p[ depth % point.size() ] < point[ depth % point.size() ] ) {
n = &left;
}else {
n = &right;
}
if( *n == NULL ) {
*n = new Node( p, setId, depth + 1 );
}else {
(*n)->insert( p, setId );
}
}
};
struct KdTree
{
Node* root;
KdTree()
: root(NULL)
{}
void insert(std::vector<float> point, int id)
{
// TODO: Fill in this function to insert a new point into the tree
// the function should create a new node and place correctly with in the root
//Ok so, actually, we are at the "root", let's just insert.
if( root == NULL ) {
root = new Node( point, id );
}else {
//Not the root, let's find out where to place
root->insert( point, id );
}
}
bool isInside( const std::vector<float> & c, float l, const std::vector<float> & p ) {
//Check if p is within of the box of center c and l size
for ( int i = 0; i < p.size(); ++ i ) {
if( !( p[i] >= ( c[i] -l ) && p[i] <= ( c[i] + l ) ) ) {
//If any of this dimensional check are false, we are outsied box
return false;
}
}
return true;
}
float distance( const std::vector< float > &p1, const std::vector< float > &p2 ) {
//Euclidian distance, just another helper function
float lenght = 0;
for( int i = 0; i < p1.size(); ++i ) {
lenght += pow( p1[i] - p2[i], 2 );
}
return sqrt( lenght );
}
void explore( Node *node, std::vector<float> target, float distanceTol, std::vector<int> &ids ) {
//Verify if node is valid. NULL -> we hit a "leaf", with nothing else to explore.
if( node == NULL )
return;
//Verify if the node point is within distance
if( isInside( target, distanceTol, node->point ) ) {
if( distance( node->point, target ) <= distanceTol ) {
ids.push_back( node->id );
}
}
size_t coord = node->depth % ( node->point.size() );
if( ( target[coord] ) < ( node->point[coord] + distanceTol ) ) {
explore( node->left, target, distanceTol, ids );
}
if( ( target[coord] ) > ( node->point[coord] - distanceTol ) ) {
explore( node->right, target, distanceTol, ids );
}
}
// return a list of point ids in the tree that are within distance of target
std::vector<int> search(std::vector<float> target, float distanceTol)
{
std::vector<int> ids;
explore( root, target, distanceTol, ids );
return ids;
}
};
| true |
417226351baceefb1e36e7dd10b5d3af9a61b7de | C++ | bin3/balgo | /src/balgo/container/min_queue.h | UTF-8 | 1,710 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2013 Binson Zhang.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Binson Zhang <bin183cs@gmail.com>
* @date 2013-1-27
*/
#ifndef MIN_QUEUE_H_
#define MIN_QUEUE_H_
#include <deque>
namespace toystl {
/**
* @brief Queue with minimum operator
*/
template<typename T>
class MinQueue {
public:
void Push(const T& x) {
q_.push_back(x);
while (!sq_.empty() && sq_.back() > x) {
sq_.pop_back();
}
sq_.push_back(x);
}
void Pop() {
if (!q_.empty()) {
if (q_.front() == sq_.front()) sq_.pop_front();
q_.pop_front();
}
}
T Front() const {
if (!q_.empty()) return q_.front();
return T();
}
std::size_t Size() const {
return q_.size();
}
bool Empty() const {
return q_.empty();
}
T Min() const {
if (!sq_.empty()) return sq_.front();
return T();
}
private:
std::deque<T> q_;
std::deque<T> sq_;
};
} /* namespace toystl */
#endif /* MIN_QUEUE_H_ */
| true |
3aeffc1506dcaf2bef48f62c8c815e488f3c7940 | C++ | diantaowang/cocoding | /963_min_area_free_rect.cc | UTF-8 | 1,867 | 2.78125 | 3 | [] | no_license | #include <cmath>
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <iostream>
#include <tuple>
#include <queue>
#include <stack>
#include <unordered_map>
using namespace::std;
class Solution {
public:
double minAreaFreeRect(vector<vector<int>>& points) {
int n = points.size();
unsigned long long area = UINT64_MAX;
unordered_map<unsigned, unordered_map<long long,vector<pair<int, int>>>> edges;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
unsigned len = pow(points[i][0] - points[j][0], 2) + pow(points[i][1] - points[j][1], 2);
long long pos = (long long)(points[i][0] + points[j][0]) << 32 | (points[i][1] + points[j][1]);
edges[len][pos].push_back({i, j});
}
}
for (auto iter = edges.begin(); iter != edges.end(); ++iter) {
auto end2 = iter->second.end();
for (auto iter2 = iter->second.begin(); iter2 != end2; ++iter2) {
int size = iter2->second.size();
for (int i = 0; i < size; ++i) {
for (int j = i + 1; j < size; ++j) {
int x = iter2->second[i].first;
int y = iter2->second[i].second;
int z = iter2->second[j].first;
unsigned long long v0 = pow(points[x][0] - points[z][0], 2) + pow(points[x][1] - points[z][1], 2);
unsigned long long v1 = pow(points[y][0] - points[z][0], 2) + pow(points[y][1] - points[z][1], 2);
area = min(area, v0 * v1);
}
}
}
}
if (area == UINT64_MAX)
return 0.0;
else
return sqrt(area);
}
};
int main()
{
return 0;
}
| true |
7d4000ed4d7ac7f2b385c99851891c7b6c201353 | C++ | iflei/Data_Structure | /Hash _Bucket/HashTable.h | GB18030 | 6,381 | 3.40625 | 3 | [] | no_license | #include <vector>
using namespace std;
//
template <typename K>
struct HashFunc
{
size_t operator()(const K& key)
{
return key;
}
};
//ػstring
template <>
struct HashFunc<string>
{
static size_t BKDRHash(const char* str)
{
unsigned int seed = 131;
unsigned int hash = 0;
while (*str)
{
hash = hash * seed + (*str++);
}
return(hash & 0x7FFFFFFF);
}
size_t operator()(const string& str)
{
return BKDRHash(str.c_str());
}
};
template <typename K, typename V>
struct HashNode
{
HashNode(const pair<K, V>& kv)
:_kv(kv)
, _next(NULL)
, _prev(NULL)
{}
pair<K, V> _kv;
HashNode<K, V>* _next;
HashNode<K, V>* _prev; //--
};
//
template <typename K, typename V, typename HashFunc = HashFunc<K>> class HashTable;
template <typename K, typename V, typename Ref, typename Ptr>
struct __HashTableIterator
{
typedef HashNode<K, V> Node;
typedef __HashTableIterator<K, V, Ref, Ptr> Self;
__HashTableIterator(Node* node, HashTable<K, V>* ht)
:_node(node)
, _ht(ht)
{}
//Refpair&
Ref operator*()
{
return _node->_kv;
}
//Ptr&pair
Ptr operator->()
{
return &_node->_kv;
}
//Selfǵ౾Self&ǵǰ
Self& operator++() //ǰ++
{
_node = _Next(_node);
return *this;
}
Self& operator--() //ǰ--
{
_node = _Prev(_node);
return *this;
}
bool operator!=(__HashTableIterator<K, V, Ref, Ptr>& it)
{
return _node != it._node;
}
protected:
Node* _Next(Node* node)
{
Node* next = _node->_next;
if (next) //nextֱӷ
{
return next;
}
else //nextڣһ_table[index]ʼҷǿսڵ
{
size_t index = _ht->_HashFunc(node->_kv.first) + 1;
for (; index < _ht->_table.size(); ++index)
{
next = _ht->_table[index];
if (next)
{
return next;
}
}
}
//nextΪգindex==_ht->_table.size()ûforѭ
return NULL;
}
Node* _Prev(Node* node)
{
Node* prev = _node->_prev;
if (prev) //prevֱӷ
{
return prev;
}
else //prevڣһ_table[index]ʼҷǿսڵ
{
int index = _ht->_HashFunc(node->_kv.first) - 1;
for (; index >= 0; --index)
{
prev = _ht->_table[index];
if (prev)
{
return prev;
}
}
}
//prevΪգindex < 0 ûforѭ
return NULL;
}
private:
Node* _node;//ָNode
HashTable<K, V>* _ht; //ͨthisָ봫ҪHashTable_size, _table_HashFunc()
};
template <typename K, typename V, typename HashFunc = HashFunc<K>>
class HashTable
{
typedef HashNode<K, V> Node;
public:
typedef __HashTableIterator<K, V, pair<K, V>&, pair<K, V>*> Iterator;
typedef __HashTableIterator<K, V, const pair<K, V>&, const pair<K, V>*> ConstIterator;
//__HashTableIteratorҪ_HashFuncԱΪԪ
friend struct Iterator;
friend struct ConstIterator;
public:
HashTable(size_t size)
:_size(0)
{
_table.resize(_GetNewSize(size));
}
~HashTable()
{
//ϣͰ
for (size_t i = 0; i < _table.size(); ++i)
{
Node* cur = _table[i];
while (cur)
{
Node* del = cur;
cur = cur->_next;
delete del;
}
_table[i] = NULL;
}
}
pair<Iterator, bool> Insert(const pair<K, V>& kv)
{
//
_CheckCapacity();
size_t index = _HashFunc(kv.first);
//ǷѴ
Node* cur = _table[index];
while (cur)
{
if (cur->_kv.first == kv.first)
return make_pair(Iterator(cur, this), false);
cur = cur->_next;
}
//ڽͷ
Node* tmp = new Node(kv);
tmp->_next = _table[index];
_table[index] = tmp;
++_size;
return make_pair(Iterator(tmp, this), true);
}
Iterator Find(const K& key)
{
size_t index = _HashFunc(key);
Node* cur = _table[index];
while (cur)
{
if (cur->_kv.first == key)
return Iterator(cur, this);
cur = cur->_next;
}
return Iterator(NULL, this);
}
bool Erase(const K& key)
{
size_t index = _HashFunc(key);
Node* prev = NULL;
Node* cur = _table[index];
while (cur)
{
//ҵ
if (cur->_kv.first == key)
{
//ɾͷڵ
if (prev == NULL)
{
delete cur;
_table[index] = NULL;
}
else
{
prev->_next = cur->_next;
delete cur;
}
return true;
}
prev = cur;
cur = cur->_next;
}
//ûҵ
return false;
}
Iterator Begin()
{
for (size_t i = 0; i < _table.size(); ++i)
{
if (_table[i]) //_tableһǿָ
{
return Iterator(_table[i], this);
}
}
return Iterator(NULL, this);
}
Iterator End()
{
return Iterator(NULL, this);
}
V& operator[](const K& key)
{
pair<Iterator, bool> ret = Insert(make_pair(key, V()));
return ret.first->second;
//ret.firstIteratorIterator->
}
protected:
void _CheckCapacity()
{
//ӵ1Ҫݣƽÿڵ¹һ
if (_size == _table.size())
{
//sizeɹ캯
HashTable<K, V, HashFunc> tmp(_table.size());
for (size_t i = 0; i < _table.size(); ++i)
{
if (_table[i]) //нڵ
{
Node* cur = _table[i];
while (cur)
{
//ĹInsert
tmp.Insert(cur->_kv);
cur = cur->_next;
}
}
}
_Swap(tmp);//ִд
}
}
void _Swap(HashTable<K, V, HashFunc>& ht)
{
swap(_size, ht._size); //_sizeʵһ
_table.swap(ht._table);//vectorswap
}
size_t _HashFunc(const K& key)
{
HashFunc hf;
size_t hash = hf(key);
return hash % _table.size();
}
size_t _GetNewSize(size_t num) //ϣСܼٹϣͻ
{
const int _PrimeSize = 28;
static const unsigned long _PrimeList[_PrimeSize] = {
53ul, 97ul, 193ul, 389ul, 769ul,
1543ul, 3079ul, 6151ul, 12289ul, 24593ul,
49157ul, 98317ul, 196613ul, 393241ul, 786433ul,
1572869ul, 3145739ul, 6291469ul, 12582917ul,
25165843ul, 50331653ul, 100663319ul, 201326611ul, 402653189ul,
805306457ul, 1610612741ul, 3221225473ul, 4294967291ul
};
for (int i = 0; i < _PrimeSize; ++i)
{
if (_PrimeList[i] > num)
return _PrimeList[i];
}
return _PrimeList[_PrimeSize - 1];
}
private:
vector<Node*> _table;
size_t _size;
};
| true |
d9996637eab48c016a804402db286959a12026fd | C++ | wzj1988tv/code-imitator | /data/dataset_2017/dataset_2017_8_formatted/OKuang/3264486_5654742835396608_OKuang.cpp | UTF-8 | 1,615 | 2.609375 | 3 | [] | no_license | #include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 1010;
class CNode {
public:
int len, l, r;
CNode() {}
CNode(int _len, int _l, int _r) : len(_len), l(_l), r(_r) {}
bool operator<(const CNode &b) const {
if (len != b.len)
return len < b.len;
else
return l > b.l;
}
bool operator>(const CNode &b) const { return !((*this) < b); }
};
int n, k;
bool vis[maxn];
priority_queue<CNode> PriorityQ;
inline void solve() {
memset(vis, false, sizeof(vis));
while (!PriorityQ.empty())
PriorityQ.pop();
scanf("%d%d", &n, &k);
int mid;
CNode cur, left, right;
PriorityQ.push(CNode(n, 0, n - 1));
for (int i = 0; i < k; i++) {
cur = PriorityQ.top();
PriorityQ.pop();
mid = (cur.l + cur.r) >> 1;
vis[mid] = true;
if (cur.len == 1)
continue;
right.l = mid + 1;
right.r = cur.r;
right.len = right.r - right.l + 1;
left.l = cur.l;
left.r = mid - 1;
left.len = left.r - left.l + 1;
if (left.l <= left.r)
PriorityQ.push(left);
if (right.l <= right.r)
PriorityQ.push(right);
}
int i, cntl = 0, cntr = 0;
i = mid;
while (--i >= 0 && !vis[i])
cntl++;
i = mid;
while (++i < n && !vis[i])
cntr++;
printf("%d %d\n", max(cntl, cntr), min(cntl, cntr));
}
int main() {
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int T;
scanf("%d", &T);
for (int tcase = 1; tcase <= T; tcase++) {
printf("Case #%d: ", tcase);
solve();
}
return 0;
} | true |
0471fc202e9acddeee0f9923ad2d1c206ae79e13 | C++ | Ediolot/IA-Coche | /include/scene.hpp | UTF-8 | 1,849 | 2.625 | 3 | [
"MIT"
] | permissive | #ifndef SCENE_HPP
#define SCENE_HPP
#include <allegro5/allegro.h>
#include "common.hpp"
#include "map.hpp"
#include "button.hpp"
#include "scrollbar.hpp"
#include "selector.hpp"
#include "numericSelector.hpp"
class scene {
const double default_animation_time_ = 0.2;
public: // Thread sync
ALLEGRO_MUTEX *mutex;
ALLEGRO_COND *cond;
bool ready;
private:
map tile_map_; // Tiles map
double map_separation_; // Tiles map's separation from the borders of the window
double screen_w_;
double screen_h_;
bool show_menu_;
bool isplaying_;
bool istracking_;
bool esc_was_pressed_;
// BUTTONS WITH IMAGES
button restart_;
button play_;
button random_;
button step_;
button tracking_;
// BUTTONS WITH TEXT
button quit_;
// LABELS
label obstacles_text_;
// LIST SELECTORS
selector algorithm_;
// NUMERIC SELECTORS
numericSelector width_;
numericSelector height_;
// BUG: No es posible crear dos label en la misma clase
// LABELS
label info_;
int fps_;
uint result_;
double time_;
// SCROLLBARS
scrollbar speed_;
scrollbar obstacles_;
public:
scene(const double screen_w, const double screen_h, const double map_separation);
virtual ~scene();
// Dibuja los elementos de la escena
void draw();
// Mueve la escena en x o y
void moveX(const double x);
void moveY(const double y);
void resize(const double w, const double h);
void update();
void updateAlgorithm();
private:
void showMenu(bool show);
void updateFPS();
};
#endif
| true |
701e42d9b9a24f30f8471f7d67d10b8f22ceb6f3 | C++ | claudiahwong/cs184-an-eh-sp10 | /rayTracer/Color.h | UTF-8 | 2,218 | 3.609375 | 4 | [] | no_license | #pragma once
class Color
{
public:
/* Members */
float r, g, b;
/* Constructors */
Color(void);
Color(float red, float green, float blue);
~Color(void);
/* Methods */
void setEqual(Color dest);
/* Operators */
const Color operator+(const Color &c1) {
Color result = Color(c1.r + this->r, c1.g + this->g, c1.b + this->b);
if (result.r > 1) result.r = 1;
if (result.g > 1) result.g = 1;
if (result.b > 1) result.b = 1;
return result;
}
const Color operator+=(const Color &c1) {
this->r+=c1.r;
this->g+=c1.g;
this->b+=c1.b;
if(this->r > 1) this->r = 1;
if(this->g > 1) this->g = 1;
if(this->b > 1) this->b = 1;
return *this;
}
const Color operator-(const Color &c1) {
return Color(this->r - c1.r, this->g - c1.g, this->b - c1.b);
}
const Color operator-=(const Color &c1) {
this->r-=c1.r;
this->g-=c1.g;
this->b-=c1.b;
return *this;
}
const Color operator*(const Color &c1) {
return Color(c1.r * this->r, c1.g * this->g, c1.b * this->b);
}
const Color operator*=(const Color &c1) {
this->r*=c1.r;
this->g*=c1.g;
this->b*=c1.b;
return *this;
}
const Color operator*(const double &num) {
return Color(num * this->r, num * this->g, num* this->b);
}
const Color operator*=(const double &num) {
this->r*=num;
this->g*=num;
this->b*=num;
return *this;
}
const Color operator/(const Color &c1) {
return Color(this->r / c1.r, this->g / c1.g, this->b / c1.b);
}
const Color operator/=(const Color &c1) {
this->r/=c1.r;
this->g/=c1.g;
this->b/=c1.b;
return *this;
}
const Color operator/(const double &d) {
return Color(this->r / d, this->g / d, this->b / d);
}
const Color operator/=(const double &d) {
this->r/=d;
this->g/=d;
this->b/=d;
return *this;
}
const bool operator>(const double &num) {
return (this->r > num || this->g > num || this->b > num);
}
const bool operator==(const Color &c1) {
return (this->r == c1.r && this->g == c1.g && this->b == c1.b);
}
const bool operator!=(const Color &c1) {
return (this->r != c1.r || this->g != c1.g || this->b != c1.b);
}
};
| true |
4c72187afc742b35908c9125013b7c42da0f5161 | C++ | rayjan0114/python_call_c_cxx_demo2 | /cxxFunc.cpp | UTF-8 | 899 | 2.859375 | 3 | [] | no_license | /*========================================================
這是關於 python ctypes call C/C++ opencv 的範例
會先從 python BGR uint8 numpy (H,W,3) <----> C++ cv::Mat
======================================*/
#include <cstdlib>
#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc/types_c.h>
#include <vector>
//=====================================================================================================
extern "C" {
unsigned char* donothing( unsigned char* ptr, int H, int W ) {
cv::Mat img( H, W, CV_8UC3, ptr );
unsigned char* buffer = ( unsigned char* )malloc( sizeof( unsigned char ) * H * W * 3 );
memcpy( buffer, img.data, H * W * 3 );
return buffer;
}
void release( unsigned char* data ) {
std::cout << "release " << std::addressof( data ) << " !!" << std::endl;
free( data );
} // end_release
} // end
| true |
2b467c1bd32c4ba65ea16de42fb6e2ec53be4433 | C++ | Bdegraaf1234/AdventOfCode-019 | /AdventOfCodeLib/Tile.h | UTF-8 | 678 | 2.6875 | 3 | [] | no_license | #pragma once
#ifdef ADVENTOFCODELIB_EXPORTS
#define ADVENTOFCODELIB_API __declspec(dllexport)
#else
#define ADVENTOFCODELIB_API __declspec(dllimport)
#endif
using namespace::std;
#include <string>
#include <vector>
#include <map>
class ADVENTOFCODELIB_API Tile
{
public:
int X;
int Y;
char Id;
Tile(int tileInstructions[]) {
X = tileInstructions[0];
Y = tileInstructions[1];
if (tileInstructions[2] == 0)
{
Id = ' ';
}
else if (tileInstructions[2] == 1)
{
Id = '|';
}
else if (tileInstructions[2] == 2)
{
Id = 'D';
}
else if (tileInstructions[2] == 3)
{
Id = '_';
}
else if (tileInstructions[2] == 4)
{
Id = 'D';
}
}
};
| true |
5f7c9b5b9575b8a1389e0f936be492a086348413 | C++ | Hwanghoseon/algorithm_test | /1032.cpp | UTF-8 | 512 | 2.828125 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
const int MAX = 50;
int n;
string st[MAX];
void input() {
cin >> n;
for (int i = 0; i < n; i++)
cin >> st[i];
}
void compare() {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < st[0].size(); j++) {
if (st[i][j] != st[i + 1][j])
st[i + 1][j] = '?';
}
}
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
input();
compare();
for (int i = 0; i < st[0].size(); i++)
cout << st[n - 1][i];
return 0;
}
| true |
52c3e8aded4aeba9137191707931f265c2d81a0c | C++ | SweepFlaw/demo | /demodata/wrongCode1.cpp | UTF-8 | 608 | 2.546875 | 3 | [
"MIT"
] | permissive | // codeforces 1204B - 59154860
// human solve time: 582s
#include <bits/stdc++.h>
using namespace std;
const int N = 1234;
int a[N], b[N];
int n, l, r;
int main() {
scanf("%d %d %d", &n, &l, &r);
for (int i = 0; i < n; i++)
a[i] = b[i] = 1;
int mt = 2;
for (int i = 0; i < l - 1; i++) {
a[i] = mt;
mt *= 2;
}
mt = 2;
for (int i = 0; i < r - 1; i++) {
b[i] = mt;
mt *= 2;
}
if (r - 2 >= 0)
for (int i = r - 1; i < n - 1; i++)
b[i] = a[r - 2];
int x = accumulate(a, a + n, 0);
int y = accumulate(b, b + n, 0);
printf("%d %d\n", x, y);
return 0;
}
| true |
9f49f219639abbc50fb62eda31ffd4c9d72d027b | C++ | SamiKhan-cse19/borgo-sample | /PingPong/PingPong.cpp | UTF-8 | 14,088 | 2.75 | 3 | [] | no_license | #include "PingPong.h"
void PingPong::handlePlayerCollision(bool isPlayerLeft)
{
std::pair<int, int> pb = ball.getTopLeftPos();
if (isPlayerLeft) {
std::pair<int, int> pl = playerL.getTopLeftPos();
switch (pb.second - pl.second) {
case -2:
case -1:
case 0:
ball.setAngle(Ball::Angle::_60d);
break;
case 1:
ball.setAngle(Ball::Angle::_45d);
break;
case 2:
ball.setAngle(Ball::Angle::_30d);
break;
case 3:
ball.setAngle(Ball::Angle::_0d);
break;
case 4:
ball.setAngle(Ball::Angle::_330d);
break;
case 5:
ball.setAngle(Ball::Angle::_315d);
break;
case 6:
case 7:
case 8:
ball.setAngle(Ball::Angle::_300d);
break;
}
}
else {
std::pair<int, int> pr = playerR.getTopLeftPos();
switch (pb.second - pr.second) {
case -2:
case -1:
case 0:
ball.setAngle(Ball::Angle::_120d);
break;
case 1:
ball.setAngle(Ball::Angle::_135d);
break;
case 2:
ball.setAngle(Ball::Angle::_150d);
break;
case 3:
ball.setAngle(Ball::Angle::_180d);
break;
case 4:
ball.setAngle(Ball::Angle::_210d);
break;
case 5:
ball.setAngle(Ball::Angle::_225d);
break;
case 6:
case 7:
case 8:
ball.setAngle(Ball::Angle::_240d);
break;
}
}
}
void PingPong::handleWallCollision(bool isTopWall)
{
std::pair<int, int> pb = ball.getTopLeftPos();
if (isTopWall) {
switch (ball.getAngle()) {
case Ball::Angle::_60d:
ball.setAngle(Ball::Angle::_300d);
break;
case Ball::Angle::_45d:
ball.setAngle(Ball::Angle::_315d);
break;
case Ball::Angle::_30d:
ball.setAngle(Ball::Angle::_330d);
break;
case Ball::Angle::_120d:
ball.setAngle(Ball::Angle::_240d);
break;
case Ball::Angle::_135d:
ball.setAngle(Ball::Angle::_225d);
break;
case Ball::Angle::_150d:
ball.setAngle(Ball::Angle::_210d);
break;
}
}
else {
switch (ball.getAngle()) {
case Ball::Angle::_300d:
ball.setAngle(Ball::Angle::_60d);
break;
case Ball::Angle::_315d:
ball.setAngle(Ball::Angle::_45d);
break;
case Ball::Angle::_330d:
ball.setAngle(Ball::Angle::_30d);
break;
case Ball::Angle::_240d:
ball.setAngle(Ball::Angle::_120d);
break;
case Ball::Angle::_225d:
ball.setAngle(Ball::Angle::_135d);
break;
case Ball::Angle::_210d:
ball.setAngle(Ball::Angle::_150d);
break;
}
}
}
PingPong::PingPong(World& world, ScoreBoard& scoreboard) : Engine(world, scoreboard), delay(0.03f), timer(0.0f),
playerL(1, this), playerR(0, this), ball(1, this), isIdle(0)
{
bgcolor = sf::Color::Black;
width = world.getWidth();
height = world.getHeight();
}
int PingPong::getWidth()
{
return width;
}
int PingPong::getHeight()
{
return height;
}
void PingPong::start()
{
sf::Clock clock;
float dt;
while (window.isOpen()) {
dt = clock.restart().asSeconds();
clear();
input();
update(dt);
render();
}
}
void PingPong::clear()
{
world.clearObject(ball.getBallPosition());
world.clearObject(playerL.getPlayerPosition());
world.clearObject(playerR.getPlayerPosition());
scoreboard.clearBoard();
}
void PingPong::input()
{
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) window.close();
if (event.type == sf::Event::KeyPressed) {
isIdle = 0;
switch (event.key.code) {
case sf::Keyboard::Escape:
window.close();
break;
case sf::Keyboard::Up:
playerR.moveUp();
break;
case sf::Keyboard::Down:
playerR.moveDown();
break;
case sf::Keyboard::W:
playerL.moveUp();
break;
case sf::Keyboard::S:
playerL.moveDown();
break;
}
}
}
}
void PingPong::update(float& dt)
{
timer += dt;
if (!isIdle && timer > delay) {
try {
ball.move();
}
catch (Ball::Collision col) {
switch (col.collisionType) {
case Ball::Collision::CollisionType::LeftPlayer:
handlePlayerCollision(1);
break;
case Ball::Collision::CollisionType::RightPlayer:
handlePlayerCollision(0);
break;
case Ball::Collision::CollisionType::TopWall:
handleWallCollision(1);
break;
case Ball::Collision::CollisionType::BottomWall:
handleWallCollision(0);
break;
}
}
catch (Ball::GameOver game) {
if (game.gameWinner == Ball::GameOver::GameWinner::LeftPlayer) {
ball = Ball(1, this);
playerL.incrementScore();
}
else {
ball = Ball(0, this);
playerR.incrementScore();
}
isIdle = 1;
playerL.resetPosition(1);
playerR.resetPosition(0);
}
timer = 0;
}
world.addObject(playerL.getPlayerColor());
world.addObject(playerR.getPlayerColor());
world.addObject(ball.getBallColor());
world.update();
scoreboard.addScore(std::pair<std::string, int>("P1", playerL.getScore()));
scoreboard.addScore(std::pair<std::string, int>("P2", playerR.getScore()));
scoreboard.update();
}
void PingPong::render()
{
window.clear();
window.draw(world);
window.draw(scoreboard);
window.display();
}
PingPongPlayer::PingPongPlayer(bool isPlayerLeft, PingPong* engine) : score(0)
{
this->engine = engine;
color = sf::Color::Cyan;
if (isPlayerLeft) {
for (int i = 0; i < 2; i++) {
for (int j = 12; j < 20; j++) {
position.insert(std::pair<int, int>(i, j));
}
}
}
else {
for (int i = 54; i < 56; i++) {
for (int j = 12; j < 20; j++) {
position.insert(std::pair<int, int>(i, j));
}
}
}
}
int PingPongPlayer::getScore() const
{
return score;
}
std::set<std::pair<int, int>> PingPongPlayer::getPlayerPosition() const
{
return position;
}
std::map<std::pair<int, int>, sf::Color> PingPongPlayer::getPlayerColor() const
{
std::map<std::pair<int, int>, sf::Color> ret;
for (auto p : position) {
ret[p] = color;
}
return ret;
}
std::pair<int, int> PingPongPlayer::getTopLeftPos() const
{
std::pair<int, int> ret(INT_MAX, INT_MAX);
for (auto p : position) {
ret = std::min(ret, p);
}
return ret;
}
void PingPongPlayer::moveUp()
{
std::set<std::pair<int, int>> newPos;
for (auto p : position) {
std::pair<int, int> np(p.first, p.second - 1);
if (np.second < 0) return;
newPos.insert(np);
}
position = newPos;
}
void PingPongPlayer::moveDown()
{
std::set<std::pair<int, int>> newPos;
for (auto p : position) {
p.second++;
if (p.second >= engine->getHeight()) return;
newPos.insert(p);
}
position = newPos;
}
void PingPongPlayer::resetPosition(bool isPlayerLeft)
{
position.clear();
if (isPlayerLeft) {
for (int i = 0; i < 2; i++) {
for (int j = 12; j < 20; j++) {
position.insert(std::pair<int, int>(i, j));
}
}
}
else {
for (int i = 54; i < 56; i++) {
for (int j = 12; j < 20; j++) {
position.insert(std::pair<int, int>(i, j));
}
}
}
}
void PingPongPlayer::incrementScore()
{
score++;
}
void Ball::moveLeft()
{
std::set<std::pair<int, int>> newPos;
for (auto p : position) {
std::pair<int, int> np(p.first - 1, p.second);
for (auto pl : engine->playerL.getPlayerPosition()) {
if (pl == np && getTopLeftPos().first - engine->playerL.getTopLeftPos().first == 2) {
throw Collision(Collision::CollisionType::LeftPlayer);
}
}
if (np.first <= 0) throw GameOver(GameOver::GameWinner::RightPlayer);
newPos.insert(np);
}
position = newPos;
}
void Ball::moveRight()
{
std::set<std::pair<int, int>> newPos;
for (auto p : position) {
std::pair<int, int> np(p.first + 1, p.second);
for (auto pr : engine->playerR.getPlayerPosition()) {
if (pr == np && engine->playerR.getTopLeftPos().first - getTopLeftPos().first == 2) {
throw Collision(Collision::CollisionType::RightPlayer);
}
}
if (np.first >= engine->getWidth() - 1) throw GameOver(GameOver::GameWinner::LeftPlayer);
newPos.insert(np);
}
position = newPos;
}
void Ball::moveUp()
{
std::set<std::pair<int, int>> newPos;
for (auto p : position) {
std::pair<int, int> np(p.first, p.second - 1);
if (np.second < 0) throw Collision(Collision::CollisionType::TopWall);
newPos.insert(np);
}
position = newPos;
}
void Ball::moveDown()
{
std::set<std::pair<int, int>> newPos;
for (auto p : position) {
std::pair<int, int> np(p.first, p.second + 1);
if (np.second >= engine->getHeight()) throw Collision(Collision::CollisionType::BottomWall);
newPos.insert(np);
}
position = newPos;
}
void Ball::setDirection(Angle a)
{
while (!direction.empty()) direction.pop();
switch (a) {
case _0d:
direction.push(TransformDirection::Right);
break;
case _30d:
direction.push(TransformDirection::Right);
direction.push(TransformDirection::Right);
direction.push(TransformDirection::Top);
break;
case _45d:
direction.push(TransformDirection::Right);
direction.push(TransformDirection::Top);
break;
case _60d:
direction.push(TransformDirection::Right);
direction.push(TransformDirection::Top);
direction.push(TransformDirection::Top);
break;
case _120d:
direction.push(TransformDirection::Left);
direction.push(TransformDirection::Top);
direction.push(TransformDirection::Top);
break;
case _135d:
direction.push(TransformDirection::Left);
direction.push(TransformDirection::Top);
break;
case _150d:
direction.push(TransformDirection::Left);
direction.push(TransformDirection::Left);
direction.push(TransformDirection::Top);
break;
case _180d:
direction.push(TransformDirection::Left);
break;
case _210d:
direction.push(TransformDirection::Left);
direction.push(TransformDirection::Left);
direction.push(TransformDirection::Bottom);
break;
case _225d:
direction.push(TransformDirection::Left);
direction.push(TransformDirection::Bottom);
break;
case _240d:
direction.push(TransformDirection::Left);
direction.push(TransformDirection::Bottom);
direction.push(TransformDirection::Bottom);
break;
case _300d:
direction.push(TransformDirection::Right);
direction.push(TransformDirection::Bottom);
direction.push(TransformDirection::Bottom);
break;
case _315d:
direction.push(TransformDirection::Right);
direction.push(TransformDirection::Bottom);
break;
case _330d:
direction.push(TransformDirection::Right);
direction.push(TransformDirection::Right);
direction.push(TransformDirection::Bottom);
break;
}
}
Ball::Ball(bool isPlayerLeft, PingPong* engine)
{
this->engine = engine;
color = sf::Color::Yellow;
if (isPlayerLeft) {
for (int i = 2; i < 4; i++) {
for (int j = 14; j < 16; j++) {
position.insert(std::pair<int, int>(i, j));
}
}
setAngle(Angle::_45d);
}
else {
for (int i = 52; i < 54; i++) {
for (int j = 14; j < 16; j++) {
position.insert(std::pair<int, int>(i, j));
}
}
setAngle(Angle::_135d);
}
}
Ball::Angle Ball::getAngle()
{
return angle;
}
void Ball::setAngle(Angle a)
{
this->angle = a;
setDirection(a);
}
std::set<std::pair<int, int>> Ball::getBallPosition() const
{
return position;
}
std::map<std::pair<int, int>, sf::Color> Ball::getBallColor() const
{
std::map<std::pair<int, int>, sf::Color> ret;
for (auto p : position) {
ret[p] = color;
}
return ret;
}
std::pair<int, int> Ball::getTopLeftPos() const
{
std::pair<int, int> ret(INT_MAX, INT_MAX);
for (auto p : position) {
ret = std::min(ret, p);
}
return ret;
}
void Ball::move()
{
TransformDirection dir = direction.front();
switch (dir) {
case TransformDirection::Left:
moveLeft();
break;
case TransformDirection::Right:
moveRight();
break;
case TransformDirection::Top:
moveUp();
break;
case TransformDirection::Bottom:
moveDown();
break;
}
direction.pop();
direction.push(dir);
}
Ball::GameOver::GameOver(GameWinner winner) : gameWinner(winner)
{
}
Ball::Collision::Collision(CollisionType type) : collisionType(type)
{
}
| true |
b94dc82b1aa9acb312cbd3afe6f7a4d65e60040b | C++ | ThePhysicsGuys/Physics3D | /application/picker/selection.cpp | UTF-8 | 6,791 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "core.h"
#include "selection.h"
#include "application.h"
#include "view/screen.h"
#include "ecs/components.h"
namespace P3D::Application {
void Selection::recalculateSelection() {
this->boundingBox = std::nullopt;
for (auto entity : this->selection)
expandSelection(entity);
}
void Selection::expandSelection(const Engine::Registry64::entity_type& entity) {
IRef<Comp::Transform> transform = screen.registry.get<Comp::Transform>(entity);
if (transform.invalid())
return;
IRef<Comp::Hitbox> hitbox = screen.registry.get<Comp::Hitbox>(entity);
if (selection.empty() || !this->boundingBox.has_value()) {
if (hitbox.valid())
this->boundingBox = hitbox->getShape().getBounds();
else
this->boundingBox = BoundingBox(0.2, 0.2, .2);
} else {
IRef<Comp::Transform> referenceTransform = screen.registry.get<Comp::Transform>(selection[0]);
GlobalCFrame referenceFrame = referenceTransform->getCFrame();
CFrame relativeFrame = referenceFrame.globalToLocal(transform->getCFrame());
if (hitbox.valid()) {
BoundingBox rotatedBounds = hitbox->getShape().getBounds(relativeFrame.getRotation());
this->boundingBox = this->boundingBox->expanded(relativeFrame.getPosition() + rotatedBounds.min).expanded(relativeFrame.getPosition() + rotatedBounds.max);
} else {
this->boundingBox = this->boundingBox->expanded(boxShape(0.2, 0.2, 0.2).getBounds(relativeFrame.getRotation()));
}
}
}
bool Selection::empty() const {
return this->selection.empty();
}
std::size_t Selection::size() const {
return this->selection.size();
}
bool Selection::contains(const Engine::Registry64::entity_type& entity) const {
for(const Engine::Registry64::entity_type& found : selection)
if(found == entity)
return true;
return false;
}
bool Selection::isMultiSelection() const {
return size() > 1;
}
bool Selection::isSingleSelection() const {
return size() == 1;
}
Engine::Registry64::entity_type& Selection::operator[](int index) {
return this->selection[index];
}
void Selection::add(const Selection& other, bool recalculateBounds) {
for (const Engine::Registry64::entity_type& entity : other)
this->add(entity, recalculateBounds);
}
void Selection::remove(const Selection& other, bool recalculateBounds) {
for (const Engine::Registry64::entity_type& entity : other)
this->remove(entity, false);
if (recalculateBounds) {
this->boundingBox = std::nullopt;
for (const Engine::Registry64::entity_type entity : *this)
expandSelection(entity);
}
}
void Selection::add(const Engine::Registry64::entity_type& entity, bool recalculateBounds) {
auto iterator = std::find(this->selection.begin(), this->selection.end(), entity);
if (iterator != this->selection.end())
return;
this->selection.push_back(entity);
if (recalculateBounds)
expandSelection(entity);
}
void Selection::remove(const Engine::Registry64::entity_type& entity, bool recalculateBounds) {
if (entity == Engine::Registry64::null_entity)
return;
auto iterator = std::find(this->selection.begin(), this->selection.end(), entity);
if (iterator == this->selection.end())
return;
this->selection.erase(iterator);
if (recalculateBounds) {
this->boundingBox = std::nullopt;
for (const Engine::Registry64::entity_type entity : *this)
expandSelection(entity);
}
}
void Selection::toggle(const Engine::Registry64::entity_type& entity, bool recalculateBounds) {
auto iterator = std::find(this->selection.begin(), this->selection.end(), entity);
if (iterator == selection.end())
add(entity, recalculateBounds);
else
remove(entity, recalculateBounds);
}
void Selection::clear() {
this->selection.clear();
this->boundingBox = std::nullopt;
}
void Selection::translate(const Vec3& translation) {
for (auto entity : this->selection) {
IRef<Comp::Transform> transform = screen.registry.get<Comp::Transform>(entity);
if (transform.valid())
transform->translate(translation);
}
}
void Selection::rotate(const Vec3& normal, double angle) {
std::optional<GlobalCFrame> reference = getCFrame();
if (!reference.has_value())
return;
Rotation rotation = Rotation::fromRotationVector(angle * normal);
for (auto entity : this->selection) {
IRef<Comp::Transform> transform = screen.registry.get<Comp::Transform>(entity);
if (transform.valid()) {
//transform->rotate(normal, angle);
transform->rotate(rotation);
Vec3 delta = transform->getPosition() - reference->getPosition();
Vec3 translation = rotation * delta - delta;
transform->translate(translation);
}
}
}
void Selection::scale(const Vec3& scale) {
std::optional<GlobalCFrame> reference = getCFrame();
if (!reference.has_value())
return;
for (auto entity : this->selection) {
IRef<Comp::Transform> transform = screen.registry.get<Comp::Transform>(entity);
Vec3 delta = transform->getPosition() - reference->getPosition();
Vec3 translation = elementWiseMul(delta, scale - Vec3(1.0, 1.0, 1.0));
transform->translate(translation);
transform->scale(scale.x, scale.y, scale.z);
}
recalculateSelection();
}
std::optional<Shape> Selection::getHitbox() const {
if (this->selection.empty())
return std::nullopt;
if (this->size() == 1) {
IRef<Comp::Hitbox> hitbox = screen.registry.get<Comp::Hitbox>(this->selection[0]);
if (hitbox.invalid())
return std::nullopt;
return hitbox->getShape();
}
return boxShape(boundingBox->getWidth(), boundingBox->getHeight(), boundingBox->getDepth());
}
std::optional<GlobalCFrame> Selection::getCFrame() const {
if (this->selection.empty())
return std::nullopt;
IRef<Comp::Transform> transform = screen.registry.get<Comp::Transform>(this->selection[0]);
if (transform.invalid())
return std::nullopt;
return GlobalCFrame(transform->getCFrame().localToGlobal(this->boundingBox->getCenter()), transform->getRotation());
}
std::vector<Engine::Registry64::entity_type>::const_iterator Selection::begin() const {
return this->selection.begin();
}
std::vector<Engine::Registry64::entity_type>::const_iterator Selection::end() const {
return this->selection.end();
}
std::vector<Engine::Registry64::entity_type>::iterator Selection::begin() {
return this->selection.begin();
}
std::vector<Engine::Registry64::entity_type>::iterator Selection::end() {
return this->selection.end();
}
std::optional<Engine::Registry64::entity_type> Selection::first() const {
if (selection.empty())
return std::nullopt;
return selection[0];
}
std::optional<Engine::Registry64::entity_type> Selection::last() const {
if (selection.empty())
return std::nullopt;
return selection[selection.size() - 1];
}
}
| true |
729f8365fe3f323a422cde4bff11c7a71199a99a | C++ | KROIA/Projekte | /Intervalometer/Versionen/1.3.0/Intervalometer.h | ISO-8859-1 | 2,440 | 2.53125 | 3 | [] | no_license | #ifndef INTERVALOMETER_H
#define INTERVALOMETER_H
#include "Arduino.h"
#include "button.h"
#include "led.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
enum modes
{
IntervallSetzen = 0,
HelligkeitSetzen = 1,
AufnahmezeitSetzen = 2,
Kontrolle1 = 3,
Running1 = 4,
Abschlussinfo1 = 5,
Hauptmenue = 6,
ToleranzSetzen = 7,
TaktSetzen = 8,
Kontrolle2 = 9,
Running2 = 10,
Abschlussinfo2 = 11,
countdown = 12
};
class Intervalometer
{
public:
Intervalometer(int bOK,int bUp,int bDown,int blUp,int blDown,int bback,boolean logicLevel,int shuter,int display,int light,int LDR);
~Intervalometer();
void init();
void run();
void setLight();
void handleUpButton();
void handleDownButton();
void handleLightUpButton();
void handleLightDownButton();
void handleOkButton();
void handleBackButton();
Button *p_buttonLightUp;
Button *p_buttonLightDown;
Button *p_buttonUp;
Button *p_buttonDown;
Button *p_buttonOk;
Button *p_buttonBack;
private:
void intro();
void checkButtons();
void stopRunning();
void reset();
void shoot();
LiquidCrystal_I2C *p_lcd;
Led *p_led;
byte kamera[8] =
{
0b00000,
0b00000,
0b00011,
0b11111,
0b11001,
0b11001,
0b11111,
0b00000
};
int shuterPin;
int displayPin;
int brightnessPin;
int countDown;
short mode;
int light; //Wert fr die helligkeit --> Wenn Wert 256 DisplayLicht = LOW;
unsigned long shootTime; // in Millisekunden
unsigned long passedTime; // Bereits abgelaufende Zeit des "shootTime"-Intervalls in Millisekunden
int stunden;
int minuten;
unsigned long images;
int lastTime; //In Sekunden --> Kann bis zu 24 Stunden --> 86400 Sekunden gehen
int lastMode;
float lastIntervall; //In 10/Sekunden --> Kann bis zu 10 Minuten --> 6000 10/Sekunden gehen
unsigned long currentMillis;
unsigned long previousMillis;
unsigned long referenceTime;
const int scrollTimer = 500; //In Ms
//------------------BLITZ-----------------\\
int toleranz;
int takt;
int ldrPin;
int ldrValue;
int lastLdrValue;
};
#endif
| true |
359b571dd30f1682825338bbaf143f9e12ccc30d | C++ | SHS-GROUP/NEO-DFT | /libcchem/src/cc/symmetrize.hpp | UTF-8 | 4,181 | 2.546875 | 3 | [] | no_license | #ifndef CC_SYMMETRIZE_HPP
#define CC_SYMMETRIZE_HPP
#include <boost/multi_array/multi_array_ref.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/mpl/vector_c.hpp>
#include "cc/tensor.hpp"
namespace cchem {
namespace cc {
namespace detail {
template<typename S>
struct symmetrize {
symmetrize(const S &a, const S &b) : a_(a), b_(b) {}
template<typename T, typename U>
void operator()(T &a, U &b) const {
T t = a;
T u = b;
a = a_*a + b_*u;
b = a_*b + b_*t;
}
private:
S a_, b_;
};
template<size_t N>
struct symmetric;
template<>
struct symmetric<2> {
private:
template<typename T, size_t N>
struct tile {
struct range {
size_t start, finish;
};
template<class A>
void load(range ri, range rj, const A &a) {
size_t ni = ri.finish - ri.start;
size_t nj = rj.finish - rj.start;
for (size_t j = 0; j < nj; ++j) {
BOOST_AUTO(aj, a[j+rj.start]);
for (size_t i = 0; i < ni; ++i) {
data[j][i] = aj[i+ri.start];
}
}
}
template<class A>
void store(range ri, range rj, A &a) {
size_t ni = ri.finish - ri.start;
size_t nj = rj.finish - rj.start;
for (size_t j = 0; j < nj; ++j) {
BOOST_AUTO(aj, a[j+rj.start]);
for (size_t i = 0; i < ni; ++i) {
//assert(j < N && i < N);
//assert(i+ri.start < aj.shape()[0]);
aj[i+ri.start] = data[j][i];
}
}
}
T data[N][N];
};
template<class F, typename T, size_t N>
static void apply(const F &f, T (&a)[N][N], T (&b)[N][N]) {
for (size_t j = 0; j < N; ++j) {
for (size_t i = 0; i < N; ++i) {
f(a[j][i], b[i][j]);
}
}
}
public:
template<class F, class A>
static void apply(const F &f, A &a) {
assert(a.shape()[0] == a.shape()[1]);
size_t N = a.shape()[0];
// for (size_t j = 0; j < N; ++j) {
// for (size_t i = 0; i <= j; ++i) {
// f(a[j][i], a[i][j]);
// }
// }
// return;
static const size_t B = 16;
typedef tile<typename A::element,B> T;
for (size_t j = 0; j < N; j += B) {
for (size_t i = 0; i <= j; i += B) {
typename T::range ri = { i, std::min(i+B, N) };
typename T::range rj = { j, std::min(j+B, N) };
// std::cout << ri.start << "-" << ri.finish << std::endl;
// std::cout << rj.start << "-" << rj.finish << std::endl;
T aij;
T aji;
aij.load(ri, rj, a);
aji.load(rj, ri, a);
apply(f, aij.data, aji.data);
aij.store(ri, rj, a);
aji.store(rj, ri, a);
}
}
}
};
template<>
struct symmetric<3> {
template<class F, class A>
static void apply(const F &f, A &a, boost::mpl::vector_c<int,1,2>) {
assert(a.shape()[0] == a.shape()[1]);
size_t N = a.shape()[1];
size_t K = a.shape()[2];
for (size_t j = 0; j < N; ++j) {
for (size_t i = 0; i <= j; ++i) {
BOOST_AUTO(aij, a[i][j]);
BOOST_AUTO(aji, a[j][i]);
for (size_t k = 0; k < K; ++k) {
f(aji[k], aij[k]);
}
}
}
}
template<class F, class A>
static void apply(const F &f, A &a, boost::mpl::vector_c<int,0,1>) {
assert(a.shape()[1] == a.shape()[2]);
size_t K = a.shape()[0];
for (size_t k = 0; k < K; ++k) {
BOOST_AUTO(ak, a[k]);
symmetric<2>::apply(f, ak);
}
}
};
}
}
namespace cc {
template<size_t I, size_t J, typename T, size_t N, typename U>
void symmetrize2(Tensor<N,T> &A, const U &a, const U &b) {
boost::mpl::vector_c<int,I,J> ij;
detail::symmetric<N>::apply(detail::symmetrize<U>(a,b), A, ij);
}
template<size_t I, size_t J, typename T, size_t N, typename U>
void symmetrize2(tensor_reference<N,T> &A, const U &a, const U &b) {
boost::mpl::vector_c<int,I,J> ij;
detail::symmetric<N>::apply(detail::symmetrize<U>(a,b), A, ij);
}
template<size_t I, size_t J, typename T>
void symmetrize2(T *p, size_t n0, size_t n1, size_t n2) {
boost::mpl::vector_c<int,I,J> ij;
boost::multi_array_ref<T,3> a(p, boost::extents[n2][n1][n0]);
detail::symmetric<3>::apply(detail::symmetrize<T>(2,-1), a, ij);
}
}
} // namespace cchem
#endif /* CC_SYMMETRIZE_HPP */
| true |
49bc084fb040e5e1c39ec5046888d93b4fb40c64 | C++ | Vinc33/CoursJeux | /Projet1/Hero.cpp | UTF-8 | 305 | 2.546875 | 3 | [] | no_license | #include "Hero.h"
#include "InputManager.h"
Hero::Hero(string unitName, short playerID, short baseDamage, short maxHP) : Character (unitName, baseDamage, maxHP)
{
this->playerID = playerID;
}
Hero::~Hero()
{
}
bool Hero::getKeyState(INPUT key)
{
return InputManager::getKeyState(playerID, key);
}
| true |
1b2ce9b214105c21883c210acafcab569156ff8d | C++ | isaacroberts/BroodwarAI | /Ref.cpp | UTF-8 | 2,496 | 2.515625 | 3 | [] | no_license | #include "Ref.h"
#include "Util.h"
int Ref::updateAmt =0;
bool Ref::hasSoldiers=true;
std::vector<Class*> Ref::clas=std::vector<Class*>();
Ref::Ref()
{
}
void Ref::onStart()
{
std::set<Player*> player=Broodwar->getPlayers();
bool terran=false,zerg=false;
for (std::set<Player*>::iterator ply=player.begin();ply!=player.end();ply++)
{
if ((*ply)->isEnemy(Broodwar->self()))
{
if ((*ply)->getRace()==Races::Zerg)
zerg=true;
else if ((*ply)->getRace()==Races::Terran)
terran=true;
else if ((*ply)->getRace()==Races::Unknown)
{
zerg=true;
terran=true;
}
}
if (zerg&&terran)
break;
}
std::set<UnitType> all=UnitTypes::allUnitTypes();
for (std::set<UnitType>::iterator ut=all.begin();ut!=all.end();ut++)
{
if ( ut->getRace()==Races::Protoss
||(ut->getRace()==Races::Terran && terran)
||(ut->getRace()==Races::Zerg && zerg) )
{
if (!ut->isHero()&& !ut->isSpecialBuilding()&& !ut->isAddon() && !ut->isSpell() && ut->getID()!=UnitTypes::Terran_Siege_Tank_Siege_Mode.getID())
{
clas.push_back(new Class(*ut));
}
}
}
}
void Ref::setPermInputs()
{
for (unsigned int n=0;n<clas.size();n++)
{
clas[n]->setPermInputs();
}
Util::debug("classes updated");
}
Class* Ref::getClass(UnitType* type)
{
for (unsigned int n=0;n<clas.size();n++)
{
if (type->getID()==clas[n]->getType().getID())
return clas[n];
}
Util::fprint("warning! someones looking for the class of "+type->getName()+" which isnt there");
return new Class();
}
bool Ref::isCore(UnitType* type)
{
for (unsigned int n=0;n<clas.size();n++)
{
if (type->getID()==clas[n]->getType().getID())
return true;
}
return false;
}
bool Ref::isHarvesting(Order order)
{
if (order==Orders::Harvest1) return true;
if (order==Orders::Harvest2) return true;
if (order==Orders::Harvest3) return true;
if (order==Orders::Harvest4) return true;
if (order==Orders::HarvestGas) return true;
if (order==Orders::MiningMinerals) return true;
if (order==Orders::MoveToGas) return true;
if (order==Orders::MoveToMinerals) return true;
if (order==Orders::WaitForGas) return true;
if (order==Orders::WaitForMinerals) return true;
if (order==Orders::ReturnGas) return true;
if (order==Orders::ReturnMinerals) return true;
return false;
}
int Ref::updates() {
return updateAmt;
}
void Ref::incUpdates() {
updateAmt++;
hasSoldiers=false;
}
Ref::~Ref(void)
{
}
| true |
f1c192ca3747908adf6e1972606fd1aaa5674b2a | C++ | LiBingtao/prictice-for-pat | /prictice/1016. 部分A+B.cpp | UTF-8 | 433 | 2.59375 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
int main()
{
string a, b;
char da, db;
int at = 0, bt = 0;
cin >> a >> da >> b >> db;
for (int i = 0; i < (int)a.length(); i++) {
if (a[i] == da) {
at = at * 10 + (int)(da-'0');
}
}
for (int i = 0; i < (int)b.length(); i++) {
if (b[i] == db) {
bt = bt * 10 + (int)(db-'0');
}
}
int result = at + bt;
cout << result;
cin.get();
cin.get();
return 0;
} | true |
dc767421c47060db9a060ab95f224f16fd371f90 | C++ | Senryoku/NESen | /src/tools/log.hpp | UTF-8 | 2,828 | 2.9375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <array>
#include <chrono>
#include <deque>
#include <functional>
#include <iostream>
#include <sstream>
namespace Log {
using Color = const char*;
const Color Black = "\033[0;30m";
const Color Red = "\033[0;31m";
const Color Green = "\033[0;32m";
const Color Brown = "\033[0;33m";
const Color Blue = "\033[0;34m";
const Color Magenta = "\033[0;35m";
const Color Cyan = "\033[0;36m";
const Color LightGray = "\033[0;37m";
const Color DarkGray = "\033[1;30m";
const Color LightRed = "\033[1;31m";
const Color LightGreen = "\033[1;32m";
const Color Yellow = "\033[1;33m";
const Color LightBlue = "\033[1;34m";
const Color LightPurple = "\033[1;35m";
const Color LightCyan = "\033[1;36m";
const Color White = "\033[1;37m";
const Color Reset = "\033[0m";
constexpr size_t BufferSize = 100;
enum LogType {
Info = 0,
Success = 1,
Warning = 2,
Error = 3,
Print = 4
};
extern LogType _min_level;
extern const std::array<const char*, 5> _log_types;
extern const std::array<Color, 5> _log_types_colors;
struct LogLine {
std::time_t time;
LogType type;
std::string message;
unsigned int repeat = 1;
inline operator std::string() const { return str(); }
inline std::string str() const {
std::string full;
char mbstr[100];
std::strftime(mbstr, sizeof(mbstr), "%H:%M:%S", std::localtime(&time));
full = std::string(Cyan) + "[" + std::string(mbstr) + "] " + Reset + _log_types_colors[type] + _log_types[type] + Reset;
if(repeat > 1)
full += " <*" + std::to_string(repeat) + ">";
full += ": " + message;
return full;
}
};
extern std::ostringstream _log_line;
extern std::deque<LogLine> _logs;
extern std::function<void(const LogLine& ll)> _log_callback;
extern std::function<void(const LogLine& ll)> _update_callback;
inline void _default_log_callback(const LogLine& ll) {
std::cout << std::endl << "\x1B[31m" << ll.str();
}
inline void _default_update_callback(const LogLine& ll) {
std::cout << '\r' << ll.str();
}
void _log(LogType lt);
template<typename T, typename... Args>
inline void _log(LogType lt, const T& msg, Args... args) {
_log_line << msg;
_log(lt, args...);
}
template<typename... Args>
inline void print(Args... args) {
_log(LogType::Print, args...);
}
template<typename... Args>
inline void info(Args... args) {
_log(LogType::Info, args...);
}
template<typename... Args>
inline void warn(Args... args) {
_log(LogType::Warning, args...);
}
template<typename... Args>
inline void error(Args... args) {
_log(LogType::Error, args...);
}
template<typename... Args>
inline void success(Args... args) {
_log(LogType::Success, args...);
}
} // namespace Log
| true |
2f9cb6490587aa16b4c2e72370ebe30ee205f218 | C++ | aleafall/DS-A | /offer/verifySquenceOfBST.cpp | UTF-8 | 733 | 3.1875 | 3 | [] | no_license | //
// Created by aleafall on 17-2-17.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool judge(const vector<int> &vi,int left,int right){
if (left >= right) {
return 1;
}
int middle = left;
while (middle < right && vi[middle] < vi[right]) {
++middle;
}
for (int i = middle; i < right; ++i) {
if (vi[i] < vi[right]) {
return 0;
}
}
return judge(vi, left, middle-1) && judge(vi, middle, right-1);
}
bool VerifySquenceOfBST(vector<int> sequence) {
if (sequence.empty()) {
return 0;
}
return judge(sequence, 0, sequence.size() - 1);
}
};
int main(){
vector<int> vi{7,4,6,5};
Solution solution;
cout << solution.VerifySquenceOfBST(vi) << endl;
} | true |
9379fdb1aa0f039d6c4e8897bccf6079094c7317 | C++ | MohitMotiani99/Leetcode | /1344.cpp | UTF-8 | 293 | 2.828125 | 3 | [] | no_license | class Solution {
public:
double angleClock(int hour, int minutes) {
double h=hour;
double m=minutes;
if(h==12)
h=0;
double total=h*60+m;
double ha=total*0.5;
double ma=m*6;
return min(abs(ha-ma),360-abs(ha-ma));
}
};
| true |
3973bf7d8dbe3b7e04cff2a9c9094b52a24bc0a6 | C++ | ruitaocc/RcEngine | /RcEngine/RcEngine/Core/Timer.h | UTF-8 | 912 | 2.578125 | 3 | [] | no_license | #ifndef Timer_h__
#define Timer_h__
#include <Core/Prerequisites.h>
namespace RcEngine {
class _ApiExport SystemClock
{
public:
static void InitClock();
static void ShutClock();
static uint64_t Now();
static inline double ToSeconds(uint64_t timeCounts) { return timeCounts * SecondsPerCount; }
private:
static int64_t StartTime;
static double SecondsPerCount;
};
/**
* Game Timer
*/
class _ApiExport Timer
{
public:
Timer();
float GetGameTime() const; // in seconds
float GetDeltaTime() const; // in seconds
void Reset(); // Call before game loop
void Start(); // Call when unpaused
void Stop(); // Call when paused
void Tick(); // Call every frame
private:
double mSecondsPerCount;
double mDeltaTime;
__int64 mBaseTime;
__int64 mPausedTime;
__int64 mStopTime;
__int64 mPrevTime;
__int64 mCurrTime;
bool mStopped;
};
} // Namespace RcEngine
#endif // Timer_h__
| true |
3bb08bc52b50524137fc4a8dba0cc97026878202 | C++ | neu-velocity/code-camp-debut | /codes/Garnetwzy/46.cpp | UTF-8 | 749 | 3.015625 | 3 | [] | no_license | class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ret;
vector<bool> visit(nums.size(), false);
vector<int> cur = {};
dfs(ret, visit, cur, nums);
return ret;
}
void dfs(vector<vector<int>>& ret, vector<bool>& visit, vector<int>& cur, vector<int>& nums) {
if(cur.size() == nums.size()) {
ret.push_back(cur);
return;
}
for(int i = 0; i < nums.size(); i++) {
if(visit[i])
continue;
cur.push_back(nums[i]);
visit[i] = true;
dfs(ret, visit, cur, nums);
visit[i] = false;
cur.pop_back();
}
}
}; | true |
2b583960b6540aca902dd2eccd3e8ad9c4647248 | C++ | luispadron/Decaf-Lang | /code-gen/tac.cc | UTF-8 | 6,229 | 2.765625 | 3 | [
"MIT"
] | permissive | /* File: tac.cc
* ------------
* Implementation of Location class and Instruction class/subclasses.
*/
#include "tac.h"
#include "mips.h"
#include <string.h>
#include <deque>
Location::Location(Segment s, int o, const char *name) :
variableName(strdup(name)), segment(s), offset(o){}
void Instruction::Print() {
printf("\t%s ;", printed);
printf("\n");
}
void Instruction::Emit(Mips *mips) {
if (*printed)
mips->Emit("# %s", printed); // emit TAC as comment into assembly
EmitSpecific(mips);
}
LoadConstant::LoadConstant(Location *d, int v)
: dst(d), val(v) {
Assert(dst != nullptr);
sprintf(printed, "%s = %d", dst->GetName(), val);
}
void LoadConstant::EmitSpecific(Mips *mips) {
mips->EmitLoadConstant(dst, val);
}
LoadStringConstant::LoadStringConstant(Location *d, const char *s)
: dst(d) {
Assert(dst != nullptr && s != nullptr);
const char *quote = (*s == '"') ? "" : "\"";
str = new char[strlen(s) + 2*strlen(quote) + 1];
sprintf(str, "%s%s%s", quote, s, quote);
quote = (strlen(str) > 50) ? "...\"" : "";
sprintf(printed, "%s = %.50s%s", dst->GetName(), str, quote);
}
void LoadStringConstant::EmitSpecific(Mips *mips) {
mips->EmitLoadStringConstant(dst, str);
}
LoadLabel::LoadLabel(Location *d, const char *l)
: dst(d), label(strdup(l)) {
Assert(dst != nullptr && label != nullptr);
sprintf(printed, "%s = %s", dst->GetName(), label);
}
void LoadLabel::EmitSpecific(Mips *mips) {
mips->EmitLoadLabel(dst, label);
}
Assign::Assign(Location *d, Location *s)
: dst(d), src(s) {
Assert(dst != nullptr && src != nullptr);
sprintf(printed, "%s = %s", dst->GetName(), src->GetName());
}
void Assign::EmitSpecific(Mips *mips) {
mips->EmitCopy(dst, src);
}
Load::Load(Location *d, Location *s, int off)
: dst(d), src(s), offset(off) {
Assert(dst != nullptr && src != nullptr);
if (offset)
sprintf(printed, "%s = *(%s + %d)", dst->GetName(), src->GetName(), offset);
else
sprintf(printed, "%s = *(%s)", dst->GetName(), src->GetName());
}
void Load::EmitSpecific(Mips *mips) {
mips->EmitLoad(dst, src, offset);
}
Store::Store(Location *d, Location *s, int off)
: dst(d), src(s), offset(off) {
Assert(dst != nullptr && src != nullptr);
if (offset)
sprintf(printed, "*(%s + %d) = %s", dst->GetName(), offset, src->GetName());
else
sprintf(printed, "*(%s) = %s", dst->GetName(), src->GetName());
}
void Store::EmitSpecific(Mips *mips) {
mips->EmitStore(dst, src, offset);
}
const char * const BinaryOp::opName[BinaryOp::NumOps] = {"+", "-", "*", "/", "%", "==", "<", "&&", "||"};;
BinaryOp::OpCode BinaryOp::OpCodeForName(const char *name) {
for (int i = 0; i < NumOps; i++)
if (opName[i] && !strcmp(opName[i], name)) {
return (OpCode)i;
}
failure("Unrecognized Tac operator: '%s'\n", name);
return Add; // can't get here, but compiler doesn't know that
}
BinaryOp::BinaryOp(OpCode c, Location *d, Location *o1, Location *o2)
: code(c), dst(d), op1(o1), op2(o2) {
Assert(dst != nullptr && op1 != nullptr && op2 != nullptr);
Assert(code >= 0 && code < NumOps);
sprintf(printed, "%s = %s %s %s", dst->GetName(), op1->GetName(), opName[code], op2->GetName());
}
void BinaryOp::EmitSpecific(Mips *mips) {
mips->EmitBinaryOp(code, dst, op1, op2);
}
Label::Label(const char *l) : label(strdup(l)) {
Assert(label != nullptr);
*printed = '\0';
}
void Label::Print() {
printf("%s:\n", label);
}
void Label::EmitSpecific(Mips *mips) {
mips->EmitLabel(label);
}
Goto::Goto(const char *l) : label(strdup(l)) {
Assert(label != nullptr);
sprintf(printed, "Goto %s", label);
}
void Goto::EmitSpecific(Mips *mips) {
mips->EmitGoto(label);
}
IfZ::IfZ(Location *te, const char *l)
: test(te), label(strdup(l)) {
Assert(test != NULL && label != NULL);
sprintf(printed, "IfZ %s Goto %s", test->GetName(), label);
}
void IfZ::EmitSpecific(Mips *mips) {
mips->EmitIfZ(test, label);
}
BeginFunc::BeginFunc() {
sprintf(printed,"BeginFunc (unassigned)");
frameSize = -555; // used as sentinel to recognized unassigned value
}
void BeginFunc::SetFrameSize(int numBytesForAllLocalsAndTemps) {
frameSize = numBytesForAllLocalsAndTemps;
sprintf(printed,"BeginFunc %d", frameSize);
}
void BeginFunc::EmitSpecific(Mips *mips) {
mips->EmitBeginFunction(frameSize);
}
EndFunc::EndFunc() : Instruction() {
sprintf(printed, "EndFunc");
}
void EndFunc::EmitSpecific(Mips *mips) {
mips->EmitEndFunction();
}
Return::Return(Location *v) : val(v) {
sprintf(printed, "Return %s", val? val->GetName() : "");
}
void Return::EmitSpecific(Mips *mips) {
mips->EmitReturn(val);
}
PushParam::PushParam(Location *p)
: param(p) {
Assert(param != NULL);
sprintf(printed, "PushParam %s", param->GetName());
}
void PushParam::EmitSpecific(Mips *mips) {
mips->EmitParam(param);
}
PopParams::PopParams(int nb)
: numBytes(nb) {
sprintf(printed, "PopParams %d", numBytes);
}
void PopParams::EmitSpecific(Mips *mips) {
mips->EmitPopParams(numBytes);
}
LCall::LCall(const char *l, Location *d)
: label(strdup(l)), dst(d) {
sprintf(printed, "%s%sLCall %s", dst? dst->GetName(): "", dst?" = ":"", label);
}
void LCall::EmitSpecific(Mips *mips) {
mips->EmitLCall(dst, label);
}
ACall::ACall(Location *ma, Location *d)
: dst(d), methodAddr(ma) {
Assert(methodAddr != NULL);
sprintf(printed, "%s%sACall %s", dst? dst->GetName(): "", dst?" = ":"",
methodAddr->GetName());
}
void ACall::EmitSpecific(Mips *mips) {
mips->EmitACall(dst, methodAddr);
}
VTable::VTable(const char *l, List<const char *> m)
: label(strdup(l)), methodLabels(m) {
Assert(label != NULL);
sprintf(printed, "VTable for class %s", l);
}
void VTable::Print() {
printf("VTable %s =\n", label);
for (int i = 0; i < methodLabels.size(); i++)
printf("\t%s,\n", methodLabels.get(i));
printf("; \n");
}
void VTable::EmitSpecific(Mips *mips) {
mips->EmitVTable(label, &methodLabels);
}
| true |
eb665216b0c2dd5f8f72bf88bb14bd5784d7b452 | C++ | ArjunAranetaCodes/MoreCodes-CPlusPlus | /Loops/problem10.cpp | UTF-8 | 432 | 3.84375 | 4 | [] | no_license | //Problem 10: Write a program to check whether a given
//number is an armstrong number or not.
#include<iostream>
using namespace std;
int main(){
int num = 371;
int sum = 0;
int temp = 0;
int rmdr = 0;
temp = num;
while (temp != 0){
rmdr = temp % 10;
sum = sum + (rmdr * rmdr * rmdr);
temp = temp / 10;
}
if(num == sum){
cout << "Armstrong number";
}else{
cout << "Not an armstrong number";
}
return 0;
}
| true |