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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
750f8a17118084d587cdea4f600c57218ed4e055 | C++ | hennin67/TreeProject | /CanadianExperience\CanadianExperience\TreeAdapter.h | UTF-8 | 1,383 | 2.78125 | 3 | [] | no_license | /**
* \file TreeAdapter.h
*
* \author Becky Henning
*
* Tree adapter for Tree Lib
*/
#pragma once
#include "Drawable.h"
#include "Tree.h"
#include "Timeline.h"
#include <memory>
class CBasketAdapter;
/**
* Class for tree in drawings
*/
class CTreeAdapter : public CDrawable
{
public:
/// Constructor
CTreeAdapter(const std::wstring& name);
/// Destructor
virtual ~CTreeAdapter() {};
/// Draw the basket
virtual void Draw(Gdiplus::Graphics* graphics) override;
/** Test to see if we have been clicked on by the mouse
* \param pos Position to test
* \return true if clicked on */
virtual bool HitTest(Gdiplus::Point pos) { return false; }
/// Set the timeline
virtual void SetTimeline(CTimeline* timeline);
/// Return the frame
/// \return mFrame
double GetFrame() { return mFrame; }
/// Harvest the fruit
std::vector<std::shared_ptr<CFruit>> Harvest();
/// Seed the dlg box
void SeedDlg();
/// Start of tree growth
/// \param start the start frame
void SetGrow(int start) { mStart = start; }
/// Get start of growth
/// \return mStart
int GetGrow() { return mStart; }
private:
/// the tree
std::shared_ptr<CTree> mTree = nullptr;
/// start of growth
int mStart = 0;
/// current frame
double mFrame = 0;
/// timeline
CTimeline* mTimeline = nullptr;
};
| true |
7984ec959ffe4b518f5b538dfe2cc3676ac16c24 | C++ | rustamojukas/jaluzi | /NTP.ino | UTF-8 | 3,522 | 3.078125 | 3 | [
"MIT"
] | permissive | #include <time.h> //Содержится в пакете
void initNTP() {
HTTP.on("/Time", handle_Time); // Синхронизировать время устройства по запросу вида /Time
HTTP.on("/timeZone", handle_time_zone); // Установка времянной зоны
timeSynch(jsonReadtoInt(configJson, "timeZone"));
modulesReg("ntp");
}
void timeSynch(int zone) {
if (WiFi.status() == WL_CONNECTED) {
// Инициализация UDP соединения с NTP сервером
configTime(zone * 3600, 0, "pool.ntp.org", "ru.pool.ntp.org");
int i = 0;
//Serial.print("\nWaiting for time ");
while (!time(nullptr) && i < 10) {
//Serial.print(".");
i++;
delay(100);
}
Serial.println("");
configJson = jsonWrite(configJson, "time", GetTime());
}
}
// ---------- Синхронизация времени
void handle_Time() {
timeSynch(jsonReadtoInt(configJson, "timeZone"));
String out = "{}";
out = jsonWrite(out, "title", "{{LangTime1}} <strong id=time>"+GetTime()+"</strong>");
HTTP.send(200, "text/plain", out); // отправляем ответ о выполнении
}
// ---------- Установка параметров времянной зоны по запросу вида http://192.168.0.101/timeZone?timezone=3
void handle_time_zone() {
int timezone = HTTP.arg("timeZone").toInt(); // Получаем значение timezone из запроса конвертируем в int сохраняем в глобальной переменной
configJson = jsonWrite(configJson, "timeZone", timezone);
timeSynch(timezone);
writeFile("config.save.json", configJson );
HTTP.send(200, "text/plain", "OK");
}
// Получение текущего времени
String GetTime() {
time_t now = time(nullptr); // получаем время с помощью библиотеки time.h
String Time = ""; // Строка для результатов времени
Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
int i = Time.indexOf(":"); //Ишем позицию первого символа :
Time = Time.substring(i - 2, i + 6); // Выделяем из строки 2 символа перед символом : и 6 символов после
return Time; // Возврашаем полученное время
}
// Получение даты
String GetDate() {
time_t now = time(nullptr); // получаем время с помощью библиотеки time.h
String Data = ""; // Строка для результатов времени
Data += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
Data.replace("\n", "");
int i = Data.lastIndexOf(" "); //Ишем позицию последнего символа пробел
String Time = Data.substring(i - 8, i+1); // Выделяем время и пробел
Data.replace(Time, ""); // Удаляем из строки 8 символов времени и пробел
return Data; // Возврашаем полученную дату
}
// Получение дня недели
String GetWeekday() {
String Data = GetDate();
int i = Data.indexOf(" "); //Ишем позицию первого символа пробел
String weekday = Data.substring(i - 3, i); // Выделяем время и пробел
return weekday;
}
| true |
07bc6790411e36a146a0f27191d890d9f006111f | C++ | lixu1/Cpp_Object_Oriented | /StudentChooseCourse/Control.cpp | GB18030 | 2,793 | 3.28125 | 3 | [] | no_license | #include "Control.h"
#include <iostream>
#include <iomanip>
using namespace std;
Control::Control()
{
allObNumber=0;
allElNumber=0;
}
Control::~Control()
{
if(student!=NULL)
delete student;
for(int i=0;i<allObNumber;i++)
{ delete ocourse[i];}
for(int j=0;j<allElNumber;j++)
{ delete ecourse[j];}//dtor
}
int Control::run()
{
cout<<"**************ӭѡϵͳ***************\n";
cout<<"աʽΪ 1991 1 1\n";
char m[10];
int a,b,c;
cin>>m>>a>>b>>c;
student=new Student(a,b,c,m);
BuildCourse();
int choose;
while( (choose=DisplayMenu())&&choose)
{
switch(choose)
{
case 1:
chooseCourse(choose);break;
case 2:
chooseCourse(choose);break;
case 3:
cout<<*student;break;
case 4:
student->printScore();break;
case 5:
cout<<"ѧǣ"<<fixed<<setprecision(2)<< student->calcCredit() <<endl;break;
case 6:
student->setScore();break;
default:
cout<<"\n";break;
}
}
return 0;
}
int Control::DisplayMenu()
{
int ans;
cout<<"\n˵£Ӧţ\n";
cout<<"0,˳ϵͳ\n";
cout<<"1,ѡ\n";
cout<<"2,ѡѡ\n";
cout<<"3,ѯѡγ\n";
cout<<"4,ѯſγ̳ɼ\n";
cout<<"5,ѯɼ\n";
cout<<"6,Ϊſγ\n";
cin>>ans;
return ans;
}
void Control::BuildCourse()
{
ocourse[0]=new ObligatoryCourse("C++ߵȳ2",3);
ocourse[1]=new ObligatoryCourse("ߵѧ",6);
ocourse[2]=new ObligatoryCourse("Դ",3);
allObNumber=3;
ecourse[0]=new ElectiveCourse("",2);
ecourse[1]=new ElectiveCourse("Դ",1);
allElNumber=2;
}
void Control::chooseCourse(int a)
{
if(a==1)
{
cout<<"£\n";
for(int i=0;i<getallObNumber();i++)
{
cout<<i<<" "<<*ocourse[i];
}
cout<<"ҪѡĿγ̱ţ븺\n";
int a;
cin>>a;
while(a>=0)
{
student->chooseObligatoryCourse((ObligatoryCourse *)ocourse[a]);
cin>>a;
}
}
if(a==2)
{
cout<<"ѡ£\n";
for(int i=0;i<getallElNumber();i++)
{
cout<<i<<" "<<* ecourse[i];
}
cout<<"ҪѡĿγ̱ţ븺\n";
int a;
cin>>a;
while(a>=0)
{
student->chooseElectiveCourse((ElectiveCourse* )ecourse[a]);
cin>>a;
}
}
} | true |
111ea8e34b9580c4da5dd7428f65f6eb0b776580 | C++ | wenpincui/leetcode | /sort-colors.cpp | UTF-8 | 490 | 3.171875 | 3 | [] | no_license | class Solution {
public:
void sortColors(int A[], int n) {
int r = 0, w = 0, b = 0;
for (int i = 0; i < n; i++) {
switch(A[i]) {
case 0: r++; break;
case 1: w++; break;
case 2: b++; break;
default: break;
}
}
int pos = 0;
while (r-- > 0)
A[pos++] = 0;
while (w-- > 0)
A[pos++] = 1;
while (b-- > 0)
A[pos++] = 2;
}
};
| true |
fd545d91cf7156e4ecdbf6b533608cbbf9cc0e1b | C++ | MrPaoBrother/C-primer-demo | /chapter13/tabletennis/tabtenn.cpp | UTF-8 | 945 | 3.0625 | 3 | [] | no_license | #include "tabtenn.h"
using std::cout;
using std::endl;
using std::string;
TableTennisPlayer::TableTennisPlayer(const string &fn, const string &ln, bool ht)
{
firstname = fn;
lastname = ln;
hasTable = ht;
}
TableTennisPlayer::TableTennisPlayer(const TableTennisPlayer &tp)
{
this->firstname = tp.firstname;
this->lastname = tp.lastname;
this->hasTable = tp.hasTable;
cout << "use copy constructor!" << endl;
}
void TableTennisPlayer::Name() const
{
cout << "firstname:" << firstname << " lastname:" << lastname << endl;
}
bool TableTennisPlayer::HasTable() const
{
return hasTable;
}
void TableTennisPlayer::ResetTable(bool ht)
{
hasTable = ht;
}
RatedPlayer::RatedPlayer(unsigned int r, const string &fn, const string &ln, bool ht) : TableTennisPlayer(fn, ln, ht)
{
rating = r;
}
RatedPlayer::RatedPlayer(unsigned int r, const TableTennisPlayer &tp) : TableTennisPlayer(tp)
{
rating = r;
}
| true |
bc4f31b62f835d326253952f2be492ee4894e88f | C++ | hoseogame/20151683 | /20151683/MiniGame/cHStage.h | UHC | 1,582 | 2.734375 | 3 | [] | no_license | #pragma once
#define CHSTAGE_H
#include <time.h>
class cHStage
{
private:
int m_iBasketX; // Note: Ʈ ٱ x ǥ
int m_iBasketY; // Note: Ʈ ٱ y ǥ
int m_iHeartCount; // Note: Stage Ʈ
int m_iGoalHeartCount; // Note: ǥ Ʈ
int m_iBarLength; // Note:
clock_t m_BasketMoveTime; // Note: Ʈ ٱϰ ̴ ̵ ð
clock_t m_BasketDownHeartTime; // Note: Ʈ ð
public:
cHStage() {};
int getBasketX()
{
return m_iBasketX;
}
int getBasketY()
{
return m_iBasketY;
}
int getHeartCount()
{
return m_iHeartCount;
}
int getGoalHeartCount()
{
return m_iGoalHeartCount;
}
int getBarLength()
{
return m_iBarLength;
}
clock_t getBasketMoveTime()
{
return m_BasketMoveTime;
}
clock_t getBasketDownHeartTime()
{
return m_BasketDownHeartTime;
}
void setBasketX(int _iBasketX)
{
m_iBasketX = _iBasketX;
}
void setBasketY(int _iBasketY)
{
m_iBasketY = _iBasketY;
}
void setHeartCount(int _iHeartCount)
{
m_iHeartCount = _iHeartCount;
}
void setGoalHeartCount(int _iGoalHeartCount)
{
m_iGoalHeartCount = _iGoalHeartCount;
}
void setBarLength(int _iBarLength)
{
m_iBarLength = _iBarLength;
}
void setBasketMoveTime(clock_t _BasketMoveTime)
{
m_BasketMoveTime = _BasketMoveTime;
}
void setBasketDownHeartTime(clock_t _BasketDownHeartTime)
{
m_BasketDownHeartTime = _BasketDownHeartTime;
}
}; | true |
f3bd62a5c56cdb1793df5aa87a58a0c60725baca | C++ | fabtosz/pjp2-projekt | /pjp2-projekt/resources/collisions.h | WINDOWS-1250 | 1,903 | 3.171875 | 3 | [] | no_license | #include <iostream>
bool isCollide(float pos1_x, float pos1_y, float size1_x, float size1_y, float pos2_x, float pos2_y, float size2_x, float size2_y)
{
if ((pos1_x > pos2_x + size2_x - 1) || // is b1 on the right side of b2?
(pos1_y > pos2_y + size2_y - 1) || // is b1 under b2?
(pos2_x > pos1_x + size1_x - 1) || // is b2 on the right side of b1?
(pos2_y > pos1_y + size1_y - 1)) // is b2 under b1?
{
// brak kolizji
return 0;
}
// jest kolizja
return 1;
}
// Sprawdzenie kolizji gracza z bloczkiem
// uycie isCollide z konkretnymi rozmiarami prostoktw
bool isCollidePlayerTile(float player_x, float player_y, float tile_x, float tile_y)
{
return isCollide(player_x, player_y, playerSizeX, playerSizeY, tile_x, tile_y, tileSize, tileSize);
}
bool isCollidePlayerGem(float player_x, float player_y, float tile_x, float tile_y)
{
return isCollide(player_x, player_y, playerSizeX, playerSizeY, tile_x, tile_y, gemSize, gemSize);
}
bool canItMove(float player_x, float player_y, /* wsprzdne gracza */float x, float y /* o ile ruszy */)
{
bool collision = false;
//sprawdz kolizje dla kadego kloca
for (int i = 0; i < sizeArrayMap; i++)
{
//jeli klocek jest powietrzem to go pomi
if (map[i] != 0 && map[i] != 5 && map[i] != 6 && map[i] != 7 && map[i] != 8)
{
if (isCollidePlayerTile(player_x + x, player_y + y, tileSize * (i % mapColumns), tileSize * (i / mapColumns)))
{
collision = true;
break;
}
}
//jeli klocek jest itemem(diamentem, potionem)
if (map[i] == 5 || map[i] == 6 || map[i] == 7 || map[i] == 8)
{
if (isCollidePlayerGem(player_x + x, player_y + y, tileSize * (i % mapColumns), tileSize * (i / mapColumns)))
{
map[i] = 0;
}
}
}
return !collision;
}
bool isOnSolidGround(int player_x, int player_y)
{
if (!canItMove(player_x, player_y, 0, 5))
{
return true;
}
else
{
return false;
}
}
| true |
f4d8e43b238f22fab7cc24777af1972fcca9d9a5 | C++ | batataOussama/RespiteServicesEvaluation | /V4/RespiteServicesEvaluation/InputData.h | ISO-8859-1 | 4,654 | 2.921875 | 3 | [] | no_license | /*
* InputData.h
*
* Created on: 12 mai 2018
* Author: Oussama BATATA
*/
#ifndef INPUTDATA_H_
#define INPUTDATA_H_
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
namespace mySpace {
class InputData {
private:
//-----Les donnes de la population de caregivers : ------------------------------------------------------
unsigned int _nbrCluster;// nombre de cluster d'aidants
unsigned int _nbrStatePerCluster;// Nombre d'tat instancier pour chaque communaut(cluster) de notre population
unsigned int _nbrCaregiverPerCluster;//Nombre d'aidant pour chaque cluster
unsigned int _timeHorizon; // L'horizon temporelle de notre simulation et des tats de la chane de Markov
vector< vector< vector< unsigned int > > > _burnoutCaregivers;// les donnes d'puisement de l'aidants
vector< vector< vector< vector< float> > > > _markovChain;//la chane des Markov pour l'puisement des aidants
//-------------------------------------------------------
// Les donnes pour construire un ensemble de services de rpit plus un hpital
unsigned int _nbrServices;//Nombre de services de rpit + l'hpital
unsigned int _maxTimeRespite;//le temps maximum qu'un aidnat peux prendre pour un soin de rpit
// Les donnes de notre simulation
float _respiteFrequence;// La frquence pour prendre le rpit des aidants.
unsigned int _nbReplication;//Le nbr de rplications requis pour valider statistiquement notre simulation
//Les donnes de la chane de Markov analytitque
vector< vector < vector<float> > > _burnoutVector;// La rpartition de la population sur les tats d'puisement
vector< vector < vector <float> > > _respiteVector;//La rpartition de la population sur les tat de rpit
vector< vector < vector < vector < float> > > > _burnoutMatrix;//La matrice de transition entre les tas d'puisement
vector< vector < vector < vector < float> > > > _respiteMatrix;//La matrice de transition entre les tas de rpit
public:
//Constructeur
//InputData(unsigned int nbrCluster, unsigned int nbrStatePerCluster, unsigned int nbrCaregiverPerCluster, unsigned int timeHorizon, unsigned int nbrServices, double respiteFrequence);
InputData();
//virtual ~InputData();
////--------------------------------------------------------------------------------------------------------------------------
// //------------------------Fonction principales----------------------------------------------------------------------
void readData();
void print();
////--------------------------------------------------------------------------------------------------------------------------
// //------------------------Les gets----------------------------------------------------------------------
//get le nbCluster
unsigned int getNemberCluster();
//get le timeHorizon
unsigned int getTImeHorizon();
//get le nbStatePerCluster
unsigned int getNbrStatePerCluster();
//getle nbCaregiverPerCluster
unsigned int getNbrCaregiverPerCluster();
//get le nbServices
unsigned int getNumberServices();
//get le maximum time in respite
unsigned int getmaxTimeInRespite();
//get nbReplications
unsigned int getNbReplications();
//get Burnout de chaque aidant chaque instanct ...!
float getBurnoutByIdByTime(unsigned int &idCluster, unsigned int &id, unsigned &time);
//get burnoutVector
vector< vector < vector<float> > > getBurnoutVector();
//get respiteVector
vector< vector < vector<float> > > getRespiteVector();
//get frequenceRespite
float getRespiteFrequence();
//get byurnoutMatrix
vector< vector < vector < vector < float> > > > getBurnoutMatrix();
//get respiteaMatrix
vector< vector < vector < vector < float> > > > getRespiteMatrix();
};
//inline InputData::InputData(unsigned int nbrCluster, unsigned int nbrStatePerCluster, unsigned int nbrCaregiverPerCluster, unsigned int timeHorizon, unsigned int nbrServices, double respiteFrequence):
// _nbrCluster(nbrCluster), _nbrStatePerCluster(nbrStatePerCluster), _nbrCaregiverPerCluster(nbrCaregiverPerCluster), _timeHorizon(timeHorizon), _nbrServices(0), _respiteFrequence(0){}
inline InputData::InputData():
_nbrCluster(0), _nbrStatePerCluster(0), _nbrCaregiverPerCluster(0), _timeHorizon(0), _nbrServices(0), _respiteFrequence(0), _nbReplication(0), _maxTimeRespite(0) {}
} /* namespace mySpace */
#endif /* INPUTDATA_H_ */
| true |
fcb8558cb8fdf04cb90e07e083d62ee9d37e38be | C++ | cecamschool2020/simplemd | /cpp/Vector.cpp | UTF-8 | 561 | 2.6875 | 3 | [] | no_license | #include "Vector.h"
#include <cmath>
namespace PLMD{
/// Small auxiliary class.
/// I use it to test a few things that I am scary of and could introduce bugs.
/// It checks at startup that Vector satifies some requirement so as to allow
/// accessing a vector of tensors as a 3 times longer array of doubles.
static class VectorChecks{
public:
VectorChecks(){
if( sizeof(VectorGeneric<2>)==2*sizeof(double)
&& sizeof(VectorGeneric<3>)==3*sizeof(double)
&& sizeof(VectorGeneric<4>)==4*sizeof(double)) return;
assert(0);
}
} checks;
}
| true |
e4249c3f5c2340faab5c6dc47e89099cefa6d423 | C++ | a-doering/kattis | /C++/fizzbuzz.cpp | UTF-8 | 401 | 2.859375 | 3 | [] | no_license | //fizzbuzz
#include <bits/stdc++.h>
using namespace std;
int main(){
//speed up of cin/cout
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int x, y, n;
cin>>x>>y>>n;
for(int i=1; i<=n; i++){
if(i%x==0)cout<<"Fizz";
if(i%y==0)cout<<"Buzz";
if(!(i%x==0||i%y==0))cout<<i;
cout<<endl;
}
return 0;
}
| true |
fd2eb41338ed2385d29269a0dc2d96ab0e937b8e | C++ | gbrlas/AVSP | /CodeJamCrawler/dataset/11_1301_6.cpp | UTF-8 | 468 | 2.78125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int t;
cin>>t;
for (int tt = 1; tt <= t; ++tt) {
int d, pd, pg;
cin>>d>>pd>>pg;
bool ans = false;
if (!(((pd > 0) && (pg == 0)) || ((pd < 100) && (pg == 100)))) {
for (int i = 1; i <= d; ++i) {
if (((i * pd) % 100) == 0) {
ans = true;
}
}
}
cout<<"Case #"<<tt<<": "<<(ans ? "Possible" : "Broken")<<endl;
}
return 0;
}
| true |
004ec50151243e0322abc30126d5bc4dddc34f56 | C++ | emiatej9/Kiwi-App | /include/kiwi/FrozenTrie.h | UTF-8 | 1,851 | 2.703125 | 3 | [] | no_license | #pragma once
#include <array>
#include <vector>
#include <deque>
#include <memory>
#include <algorithm>
#include <numeric>
#include <kiwi/Trie.hpp>
namespace kiwi
{
namespace utils
{
namespace detail
{
template<class Value, class = void>
struct HasSubmatch {};
template<class Value>
struct HasSubmatch<Value, typename std::enable_if<std::is_integral<Value>::value>::type>
{
static constexpr Value hasSubmatch = (Value)-1;
};
template<class Value>
struct HasSubmatch<Value, typename std::enable_if<std::is_pointer<Value>::value>::type>
{
static constexpr ptrdiff_t hasSubmatch = -1;
};
}
template<class _Key, class _Value, class _Diff = int32_t>
class FrozenTrie : public detail::HasSubmatch<_Value>
{
public:
using Key = _Key;
using Value = _Value;
using Diff = _Diff;
struct Node
{
Key numNexts = 0;
Diff lower = 0;
uint32_t nextOffset = 0;
const Node* next(const FrozenTrie& ft, Key c) const;
const Node* fail() const;
const Node* findFail(const FrozenTrie& ft, Key c) const;
const Value& val(const FrozenTrie& ft) const;
};
private:
size_t numNodes = 0;
size_t numNexts = 0;
std::unique_ptr<Node[]> nodes;
std::unique_ptr<Value[]> values;
std::unique_ptr<Key[]> nextKeys;
std::unique_ptr<Diff[]> nextDiffs;
public:
FrozenTrie() = default;
template<class TrieNode>
FrozenTrie(const ContinuousTrie<TrieNode>& trie);
FrozenTrie(const FrozenTrie& o);
FrozenTrie(FrozenTrie&&) = default;
FrozenTrie& operator=(const FrozenTrie& o);
FrozenTrie& operator=(FrozenTrie&& o) = default;
bool empty() const { return !numNodes; }
size_t size() const { return numNodes; }
const Node* root() const { return nodes.get(); }
const Value& value(size_t idx) const { return values[idx]; };
};
}
}
| true |
70a6827aab6a4909a083878fb678f991789b81cb | C++ | Dyex719/OCRF | /sklearn/ensemble/ocrf_open/ocrf_v0.6/src/dforest.cpp | UTF-8 | 17,004 | 2.796875 | 3 | [
"BSD-3-Clause"
] | permissive | #include "../include/dforest.h"
/* *************************************************************
* Constructor
* param :
* set : pointer to the training set
*/
DForest::DForest(DataHandler * set) {
trainSet = set;
minmax = trainSet->computeMinMax();
rsm_predict = false;
}
//DForest::DForest(DataHandler * set,bool rsm_bool){
// trainSet = set;
// rsm=rsm_bool;
//}
/* *************************************************************
* Constructor
* param :
* filename: string path to a .forest file that contains the forest to be loaded.
*/
DForest::DForest(string filename) {
rsm_predict = false;
minmax = nullptr;
ifstream f(filename.c_str(), ios_base::in);
if (f.is_open()) {
string line;
getline(f, line, '\n');
/*DataHandler * handler*/
trainSet = Arff::load(line.c_str());
getline(f, line, '\n');
getline(f, line, '\n');
int nbTrees = Utils::from_string(line);
for (int i = 0; i < nbTrees; i++) {
getline(f, line, '\n');
F_DTree* ftree=new F_DTree(line);
forest.push_back(ftree);
ftree->save("results/test",-1);
}
}
}
/* *************************************************************
* Destructor
*/
DForest::~DForest() {
delete[] minmax[0];
delete[] minmax[1];
delete[] minmax;
for (vector<F_DTree *>::iterator it = forest.begin(); it != forest.end();
it++) {
delete *it; //*it;
}
forest.clear();
}
/* *************************************************************
* return a pointer to the training set
*/
DataHandler * DForest::getDataHandler() {
return trainSet;
}
/* *************************************************************
* return the number of trees in the forest
*/
u_int DForest::getNbTrees() {
return forest.size();
}
/* *************************************************************
* return a trees of the forest
*/
F_DTree * DForest::getTree(u_int i) {
return forest[i];
}
/* *************************************************************
* add a decision tree to the forest
* param :
* tree : the Decision Tree to be added
*/
void DForest::addTree(F_DTree * tree) {
forest.push_back(tree);
}
/* *************************************************************
* Remove a decision tree from the forest
* param :
* ind : an index to the tree to remove.
*/
void DForest::removeTree(u_int ind) {
//...
}
/* *************************************************************
* Computes the margin function according to the given test dataset
* param :
* inst : a pointer to the instance on which the margin function is computed
*/
double DForest::margin(Instance * inst) {
int truClass = trainSet->getClass(inst);
double A = 0.0, B = 0.0;
vector<double> tabRes;
for (u_int i = 0; i < trainSet->getNbClass(); i++)
tabRes.push_back(0.0);
for (u_int i = 0; i < forest.size(); i++) {
//cerr<<"predict tree "<<i<<":";
u_int res = forest[i]->predict(inst);
tabRes[res]++;
//cerr<<"classe:"<<res<<endl;
//cin.get();
}
u_int * ind = Utils::sort(tabRes);
int max1 = ind[trainSet->getNbClass() - 1];
int max2 = ind[trainSet->getNbClass() - 2];
A = tabRes[truClass];
if (max1 == truClass)
B = tabRes[max2];
else
B = tabRes[max1];
A /= forest.size();
B /= forest.size();
delete[] ind;
tabRes.clear();
return (A - B);
}
/* *************************************************************
* Computes the strength of the forest according to the given test dataset.
* param :
* testset : the test set to be used for computing the strength
*/
double DForest::strength(DataHandler * testset) {
double mgs = 0.0;
for (int k = 0; k < (int) testset->size(); k++) {
Instance * inst = testset->getInstance(k);
mgs += margin(inst);
}
mgs /= testset->size();
return mgs;
}
/* *************************************************************
* Computes out-of-bag estimates of the strength of the forest.
*/
double DForest::strength() {
double str = 0.0;
for (u_int k = 0; k < trainSet->size(); k++) {
Instance * inst = trainSet->getInstance(k);
int truClass = trainSet->getClass(inst);
double A = 0.0, B = 0.0;
int nbTr = 0;
vector<double> tabRes;
for (u_int i = 0; i < trainSet->getNbClass(); i++)
tabRes.push_back(0.0);
for (u_int i = 0; i < forest.size(); i++) {
vector<u_int> bag = forest[i]->getBag();
if (find(bag.begin(), bag.end(), inst->getId()) == bag.end()) {
nbTr++;
u_int predictClass = forest[i]->predict(inst);
tabRes[predictClass]++;
}
}
u_int * ind = Utils::sort(tabRes);
int max1 = ind[trainSet->getNbClass() - 1];
int max2 = ind[trainSet->getNbClass() - 2];
A = tabRes[truClass];
if (max1 == truClass)
B = tabRes[max2];
else
B = tabRes[max1];
A /= nbTr;
B /= nbTr;
delete ind;
str += (A - B);
}
str /= trainSet->size();
return str;
}
double DForest::correlation(DataHandler * testset) {
// double corr = 0.0;
///double rmg_plus=0;
///double mean_rmg_plus=0;
///double rmg_uncorrect_max=0;
vector<double> rmg_theta_1;
vector<double> rmg_theta_2;
double sigma_theta_1 = 0;
double sigma_theta_2 = 0;
double sigma = 0;
double rho_final = 0;
///double s_mean_1=0;
///double s_mean_2=0;
///double s2_theta_1=0;
///double s2_theta_2=0;
int iter = 0;
int nb = (int) testset->size();
int nbTree = forest.size();
for (int t1 = 0; t1 < nbTree; t1++) {
for (int t2 = t1 + 1; t2 < nbTree; t2++) {
//calcul de la marge brute
double s_mean_1 = 0;
double s_mean_2 = 0;
double s2_theta_1 = 0;
double s2_theta_2 = 0;
for (int j = 0; j < nb; j++) {
Instance* inst = testset->getInstance(j);
int trueclass = inst->getClass();
int pred1 = forest.at(t1)->predict(inst);
int pred2 = forest.at(t2)->predict(inst);
double rmg_val = 0;
if (trueclass == pred1)
rmg_val = 1;
else
rmg_val = -1;
rmg_theta_1.push_back(rmg_val);
s_mean_1 += rmg_val / nb;
s2_theta_1 += rmg_val * rmg_val / nb;
rmg_val = 0;
if (trueclass == pred2)
rmg_val = 1;
else
rmg_val = -1;
rmg_theta_2.push_back(rmg_val);
s_mean_2 += rmg_val / nb;
s2_theta_2 += rmg_val * rmg_val / nb;
}
sigma_theta_1 = sqrt(s2_theta_1 - s_mean_1 * s_mean_1);
sigma_theta_2 = sqrt(s2_theta_2 - s_mean_2 * s_mean_2);
for (int j = 0; j < nb; j++) {
sigma += (rmg_theta_1.at(j) - s_mean_1)
* (rmg_theta_2.at(j) - s_mean_2) / nb;
}
rmg_theta_1.clear();
rmg_theta_2.clear();
if (sigma_theta_1 * sigma_theta_2 == 0)
return -2; //error
double rho = sigma / (sigma_theta_1 * sigma_theta_2);
sigma = 0;
rho_final += 2 * rho / (nbTree * nbTree - nbTree);
iter++;
}
}
return rho_final;
}
double DForest::correlation() {
cerr << "WARNING - NO VALUE ADDED YET" << endl;
return -1;
}
/* *************************************************************
* Computes the Out-Of-Bag Estimates
*/
Result * DForest::getOOBestimates() {
Result * res = new Result(trainSet, stats.timeTrain);
for (u_int k = 0; k < trainSet->size(); k++) {
Instance * inst = trainSet->getInstance(k);
u_int trueClass = trainSet->getClass(inst);
int cpt = 0;
u_int * tabRes = new u_int[trainSet->getNbClass()];
for (u_int i = 0; i < trainSet->getNbClass(); i++)
tabRes[i] = 0;
for (u_int i = 0; i < forest.size(); i++) {
vector<u_int> bag = forest[i]->getBag();
if (find(bag.begin(), bag.end(), inst->getId()) == bag.end()) {
cpt++;
u_int predictClass = forest[i]->predict(inst);
tabRes[predictClass]++;
}
}
u_int max = 0;
for (u_int i = 1; i < trainSet->getNbClass(); i++)
if (tabRes[max] < tabRes[i])
max = i;
res->maj_confMat(trueClass, max);
}
return res;
}
Result * DForest::getOOBOCestimates(u_int ** listsubspace, bool rsmOk, int nbRSM) {
///TODO:to move to OCFOREST_H
rsm_predict=rsmOk;
Result * res = new Result(trainSet, stats.timeTrain);
for (u_int k = 0; k < trainSet->size(); k++) {
Instance * inst = trainSet->getInstance(k);
u_int trueClass = trainSet->getClass(inst);
int cpt = 0;
u_int * tabRes = new u_int[2];
//for(u_int i=0;i<trainSet->getNbClass();i++) tabRes[i] = 0;
for (u_int i = 0; i < forest.size(); i++) {
vector<u_int> bag = forest[i]->getBag();
if (find(bag.begin(), bag.end(), inst->getOriginalId()) == bag.end()) {
cpt++;
Instance * curinst;
if (!rsm_predict) {
curinst = new Instance(inst->getOriginalId(), inst->getVect());
} else { //onrecopie les attributs des dimensions du rsm
int nbAttTrainSet = (int) trainSet->getNbAttributes();
vector<double> vals(nbRSM+1);
vector<int> vals_att(nbRSM+1);
int compt = 0;
for (int f = 0; f < nbAttTrainSet; f++) {
if (Utils::contains(listsubspace[i], f, nbRSM)) {
vals[compt] = inst->at(f);
vals_att[compt] = f;
compt++;
}
}
vals[nbRSM] = inst->getClass();
curinst = new Instance(inst->getOriginalId(), &vals);
}
u_int predictClass = forest[i]->predict(curinst);
delete curinst;
tabRes[predictClass]++;
}
}
u_int max = 0;
for (u_int i = 1; i < 2; i++){
if (tabRes[max] < tabRes[i]){
max = i;
}
}
delete[] tabRes;
res->maj_confMat(trueClass, max);
}
return res;
}
/* *************************************************************
* Give the Decision Forest prediction for a given instance
* param :
* inst : the instance that we want to predict the class
*/
u_int DForest::predict(Instance * inst) {
u_int * tabRes = new u_int[trainSet->getNbClass()];
for (u_int i = 0; i < trainSet->getNbClass(); i++)
tabRes[i] = 0;
for (u_int i = 0; i < forest.size(); i++) {
u_int res = forest[i]->predict(inst);
tabRes[res]++;
}
u_int max = 0;
for (u_int i = 1; i < trainSet->getNbClass(); i++)
if (tabRes[max] < tabRes[i])
max = i;
delete tabRes;
return max;
}
u_int DForest::predictOC(Instance * inst, u_int ** listsubspace, bool rsmOk,
int nbRSM, string filename) {
int nb = trainSet->getNbClass();
u_int * tabRes = new u_int[nb];
vector<double> vals(nbRSM + 1);
vector<int> vals_att(nbRSM + 1);
int compt;
rsm_predict = rsmOk;
for (int i = 0; i < (int) trainSet->getNbClass(); i++)
tabRes[i] = 0;
for (int i = 0; i < (int) forest.size(); i++) {
Instance * curinst;
if (!rsm_predict) {
curinst = new Instance(inst->getId(), inst->getVect());
} else { //onrecopie les attributs des dimensions du rsm
///mettre ici la liste des sous-esapces dans fdtree; couteux dans la boucle appelante a predictOC cependant
///forest[i]->setListSubspace(listsubspace[i]);
int nbAttTrainSet = (int) trainSet->getNbAttributes();
compt = 0;
for (int f = 0; f < nbAttTrainSet; f++) {
if (Utils::contains(listsubspace[i], f, nbRSM)) {
vals[compt] = inst->at(f);
vals_att[compt] = f;
compt++;
}
}
vals[nbRSM] = inst->getClass();
curinst = new Instance(inst->getId(), &vals);
forest[i]->setListDim(vals_att);
//forest[i]->setListSubspace(listsubspace[i]);
}
u_int res = forest[i]->predict(curinst);
delete curinst;
tabRes[res]++;
}
if (filename.compare("") != 0) {
ofstream resultsDecision(filename.c_str(), ios::out | ios::app);
resultsDecision << "\n" << inst->getId() << "\t" << inst->getClass()
<< "\t";
for (int j = 0; j < nb - 1; j++) {
resultsDecision << tabRes[j] << "\t";
}
resultsDecision << tabRes[nb - 1];
resultsDecision.close();
}
u_int max = 0;
for (u_int i = 1; i < trainSet->getNbClass(); i++)
if (tabRes[max] < tabRes[i])
max = i;
vals.clear();
vals_att.clear();
delete[] tabRes;
return max;
}
/* *************************************************************
* launch the test procedure for a given test set
* param :
* testSet : the test set to be used for the test procedure.
*/
Result * DForest::test(DataHandler * testSet) {
Result * res = new Result(testSet, stats.timeTrain);
for (v_inst_it it=testSet->begin();it!=testSet->end();it++)
{
cout << "test pour : "<<(*it)->toString()<<"\n";
u_int trueClass = testSet->getClass(*it);
u_int predictClass = predict(*it);
cout << "resultat : "<<predictClass<< " pour : "<<trueClass<<"\n";
res->maj_confMat(trueClass, predictClass);
}
return res;
}
Result * DForest::testOC(DataHandler * testSet, u_int ** listsubspace,
bool rsmOk, int nbRSM, string filename) {
Result * res = new Result(testSet, stats.timeTrain);
int i = 0;
for (v_inst_it it=testSet->begin();it!=testSet->end();it++)
{
u_int trueClass = testSet->getClass(*it);
u_int predictClass = predictOC(*it,listsubspace,rsmOk,nbRSM,filename);
res->maj_confMat(trueClass, predictClass);
/*
if(trueClass!=predictClass){
cout<<"["<<(*it)->getId()<<"/"<<(*it)->getOriginalId()<<":"<<trueClass<<"=>"<<predictClass<<"]"<<endl;
}
*/
i++;
}
return res;
}
int DForest::saveFile(string dest) {
int nb = forest.size();
for (int i = 0; i < nb; i++) {
/*backup
*nodes
*rule
*prediction
*/
//fileForest<<forest[i]->
stringstream out;
out << i;
string dest_tree = dest + "/tree_" + out.str() + ".txt";
Node * start_node = forest[i]->getRootNode();
writeFileForest(dest_tree, start_node); //starting node
}
return 0;
}
int DForest::writeFileForest(string dest_tree, Node * starting_node) {
ofstream fileForest(dest_tree.c_str(), ios::out | ios::app);
fileForest << "#parent\t" << starting_node->getId() << "\t#node_size\t"
<< starting_node->getSize() << "\t";
Rule * rule_split = starting_node->getSplitRule();
fileForest << "#attribute\t" << rule_split->getAttId() << "\t#split\t"
<< rule_split->getSupSplit() << "\t";
if (!starting_node->is_leaf()) {
fileForest << "#parent_split\t#left\t" << starting_node->getChild(0)->getId()
<< "\t";
fileForest << "#right\t" << starting_node->getChild(1)->getId() << "\n";
fileForest.close();
for (u_int j = 0; j < starting_node->getNbChildren(); j++) {
Node * child = starting_node->getChild(j);
writeFileForest(dest_tree, child); //starting node
}
} else {
/*
*prediction
*/
fileForest << "#leaf\t" << starting_node->getPrediction() << "\n";
}
fileForest.close();
return 0;
}
double DForest::stat_getTimeTrain() {
return stats.timeTrain;
}
double DForest::stat_getMeanDTTimeTrain() {
return stats.meanDTTimeTrain;
}
char DForest::stat_getLoadingBar(u_int n) {
return stats.loadingBar[n % 4];
}
void DForest::stat_setTimeTrain(double time) {
stats.timeTrain = time;
}
void DForest::stat_setMeanDTTimeTrain(double time) {
stats.meanDTTimeTrain = time;
}
void DForest::save(string filename) {
cout << "Saving file ..." << endl;
ofstream file(filename.c_str());
if (file.is_open()) {
if (trainSet->getFileName().empty()) {///Unable to retrieve original file path (inputstream or else)
string fileDataBackup = filename;
fileDataBackup += "_data.arff";
Arff::save(fileDataBackup.c_str(), trainSet);
}
file << trainSet->getFileName() << endl;
for (u_int i = 0; i < trainSet->size(); i++) {
file << trainSet->getInstance(i)->getId();
file << " ";
}
file << endl;
file << Utils::to_string((int) forest.size());
file << endl;
for (u_int i = 0; i < forest.size(); i++) {
string fileTreeName = filename;
//fileTreeName.erase(fileTreeName.end() - 6, fileTreeName.end());///TODO:search for last occurrence of "."
size_t pos=fileTreeName.rfind(".");
if(pos!=string::npos){
fileTreeName.erase(fileTreeName.begin()+pos, fileTreeName.end());///TODO:search for last occurrence of "."
}
else{
}
fileTreeName += Utils::to_string(i);
fileTreeName += ".tree";
forest[i]->save(fileTreeName, i);
file << fileTreeName << "\n";
file.flush();
}
} else {
cerr << "Unable to save model" << endl;
}
file.close();
cout << "Saving file OK." << endl;
}
string DForest::statsToString() {
string out = "";
/////////////////////////////////////////////
return out;
}
string DForest::toString() {
string res = "";
res += "Nombre d'arbres : ";
res += Utils::to_string((int) forest.size());
return res;
}
double DForest::getMeanNode() {
int nbArbre = forest.size();
unsigned long int totalnode = 0;
for (int i = 0; i < nbArbre; i++) {
totalnode += forest[i]->getNbNode();
}
return ((double) totalnode / (double) nbArbre);
}
| true |
ff1078b3a14dcefc52168183bb29e64b190b5728 | C++ | wangqiim/mycode | /CF/1324D.cpp | GB18030 | 596 | 2.578125 | 3 | [] | no_license | #include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 200005;
int nums[maxn]; //nums[i] = ai-bi
int main(){
int n; //nʦѧ
long long res = 0;
scanf("%d",&n);
int b;
for(int i=0;i<n;i++)
scanf("%d",&nums[i]);
for(int i=0;i<n;i++){
scanf("%d",&b);
nums[i]-=b;
}
sort(nums,nums+n);
for(int i=1;i<n;i++){
int L = 0,R = i-1;
int mid;
while(L<R){ //ҵһӺʹ0
mid = (L+R)/2;
if(nums[mid]+nums[i]>0)
R = mid;
else
L = mid+1;
}
if(nums[L]+nums[i]>0)
res += i-L;
}
printf("%lld",res);
return 0;
}
| true |
122da014120b8e2c5f5214b44cb002de4dce62ae | C++ | nowiwr01w/itmo | /algo/3 term/lab1/H.cpp | UTF-8 | 1,873 | 2.765625 | 3 | [] | no_license | #include <vector>
#include <iostream>
using namespace std;
const int MAX_N = 1001;
int n;
int ans, reversed_ans;
vector<bool> used;
vector<bool> reversed_used;
vector<vector<uint32_t>> graph;
vector<vector<uint32_t>> reversed_graph;
void dfs1(int vertex, int cur_min) {
used[vertex] = true;
ans++;
for (int cur_vertex = 0; cur_vertex < n; cur_vertex++)
if (!used[cur_vertex] && graph[vertex][cur_vertex] <= cur_min)
dfs1(cur_vertex, cur_min);
}
void dfs2(int vertex, int cur_min) {
reversed_used[vertex] = true;
reversed_ans++;
for (int cur_vertex = 0; cur_vertex < n; cur_vertex++) {
if (!reversed_used[cur_vertex] && reversed_graph[vertex][cur_vertex] <= cur_min) {
dfs2(cur_vertex, cur_min);
}
}
}
int main() {
cin.tie(nullptr);
ios_base::sync_with_stdio(false);
freopen("avia.in", "r", stdin);
freopen("avia.out", "w", stdout);
cin >> n;
used.resize(MAX_N);
reversed_used.resize(MAX_N);
graph.resize(MAX_N);
reversed_graph.resize(MAX_N);
for (int i = 0; i < MAX_N; i++) {
graph[i].resize(MAX_N);
reversed_graph[i].resize(MAX_N);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> graph[i][j];
reversed_graph[j][i] = graph[i][j];
}
}
int64_t left = -1;
int64_t right = MAX_N * MAX_N * MAX_N;
while (right - left > 1) {
int64_t middle = left - (left - right) / 2;
for (int i = 0; i < n; i++) {
used[i] = reversed_used[i] = false;
}
ans = reversed_ans = 0;
dfs1(0, middle);
dfs2(0, middle);
if (ans < n || reversed_ans < n) {
left = middle;
} else {
right = middle;
}
}
cout << right << endl;
return 0;
} | true |
c4235993a73f19d6a2619fee0bee3fe1ea1e65cf | C++ | StanleyDing/OnlineJudge | /UVA/UVA_10507_Waking_up_brain.cpp | UTF-8 | 1,315 | 2.59375 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int main()
{
int N, M, x, y, now, counter[26], wake[26], count;
bool con[26][26];
char in[5];
queue<int> q;
while(scanf("%d%d", &N, &M) != EOF){
memset(con, 0, sizeof(con));
memset(wake, -1, sizeof(wake));
memset(counter, 0, sizeof(counter));
count = 3;
scanf("%s", in);
for(int i = 0; i < 3; i++){
q.push(in[i] - 'A');
wake[in[i]-'A'] = 0;
}
for(int i = 0; i < M; i++){
scanf("%s", in);
x = in[0] - 'A', y = in[1] - 'A';
con[x][y] = con[y][x] = true;
}
while(!q.empty()){
now = q.front(), q.pop();
for(int i = 0; i < 26; i++){
if(con[now][i] && wake[i] < 0){
counter[i]++;
if(counter[i] == 3){
wake[i] = wake[now] + 1;
q.push(i);
count++;
}
}
}
}
if(count != N)
printf("THIS BRAIN NEVER WAKES UP\n");
else
printf("WAKE UP IN, %d, YEARS\n", wake[now]);
}
return 0;
}
| true |
505509fcaefcf198031fc18718a47c67b6bfd326 | C++ | jawwadmateen/OOP-concepts | /override keyword.cpp | UTF-8 | 323 | 2.984375 | 3 | [] | no_license | #include <iostream>
using namespace std;
class base
{
public:
virtual void show()
{
cout<<"Base Class"<<endl;
}
};
class derived:public base
{
public:
virtual void show()override
{
cout<<"Derived Class"<<endl;
}
};
int main()
{
derived d1;
base* b1;
b1=&d1;
b1->show();
}
| true |
29cb369b78239d36ece4b24f1b4e1bc735b1a499 | C++ | tklee1975/SimpleTDD-cocos2dx | /Classes/SimpleTDD/TDDData.cpp | UTF-8 | 3,496 | 2.59375 | 3 | [] | no_license | //
// TDDData.cpp
// Cocos2dxTDDLib
//
// Created by Ken Lee on 14/8/14.
//
//
#ifdef ENABLE_TDD
#include "TDDData.h"
#include "TDDHelper.h"
#define kKeyTestHistory "simpleTDD.ccx.history"
#define kKeySearchType "simpleTDD.ccx.searchType"
#define kKeyKeywordAll "simpleTDD.ccx.keyword.all"
#define kKeyKeywordRecent "simpleTDD.ccx.keyword.recent"
// singleton stuff
static TDDData *sShareInstance = nullptr;
TDDData::TDDData()
: mSearchType(TDDSearchAll)
, mKeywordAll("")
, mKeywordRecent("")
{
}
TDDData *TDDData::instance()
{
if (!sShareInstance)
{
sShareInstance = new TDDData();
sShareInstance->load();
}
return sShareInstance;
}
void TDDData::addTest(const std::string &testName)
{
// Remove the existing first
vector<std::string>::iterator it;
for(it = mTestHistory.begin(); it != mTestHistory.end(); )
{
std::string value = *it;
if(value.compare(testName) == 0) {
mTestHistory.erase(it);
} else {
it++;
}
}
//
it = mTestHistory.begin();
mTestHistory.insert(it, testName);
// mTestHistory
save();
}
void TDDData::clearHistory()
{
if(mTestHistory.size() <= 1) {
// No need to clear
return;
}
vector<std::string>::iterator begin = mTestHistory.begin() + 1;
vector<std::string>::iterator end = mTestHistory.end();
mTestHistory.erase(begin, end);
save();
}
void TDDData::save()
{
// Combine the history first
std::string content = TDDHelper::joinString(mTestHistory, "\n");
TDDHelper::saveStringToDevice(kKeyTestHistory, content);
// Save the search type
std::string value = mSearchType == TDDSearchRecent ? "recent" : "all";
TDDHelper::saveStringToDevice(kKeySearchType, value);
}
void TDDData::load()
{
// Load keyword
mKeywordRecent = TDDHelper::loadStringFromDevice(kKeyKeywordRecent);
mKeywordAll = TDDHelper::loadStringFromDevice(kKeyKeywordAll);
// Load the test history
std::string content = TDDHelper::loadStringFromDevice(kKeyTestHistory);
std::vector<std::string> history = TDDHelper::splitString(content, '\n', 0);
mTestHistory.clear();
//
for(int i=0; i<history.size(); i++)
{
std::string str = history[i];
if(str.length() == 0) {
continue;
}
mTestHistory.push_back(str);
}
// Search Type
content = TDDHelper::loadStringFromDevice(kKeySearchType);
mSearchType = (content == "recent") ? TDDSearchRecent : TDDSearchAll;
}
std::string TDDData::toString()
{
std::string result = "";
result += StringUtils::format("SearchType=%d\n", mSearchType);
result += StringUtils::format("History count=%ld\n", mTestHistory.size());
// List of history test
for(int i=0; i<mTestHistory.size(); i++) {
result += mTestHistory[i];
result += "\n";
}
return result;
}
std::vector<std::string> TDDData::getTestHistory()
{
return mTestHistory;
}
void TDDData::setSearchType(const TDDSearchType &searchType)
{
mSearchType = searchType;
save();
}
TDDSearchType TDDData::getSearchType()
{
return mSearchType;
}
void TDDData::saveKeyword(TDDSearchType type, const std::string &keyword)
{
if(TDDSearchAll == type) {
mKeywordAll = keyword;
TDDHelper::saveStringToDevice(kKeyKeywordAll, keyword);
} else if(TDDSearchRecent == type) {
mKeywordRecent = keyword;
TDDHelper::saveStringToDevice(kKeyKeywordRecent, keyword);
}
}
std::string TDDData::getKeyword(TDDSearchType type)
{
if(TDDSearchAll == type) {
return mKeywordAll;
} else if(TDDSearchRecent == type) {
return mKeywordRecent;
} else {
return "";
}
}
#endif /* ENABLE_TDD */ | true |
d91011bbaf0b83f6cccd84a32b8da78632c0f500 | C++ | pauldepalma/CPSC121 | /ex9.cpp | UTF-8 | 523 | 3.265625 | 3 | [] | no_license | /*
CPSC 121-0X
Paul De Palma
depalma
Example 9
*/
//exponentiation with ints
//try using exponents greater than 30
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
int base, exp, i, total;
base = exp = i = total = 0;
cout << "Enter a base and the highest power you'd like to see" << endl;
cin >> base >> exp;
cout << setprecision(0) << fixed;
while(i <= exp)
{
total = pow(base,i);
cout << i << ":" << setw(10) << total << endl;
++i;
}
return 0;
}
| true |
2e48875c5ca432a00d2f2aaa690908693f5cb713 | C++ | Juan14-mart/Tarea-I | /Ejercicio_005.cpp | UTF-8 | 332 | 2.96875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int main () {
int edad,b,c;
printf("Ingrese la edad");
scanf("%d",&edad);
if(edad>60){
c=75*.45;
printf ("El costo del boleto es: %d",c);
}else if(edad<18){
b=75*.4;
printf ("El costo del boleto es: %d",b);
}else if (edad>=18){
printf("El costo del boleto es:75");
}
}
| true |
5fd4e3c93b9be78dd091009934ad87786a5d8078 | C++ | arunxls/GraphReLabel | /GraphReLabel/GraphHeaderReader.cpp | UTF-8 | 2,176 | 3.03125 | 3 | [] | no_license | #include "stdafx.h"
#include "GraphHeaderReader.h"
template <typename T>
GraphHeaderReader<T>::GraphHeaderReader()
{
}
template<typename T>
GraphHeaderReader<T>::GraphHeaderReader(char * filename)
{
this->FR = new FileReader(filename);
this->length = 0;
//Save some extra buffer space for partial reads
uint32 extra_buffer = sizeof(HeaderGraph<T>);
this->buffer_start = new char[GRAPH_HEADER_READ_BUFFER*_1_MB + extra_buffer];
this->buffer_start = this->buffer_start + extra_buffer;
this->buffer_end = this->buffer_start + GRAPH_HEADER_READ_BUFFER*_1_MB;
this->header_start = this->buffer_start;
this->neighbour_start = this->header_start + sizeof(HeaderGraph<T>);
this->end = this->buffer_start;
}
template <typename T>
GraphHeaderReader<T>::~GraphHeaderReader()
{
}
template<typename T>
HeaderGraph<T> GraphHeaderReader<T>::currentHeader()
{
if (this->header_start == this->end)
{
this->load();
this->header_start = this->buffer_start;
}
uint32 sizeToRead = sizeof(HeaderGraph<T>);
if (this->header_start + sizeToRead > this->end)
{
uint32 bytesToCopy = this->end - this->header_start;
char* dst = this->buffer_start - bytesToCopy;
memcpy(dst, this->header_start, bytesToCopy);
this->header_start = dst;
this->load();
}
return *(HeaderGraph<T>*) this->header_start;
}
template<typename T>
uint32 GraphHeaderReader<T>::currentNeighbour()
{
return uint32();
}
template<typename T>
void GraphHeaderReader<T>::nextHeader()
{
}
template<typename T>
void GraphHeaderReader<T>::nextNeighbour()
{
}
template<typename T>
bool GraphHeaderReader<T>::hasNextHeader()
{
return this->FR->has_next() ? true : this->header_start < this->end;
}
template<typename T>
bool GraphHeaderReader<T>::hasNextNeighbour()
{
return this->FR->has_next() ? true : this->neighbour_start < this->end;
}
template<typename T>
void GraphHeaderReader<T>::load()
{
uint32 bytesTransferred = 0;
this->FR->read(this->buffer_start, this->buffer_end - this->buffer_start, bytesTransferred);
this->end = this->buffer_start + bytesTransferred;
}
| true |
2c96e58b2ac7e0363badbf791dd2719dab8148de | C++ | akstraw/PokerAI | /ai/randomPlayer.cpp | UTF-8 | 1,497 | 3.09375 | 3 | [] | no_license | #include "randomPlayer.h"
#include <chrono>
#include <random>
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <fstream>
using std::ofstream;
using std::ifstream;
RandomPlayer::RandomPlayer() : Player{}
{}
int RandomPlayer::raise(int highestBet)
{
int rv = highestBet;
int bet = rand() % dollars;
if (bet > highestBet) rv = bet;
std::cout << "Player " << number << " raises " << rv << std::endl;
currentBet += rv;
dollars -= rv;
return rv;
}
int RandomPlayer::foldCallRaise(GameState& gamestate)
{
int rv = 0;
for(Card c : gamestate.communityCards)
rv++;
rv = 0;
int confidence = rand() % 2;
if (confidence == 0)
fold();
else{
confidence = rand() % 2;
if (confidence == 0)
call(gamestate.highestBet);
else
rv = raise(gamestate.highestBet);
}
return rv;
}
int RandomPlayer::foldOrCall(GameState& gamestate)
{
int rv = 0;
for(Card c : gamestate.communityCards)
rv++;
rv = 0;
int confidence = rand() % 2;
if (confidence == 0)
fold();
else
rv = call(gamestate.highestBet);
return rv;
}
int RandomPlayer::checkOrRaise(GameState& gamestate)
{
int rv = 0;
for(Card c : gamestate.communityCards)
rv++;
rv = 0;
int confidence = rand() % 2;
if (confidence == 0)
check();
else
rv = raise(gamestate.highestBet);
return rv;
} | true |
dc37bf81dc8ce0952c0bf68152d726f790041443 | C++ | ritabugking/Programming | /array.cpp | UTF-8 | 14,777 | 3.953125 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <cassert>
using namespace std;
// Return the number of strings in the array that are equal to target.
int tally(const string a[], int n, string target) {
int num = 0;
if (n < 0 ) // If the size of input array is less than zero, return -1.
return -1;
for (int i = 0; i < n; i++) { // Go through the whole array and check the number of string which is equal to target string.
if (a[i] == target)
num++;
}
return num; // Return the number of target string in the array.
};
// Return the position of the first string in the array that is equal to target. Return −1 if there is no such string.
int findFirst(const string a[], int n, string target) {
if ( n < 0 ) // If the size of input array is less than zero, return -1.
return -1;
for (int i = 0; i < n; i++) { // Go through the whole array and find the first target string. If find it, return the position of the target string.
if (a[i] == target)
return i;
}
return -1; // If there is no target string among array, return -1.
};
// Find the earliest occurrence in a of one or more consecutive strings that are equal to target.
// Set begin to the position of the first occurrence of target; set end to the last occurrence of target in that earliest consecutive sequence. Return true.
// If n is negative or if no string in a is equal to target, leave begin and end unchanged and return false.
bool findFirstSequence(const string a[], int n, string target, int& begin, int& end) {
if (n < 0) // If the size of input array is less than zero, return -1.
return -1;
for (int i = 0; i < n; i++) { // Go through the array and find the target.
if (a[i] == target) { // While finding the target, set "begin" and "end" equal to the position of target.
begin = i;
end = i;
for (int j = i; j < n; j++) { // Find the consecutive strings that are equal to target, and set "end" at the end of consecutive string.
if (j!= n) {
if (a[j] == target)
end = j;
else
break;
}
else
break;
}
return true;
}
}
return false; // If no string in a is equal to target, return false.
};
// Return the position of a string in the array such that that string is <= every string in the array.
// If there is more than one such string, return the smallest position of such a string. Return −1 if the array has no elements.
int positionOfMin(const string a[], int n) {
if (n <= 0 ) // If the size of input array less than or equal to zero, return -1.
return -1;
int min = 0;
for (int i = 1; i < n; i++) { // Go through the array and find minimum string.
if (a[min] > a[i])
min = i;
}
return min; // Return the position of that string.
};
// Eliminate the item at position pos by copying all elements after it one place to the left.
// Put the item that was thus eliminated into the last position of the array.
// Return the original position of the item that was moved to the end.
int moveToEnd(string a[], int n, int pos) {
if (n < 0 || pos > n-1) // If the size of input array is less than zero, or pos is larger than the last position among array, return -1.
return -1;
string temp = a[pos];
for (int i = pos; i < n-1; i++) { // Move all elements after pos one place to the left.
a[pos] = a[pos + 1];
}
a[n - 1] = temp; // Put the item that was thus eliminated into the last position of the array.
return pos; // Return the original position of the item that was moved to the end.
};
// Eliminate the item at position pos by copying all elements before it one place to the right.
// Put the item that was thus eliminated into the first position of the array.
// Return the original position of the item that was moved to the beginning.
int moveToBeginning(string a[], int n, int pos) {
if (n < 0 || pos > n - 1) // If the size of input array is less than zero, or pos is larger than the last position among array, return -1.
return -1;
string temp = a[pos];
for (int i = pos; i > 0; i--) { // Move all elements after pos one place to the right.
a[pos] = a[pos - 1];
}
a[0] = temp; // Put the item that was thus eliminated into the first position of the array.
return pos; // Return the original position of the item that was moved to the end.
};
// Return the position of the first corresponding elements of a1 and a2 that are not equal.
// n1 is the number of interesting elements in a1, and n2 is the number of interesting elements in a2.
// If the arrays are equal up to the point where one or both runs out, return the smaller of n1 and n2.
int disagree(const string a1[], int n1, const string a2[], int n2) {
if (n1 < 0 || n2 < 0 ) // If the size of input array less than zero, return -1.
return -1;
int equal=-1; // First, initiate "equal" as the position of the first corresponding elements of a1 and a2 that are not equal.
int pos;
if (n1 > n2) // Set the smaller number among two arrays as the last position that need to be checked.
pos = n2;
else
pos = n1;
for (int i = 0; i < pos; i++) { // Go through the two arrays and check if the element at each position is equal.
if (a1[i] == a2[i]) {
equal++;
}
else
break;
}
return (equal + 1); // Return the position of the first corresponding elements of a1 and a2 that are not equal. If there is no equal element, return the first position which is 0.
};
// For every sequence of consecutive identical items in a, retain only one item of that sequence. Return the number of retained items.
int removeDups(string a[], int n) {
if ( n < 0 ) // If the size of input array less than zero, return -1.
return -1;
int total = n; // Set total equal to the number of items in the array.
int i = 0;
for (i; i < total-1; i++){ // Go through the array, if there are identical items at position i and i+1, then delete the ith item and move all the item at the left side of i to one step right.
if (a[i] == a[i + 1]) {
for (int j = i; j < total - 1; j++)
a[j] = a[j + 1];
total--; // Minus one from the number of items in the array.
i--; // Minus one from i so the loop can start from ith position again.
}
}
return total; // Return the number of retained items.
};
// If all n2 elements of a2 appear in a1, in the same order, then return true.
// Return false if a1 does not contain a2 as a subsequence.
// Return false if this function is passed any bad arguments.
bool subsequence(const string a1[], int n1, const string a2[], int n2) {
if ( n1 < 0 || n2 < 0 || n2 > n1) // If the size of input array less than zero, or if n2 is larger than n1, return -1.
return false;
if (n2 == 0) // Since the empty sequence is a subsequence of any sequence, return true if n2 = 0.
return true;
int pos = 0;
for (int i = 0; i < n2; i++) { // Go through each element among the a2 array.
for (int j = pos; j < n1; j++) { // Go through a1 array and check if every element in a2 can be found among a1 in the same order.
if (a2[i] == a1[j]) {
pos = j + 1;
break;
}
else if (i == n2 - 1 && j == n1 - 1) // If both of the arrays reach the last position without equal to the value at last position of each other, return false.
return false;
}
}
return true; // If all n2 elements of a2 appear in a1 in the same order, return true.
};
// If a1 has n1 elements in nondecreasing order, and a2 has n2 elements in nondecreasing order, place in result all the elements of a1 and a2, arranged in nondecreasing order.
// Return the number of all the elements in new array.
// Return −1 if the result would have more than max elements or if a1 and/or a2 are not in nondecreasing order.
int mingle(const string a1[], int n1, const string a2[], int n2, string result[], int max) {
if ( n1 < 0 || n2 < 0 || (n1+n2) > max) // If the size of input array less than zero, or if the total number of items is larger than max, return -1.
return -1;
for (int i = 0; i < n1-1; i++) { // Return -1 if a1 is not in nondecreasing order.
if (a1[i] > a1[i + 1])
return -1;
}
for (int i = 0; i < n2 - 1; i++) { // Return -1 if a2 is not in nondecreasing order.
if (a2[i] > a2[i + 1])
return -1;
}
int order_a1 = 0; // Set order_a1 equal to the position of concerning element among a1.
int order_a2 = 0; // Set order_a2 equal to the position of concerning element among a2.
int order_result = 0; // Set order_result equal to the position of concerning element among result.
for (int i = 0; i < (n1 + n2); i++) { // Go through the array until every elements among a1 and a2 are all append to the new array "result".
if (order_a2 == n2) { // If no element of array a2 can be reached, append the rest element among a1 to the result array. Return the number of all the elements in the new array.
for (int j = order_a1; j < n1; j++) {
result[order_result] = a1[j];
order_result++;
}
return (n1 + n2);
}
if (order_a1 == n1) { // If no element of array a1 can be reached, append the rest element among a2 to the result array. Return the number of all the elements in the new array.
for (int j = order_a2; j < n2; j++) {
result[order_result] = a2[j];
order_result++;
}
return (n1 + n2);
}
// Compare the element among a1 and a2 and append the smaller element to the new array "result".
if (a1[order_a1] > a2[order_a2]) {
result[order_result] = a2[order_a2];
order_result++;
order_a2++;
}
else {
result[order_result] = a1[order_a1];
order_result++;
order_a1++;
}
}
return (n1 + n2); // Return the number of all the elements in new array.
};
// Rearrange the elements of the array so that all the elements whose value is < divider come before all the other elements, and all the elements whose value is > divider come after all the other elements.
// Return the position of the first element that, after the rearrangement, is not < divider, or n if there are none.
int divide(string a[], int n, string divider) {
if (n < 0) // If the size of input array less than zero, return -1.
return -1;
int pos = 0;
string temp;
for (int i = 0; i < n; i++) { // Go through all the elements in array a.
if (a[i] >= divider) { // Find the first element which >= divider, and set "pos" equal to the position of this first element.
pos = i;
for (int j = i+1; j < n; j++) { // If there is element at the right side of "pos" < divider, exchange this element with the element at "pos".
if (a[j] < divider) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
pos++; // Move the "pos" one step forward toward the tail of the array.
}
}
return pos; // Return the position of the first element which is >= divider after arrangement.
}
}
return n; // Return n if there is no element >= divider.
};
int main() {
// Test
string a1[1] = { "" };
string a2[3] = { " ", " a ", " abc" };
string a3[4] = { "!!!@@", "\n", """", "{}" };
string h[7] = { "petyr", "jaime", "jon", "daenerys", "", "tyrion", "jon" };
string a5[8] = { "petyr", "petyr", "jon", "petyr", "petyr", "petyr", "jon", "jon" };
//assert(tally(a1, 7, "jon") == 0); // cannot detect this error
assert(tally(a1, 1, "jon") == 0);
assert(tally(a1, 1, "") == 1);
assert(tally(a1, 0, "") == 0);
assert(tally(a2, 3, "") == 0);
assert(tally(a2, 3, " ") == 1);
assert(tally(a2, 3, "a") == 0);
assert(tally(a2, 3, "abc") == 0);
assert(tally(a2, 3, " abc") == 1);
assert(tally(a3, 4, "\n") == 1);
assert(tally(a3, 4, """") == 1);
assert(tally(a3, 4, "{}") == 1);
assert(tally(a3, 4, "!!!@@") == 1);
assert(tally(h, 7, "jon") == 2);
assert(tally(h, 7, "") == 1);
assert(tally(h, 7, "theon") == 0);
assert(tally(h, 0, "jon") == 0);
//assert(findFirst(h, 10, "jon") == 2); //cannot detect the error
assert(findFirst(h, 2, "jon") == -1);
assert(findFirst(h, 3, "jon") == 2);
assert(findFirst(h, 7, "Jon") == -1);
assert(findFirst(a1, 1, "") == 0);
int bg;
int en;
//assert(findFirstSequence(h, 10, "daenerys", bg, en) && bg == 3 && en == 3); //cannot detect the error
assert(findFirstSequence(h, 7, "daenerys", bg, en) && bg == 3 && en == 3);
assert(findFirstSequence(a5, 8, "petyr", bg, en) && bg == 0 && en == 1);
assert(findFirstSequence(a5, 1, "petyr", bg, en) && bg == 0 && en == 0);
assert(findFirstSequence(a5, 8, "jon", bg, en) && bg == 2 && en == 2);
assert(!findFirstSequence(a5, 8, "Jon", bg, en));
string g[4] = { "petyr", "jaime", "daenerys", "tyrion" };
string a7[4] = { "aaaaa", "d", " ", " " };
//assert(positionOfMin(g, 10) == 2); //cannot detect the error
assert(positionOfMin(g, 4) == 2);
assert(positionOfMin(h, 7) == 4);
assert(positionOfMin(h, 0) == -1);
assert(positionOfMin(a5, 8) == 2);
assert(positionOfMin(a7, 2) == 0);
assert(positionOfMin(a7, 3) == 2);
assert(positionOfMin(a7, 4) == 3);
string a8[4] = { "petyr", "jaime", "daenerys", "tyrion" };
//assert(disagree(h, 10, g, 4) == 2); //cannot detect the error
assert(disagree(h, 4, g, 4) == 2);
assert(disagree(g, 3, g, 4) == 3);
assert(disagree(h, 0, g, 4) == 0);
//assert(subsequence(h, 10, g, 4)); //cannot detect the error
assert(subsequence(h, 7, g, 4));
assert(!subsequence(h, 0, g, 4));
assert(subsequence(h, 4, g, 0)); //the empty sequence is a subsequence of any sequence
string a9[1] = { "petyr" };
//assert(moveToEnd(a9, 10, 0) == 0 && a9[0] == "petyr"); //cannot detect the error
assert(moveToEnd(g, 0, 1) == -1);
assert(moveToEnd(g, 4, 1) == 1 && g[1] == "daenerys" && g[3] == "jaime");
assert(moveToEnd(a9, 1, 0) == 0 && a9[0] == "petyr");
string f[4] = { "daenerys", "tyrion", "jon", "jaime" };
//assert(moveToBeginning(f, 10, 2) == -1); //cannot detect the error
assert(moveToBeginning(f, 0, 2) == -1);
assert(moveToBeginning(f, 4, 2) == 2 && f[0] == "jon" && f[2] == "tyrion");
assert(moveToBeginning(a9, 1, 0) == 0 && a9[0] == "petyr");
string e[5] = { "daenerys", "daenerys", "daenerys", "jon", "jon" };
string a10[5] = { "daenerys", "jon", "daenerys", "jon", "daenerys" };
//assert(removeDups(e, 10) == 2 && e[1] == "jon"); //cannot detect the error
assert(removeDups(e, 5) == 2 && e[1] == "jon");
assert(removeDups(a10, 5) == 5 && e[1] == "jon");
string x[4] = { "cersei", "jaime", "jaime", "theon" };
string y[4] = { "daenerys", "jaime", "jon", "tyrion" };
string z[10];
//assert(mingle(x, 5, y, 4, z, 10) == 8 && z[5] == "jon"); //cannot detect the error
assert(mingle(x, 4, y, 4, z, 10) == 8 && z[5] == "jon");
assert(mingle(x, 4, y, 0, z, 10) == 4 && z[1] == "jaime");
//assert(divide(h, 10, "jon") == 3); //cannot detect the error
assert(divide(h, 7, "jon") == 3);
assert(divide(h, 7, "z") == 7);
assert(divide(h, 7, "") == 0);
assert(divide(h, 0, "jon") == 0);
cout << "All tests succeeded" << endl;
system("pause");
}
| true |
23e7389e982943282e6000d960a91ab55a15f499 | C++ | newsb/qtdemo | /deevBean/QTGraphicsViewDemo/mainwindow - 副本.cpp | UTF-8 | 1,666 | 2.71875 | 3 | [] | no_license | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#define TILE_SIZE 22
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
// , ui(new Ui::MainWindow)
,scene(new QGraphicsScene(this))
,view(new QGraphicsView(scene,this))
// ,game(new GameController(*scene, this))
{
// ui->setupUi(this);
setCentralWidget(view);
resize(600, 600);
initScene();
initSceneBackground();
// 在下一次事件循环开始时,立刻 调用this->adjustViewSize()
// 我们需要在视图绘制完毕后才去改变大小(视图绘制当然是在paintEvent()事件中),因此我们需要在下一次事件循环中调用adjustViewSize()函数。
QTimer::singleShot(0, this, SLOT(adjustViewSize()));
}
void MainWindow::initScene()
{ //默认情况下,场景是无限大的
scene->setSceneRect(-100, -100, 200, 200);
/*Graphics View Framework 为每一个元素维护三个不同的坐标系:
场景坐标,
元素自己的坐标
以及其相对于父组件的坐标。
除了元素在场景中的位置,其它几乎所有位置都是相对于元素坐标系的。
*/
}
void MainWindow::initSceneBackground()
{
//创建一个边长TILE_SIZE的QPixmap
QPixmap bg(TILE_SIZE, TILE_SIZE);
//其使用灰色填充矩形。我们没有设置边框颜色,默认就是黑色。
QPainter p(&bg);
//然后将这个QPixmap作为背景画刷,铺满整个视图。
p.setBrush(QBrush(Qt::gray));
p.drawRect(0, 0, TILE_SIZE, TILE_SIZE);
view->setBackgroundBrush(QBrush(bg));
}
MainWindow::~MainWindow()
{
// delete ui;
}
| true |
413eb1bad8458820708a97b7f3546af9ab721f3a | C++ | MaxenceRobin/CompilerForRobotic | /compilers/micropython/micropythoncompiler.cpp | UTF-8 | 19,065 | 2.734375 | 3 | [] | no_license | #include "ANTLR/antlr4-runtime/PivotLexer.h"
#include "micropythoncompiler.h"
using namespace antlr4;
#include <QDebug>
/**
* @brief Constructor of the MicroPython compiler class
*/
MicroPythonCompiler::MicroPythonCompiler()
: PivotBaseVisitor()
{
}
/**
* @brief Initializes the intern attributes used during the compilation process
*/
void MicroPythonCompiler::initialize()
{
indentationCount = 0;
}
// Methods ----------------------------------------------------------------------------------------
/**
* @brief Increments the number of indentations
*/
void MicroPythonCompiler::incrementIndentation()
{
indentationCount++;
}
/**
* @brief Decrements the number of indentation, or does nothing if the value is already 0
*/
void MicroPythonCompiler::decrementIndentation()
{
if (indentationCount > 0)
{
indentationCount--;
}
}
/**
* @brief Returns the current indentation
* @return the current indentation
*/
string MicroPythonCompiler::getIndentation()
{
string result = "";
for (unsigned int i = 0; i < indentationCount; i++)
{
result += "\t";
}
return result;
}
/**
* @brief Returns the MicroPython code for the given pivot code
* @param pivot : The code to translate into MicroPython
* @return The MicroPython code for the given pivot code
*/
string MicroPythonCompiler::getMicroPythonFromPivot(const string &pivot)
{
ANTLRInputStream stream(pivot);
PivotLexer lexer(&stream);
CommonTokenStream tokens(&lexer);
PivotParser parser(&tokens);
PivotParser::FileContext* tree = parser.file();
initialize();
string result = visitFile(tree).as<string>();
return result;
}
/**
* @brief Returns the MicroPython representation of a file
* @param context : The tree representation of the file
* @return The string that represents the MicroPython code of the file
*/
Any MicroPythonCompiler::visitFile(PivotParser::FileContext *context)
{
/*string result = visitStatements(context->statements()).as<string>();
return std::move(result);*/
return visitStatements(context->statements());
}
/**
* @brief Returns the MicroPython representation of a block of statements
* @param context : The tree representation of a block of statements
* @return The string that represents the MicroPython code of the block of statements
*/
Any MicroPythonCompiler::visitStatements(PivotParser::StatementsContext* context)
{
string result = "";
for (auto statement : context->statement())
{
result += visitStatement(statement).as<string>();
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a statement
* @param context : The tree representation of the statement
* @return The string that represents the MicroPython code of the statement
*/
Any MicroPythonCompiler::visitStatement(PivotParser::StatementContext *context)
{
string result = getIndentation();
if (context->action())
{
result += visitAction(context->action()).as<string>() + "\n";
}
else if (context->declaration())
{
result += visitDeclaration(context->declaration()).as<string>() + "\n";
}
else if (context->assignment())
{
result += visitAssignment(context->assignment()).as<string>() + "\n";
}
else if (context->loop())
{
result += visitLoop(context->loop()).as<string>();
}
else if (context->if_elif_else())
{
result += visitIf_elif_else(context->if_elif_else()).as<string>();
}
else if (context->while_loop())
{
result += visitWhile_loop(context->while_loop()).as<string>();
}
else if (context->until_loop())
{
result += visitUntil_loop(context->until_loop()).as<string>();
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of an action
* @param context : The tree representation of the action
* @return The string that represents the MicroPython code of the action
*/
Any MicroPythonCompiler::visitAction(PivotParser::ActionContext *context)
{
string result = "";
// Movement actions -------------------------
if (context->move_type)
{
const string moveType = context->move_type->getText();
if (moveType == "forward")
{
result = "Avancer_droit";
}
else if (moveType == "backward")
{
result = "Reculer_droit";
}
else if (moveType == "left")
{
result = "Pivoter_gauche";
}
else if (moveType == "right")
{
result = "Pivoter_droite";
}
result += "(";
if (context->move_speed)
{
const string moveSpeed = context->move_speed->getText();
if (moveSpeed == "slow")
{
result += "V_MIN";
}
else if (moveSpeed == "normal")
{
result += "V_MOYEN";
}
else if (moveSpeed == "fast")
{
result += "V_MAX";
}
}
else
{
result += visitNumeric_expression(context->numeric_expression()).as<string>();
}
result += ")";
}
// Stoping action ---------------------------
else if (context->STOP())
{
result = "Arret()";
}
// Waiting action ---------------------------
else if (context->WAIT())
{
result = "time.sleep(" + visitNumeric_expression(context->duration).as<string>() + ")";
}
else if (context->LED())
{
string color = "";
if (context->RGB())
{
color = visitRGB(context->RGB());
}
else if (context->special_color())
{
color = visitSpecial_color(context->special_color()).as<string>();
}
else if (context->VARIABLE())
{
color = context->VARIABLE()->getText();
}
result = "pycom.rgbled(" + color + ")";
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a special color expression
* @param context : The tree representation of the special color expression
* @return The string that represents the MicroPython code of the special color expression
*/
Any MicroPythonCompiler::visitSpecial_color(PivotParser::Special_colorContext* context)
{
string result = "";
if (context->RANDOMCOLOR())
{
result = "random_color()";
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of an assignment
* @param context : The tree representation of the assignment
* @return The string that represents the MicroPython code of the assignment
*/
Any MicroPythonCompiler::visitDeclaration(PivotParser::DeclarationContext* context)
{
string result = "";
bool first = true;
for (auto variable : context->var_name)
{
if (!first)
{
result += "\n" + getIndentation();
}
result += variable->getText() + " = 0";
first = false;
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of an assignment
* @param context : The tree representation of the assignment
* @return The string that represents the MicroPython code of the assignment
*/
Any MicroPythonCompiler::visitAssignment(PivotParser::AssignmentContext* context)
{
string result = context->VARIABLE()->getText() + " = " + visitExpression(context->expression()).as<string>();
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of an expression
* @param context : The tree representation of the expression
* @return The string that represents the MicroPython code of the expression
*/
Any MicroPythonCompiler::visitExpression(PivotParser::ExpressionContext* context)
{
string result = "";
if (context->numeric_expression())
{
result = visitNumeric_expression(context->numeric_expression()).as<string>();
}
else if (context->boolean_expression())
{
result = visitBoolean_expression(context->boolean_expression()).as<string>();
}
else if (context->RGB())
{
result = visitRGB(context->RGB());
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a loop
* @param context : The tree representation of the loop
* @return The string that represents the MicroPython code of the loop
*/
Any MicroPythonCompiler::visitLoop(PivotParser::LoopContext *context)
{
string result = "for _ in range(" + visitNumeric_expression(context->repetition_number).as<string>() + ") :\n";
incrementIndentation();
result += visitStatements(context->statements()).as<string>();
decrementIndentation();
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a while loop
* @param context : The tree representation of the while loop
* @return The string that represents the MicroPython code of the while loop
*/
Any MicroPythonCompiler::visitWhile_loop(PivotParser::While_loopContext* context)
{
string result = "while " + visitBoolean_expression(context->condition).as<string>() + " :\n";
incrementIndentation();
result += visitStatements(context->statements()).as<string>();
decrementIndentation();
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a until loop
* @param context : The tree representation of the until loop
* @return The string that represents the MicroPython code of the until loop
*/
Any MicroPythonCompiler::visitUntil_loop(PivotParser::Until_loopContext *context)
{
string result = "while True :\n";
incrementIndentation();
result += visitStatements(context->statements()).as<string>();
result += getIndentation() + "if " + visitBoolean_expression(context->condition).as<string>() + " :\n";
incrementIndentation();
result += getIndentation() + "break\n";
decrementIndentation();
decrementIndentation();
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a numeric expression
* @param context : The tree representation of the numeric expression
* @return The string that represents the MicroPython code of the numeric expression
*/
Any MicroPythonCompiler::visitNumeric_expression(PivotParser::Numeric_expressionContext* context)
{
string result = "";
bool first = true;
unsigned int operatorNumber = 0;
for (auto currentValue : context->value)
{
if (!first)
{
result += context->op[operatorNumber]->getText();
operatorNumber++;
}
result += visitNumeric_mul_div(currentValue).as<string>();
first = false;
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a numeric multiplication or division
* @param context : The tree representation of a numeric multiplication or division
* @return The string that represents the MicroPython code of the numeric multiplication or division
*/
Any MicroPythonCompiler::visitNumeric_mul_div(PivotParser::Numeric_mul_divContext* context)
{
string result = "";
bool first = true;
unsigned int operatorNumber = 0;
for (auto currentValue : context->value)
{
if (!first)
{
result += context->op[operatorNumber]->getText();
operatorNumber++;
}
result += visitNumeric_pow(currentValue).as<string>();
first = false;
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a power expression
* @param context : The tree representation of the power expression
* @return The string that represents the MicroPython code of the power expression
*/
Any MicroPythonCompiler::visitNumeric_pow(PivotParser::Numeric_powContext* context)
{
string result = "";
bool first = true;
for (auto currentValue : context->value)
{
if (!first)
{
result += "**";
}
result += visitNumeric_inversion(currentValue).as<string>();
first = false;
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a numeric inversion
* @param context : The tree representation of the numeric inversion
* @return The string that represents the MicroPython code of the numeric inversion
*/
Any MicroPythonCompiler::visitNumeric_inversion(PivotParser::Numeric_inversionContext* context)
{
string result = visitNumeric_atom(context->numeric_atom()).as<string>();
if (context->MINUS())
{
result = "-" + result;
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a numeric atom
* @param context : The tree representation of the numeric atom
* @return The string that represents the MicroPython code of the numeric atom
*/
Any MicroPythonCompiler::visitNumeric_atom(PivotParser::Numeric_atomContext* context)
{
string result = "";
if (context->NUMBER() || context->VARIABLE())
{
result = context->getText();
}
else if (context->special_numerics())
{
result = visitSpecial_numerics(context->special_numerics()).as<string>();
}
else
{
result = "(" + visitNumeric_expression(context->numeric_expression()).as<string>() + ")";
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a special numeric element
* @param context : The tree representation of the special numeric element
* @return The string that represents the MicroPython code of the special numeric element
*/
Any MicroPythonCompiler::visitSpecial_numerics(PivotParser::Special_numericsContext* context)
{
string result = "";
if (context->VERYCLOSE())
{
result = "d_Thd1";
}
else if (context->CLOSE())
{
result = "d_Thd2";
}
else if (context->SENSOR_ONE())
{
result = "getDistance(0)";
}
else if (context->SENSOR_TWO())
{
result = "getDistance(1)";
}
else if (context->SENSOR_THREE())
{
result = "getDistance(2)";
}
else if (context->SENSOR_FOUR())
{
result = "getDistance(3)";
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of an if-elif-else expression
* @param context : The tree representation of the if-elif-else expression
* @return The string that represents the MicroPython code of the if-elif-else expression
*/
Any MicroPythonCompiler::visitIf_elif_else(PivotParser::If_elif_elseContext* context)
{
incrementIndentation();
string result = "if " + visitBoolean_expression(context->if_condition).as<string>() + " :\n" + visitStatements(context->if_block).as<string>();
decrementIndentation();
unsigned int blockNumber = 0;
for (auto currentElif : context->elif_condition)
{
result += getIndentation() + "elif ";
incrementIndentation();
result += visitBoolean_expression(currentElif).as<string>() + " :\n" + visitStatements(context->elif_block[blockNumber]).as<string>();
decrementIndentation();
blockNumber++;
}
if (context->ELSE())
{
result += getIndentation() + "else :\n";
incrementIndentation();
result += visitStatements(context->else_block).as<string>();
decrementIndentation();
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a boolean expression
* @param context : The tree representation of the boolean expression
* @return The string that represents the MicroPython code of the boolean expression
*/
Any MicroPythonCompiler::visitBoolean_expression(PivotParser::Boolean_expressionContext* context)
{
string result = "";
bool first = true;
for (auto currentValue : context->value)
{
if (!first)
{
result += " or ";
}
result += visitBoolean_and(currentValue).as<string>();
first = false;
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of an and expression
* @param context : The tree representation of the and expression
* @return The string that represents the MicroPython code of the and expression
*/
Any MicroPythonCompiler::visitBoolean_and(PivotParser::Boolean_andContext* context)
{
string result = "";
bool first = true;
for (auto currentValue : context->value)
{
if (!first)
{
result += " and ";
}
result += visitBoolean_comparator(currentValue).as<string>();
first = false;
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of an comparison
* @param context : The tree representation of the comparison
* @return The string that represents the MicroPython code of the comparison
*/
Any MicroPythonCompiler::visitBoolean_comparator(PivotParser::Boolean_comparatorContext* context)
{
string result = visitBoolean_not(context->left).as<string>();
if (context->right)
{
result += context->comparator->getText() + visitBoolean_not(context->right).as<string>();
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a not expression
* @param context : The tree representation of the not expression
* @return The string that represents the MicroPython code of the not expression
*/
Any MicroPythonCompiler::visitBoolean_not(PivotParser::Boolean_notContext* context)
{
string result = visitBoolean_atom(context->boolean_atom()).as<string>();
if (context->NOT())
{
result = "not " + result;
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of a boolean atom
* @param context : The tree representation of the boolean atom
* @return The string that represents the MicroPython code of the boolean atom
*/
Any MicroPythonCompiler::visitBoolean_atom(PivotParser::Boolean_atomContext* context)
{
string result = "";
if (context->LPAR())
{
result = "(" + visitBoolean_expression(context->boolean_expression()).as<string>() + ")";
}
else if (context->TRUE())
{
result = "True";
}
else if (context->VARIABLE())
{
result = context->VARIABLE()->getText();
}
else if (context->FALSE())
{
result = "False";
}
else if (context->numeric_expression())
{
result = visitNumeric_expression(context->numeric_expression()).as<string>();
}
return std::move(result);
}
/**
* @brief Returns the MicroPython representation of an RGB expression
* @param context : The tree representation of the RGB expression
* @return The string that represents the MicroPython code of the RGB expression
*/
string MicroPythonCompiler::visitRGB(antlr4::tree::TerminalNode* node)
{
string color = node->getText();
color.replace(0, 1, "0x");
return color;
}
| true |
8d0bbb80b8357b7bc479e2cc284c8f6b002b70c9 | C++ | rithram/bregman_mst | /mlpack_code/enhanced_bregman_ball_impl.hpp | UTF-8 | 3,044 | 2.5625 | 3 | [] | no_license | /**
* @file enhanced_bregman_ball_impl.hpp
*
* Implementation for EnhancedBregmanBall class
*/
#ifndef BMST_ENHANCED_BREGMAN_BALL_IMPL_HPP_
#define BMST_ENHANCED_BREGMAN_BALL_IMPL_HPP_
#include "enhanced_bregman_ball.hpp"
#include "L2Divergence.hpp"
namespace bmst {
template <typename T, class TBDiv>
EnhancedBregmanBall<T, TBDiv>::EnhancedBregmanBall() :
TBase(),
l2_radius_(0),
jbdiv_radius_(0)
{}
template <typename T, class TBDiv>
EnhancedBregmanBall<T, TBDiv>::EnhancedBregmanBall(
const Point<T>& right_center, const double right_radius) :
TBase(right_center, right_radius)
{}
template <typename T, class TBDiv>
EnhancedBregmanBall<T, TBDiv>::EnhancedBregmanBall(
const Point<T>& right_center,
const double right_radius,
const Point<T>& left_center,
const double left_radius) :
TBase(right_center, right_radius, left_center, left_radius)
{}
template <typename T, class TBDiv>
EnhancedBregmanBall<T, TBDiv>::~EnhancedBregmanBall()
{}
template <typename T, class TBDiv>
void EnhancedBregmanBall<T, TBDiv>::AddExtraStats(
const Table<T>& data, const size_t start, const size_t end)
{
double max_sq_l2_dist = 0;
double max_sq_jbdiv = 0;
for (size_t i = 0; i < data.n_points(); ++i) {
assert(TBase::right_centroid_.n_dims() == data[i].n_dims());
double sq_l2_dist = L2Divergence<T>::BDivergence(data[i], TBase::right_centroid_);
if (sq_l2_dist > max_sq_l2_dist)
max_sq_l2_dist = sq_l2_dist;
double sq_jbdiv = TBDiv::JBDivergence(data[i], TBase::right_centroid_);
if (sq_jbdiv > max_sq_jbdiv)
max_sq_jbdiv = sq_jbdiv;
}
l2_radius_ = std::sqrt(max_sq_l2_dist);
jbdiv_radius_ = std::sqrt(max_sq_jbdiv);
return;
}
template<typename T, class TBDiv>
bool EnhancedBregmanBall<T, TBDiv>::CanPruneRight(
const Point<T>& q, const Point<T>& q_prime, const double q_div_to_best_candidate) const
{
// try pruning using strong convexity
if (TBDiv::StrongConvexityCoefficient() > 0)
{
const double l2_q_mu = std::sqrt(L2Divergence<T>::BDivergence(q, TBase::right_centroid_));
if (l2_q_mu > l2_radius_)
{
const double diff = l2_q_mu - l2_radius_;
const double lb = TBDiv::StrongConvexityCoefficient() * diff * diff;
if (lb >= q_div_to_best_candidate)
return true;
}
}
// check here for CPD-ness, which is known for each divergence
if (TBDiv::IsCPD())
{
// try pruning using CPD condition
const double jbdiv_q_mu = std::sqrt(TBDiv::JBDivergence(q, TBase::right_centroid_));
if (jbdiv_q_mu > jbdiv_radius_)
{
const double diff = jbdiv_q_mu - jbdiv_radius_;
const double lb = diff * diff;
if (lb >= q_div_to_best_candidate)
return true;
}
}
double d_q_mu = TBDiv::BDivergence(q, TBase::right_centroid_);
//std::cout << "d_q_mu: " << d_q_mu << ", radius: " << radius_ <<
// ", q_div_to_best_candidate: " << q_div_to_best_candidate << "\n";
return TBase::CanPruneRight(q, q_prime, q_div_to_best_candidate, d_q_mu);
}
} // namespace
#endif
| true |
64775a78a385809d1f239c9b908e492240b2fa15 | C++ | ferserc1/bg2-unreal-tools | /Source/Bg2UnrealTools/Private/Bg2MeshParser.h | UTF-8 | 1,866 | 2.609375 | 3 | [] | no_license | #pragma once
#include <string>
#include <vector>
#include <fstream>
class Bg2MeshParser
{
public:
enum OpenMode
{
kModeClosed,
kModeRead,
kModeWrite
};
enum BlockType {
kHeader = 'hedr',
kPolyList = 'plst',
kVertexArray = 'varr',
kNormalArray = 'narr',
kTexCoord0Array = 't0ar',
kTexCoord1Array = 't1ar',
kTexCoord2Array = 't2ar',
kTexCoord3Array = 't3ar',
kTexCoord4Array = 't4ar',
kIndexArray = 'indx',
kMaterials = 'mtrl',
kPlistName = 'pnam',
kMatName = 'mnam',
kShadowProjector = 'proj',
kJoint = 'join',
kEnd = 'endf'
};
Bg2MeshParser();
virtual ~Bg2MeshParser();
bool Open(const std::string & path, OpenMode mode);
void Close();
bool WriteByte(unsigned char byte);
bool WriteBlock(BlockType b);
bool WriteInteger(int value);
bool WriteFloat(float value);
bool WriteString(const std::string & str);
bool WriteArray(const std::vector<float> array);
bool WriteArray(const std::vector<int> array);
bool WriteArray(const std::vector<unsigned int> array);
bool ReadByte(unsigned char & byte);
bool ReadBlock(BlockType & b);
bool ReadInteger(int & value);
bool ReadFloat(float & value);
bool ReadString(std::string & str);
bool ReadArray(std::vector<float> & array);
bool ReadArray(std::vector<int> & array);
bool ReadArray(std::vector<unsigned int> & array);
void SetBigEndian();
void SetLittleEndian();
void SeekForward(int bytes);
std::fstream & Stream() { return mStream; }
bool IsBigEndian();
bool IsLittleEndian();
protected:
std::fstream mStream;
OpenMode mMode;
bool mSwapBytes;
};
| true |
b805b1c8accd71bf4eb74a056625941cd548b432 | C++ | siberiy4/comp_prog | /2018.10.18/slime2.cpp | UTF-8 | 498 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<deque>
using namespace std;
int main(){
int N;
int ans=0;
deque<int> slimes(N);
cin>>N;
int now,pre;
cin>>pre;
int continuous=1;
for(int i = 1; i < N; i++)
{
cin>>now;
if(pre==now){
continuous++;
}else{
ans+=continuous/2;
continuous=1;
}
pre=now;
}
ans+=continuous/2;
cout<<ans<<endl;
} | true |
56fb588b4e2811bde2aa3356c1a9847243bc532d | C++ | nguyenviettien13/CodeLearning | /DesignPattern/Singleton class using inheritance/Singleton class using inheritance/MyBase.cpp | UTF-8 | 482 | 2.640625 | 3 | [] | no_license | #include "MyBase.h"
#include <iostream>
using namespace std;
MyBase* MyBase::m_pMyBaseInstance = nullptr;
MyBase::MyBase()
{
}
MyBase::MyBase(int X):
m_data(X)
{
}
MyBase::~MyBase()
{
}
void MyBase::setDataX(int value)
{
m_data = value;
}
int MyBase::getDataX() const
{
return m_data;
}
MyBase * MyBase::getInstance()
{
if (m_pMyBaseInstance)
{
//cout << "Doi tuong chua duoc tao" << endl;
}
return m_pMyBaseInstance ;
}
| true |
b27df1ccca9e21b2deff8dcb7412391e18581cc0 | C++ | MrrrrFox/OOP | /CPP/3rd semester - Fundamental Concepts of Object-Oriented Programming/lab05/Sources/MapDist.cpp | UTF-8 | 508 | 2.671875 | 3 | [] | no_license | #include "MapDist.h"
#include <cmath>
using namespace std;
const MapDist distance(MapPoint miasto1, MapPoint miasto2)
{
const MapDist dystans = new MapDist;
// dystans->longitude =
return 0;
}
double angularDistance(const MapDist delty)
{
return 0;
}
const MapPoint& closestFrom(MapPoint * miastoRef, MapPoint * miasto1, MapPoint * miasto2)
{
if(angularDistance(distance(maistoRef, miasto1)) > angularDistance(distance(maistoRef, miasto2)) )
{
return miasto2;
}
else
{
return miasto1;
}
}
| true |
8628903021a37f82f30d2ab61b08be839acbfa31 | C++ | NeilWangziyu/NewJourneyOfCPlusPlus | /NewJourneyOfCPlusPlus.git/15-4/main.cpp | UTF-8 | 1,769 | 3.421875 | 3 | [] | no_license | //
// main.cpp
// 15-4
//
// Created by 王子昱 on 2019/12/9.
// Copyright © 2019 王子昱. All rights reserved.
//
#include <iostream>
#include <vector>
#include <string>
#include <memory>
using namespace std;
class Quote{
public:
Quote() =default;
Quote(const string &book, double sales_price) :
bookNo(book), price(sales_price) { }
string isbn() const { return bookNo;}
virtual double net_price(size_t n) const
{return n * price;}
virtual ~Quote() = default; //析构函数动态绑定
private:
string bookNo;
protected:
double price = 0.0;
};
class Disc_quote : public Quote
{
public:
Disc_quote() = default;
Disc_quote(const string& book, double price, size_t qty, double disc):
Quote(book, price), quantity(qty), discont(disc) { }
double net_price(size_t) const = 0;
protected:
size_t quantity = 0;
double discont = 0.0;
};
class Bulk_quote : public Disc_quote{
public:
Bulk_quote() = default;
Bulk_quote(const string& book, double price, size_t qty, double disc):
Disc_quote(book, price, qty, disc) { }
double net_price(size_t) const override;
};
double Bulk_quote::net_price(size_t n) const
{
if (n >= quantity) {
return n * ( 1 - discont) * price;
}
else
return n * price;
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
vector<shared_ptr<Quote>> basket;
basket.push_back(make_shared<Quote>("0-12-1", 50));
basket.push_back(make_shared<Bulk_quote>("9-1-1-1", 50, 10, 0.25));
cout << basket.back()->net_price(15) << endl;
// if use vector to manage class, use the pointer
return 0;
}
| true |
ee8d5f453abe8d8a53e7615f1f1cffe20838b3ba | C++ | jhuni45/TCG-Laboratorio | /Practicas/Practica 3/Hayde/Codigo/ejercicio5.cpp | UTF-8 | 700 | 2.609375 | 3 | [] | no_license | #include <opencv2/opencv.hpp>
#include <bits/stdc++.h>
using namespace cv;
using namespace std;
int main(){
Mat img=imread("imagen1.jpg");
if ( !img.data){
return -1;
}
Mat pt1(1, 3, CV_32FC2); // Puntos en el origen
pt1.at<Vec2f>(0,0)= Vec2f(0, 0); // Rellenar los tres puntos
pt1.at<Vec2f>(0,1)= Vec2f(100, 0);
pt1.at<Vec2f>(0,2)= Vec2f(100, 100);
Mat pt2(1, 3, CV_32FC2); // Puntos en el destino
pt2.at<Vec2f>(0,0)= Vec2f(10, 20); // Rellenar los tres puntos
pt2.at<Vec2f>(0,1)= Vec2f(80, 40);
pt2.at<Vec2f>(0,2)= Vec2f(20, 70);
Mat c= getAffineTransform(pt1, pt2);
warpAffine(img, img, c, img.size());
imwrite("5_Transformacion_Afin.jpg", img);
return 0;
} | true |
fa5e4ed1ca81fcf4a9dc8356fb3362a29a9534f1 | C++ | electro-smith/DaisySP | /Source/Synthesis/oscillatorbank.h | UTF-8 | 1,907 | 2.796875 | 3 | [
"MIT"
] | permissive | #pragma once
#ifndef DSY_OSCILLATORBANK_H
#define DSY_OSCILLATORBANK_H
#include <stdint.h>
#ifdef __cplusplus
/** @file oscillatorbank.h */
namespace daisysp
{
/**
@brief Oscillator Bank module.
@author Ben Sergentanis
@date Dec 2020
A mixture of 7 sawtooth and square waveforms in the style of divide-down organs \n \n
Ported from pichenettes/eurorack/plaits/dsp/oscillator/string_synth_oscillator.h \n
\n to an independent module. \n
Original code written by Emilie Gillet in 2016. \n
*/
class OscillatorBank
{
public:
OscillatorBank() {}
~OscillatorBank() {}
/** Init string synth module
\param sample_rate Audio engine sample rate
*/
void Init(float sample_rate);
/** Get next floating point sample
*/
float Process();
/** Set oscillator frequency (8' oscillator)
\param freq Frequency in Hz
*/
void SetFreq(float freq);
/** Set amplitudes of 7 oscillators. 0-6 are Saw 8', Square 8', Saw 4', Square 4', Saw 2', Square 2', Saw 1'
\param amplitudes array of 7 floating point amplitudes. Must sum to 1.
*/
void SetAmplitudes(const float* amplitudes);
/** Set a single amplitude
\param amp Amplitude to set.
\param idx Which wave's amp to set
*/
void SetSingleAmp(float amp, int idx);
/** Set overall gain.
\param gain Gain to set. 0-1.
*/
void SetGain(float gain);
private:
// Oscillator state.
float phase_;
float next_sample_;
int segment_;
float gain_;
float registration_[7];
float unshifted_registration_[7];
float frequency_;
float saw_8_gain_;
float saw_4_gain_;
float saw_2_gain_;
float saw_1_gain_;
float sample_rate_;
bool recalc_, recalc_gain_;
bool cmp(float a, float b) { return fabsf(a - b) > .0000001; }
};
} // namespace daisysp
#endif
#endif | true |
fe2b3c7289f281f0a1ef42c7aac40cd2d9b80964 | C++ | ShariqueMohd/B-tree-and-Linear-Hashing | /LinearHashing.hpp | UTF-8 | 3,031 | 3.140625 | 3 | [] | no_license | #ifndef __LHASHING__
#define __LHASHING__
#include <bits/stdc++.h>
using namespace std;
template<typename T>
class Block {
int capacity;
vector<T> data;
Block *next;
public:
Block(int capacity): capacity(capacity), data(), next(nullptr) {}
bool isOverflow() const {
if(next != nullptr) {
return true;
}
return false;
}
bool Find(const T& key) const {
for(T possibleKey : data) {
if(possibleKey == key) {
return true;
}
}
if(next != nullptr) {
return next->Find(key);
}
return false;
}
bool Insert(const T& key) {
if(data.size() < capacity) {
data.push_back(key); return false;
}
if( next == nullptr) {
next = new Block<T>(capacity);
}
next->Insert(key); return true;
}
bool Empty() const {
return data.empty();
}
unsigned long getHash(function<unsigned long(const T&)> HF) const {
return HF(data[0]);
}
#define RT pair<Block<T>*, Block<T>*>
RT Split(function<unsigned long(const T&)> HF) {
RT splited;
if(next != nullptr) {
splited = next->Split(HF);
delete next;
next = nullptr;
}
else {
splited = RT(new Block<T>(capacity), new Block<T>(capacity));
}
for(T key: data) {
unsigned long hash = HF(key);
if(splited.first->data.empty() && !splited.second->data.empty()) {
if(hash == HF(splited.second->data[0]))
splited.second->Insert(key);
else
splited.first->Insert(key);
}
else if(splited.first->data.empty() && splited.second->data.empty()) {
splited.first->Insert(key);
}
else {
if(hash != HF(splited.first->data[0]))
splited.second->Insert(key);
else
splited.first->Insert(key);
}
}
return splited;
}
};
template<typename T>
class Hash {
int capacity;
vector<Block<T>*> blocks;
int current, currentHash;
const function<unsigned long(unsigned long, const T&)> HF;
public:
Hash(unsigned long capacity, function<unsigned long(unsigned long, const T&)> HF):
capacity(capacity), blocks({new Block<T>(capacity), new Block<T>(capacity)}),
current(0), currentHash(0), HF(HF) {}
void Insert(const T& key) {
unsigned long hash = HF(currentHash, key);
if(hash < current)
hash = HF(currentHash + 1, key);
bool overFlow = blocks[hash]->Insert(key);
auto splitLambda = [this](const T& key) {
return HF(currentHash+1, key);
};
if(overFlow) {
pair<Block<T>*, Block<T>*> splited = blocks[current]->Split(splitLambda);
if((!splited.first->Empty() && splited.first->getHash(splitLambda) != current)) ||
(!splited.second->Empty() && splited.second->getHash(splitLambda) == current)
std::swap(splited.first, splited.second);
delete blocks[current]; blocks[current] = splited.first; blocks.push_back(splited.second);
current++;
if(blocks.size() == 2*current) {
current = 0;currentHash++;
}
}
}
bool Find(const T& key) const {
unsigned long hash = HF(currentHash, key);
if(hash < current) {
hash = HF(currentHash + 1, key);
}
return blocks[hash]->Find(key);
}
};
#endif | true |
8fd602ad02d6244b72afaca7278d713114739baa | C++ | tjgykhulj/Pencil-Drawing-Builder | /Code/第一次迭代/method.h | GB18030 | 1,259 | 2.609375 | 3 | [] | no_license | #ifndef METHOD_H
#define METHOD_H
#include <opencv2\opencv.hpp>
#include <opencv2/legacy/compat.hpp>
using namespace cv;
//תͼƬdegreeȣ˫Բֵ
Mat rotateImage(Mat img, double degree)
{
Point2f center = Point2f((img.cols-1) / 2.0, (img.rows-1) / 2.0);
Mat M = getRotationMatrix2D(center, degree, 1);
Mat result;
warpAffine(img, result, M, img.size(), CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS);
return result;
}
//
void conv2(const Mat &img, const Mat &kernel, Mat& dest) {
Point anchor(kernel.cols - kernel.cols / 2 - 1, kernel.rows - kernel.rows / 2 - 1);
filter2D(img, dest, img.depth(), kernel, anchor);
}
//ƽ
void smooth(double a[], int n)
{
if (n < 3) {
printf("too short");
return;
}
double *s = new double[n];
s[0] = a[0];
for (int i = 1; i < n; i++) s[i] = s[i - 1] + a[i];
a[0] = s[1]/2;
a[1] = s[2]/3;
for (int i = 2; i < n-1; i++) a[i] = (s[i + 1] - s[i - 2]) / 3;
}
//ֱͼ
CvHistogram* CreateGrayImageHist(IplImage **img)
{
int nHistSize = 256;
float fRange[] = { 0, 255 }; //ҶȼķΧ
float *pfRanges[] = { fRange };
CvHistogram *pcvHistogram = cvCreateHist(1, &nHistSize, CV_HIST_ARRAY, pfRanges);
cvCalcHist(img, pcvHistogram);
return pcvHistogram;
}
#endif | true |
cec5f4b7c01e3b0282a0a75a3f72a40cc7b42537 | C++ | brunobonfim01/Projeto-Telecom | /Projeto.cpp | ISO-8859-1 | 4,422 | 2.84375 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<windows.h>
#include<stdlib.h>
struct cliente
{
char cpf[15];
char nome[50];
float plano;
}s;
void criarplano();
void listarplanos();
void mudarplanos();
void deletar();
void procurar();
char get;
int main()
{ int senha;
int cpf;
char escolha;
system("cls");
printf("\n\t\t------Sistema de Controle de Planos Telecom------");
Sleep(2000);
getch();
system("cls");
while (1)
{
system("cls");
printf("\n Digite\n A : para adicionar um novo plano.\n L : para listar os planos.");
printf("\n M : para modificar os planos.");
printf("\n S : para procurar planos.");
printf("\n D : para deletar planos.\n E : para sair.\n");
escolha=getche();
escolha=toupper(escolha);
switch(escolha)
{
case 'A':
criarplano();break;
case 'L':
listarplanos();break;
case 'M':
mudarplanos();break;
case 'S':
procurar();break;
case 'D':
deletar();break;
case 'E':
system("cls");
printf("\n\n\t\t\t\tOBRIGADO POR USAR NOSSOS SERVICOS!!");
Sleep(2000);
exit(0);
break;
default:
system("cls");
printf("Dados Incorretos");
printf("\nAperte qualquer tecla para continuar");
getch();
}
}
}
void criarplano()
{
FILE *f;
char teste;
f=fopen("c:/file.ojs","ab+");
if(f==0)
{ f=fopen("c:/file.ojs","wb+");
system("cls");
printf("/naperte qualquer tecla para continuar");
getch();
}
while(1)
{
system("cls");
printf("\n Numero do CPF: ");
scanf("%s",&s.cpf);
printf("\n Nome: ");
fflush(stdin);
scanf("%[^\n]",&s.nome);
printf("\n Valor do Plano: ");
scanf("%f",&s.plano);
fwrite(&s,sizeof(s),1,f);
fflush(stdin);
system("cls");
printf("O plano foi adicionado com sucesso");
printf("\n Aperte ESC para sair, ou qualquer outra tecla para adicionar outro plano:");
teste=getche();
if(teste==27)
break;
}
fclose(f);
}
void listarplanos()
{
FILE *f;
int i;
if((f=fopen("c:/file.ojs","rb"))==NULL)
exit(0);
system("cls");
printf("Numero do CPF\t\tNome do Cliente\t\t\tValor do Plano\n");
for(i=0;i<79;i++)
printf("-");
while(fread(&s,sizeof(s),1,f)==1)
{
printf("\n%-10s\t\t%-20s\t\tRs. %.2f /-",s.cpf,s.nome,s.plano);
}
printf("\n");
for(i=0;i<79;i++)
printf("-");
fclose(f);
getch();
}
void deletar()
{
FILE *f,*t;
int i=1;
char cpf[20];
if((t=fopen("c:/temp.ojs","w+"))==NULL)
exit(0);
if((f=fopen("c:/file.ojs","rb"))==NULL)
exit(0);
system("cls");
printf("Digite o CPF que vai ser deletado: ");
fflush(stdin);
scanf("%[^\n]",cpf);
while(fread(&s,sizeof(s),1,f)==1)
{
if(strcmp(s.cpf,cpf)==0)
{ i=0;
continue;
}
else
fwrite(&s,sizeof(s),1,t);
}
if(i==1)
{ system("cls");
printf("CPF \"%s\" nao encontrado ):",cpf);
remove("c:/file.ojs");
rename("c:/temp.ojs","c:/file.ojs");
getch();
fclose(f);
fclose(t);
main();
}
remove("c:/file.ojs");
rename("c:/temp.ojs","c:/file.ojs");
system("cls");
printf("o CPF %s foi deletado com sucesso!!!!",cpf);
fclose(f);
fclose(t);
getch();
}
void procurar()
{
FILE *f;
char cpf[20];
int flag=1;
f=fopen("c:/file.ojs","rb+");
if(f==0)
exit(0);
fflush(stdin);
system("cls");
printf("Digite o CPF que deseja procurar: ");
scanf("%s", cpf);
while(fread(&s,sizeof(s),1,f)==1)
{
if(strcmp(s.cpf,cpf)==0)
{ system("cls");
printf(" Cliente Encontrado ");
printf("\n\ncpf: %s\nnome: %s\nplano: Rs.%0.2f\n",s.cpf,s.nome,s.plano);
flag=0;
break;
}
else if(flag==1)
{ system("cls");
printf("CPF no encontrado ):");
}
}
getch();
fclose(f);
}
void mudarplanos()
{
FILE *f;
char cpf[20];
long int size=sizeof(s);
if((f=fopen("c:/file.ojs","rb+"))==NULL)
exit(0);
system("cls");
printf("Digite o CPF do cliente que voc deseja modificar: ");
scanf("%[^\n]",cpf);
fflush(stdin);
while(fread(&s,sizeof(s),1,f)==1)
{
if(strcmp(s.cpf,cpf)==0)
{
system("cls");
printf("\n Digite o CPF: ");
scanf("%s",&s.cpf);
printf("\n Digite o Nome: ");
fflush(stdin);
scanf("%[^\n]",&s.nome);
printf("\n Digite o Valor do Plano: ");
scanf("%f",&s.plano);
fseek(f,-size,SEEK_CUR);
fwrite(&s,sizeof(s),1,f);
break;
}
}
fclose(f);
}
| true |
8607ecec8548f01d3418246bfe40f0ebe22c09f8 | C++ | Xarvie/chain-socket | /code/ChainSocket/Ip.cpp | UTF-8 | 1,471 | 2.671875 | 3 | [
"MIT"
] | permissive | //
// Created by ftp on 7/3/2021.
//
#include "Ip.h"
#include <ws2tcpip.h>
void IP::fromString(std::string ip, std::string port, IP::Version ipv) {
//addrinfo结构体是为了消除IPv6协议与IPv4协议之间的差异,编制统一的程序而追加的结构。并且允许多个IPv4地址或IPv6地址链成链表
struct addrinfo hints, //服务器端地址信息
*result = NULL; //若有多个地址,res是地址信息链表指针
memset(&hints, 0, sizeof(hints));//如果没有这句话就会出现绑定错误,也就是在调用getaddrinfo()之前该参数必须清0
hints.ai_family = ipv; //地址簇,这里指定是ipv6协议,其值可以是 AF_INET:ipv4, AF_INET6:ipv6
hints.ai_socktype = SOCK_STREAM; //套接字类型,这里是流式,其值可以是 SOCK_STREAM:流式, SOCK_DGRAM:数据报, SOCK_RAW:原始套接字
hints.ai_protocol = IPPROTO_TCP; //传输层协议,这里是TCP协议,其值可以是: IPPROTO_TCP:TCP, IPPROTO_UDP:UDP, 若为0系统根据套接字类型自动选择
// Ip cim es port beallitas
int iResult = getaddrinfo(ip.c_str(), port.c_str(), &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
}
ai_flags = result->ai_flags;
ai_family = result->ai_family;
ai_socktype = result->ai_socktype;
ai_protocol = result->ai_protocol;
ai_addrlen = result->ai_addrlen;
ai_canonname = result->ai_canonname;
ai_addr = *result->ai_addr;
freeaddrinfo(result);
} | true |
2c0ecec9071e108fa3b0c817d38738f618250105 | C++ | LiLiaoMing/chipset | /X1/charUtile.cpp | UTF-8 | 1,612 | 2.703125 | 3 | [] | no_license | #include "stdafx.h"
#include "charUtile.h"
#include <assert.h>
int AnsiToUTF8(char* szSrc, char* strDest, int destSize)
{
WCHAR szUnicode[2048];
char szUTF8code[2048];
int nUnicodeSize = MultiByteToWideChar(CP_ACP, 0, szSrc, (int)strlen(szSrc), szUnicode, sizeof(szUnicode));
int nUTF8codeSize = WideCharToMultiByte(CP_UTF8, 0, szUnicode, nUnicodeSize, szUTF8code, sizeof(szUTF8code), NULL, NULL);
assert(destSize > nUTF8codeSize);
memcpy(strDest, szUTF8code, nUTF8codeSize);
strDest[nUTF8codeSize] = 0;
return nUTF8codeSize;
}
int UTF8ToAnsi(char* szSrc, char* strDest, int destSize)
{
WCHAR szUnicode[2048];
char szAnsi[2048];
int nSize = MultiByteToWideChar(CP_UTF8, 0, szSrc, -1, 0, 0);
int nUnicodeSize = MultiByteToWideChar(CP_UTF8, 0, szSrc, -1, szUnicode, nSize);
int nAnsiSize = WideCharToMultiByte(CP_ACP, 0, szUnicode, nUnicodeSize, szAnsi, sizeof(szAnsi), NULL, NULL);
assert(destSize > nAnsiSize);
memcpy(strDest, szAnsi, nAnsiSize);
strDest[nAnsiSize] = 0;
return nAnsiSize;
}
//std::string ===> CString
CString str2CString(string &str)
{
CString ss;
ss.Format(_T("%S"), str.c_str());
return ss;
}
void UnicodeCString2Ansi(CString &str, char* pDst, int nDstLen)
{
USES_CONVERSION;
#if _UNICODE
char* pTmp = W2A(str);
#else
char* pTmp = (char*)(LPCTSTR)str;
#endif
int nLen = strnlen_s(pTmp, nDstLen-1);
ZeroMemory(pDst, nDstLen);
strcpy_s(pDst, nLen+1, pTmp);
}
void UnicodeCString2Float(CString &str, float &fVal)
{
USES_CONVERSION;
#if _UNICODE
char* pTmp = W2A(str);
#else
char* pTmp = (char*)(LPCTSTR)str;
#endif
fVal = (float)atof(pTmp);
} | true |
ff50966454064f03b8a4677842303eed41d8991b | C++ | ameetgohil/ulcdDemo | /main.cpp | UTF-8 | 1,654 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "mbed.h"
#include "uLCD_4DGL.h"
uLCD_4DGL uLCD(p9,p10,p11);
int main() {
int x;
int y;
int radius;
int vx;
//Set out UART baudrate to somehting reasonable
uLCD.baudrate(921600);
//Change background color (must be caclled before cls)
uLCD.background_color(WHITE);
//Clear screen with background color
uLCD.cls();
//Change background color of text
uLCD.textbackground_color(WHITE);
//Make some colorful text
uLCD.locate(4,1); //Move cursor
uLCD.color(BLUE);
//uLCD.printf("I\n");
uLCD.locate(2,3); //Move cursor
uLCD.text_width(2); //2x normal size
uLCD.text_height(2); //2x normal size
//uLCD.color(RED); //Change text color
uLCD.printf("BATMAN!");
uLCD.text_width(1); //Normal size
uLCD.text_height(1); //Move cursor
uLCD.locate(3,6); //Move cursor
uLCD.color(BLACK); //Change text color
//uLCD.printf("of my new LCD");
// Initial parameters for the circle
x=50;
y=100;
radius=4;
vx=1;
//Make a ball bounce back and forth
while (1) {
// Draw a dark green
uLCD.filled_circle(x,y,radius, 0x008000);
// Bounce off the edges
if ((x <= radius + 1) || (x >= 126 -radius)) {
vx = -1 * vx;
}
//Wait before erasing old circlce
wait(0.1); //In seconds
// Erase old circle
uLCD.filled_circle(x,y,radius,WHITE);
// Move circle
x = x + vx;
}
}
| true |
c038f48f2f95cc19818c1fca7d4037d5ac5982eb | C++ | dev-akashparmar/dev-cpp | /binary_search_array.cpp | UTF-8 | 991 | 3.78125 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int n;
cout << "enter the size of array:";
cin >> n;
int a[n] = {};
cout << "enter the elements of array:" << endl;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
cout << "the elements of array are:";
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
int l = 0, h = n - 1, m, x;
cout << "\n";
cout << "enter the element you want to find:";
cin >> x;
while (l <= h) //if l becomes greater than h then number not found
{
m = (l + h) / 2;
if (x == a[m])
{
cout << "the index of the element is:" << m;
return 0; //to stop the loop as number is found
}
else if (x < a[m])
{
h = m - 1;
}
else
{
l = m + 1;
}
}
cout << "number not found" << endl; //outside of while loop
}
| true |
cbbbefdf314e61fb9d2b529d1da2d96ae9bcc59f | C++ | monkbroc/Thermomatic | /firmware/src/thermomatic.ino | UTF-8 | 1,804 | 2.546875 | 3 | [] | no_license | /*
* Internet connected fleet of thermometers
*
* Connect the MCP9808 temperature sensor
* Vdd to 3V3
* Gnd to GND
* SCL to D1
* SDA to D0
*/
#include "MCP9808.h"
PRODUCT_ID(3341);
PRODUCT_VERSION(1);
SYSTEM_THREAD(ENABLED);
MCP9808 sensor = MCP9808();
int publishDelay = 60; // seconds
String deviceName;
void setup() {
Serial.begin(9600);
delay(200);
// What's my name?
Particle.function("name", saveDeviceName);
loadDeviceName();
// Doesn't this work for products??
//Particle.subscribe("spark/device/name", setDeviceName);
//Particle.publish("spark/device/name", PRIVATE);
// Don't have a bright light in our bedrooms
RGB.control(true);
RGB.brightness(0);
while (!sensor.begin()) {
delay(500);
Serial.println("MCP9808 not found");
}
sensor.setResolution(MCP9808_SLOWEST);
}
void loop(void) {
// Wait for device name
if (deviceName.length() == 0) {
return;
}
// Read the temperature
float celsius = sensor.getTemperature();
Serial.printlnf("Sensor T=%f C", celsius);
if (celsius >= 5 && celsius < 50) {
String eventName = "HouseTemp/" + deviceName;
String eventData = String::format("%.2f", celsius);
Particle.publish(eventName, eventData, PRIVATE);
}
// Publish temperature once per minute
delay(publishDelay * 1000);
}
void setDeviceName(const char *topic, const char *data) {
deviceName = data;
}
int saveDeviceName(String newName) {
deviceName = newName;
char buffer[32];
newName.toCharArray(buffer, sizeof(buffer));
buffer[sizeof(buffer)] = '\0';
EEPROM.put(0, buffer);
return 0;
}
void loadDeviceName() {
char buffer[32];
EEPROM.get(0, buffer);
buffer[sizeof(buffer)] = '\0';
if (buffer[0] == 0xFF) {
deviceName = System.deviceID();
} else {
deviceName = buffer;
}
}
| true |
2b5625f54a14448c5fba82bcc73af8ce86dca708 | C++ | Doc-Zegno/handmada | /include/misc/ComparisonFlag.h | UTF-8 | 1,066 | 2.78125 | 3 | [] | no_license | //
// Created by syzegno on 07.05.17.
//
#ifndef EQUEUE_V2_COMPAREFLAG_H
#define EQUEUE_V2_COMPAREFLAG_H
namespace Handmada {
class ComparisonFlag
{
public:
ComparisonFlag() = delete;
enum Type {
LESS,
EQUAL,
GREATER,
NOT_EQUAL,
LESS_OR_EQUAL,
GREATER_OR_EQUAL,
};
static const char* toString(ComparisonFlag::Type flag);
/**
* Each comparator needs to decide whether the result of comparing
* satisfies requirements. Obviously, such analysis requires
* significant effort since, for example, negative result of comparing
* satisfies both LESS and LESS_OR_EQUAL requirements.
* @param result result of comparing attributes
* @param flag requirements, i.e. LESS, LESS_OR_EQUAL and so on
* @return true if result satisfies flag and false otherwise
*/
static bool isCompatible(int result, ComparisonFlag::Type flag);
};
}
#endif //EQUEUE_V2_COMPAREFLAG_H
| true |
14829ec23742be5a815ba3757e72b173a5e74516 | C++ | AmborFei/cpphomework | /15.cpp | GB18030 | 384 | 2.84375 | 3 | [] | no_license | #include<iostream>
#include<stdlib.h>
using namespace std;
void main()
{
int n=10;
float *p;
if((p=new float[n])==0)
{
cout<<"ڴʧ\n";
exit(1);
}
float sum=0;
for(int i=1;i<=n;i++)
{
p[i-1]=i*(1.0/10);
sum+=p[i-1];
cout<<"sum="<<sum<<endl;
}
cout<<"飺"<<endl;
for(int i=0;i<n;i++)
{
cout<<p[i]<<" ";
}
delete []p;
system("pause");
} | true |
71f07ddf0c571c8237aee69336357cd008e2a451 | C++ | RichardBruce/RAPTor | /RAPTor/convex_decomposition/unit_tests/voxel_set_tests.cc | UTF-8 | 39,195 | 2.609375 | 3 | [] | no_license | #ifdef STAND_ALONE
#define BOOST_TEST_MODULE voxel_set test
#endif /* #ifdef STAND_ALONE */
/* Standard headers */
/* Boost headers */
#include "boost/noncopyable.hpp"
#include "boost/test/unit_test.hpp"
/* Convex Decomposition headers */
#include "voxel_set.h"
namespace raptor_convex_decomposition
{
namespace test
{
/* Test data */
struct voxel_set_fixture : private boost::noncopyable
{
voxel_set_fixture() :
empty( { }, point_t<>( 3.5f, -2.7f, 1.6f), 1.0f),
cube( { voxel(point_ti<>(3, 4, 2)) }, point_t<>( 3.5f, -2.7f, 1.6f), 1.0f),
cube2_5x({ voxel(point_ti<>(3, 4, 2)) }, point_t<>(-7.8f, 3.9f, 4.6f), 2.5f),
cube3x( { voxel(point_ti<>(3, 4, 2)) }, point_t<>(-7.8f, 3.9f, 4.6f), 3.0f),
diagonal(
{
voxel(point_ti<>(3, 4, 2)),
voxel(point_ti<>(4, 6, 4)),
voxel(point_ti<>(5, 8, 8)),
voxel(point_ti<>(6, 10, 16)),
voxel(point_ti<>(7, 12, 32)),
voxel(point_ti<>(8, 14, 64))
}, point_t<>(-7.8f, 3.9f, 4.6f), 2.0f),
row(
{
voxel(point_ti<>(0, 0, 0)),
voxel(point_ti<>(1, 0, 0)),
voxel(point_ti<>(2, 0, 0)),
voxel(point_ti<>(3, 0, 0)),
voxel(point_ti<>(4, 0, 0)),
voxel(point_ti<>(5, 0, 0)),
voxel(point_ti<>(6, 0, 0)),
voxel(point_ti<>(7, 0, 0))
}, point_t<>(1.0f, 2.0f, 3.0f), 1.0f),
on_surface(
{
voxel(point_ti<>(0, 0, 0), voxel_value_t::primitive_on_surface),
voxel(point_ti<>(1, 0, 0), voxel_value_t::primitive_on_surface),
voxel(point_ti<>(2, 0, 0), voxel_value_t::primitive_undefined),
voxel(point_ti<>(3, 0, 0), voxel_value_t::primitive_outside_surface),
voxel(point_ti<>(4, 0, 0), voxel_value_t::primitive_inside_surface),
voxel(point_ti<>(5, 0, 0), voxel_value_t::primitive_on_surface),
voxel(point_ti<>(6, 0, 0), voxel_value_t::primitive_undefined),
voxel(point_ti<>(7, 0, 0), voxel_value_t::primitive_undefined)
}, point_t<>(1.0f, 2.0f, 3.0f), 1.0f)
{ }
voxel_set empty;
voxel_set cube;
voxel_set cube2_5x;
voxel_set cube3x;
voxel_set diagonal;
voxel_set row;
voxel_set on_surface;
};
BOOST_FIXTURE_TEST_SUITE( voxel_set_tests, voxel_set_fixture )
const float result_tolerance = 0.0005f;
/* Test Ctor */
BOOST_AUTO_TEST_CASE( ctor_test )
{
BOOST_CHECK(cube.get_min_bb() == point_t<>(3.5f, -2.7f, 1.6f));
BOOST_CHECK(cube.get_barycenter() == point_ti<>(0, 0, 0));
BOOST_CHECK(cube.compute_volume() == 1.0f);
BOOST_CHECK(cube.max_volume_error() == 0.0f);
BOOST_CHECK(cube.get_scale() == 1.0f);
BOOST_CHECK(cube.get_unit_volume() == 1.0f);
BOOST_CHECK(cube.number_of_primitives() == 1);
BOOST_CHECK(cube.number_of_primitives_on_surface() == 0);
BOOST_CHECK(cube.number_of_primitives_inside() == 0);
BOOST_CHECK(cube3x.get_min_bb() == point_t<>(-7.8f, 3.9f, 4.6f));
BOOST_CHECK(cube3x.get_barycenter() == point_ti<>(0, 0, 0));
BOOST_CHECK(cube3x.compute_volume() == 27.0f);
BOOST_CHECK(cube3x.max_volume_error() == 0.0f);
BOOST_CHECK(cube3x.get_scale() == 3.0f);
BOOST_CHECK(cube3x.get_unit_volume() == 27.0f);
BOOST_CHECK(cube3x.number_of_primitives() == 1);
BOOST_CHECK(cube3x.number_of_primitives_on_surface() == 0);
BOOST_CHECK(cube3x.number_of_primitives_inside() == 0);
BOOST_CHECK(diagonal.get_min_bb() == point_t<>(-7.8f, 3.9f, 4.6f));
BOOST_CHECK(diagonal.get_barycenter() == point_ti<>(0, 0, 0));
BOOST_CHECK(diagonal.compute_volume() == 48.0f);
BOOST_CHECK(diagonal.max_volume_error() == 0.0f);
BOOST_CHECK(diagonal.get_scale() == 2.0f);
BOOST_CHECK(diagonal.get_unit_volume() == 8.0f);
BOOST_CHECK(diagonal.number_of_primitives() == 6);
BOOST_CHECK(diagonal.number_of_primitives_on_surface() == 0);
BOOST_CHECK(diagonal.number_of_primitives_inside() == 0);
}
/* Test get voxels */
BOOST_AUTO_TEST_CASE( const_get_voxels_test )
{
const auto *const const_diagonal = &diagonal;
const auto &v = const_diagonal->get_voxels();
BOOST_REQUIRE(v.size() == 6);
BOOST_CHECK(v[0].coord == point_ti<>(3, 4, 2));
BOOST_CHECK(v[1].coord == point_ti<>(4, 6, 4));
BOOST_CHECK(v[2].coord == point_ti<>(5, 8, 8));
BOOST_CHECK(v[3].coord == point_ti<>(6, 10, 16));
BOOST_CHECK(v[4].coord == point_ti<>(7, 12, 32));
BOOST_CHECK(v[5].coord == point_ti<>(8, 14, 64));
}
BOOST_AUTO_TEST_CASE( get_voxels_test )
{
auto &v = diagonal.get_voxels();
BOOST_REQUIRE(v.size() == 6);
BOOST_CHECK(v[0].coord == point_ti<>(3, 4, 2));
BOOST_CHECK(v[1].coord == point_ti<>(4, 6, 4));
BOOST_CHECK(v[2].coord == point_ti<>(5, 8, 8));
BOOST_CHECK(v[3].coord == point_ti<>(6, 10, 16));
BOOST_CHECK(v[4].coord == point_ti<>(7, 12, 32));
BOOST_CHECK(v[5].coord == point_ti<>(8, 14, 64));
}
/* Test set scale */
BOOST_AUTO_TEST_CASE( set_scale_test )
{
cube.set_scale(5.0f);
BOOST_CHECK(cube.get_scale() == 5.0f);
cube3x.set_scale(5.1f);
BOOST_CHECK(cube3x.get_scale() == 5.1f);
diagonal.set_scale(5.2f);
BOOST_CHECK(diagonal.get_scale() == 5.2f);
}
/* Test set min bb */
BOOST_AUTO_TEST_CASE( set_min_bb_test )
{
cube.set_min_bb(point_t<>(-9.0f, 1.4f, 5.0f));
BOOST_CHECK(cube.get_min_bb() == point_t<>(-9.0f, 1.4f, 5.0f));
cube3x.set_min_bb(point_t<>(-9.4f, 2.4f, 4.0f));
BOOST_CHECK(cube3x.get_min_bb() == point_t<>(-9.4f, 2.4f, 4.0f));
diagonal.set_min_bb(point_t<>(-9.8f, 6.4f, 2.0f));
BOOST_CHECK(diagonal.get_min_bb() == point_t<>(-9.8f, 6.4f, 2.0f));
}
/* Test reserve */
BOOST_AUTO_TEST_CASE( reserve_test )
{
cube.reserve(1);
cube3x.reserve(2);
diagonal.reserve(3);
}
/* Test get point */
BOOST_AUTO_TEST_CASE( get_point_point_test )
{
BOOST_CHECK(fabs(magnitude(cube3x.get_point(point_t<>(0.0f, 0.0f, 0.0f)) - point_t<>(-7.8f, 3.9f, 4.6f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(cube3x.get_point(point_t<>(1.0f, 1.0f, 1.0f)) - point_t<>(-4.8f, 6.9f, 7.6f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(cube3x.get_point(point_t<>(1.7f, -3.6f, 8.6f)) - point_t<>(-2.7f, -6.9f, 30.4f))) < result_tolerance);
}
BOOST_AUTO_TEST_CASE( get_point_voxel_test )
{
BOOST_CHECK(fabs(magnitude(cube3x.get_point(voxel(point_ti<>(0, 0, 0))) - point_t<>(-7.8f, 3.9f, 4.6f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(cube3x.get_point(voxel(point_ti<>(1, 1, 1))) - point_t<>(-4.8f, 6.9f, 7.6f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(cube3x.get_point(voxel(point_ti<>(2, -4, 9))) - point_t<>(-1.8f, -8.1f, 31.6f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(cube2_5x.get_point(voxel(point_ti<>(0, 0, 0))) - point_t<>(-7.8f, 3.9f, 4.6f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(cube2_5x.get_point(voxel(point_ti<>(1, 1, 1))) - point_t<>(-5.3f, 6.4f, 7.1f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(cube2_5x.get_point(voxel(point_ti<>(2, -4, 9))) - point_t<>(-2.8f, -6.1f, 27.1f))) < result_tolerance);
}
BOOST_AUTO_TEST_CASE( get_points_test )
{
point_t<> pts[8];
cube.get_points(voxel(point_ti<>(0, 0, 0)), &pts[0]);
BOOST_CHECK(pts[0] == point_t<>(3.0f, -3.2f, 1.1f));
BOOST_CHECK(pts[1] == point_t<>(4.0f, -3.2f, 1.1f));
BOOST_CHECK(pts[2] == point_t<>(4.0f, -2.2f, 1.1f));
BOOST_CHECK(pts[3] == point_t<>(3.0f, -2.2f, 1.1f));
BOOST_CHECK(pts[4] == point_t<>(3.0f, -3.2f, 2.1f));
BOOST_CHECK(pts[5] == point_t<>(4.0f, -3.2f, 2.1f));
BOOST_CHECK(pts[6] == point_t<>(4.0f, -2.2f, 2.1f));
BOOST_CHECK(pts[7] == point_t<>(3.0f, -2.2f, 2.1f));
cube.get_points(voxel(point_ti<>(1, 1, 1)), &pts[0]);
BOOST_CHECK(pts[0] == point_t<>(4.0f, -2.2f, 2.1f));
BOOST_CHECK(pts[1] == point_t<>(5.0f, -2.2f, 2.1f));
BOOST_CHECK(pts[2] == point_t<>(5.0f, -1.2f, 2.1f));
BOOST_CHECK(pts[3] == point_t<>(4.0f, -1.2f, 2.1f));
BOOST_CHECK(pts[4] == point_t<>(4.0f, -2.2f, 3.1f));
BOOST_CHECK(pts[5] == point_t<>(5.0f, -2.2f, 3.1f));
BOOST_CHECK(pts[6] == point_t<>(5.0f, -1.2f, 3.1f));
BOOST_CHECK(pts[7] == point_t<>(4.0f, -1.2f, 3.1f));
cube.get_points(voxel(point_ti<>(2, -4, 9)), &pts[0]);
BOOST_CHECK(pts[0] == point_t<>(5.0f, -7.2f, 10.1f));
BOOST_CHECK(pts[1] == point_t<>(6.0f, -7.2f, 10.1f));
BOOST_CHECK(pts[2] == point_t<>(6.0f, -6.2f, 10.1f));
BOOST_CHECK(pts[3] == point_t<>(5.0f, -6.2f, 10.1f));
BOOST_CHECK(pts[4] == point_t<>(5.0f, -7.2f, 11.1f));
BOOST_CHECK(pts[5] == point_t<>(6.0f, -7.2f, 11.1f));
BOOST_CHECK(pts[6] == point_t<>(6.0f, -6.2f, 11.1f));
BOOST_CHECK(pts[7] == point_t<>(5.0f, -6.2f, 11.1f));
cube2_5x.get_points(voxel(point_ti<>(0, 0, 0)), &pts[0]);
BOOST_CHECK(pts[0] == point_t<>(-9.05f, 2.65f, 3.35f));
BOOST_CHECK(pts[1] == point_t<>(-6.55f, 2.65f, 3.35f));
BOOST_CHECK(pts[2] == point_t<>(-6.55f, 5.15f, 3.35f));
BOOST_CHECK(pts[3] == point_t<>(-9.05f, 5.15f, 3.35f));
BOOST_CHECK(pts[4] == point_t<>(-9.05f, 2.65f, 5.85f));
BOOST_CHECK(pts[5] == point_t<>(-6.55f, 2.65f, 5.85f));
BOOST_CHECK(pts[6] == point_t<>(-6.55f, 5.15f, 5.85f));
BOOST_CHECK(pts[7] == point_t<>(-9.05f, 5.15f, 5.85f));
cube2_5x.get_points(voxel(point_ti<>(1, 1, 1)), &pts[0]);
BOOST_CHECK(pts[0] == point_t<>(-6.55f, 5.15f, 5.85f));
BOOST_CHECK(pts[1] == point_t<>(-4.05f, 5.15f, 5.85f));
BOOST_CHECK(pts[2] == point_t<>(-4.05f, 7.65f, 5.85f));
BOOST_CHECK(pts[3] == point_t<>(-6.55f, 7.65f, 5.85f));
BOOST_CHECK(pts[4] == point_t<>(-6.55f, 5.15f, 8.35f));
BOOST_CHECK(pts[5] == point_t<>(-4.05f, 5.15f, 8.35f));
BOOST_CHECK(pts[6] == point_t<>(-4.05f, 7.65f, 8.35f));
BOOST_CHECK(pts[7] == point_t<>(-6.55f, 7.65f, 8.35f));
cube2_5x.get_points(voxel(point_ti<>(2, -4, 9)), &pts[0]);
BOOST_CHECK(fabs(magnitude(pts[0] - point_t<>(-4.05f, -7.35f, 25.85f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(pts[1] - point_t<>(-1.55f, -7.35f, 25.85f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(pts[2] - point_t<>(-1.55f, -4.85f, 25.85f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(pts[3] - point_t<>(-4.05f, -4.85f, 25.85f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(pts[4] - point_t<>(-4.05f, -7.35f, 28.35f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(pts[5] - point_t<>(-1.55f, -7.35f, 28.35f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(pts[6] - point_t<>(-1.55f, -4.85f, 28.35f))) < result_tolerance);
BOOST_CHECK(fabs(magnitude(pts[7] - point_t<>(-4.05f, -4.85f, 28.35f))) < result_tolerance);
}
/* Test compute bounding box */
BOOST_AUTO_TEST_CASE( compute_bounding_box_test )
{
empty.compute_bounding_box();
BOOST_CHECK(empty.get_min_bb_voxels() == point_ti<>(0, 0, 0));
BOOST_CHECK(empty.get_max_bb_voxels() == point_ti<>(0, 0, 0));
BOOST_CHECK(empty.get_barycenter() == point_ti<>(0, 0, 0));
cube.compute_bounding_box();
BOOST_CHECK(cube.get_min_bb_voxels() == point_ti<>(3, 4, 2));
BOOST_CHECK(cube.get_max_bb_voxels() == point_ti<>(3, 4, 2));
BOOST_CHECK(cube.get_barycenter() == point_ti<>(3, 4, 2));
diagonal.compute_bounding_box();
BOOST_CHECK(diagonal.get_min_bb_voxels() == point_ti<>(3, 4, 2));
BOOST_CHECK(diagonal.get_max_bb_voxels() == point_ti<>(8, 14, 64));
BOOST_CHECK(diagonal.get_barycenter() == point_ti<>(6, 9, 21));
}
/* Test intersect */
BOOST_AUTO_TEST_CASE( intersect_clean_test )
{
point_t<> pts[8];
std::vector<point_t<>> pos_pts;
std::vector<point_t<>> neg_pts;
diagonal.intersect(plane(point_t<>(1.0f, 0.0f, 0.0f), 3.2f, axis_t::x_axis), &pos_pts, &neg_pts, 1);
BOOST_REQUIRE(pos_pts.size() == 24);
diagonal.get_points(voxel(point_ti<>(6, 10, 16)), &pts[0]);
BOOST_CHECK(pos_pts[0] == pts[0]);
BOOST_CHECK(pos_pts[1] == pts[1]);
BOOST_CHECK(pos_pts[2] == pts[2]);
BOOST_CHECK(pos_pts[3] == pts[3]);
BOOST_CHECK(pos_pts[4] == pts[4]);
BOOST_CHECK(pos_pts[5] == pts[5]);
BOOST_CHECK(pos_pts[6] == pts[6]);
BOOST_CHECK(pos_pts[7] == pts[7]);
diagonal.get_points(voxel(point_ti<>(7, 12, 32)), &pts[0]);
BOOST_CHECK(pos_pts[ 8] == pts[0]);
BOOST_CHECK(pos_pts[ 9] == pts[1]);
BOOST_CHECK(pos_pts[10] == pts[2]);
BOOST_CHECK(pos_pts[11] == pts[3]);
BOOST_CHECK(pos_pts[12] == pts[4]);
BOOST_CHECK(pos_pts[13] == pts[5]);
BOOST_CHECK(pos_pts[14] == pts[6]);
BOOST_CHECK(pos_pts[15] == pts[7]);
diagonal.get_points(voxel(point_ti<>(8, 14, 64)), &pts[0]);
BOOST_CHECK(pos_pts[16] == pts[0]);
BOOST_CHECK(pos_pts[17] == pts[1]);
BOOST_CHECK(pos_pts[18] == pts[2]);
BOOST_CHECK(pos_pts[19] == pts[3]);
BOOST_CHECK(pos_pts[20] == pts[4]);
BOOST_CHECK(pos_pts[21] == pts[5]);
BOOST_CHECK(pos_pts[22] == pts[6]);
BOOST_CHECK(pos_pts[23] == pts[7]);
BOOST_REQUIRE(neg_pts.size() == 24);
diagonal.get_points(voxel(point_ti<>(3, 4, 2)), &pts[0]);
BOOST_CHECK(neg_pts[0] == pts[0]);
BOOST_CHECK(neg_pts[1] == pts[1]);
BOOST_CHECK(neg_pts[2] == pts[2]);
BOOST_CHECK(neg_pts[3] == pts[3]);
BOOST_CHECK(neg_pts[4] == pts[4]);
BOOST_CHECK(neg_pts[5] == pts[5]);
BOOST_CHECK(neg_pts[6] == pts[6]);
BOOST_CHECK(neg_pts[7] == pts[7]);
diagonal.get_points(voxel(point_ti<>(4, 6, 4)), &pts[0]);
BOOST_CHECK(neg_pts[ 8] == pts[0]);
BOOST_CHECK(neg_pts[ 9] == pts[1]);
BOOST_CHECK(neg_pts[10] == pts[2]);
BOOST_CHECK(neg_pts[11] == pts[3]);
BOOST_CHECK(neg_pts[12] == pts[4]);
BOOST_CHECK(neg_pts[13] == pts[5]);
BOOST_CHECK(neg_pts[14] == pts[6]);
BOOST_CHECK(neg_pts[15] == pts[7]);
diagonal.get_points(voxel(point_ti<>(5, 8, 8)), &pts[0]);
BOOST_CHECK(neg_pts[16] == pts[0]);
BOOST_CHECK(neg_pts[17] == pts[1]);
BOOST_CHECK(neg_pts[18] == pts[2]);
BOOST_CHECK(neg_pts[19] == pts[3]);
BOOST_CHECK(neg_pts[20] == pts[4]);
BOOST_CHECK(neg_pts[21] == pts[5]);
BOOST_CHECK(neg_pts[22] == pts[6]);
BOOST_CHECK(neg_pts[23] == pts[7]);
}
BOOST_AUTO_TEST_CASE( intersect_pos_sampling_test )
{
point_t<> pts[8];
std::vector<point_t<>> pos_pts;
std::vector<point_t<>> neg_pts;
row.intersect(plane(point_t<>(0.0f, 1.0f, 0.0f), 0.9f, axis_t::x_axis), &pos_pts, &neg_pts, 3);
BOOST_REQUIRE(pos_pts.size() == 16);
row.get_points(voxel(point_ti<>(2, 0, 0)), &pts[0]);
BOOST_CHECK(pos_pts[0] == pts[0]);
BOOST_CHECK(pos_pts[1] == pts[1]);
BOOST_CHECK(pos_pts[2] == pts[2]);
BOOST_CHECK(pos_pts[3] == pts[3]);
BOOST_CHECK(pos_pts[4] == pts[4]);
BOOST_CHECK(pos_pts[5] == pts[5]);
BOOST_CHECK(pos_pts[6] == pts[6]);
BOOST_CHECK(pos_pts[7] == pts[7]);
row.get_points(voxel(point_ti<>(5, 0, 0)), &pts[0]);
BOOST_CHECK(pos_pts[ 8] == pts[0]);
BOOST_CHECK(pos_pts[ 9] == pts[1]);
BOOST_CHECK(pos_pts[10] == pts[2]);
BOOST_CHECK(pos_pts[11] == pts[3]);
BOOST_CHECK(pos_pts[12] == pts[4]);
BOOST_CHECK(pos_pts[13] == pts[5]);
BOOST_CHECK(pos_pts[14] == pts[6]);
BOOST_CHECK(pos_pts[15] == pts[7]);
BOOST_REQUIRE(neg_pts.size() == 0);
}
BOOST_AUTO_TEST_CASE( intersect_neg_sampling_test )
{
point_t<> pts[8];
std::vector<point_t<>> pos_pts;
std::vector<point_t<>> neg_pts;
row.intersect(plane(point_t<>(0.0f, -1.0f, 0.0f), 3.1f, axis_t::x_axis), &pos_pts, &neg_pts, 3);
BOOST_REQUIRE(pos_pts.size() == 0);
BOOST_REQUIRE(neg_pts.size() == 16);
row.get_points(voxel(point_ti<>(2, 0, 0)), &pts[0]);
BOOST_CHECK(neg_pts[0] == pts[0]);
BOOST_CHECK(neg_pts[1] == pts[1]);
BOOST_CHECK(neg_pts[2] == pts[2]);
BOOST_CHECK(neg_pts[3] == pts[3]);
BOOST_CHECK(neg_pts[4] == pts[4]);
BOOST_CHECK(neg_pts[5] == pts[5]);
BOOST_CHECK(neg_pts[6] == pts[6]);
BOOST_CHECK(neg_pts[7] == pts[7]);
row.get_points(voxel(point_ti<>(5, 0, 0)), &pts[0]);
BOOST_CHECK(neg_pts[ 8] == pts[0]);
BOOST_CHECK(neg_pts[ 9] == pts[1]);
BOOST_CHECK(neg_pts[10] == pts[2]);
BOOST_CHECK(neg_pts[11] == pts[3]);
BOOST_CHECK(neg_pts[12] == pts[4]);
BOOST_CHECK(neg_pts[13] == pts[5]);
BOOST_CHECK(neg_pts[14] == pts[6]);
BOOST_CHECK(neg_pts[15] == pts[7]);
}
/* Test compute principal axes */
BOOST_AUTO_TEST_CASE( compute_principal_axes_test )
{
cube.compute_bounding_box();
cube.compute_principal_axes();
BOOST_CHECK(cube.eigen_value(axis_t::x_axis) == 0.0f);
BOOST_CHECK(cube.eigen_value(axis_t::y_axis) == 0.0f);
BOOST_CHECK(cube.eigen_value(axis_t::z_axis) == 0.0f);
row.compute_bounding_box();
row.compute_principal_axes();
BOOST_CHECK(row.eigen_value(axis_t::x_axis) == 5.5f);
BOOST_CHECK(row.eigen_value(axis_t::y_axis) == 0.0f);
BOOST_CHECK(row.eigen_value(axis_t::z_axis) == 0.0f);
diagonal.compute_bounding_box();
diagonal.compute_principal_axes();
BOOST_CHECK(fabs(diagonal.eigen_value(axis_t::x_axis) - 0.195948f) < result_tolerance);
BOOST_CHECK(fabs(diagonal.eigen_value(axis_t::y_axis) - 2.60634f) < result_tolerance);
BOOST_CHECK(fabs(diagonal.eigen_value(axis_t::z_axis) - 481.031f) < result_tolerance);
}
/* Test select on surface */
BOOST_AUTO_TEST_CASE( select_on_surface_empty_test )
{
std::unique_ptr<voxel_set> on_surf(empty.select_on_surface());
BOOST_CHECK(on_surf == nullptr);
}
BOOST_AUTO_TEST_CASE( select_on_surface_test )
{
std::unique_ptr<voxel_set> on_surf(on_surface.select_on_surface());
BOOST_REQUIRE(on_surf != nullptr);
const auto &v = on_surf->get_voxels();
BOOST_REQUIRE(v.size() == 3);
BOOST_CHECK(v[0].coord == point_ti<>(0, 0, 0));
BOOST_CHECK(v[1].coord == point_ti<>(1, 0, 0));
BOOST_CHECK(v[2].coord == point_ti<>(5, 0, 0));
BOOST_CHECK(v[0].loc == voxel_value_t::primitive_on_surface);
BOOST_CHECK(v[1].loc == voxel_value_t::primitive_on_surface);
BOOST_CHECK(v[2].loc == voxel_value_t::primitive_on_surface);
}
/* Test cut */
BOOST_AUTO_TEST_CASE( cut_diagonal_test )
{
primitive_set *pos_part_p = nullptr;
primitive_set *neg_part_p = nullptr;
diagonal.cut(plane(point_t<>(1.0f, 0.0f, 0.0f), 3.1f, axis_t::x_axis), &pos_part_p, &neg_part_p);
voxel_set* pos_part = static_cast<voxel_set *>(pos_part_p);
voxel_set* neg_part = static_cast<voxel_set *>(neg_part_p);
BOOST_CHECK(pos_part->number_of_primitives_on_surface() == 1);
BOOST_CHECK(pos_part->number_of_primitives_inside() == 2);
BOOST_CHECK(pos_part->max_volume_error() == 8.0f);
BOOST_REQUIRE(pos_part->number_of_primitives() == 3);
BOOST_CHECK(pos_part->get_voxels()[0].coord == point_ti<>(6, 10, 16));
BOOST_CHECK(pos_part->get_voxels()[1].coord == point_ti<>(7, 12, 32));
BOOST_CHECK(pos_part->get_voxels()[2].coord == point_ti<>(8, 14, 64));
BOOST_CHECK(neg_part->number_of_primitives_on_surface() == 1);
BOOST_CHECK(neg_part->number_of_primitives_inside() == 2);
BOOST_CHECK(neg_part->max_volume_error() == 8.0f);
BOOST_REQUIRE(neg_part->number_of_primitives() == 3);
BOOST_CHECK(neg_part->get_voxels()[0].coord == point_ti<>(3, 4, 2));
BOOST_CHECK(neg_part->get_voxels()[1].coord == point_ti<>(4, 6, 4));
BOOST_CHECK(neg_part->get_voxels()[2].coord == point_ti<>(5, 8, 8));
delete pos_part;
delete neg_part;
}
BOOST_AUTO_TEST_CASE( cut_on_surface_test )
{
primitive_set *pos_part_p = nullptr;
primitive_set *neg_part_p = nullptr;
on_surface.cut(plane(point_t<>(1.0f, 0.0f, 0.0f), 1.25f, axis_t::x_axis), &pos_part_p, &neg_part_p);
voxel_set* pos_part = static_cast<voxel_set *>(pos_part_p);
voxel_set* neg_part = static_cast<voxel_set *>(neg_part_p);
BOOST_CHECK(pos_part->number_of_primitives_on_surface() == 2);
BOOST_CHECK(pos_part->number_of_primitives_inside() == 5);
BOOST_CHECK(pos_part->max_volume_error() == 2.0f);
BOOST_REQUIRE(pos_part->number_of_primitives() == 7);
BOOST_CHECK(pos_part->get_voxels()[0].coord == point_ti<>(1, 0, 0));
BOOST_CHECK(pos_part->get_voxels()[1].coord == point_ti<>(2, 0, 0));
BOOST_CHECK(pos_part->get_voxels()[2].coord == point_ti<>(3, 0, 0));
BOOST_CHECK(pos_part->get_voxels()[3].coord == point_ti<>(4, 0, 0));
BOOST_CHECK(pos_part->get_voxels()[4].coord == point_ti<>(5, 0, 0));
BOOST_CHECK(pos_part->get_voxels()[5].coord == point_ti<>(6, 0, 0));
BOOST_CHECK(pos_part->get_voxels()[6].coord == point_ti<>(7, 0, 0));
BOOST_CHECK(neg_part->number_of_primitives_on_surface() == 1);
BOOST_CHECK(neg_part->number_of_primitives_inside() == 0);
BOOST_CHECK(neg_part->max_volume_error() == 1.0f);
BOOST_REQUIRE(neg_part->number_of_primitives() == 1);
BOOST_CHECK(neg_part->get_voxels()[0].coord == point_ti<>(0, 0, 0));
delete pos_part;
delete neg_part;
}
/* Test compute cut volumes */
BOOST_AUTO_TEST_CASE( cut_volumes_test )
{
float pos_vol;
float neg_vol;
diagonal.compute_cut_volumes(plane(point_t<>(1.0f, 0.0f, 0.0f), 3.1f, axis_t::x_axis), &pos_vol, &neg_vol);
BOOST_CHECK(pos_vol == 24.0f);
BOOST_CHECK(neg_vol == 24.0f);
on_surface.compute_cut_volumes(plane(point_t<>(1.0f, 0.0f, 0.0f), 1.25f, axis_t::x_axis), &pos_vol, &neg_vol);
BOOST_CHECK(pos_vol == 7.0f);
BOOST_CHECK(neg_vol == 1.0f);
empty.compute_cut_volumes(plane(point_t<>(1.0f, 0.0f, 0.0f), 2.25f, axis_t::x_axis), &pos_vol, &neg_vol);
BOOST_CHECK(pos_vol == 0.0f);
BOOST_CHECK(neg_vol == 0.0f);
}
/* Test convert */
BOOST_AUTO_TEST_CASE( convert_test )
{
convex_mesh mesh;
cube.convert(&mesh, voxel_value_t::primitive_undefined);
BOOST_CHECK(mesh.number_of_points() == 8);
BOOST_CHECK(mesh.number_of_triangles() == 12);
BOOST_CHECK(mesh.volume() == 1.0f);
cube3x.convert(&mesh, voxel_value_t::primitive_undefined);
BOOST_CHECK(mesh.number_of_points() == 16);
BOOST_CHECK(mesh.number_of_triangles() == 24);
BOOST_CHECK(mesh.volume() == 28.0f);
on_surface.convert(&mesh, voxel_value_t::primitive_on_surface);
BOOST_CHECK(mesh.number_of_points() == 40);
BOOST_CHECK(mesh.number_of_triangles() == 60);
BOOST_CHECK(fabs(mesh.volume() - 31.0f) < result_tolerance);
}
/* Test compute axes aligned clipping planes */
BOOST_AUTO_TEST_CASE( compute_axes_aligned_clipping_planes_test )
{
std::vector<plane> planes;
diagonal.compute_bounding_box();
diagonal.compute_axes_aligned_clipping_planes(&planes, 9);
BOOST_REQUIRE(planes.size() == 10);
BOOST_CHECK(planes[0].n == point_t<>(1.0f, 0.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[0].p, -0.8f, result_tolerance);
BOOST_CHECK(planes[0].major_axis == axis_t::x_axis);
BOOST_CHECK(planes[1].n == point_t<>(0.0f, 1.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[1].p, 12.9f, result_tolerance);
BOOST_CHECK(planes[1].major_axis == axis_t::y_axis);
BOOST_CHECK(planes[2].n == point_t<>(0.0f, 1.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[2].p, 30.9f, result_tolerance);
BOOST_CHECK(planes[2].major_axis == axis_t::y_axis);
BOOST_CHECK(planes[3].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[3].p, 9.6f, result_tolerance);
BOOST_CHECK(planes[3].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[4].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[4].p, 27.6f, result_tolerance);
BOOST_CHECK(planes[4].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[5].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[5].p, 45.6f, result_tolerance);
BOOST_CHECK(planes[5].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[6].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[6].p, 63.6f, result_tolerance);
BOOST_CHECK(planes[6].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[7].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[7].p, 81.6f, result_tolerance);
BOOST_CHECK(planes[7].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[8].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[8].p, 99.6f, result_tolerance);
BOOST_CHECK(planes[8].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[9].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[9].p, 117.6f, result_tolerance);
BOOST_CHECK(planes[9].major_axis == axis_t::z_axis);
}
/* Test refine axes aligned clipping planes */
BOOST_AUTO_TEST_CASE( refine_axes_aligned_clipping_planes_x_test )
{
std::vector<plane> planes;
diagonal.compute_bounding_box();
diagonal.refine_axes_aligned_clipping_planes(&planes, plane(point_t<>(0.0f, 0.0f, 0.0f), 0.0f, axis_t::x_axis), 9, 1);
BOOST_REQUIRE(planes.size() == 6);
BOOST_CHECK(planes[0].n == point_t<>(1.0f, 0.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[0].p, -0.8f, result_tolerance);
BOOST_CHECK(planes[0].major_axis == axis_t::x_axis);
BOOST_CHECK(planes[1].n == point_t<>(1.0f, 0.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[1].p, 1.2f, result_tolerance);
BOOST_CHECK(planes[1].major_axis == axis_t::x_axis);
BOOST_CHECK(planes[2].n == point_t<>(1.0f, 0.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[2].p, 3.2f, result_tolerance);
BOOST_CHECK(planes[2].major_axis == axis_t::x_axis);
BOOST_CHECK(planes[3].n == point_t<>(1.0f, 0.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[3].p, 5.2f, result_tolerance);
BOOST_CHECK(planes[3].major_axis == axis_t::x_axis);
BOOST_CHECK(planes[4].n == point_t<>(1.0f, 0.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[4].p, 7.2f, result_tolerance);
BOOST_CHECK(planes[4].major_axis == axis_t::x_axis);
BOOST_CHECK(planes[5].n == point_t<>(1.0f, 0.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[5].p, 9.2f, result_tolerance);
BOOST_CHECK(planes[5].major_axis == axis_t::x_axis);
}
BOOST_AUTO_TEST_CASE( refine_axes_aligned_clipping_planes_y_test )
{
std::vector<plane> planes;
diagonal.compute_bounding_box();
diagonal.refine_axes_aligned_clipping_planes(&planes, plane(point_t<>(0.0f, 0.0f, 0.0f), 0.0f, axis_t::y_axis), 9, 6);
BOOST_REQUIRE(planes.size() == 11);
BOOST_CHECK(planes[0].n == point_t<>(0.0f, 1.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[0].p, 12.9f, result_tolerance);
BOOST_CHECK(planes[0].major_axis == axis_t::y_axis);
BOOST_CHECK(planes[1].n == point_t<>(0.0f, 1.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[1].p, 14.9f, result_tolerance);
BOOST_CHECK(planes[1].major_axis == axis_t::y_axis);
BOOST_CHECK(planes[2].n == point_t<>(0.0f, 1.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[2].p, 16.9f, result_tolerance);
BOOST_CHECK(planes[2].major_axis == axis_t::y_axis);
BOOST_CHECK(planes[3].n == point_t<>(0.0f, 1.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[3].p, 18.9f, result_tolerance);
BOOST_CHECK(planes[3].major_axis == axis_t::y_axis);
BOOST_CHECK(planes[4].n == point_t<>(0.0f, 1.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[4].p, 20.9f, result_tolerance);
BOOST_CHECK(planes[4].major_axis == axis_t::y_axis);
BOOST_CHECK(planes[5].n == point_t<>(0.0f, 1.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[5].p, 22.9f, result_tolerance);
BOOST_CHECK(planes[5].major_axis == axis_t::y_axis);
BOOST_CHECK(planes[6].n == point_t<>(0.0f, 1.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[6].p, 24.9f, result_tolerance);
BOOST_CHECK(planes[6].major_axis == axis_t::y_axis);
BOOST_CHECK(planes[7].n == point_t<>(0.0f, 1.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[7].p, 26.9f, result_tolerance);
BOOST_CHECK(planes[7].major_axis == axis_t::y_axis);
BOOST_CHECK(planes[8].n == point_t<>(0.0f, 1.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[8].p, 28.9f, result_tolerance);
BOOST_CHECK(planes[8].major_axis == axis_t::y_axis);
BOOST_CHECK(planes[9].n == point_t<>(0.0f, 1.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[9].p, 30.9f, result_tolerance);
BOOST_CHECK(planes[9].major_axis == axis_t::y_axis);
BOOST_CHECK(planes[10].n == point_t<>(0.0f, 1.0f, 0.0f));
BOOST_CHECK_CLOSE(planes[10].p, 32.9f, result_tolerance);
BOOST_CHECK(planes[10].major_axis == axis_t::y_axis);
}
BOOST_AUTO_TEST_CASE( refine_axes_aligned_clipping_planes_z_test )
{
std::vector<plane> planes;
diagonal.compute_bounding_box();
diagonal.refine_axes_aligned_clipping_planes(&planes, plane(point_t<>(0.0f, 0.0f, 0.0f), 0.0f, axis_t::z_axis), 4, 30);
BOOST_REQUIRE(planes.size() == 9);
BOOST_CHECK(planes[0].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[0].p, 61.6f, result_tolerance);
BOOST_CHECK(planes[0].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[1].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[1].p, 63.6f, result_tolerance);
BOOST_CHECK(planes[1].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[2].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[2].p, 65.6f, result_tolerance);
BOOST_CHECK(planes[2].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[3].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[3].p, 67.6f, result_tolerance);
BOOST_CHECK(planes[3].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[4].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[4].p, 69.6f, result_tolerance);
BOOST_CHECK(planes[4].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[5].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[5].p, 71.6f, result_tolerance);
BOOST_CHECK(planes[5].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[6].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[6].p, 73.6f, result_tolerance);
BOOST_CHECK(planes[6].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[7].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[7].p, 75.6f, result_tolerance);
BOOST_CHECK(planes[7].major_axis == axis_t::z_axis);
BOOST_CHECK(planes[8].n == point_t<>(0.0f, 0.0f, 1.0f));
BOOST_CHECK_CLOSE(planes[8].p, 77.6f, result_tolerance);
BOOST_CHECK(planes[8].major_axis == axis_t::z_axis);
}
/* Test compute convex hull */
BOOST_AUTO_TEST_CASE( empty_compute_convex_hull_test )
{
convex_mesh mesh;
empty.compute_convex_hull(&mesh, 1);
/* Checks */
BOOST_REQUIRE(mesh.number_of_points() == 0);
BOOST_REQUIRE(mesh.number_of_triangles() == 0);
}
BOOST_AUTO_TEST_CASE( cube_compute_convex_hull_test )
{
convex_mesh mesh;
cube.compute_convex_hull(&mesh, 1);
/* Checks */
BOOST_REQUIRE(mesh.number_of_points() == 0);
BOOST_REQUIRE(mesh.number_of_triangles() == 0);
}
BOOST_AUTO_TEST_CASE( on_surface_compute_convex_hull_test )
{
convex_mesh mesh;
on_surface.compute_convex_hull(&mesh, 1);
/* Checks */
BOOST_REQUIRE(mesh.number_of_points() == 8);
BOOST_CHECK(mesh.points()[0] == point_t<>(6.5f, 2.5f, 3.5f));
BOOST_CHECK(mesh.points()[1] == point_t<>(6.5f, 2.5f, 2.5f));
BOOST_CHECK(mesh.points()[2] == point_t<>(0.5f, 2.5f, 3.5f));
BOOST_CHECK(mesh.points()[3] == point_t<>(6.5f, 1.5f, 3.5f));
BOOST_CHECK(mesh.points()[4] == point_t<>(6.5f, 1.5f, 2.5f));
BOOST_CHECK(mesh.points()[5] == point_t<>(0.5f, 2.5f, 2.5f));
BOOST_CHECK(mesh.points()[6] == point_t<>(0.5f, 1.5f, 3.5f));
BOOST_CHECK(mesh.points()[7] == point_t<>(0.5f, 1.5f, 2.5f));
BOOST_REQUIRE(mesh.number_of_triangles() == 12);
BOOST_CHECK(mesh.triangles()[ 0].x == 1);
BOOST_CHECK(mesh.triangles()[ 0].y == 5);
BOOST_CHECK(mesh.triangles()[ 0].z == 2);
BOOST_CHECK(mesh.triangles()[ 1].x == 1);
BOOST_CHECK(mesh.triangles()[ 1].y == 2);
BOOST_CHECK(mesh.triangles()[ 1].z == 0);
BOOST_CHECK(mesh.triangles()[ 2].x == 2);
BOOST_CHECK(mesh.triangles()[ 2].y == 6);
BOOST_CHECK(mesh.triangles()[ 2].z == 3);
BOOST_CHECK(mesh.triangles()[ 3].x == 2);
BOOST_CHECK(mesh.triangles()[ 3].y == 3);
BOOST_CHECK(mesh.triangles()[ 3].z == 0);
BOOST_CHECK(mesh.triangles()[ 4].x == 3);
BOOST_CHECK(mesh.triangles()[ 4].y == 4);
BOOST_CHECK(mesh.triangles()[ 4].z == 1);
BOOST_CHECK(mesh.triangles()[ 5].x == 3);
BOOST_CHECK(mesh.triangles()[ 5].y == 1);
BOOST_CHECK(mesh.triangles()[ 5].z == 0);
BOOST_CHECK(mesh.triangles()[ 6].x == 4);
BOOST_CHECK(mesh.triangles()[ 6].y == 7);
BOOST_CHECK(mesh.triangles()[ 6].z == 5);
BOOST_CHECK(mesh.triangles()[ 7].x == 4);
BOOST_CHECK(mesh.triangles()[ 7].y == 5);
BOOST_CHECK(mesh.triangles()[ 7].z == 1);
BOOST_CHECK(mesh.triangles()[ 8].x == 5);
BOOST_CHECK(mesh.triangles()[ 8].y == 7);
BOOST_CHECK(mesh.triangles()[ 8].z == 6);
BOOST_CHECK(mesh.triangles()[ 9].x == 5);
BOOST_CHECK(mesh.triangles()[ 9].y == 6);
BOOST_CHECK(mesh.triangles()[ 9].z == 2);
BOOST_CHECK(mesh.triangles()[10].x == 6);
BOOST_CHECK(mesh.triangles()[10].y == 7);
BOOST_CHECK(mesh.triangles()[10].z == 4);
BOOST_CHECK(mesh.triangles()[11].x == 6);
BOOST_CHECK(mesh.triangles()[11].y == 4);
BOOST_CHECK(mesh.triangles()[11].z == 3);
}
BOOST_AUTO_TEST_CASE( on_surface_down_sampling_compute_convex_hull_test )
{
convex_mesh mesh;
on_surface.compute_convex_hull(&mesh, 3);
/* Checks */
BOOST_REQUIRE(mesh.number_of_points() == 8);
BOOST_CHECK(mesh.points()[0] == point_t<>(6.5f, 2.5f, 3.5f));
BOOST_CHECK(mesh.points()[1] == point_t<>(6.5f, 2.5f, 2.5f));
BOOST_CHECK(mesh.points()[2] == point_t<>(5.5f, 2.5f, 3.5f));
BOOST_CHECK(mesh.points()[3] == point_t<>(6.5f, 1.5f, 3.5f));
BOOST_CHECK(mesh.points()[4] == point_t<>(6.5f, 1.5f, 2.5f));
BOOST_CHECK(mesh.points()[5] == point_t<>(5.5f, 2.5f, 2.5f));
BOOST_CHECK(mesh.points()[6] == point_t<>(5.5f, 1.5f, 3.5f));
BOOST_CHECK(mesh.points()[7] == point_t<>(5.5f, 1.5f, 2.5f));
BOOST_REQUIRE(mesh.number_of_triangles() == 12);
BOOST_CHECK(mesh.triangles()[ 0].x == 1);
BOOST_CHECK(mesh.triangles()[ 0].y == 5);
BOOST_CHECK(mesh.triangles()[ 0].z == 2);
BOOST_CHECK(mesh.triangles()[ 1].x == 1);
BOOST_CHECK(mesh.triangles()[ 1].y == 2);
BOOST_CHECK(mesh.triangles()[ 1].z == 0);
BOOST_CHECK(mesh.triangles()[ 2].x == 2);
BOOST_CHECK(mesh.triangles()[ 2].y == 6);
BOOST_CHECK(mesh.triangles()[ 2].z == 3);
BOOST_CHECK(mesh.triangles()[ 3].x == 2);
BOOST_CHECK(mesh.triangles()[ 3].y == 3);
BOOST_CHECK(mesh.triangles()[ 3].z == 0);
BOOST_CHECK(mesh.triangles()[ 4].x == 3);
BOOST_CHECK(mesh.triangles()[ 4].y == 4);
BOOST_CHECK(mesh.triangles()[ 4].z == 1);
BOOST_CHECK(mesh.triangles()[ 5].x == 3);
BOOST_CHECK(mesh.triangles()[ 5].y == 1);
BOOST_CHECK(mesh.triangles()[ 5].z == 0);
BOOST_CHECK(mesh.triangles()[ 6].x == 4);
BOOST_CHECK(mesh.triangles()[ 6].y == 7);
BOOST_CHECK(mesh.triangles()[ 6].z == 5);
BOOST_CHECK(mesh.triangles()[ 7].x == 4);
BOOST_CHECK(mesh.triangles()[ 7].y == 5);
BOOST_CHECK(mesh.triangles()[ 7].z == 1);
BOOST_CHECK(mesh.triangles()[ 8].x == 5);
BOOST_CHECK(mesh.triangles()[ 8].y == 7);
BOOST_CHECK(mesh.triangles()[ 8].z == 6);
BOOST_CHECK(mesh.triangles()[ 9].x == 5);
BOOST_CHECK(mesh.triangles()[ 9].y == 6);
BOOST_CHECK(mesh.triangles()[ 9].z == 2);
BOOST_CHECK(mesh.triangles()[10].x == 6);
BOOST_CHECK(mesh.triangles()[10].y == 7);
BOOST_CHECK(mesh.triangles()[10].z == 4);
BOOST_CHECK(mesh.triangles()[11].x == 6);
BOOST_CHECK(mesh.triangles()[11].y == 4);
BOOST_CHECK(mesh.triangles()[11].z == 3);
}
BOOST_AUTO_TEST_CASE( low_cluster_size_on_surface_compute_convex_hull_test )
{
convex_mesh mesh;
on_surface.compute_convex_hull(&mesh, 1, 1);
/* Checks */
BOOST_REQUIRE(mesh.number_of_points() == 8);
BOOST_CHECK(mesh.points()[0] == point_t<>(6.5f, 2.5f, 3.5f));
BOOST_CHECK(mesh.points()[1] == point_t<>(6.5f, 1.5f, 3.5f));
BOOST_CHECK(mesh.points()[2] == point_t<>(6.5f, 2.5f, 2.5f));
BOOST_CHECK(mesh.points()[3] == point_t<>(0.5f, 2.5f, 3.5f));
BOOST_CHECK(mesh.points()[4] == point_t<>(6.5f, 1.5f, 2.5f));
BOOST_CHECK(mesh.points()[5] == point_t<>(0.5f, 1.5f, 3.5f));
BOOST_CHECK(mesh.points()[6] == point_t<>(0.5f, 2.5f, 2.5f));
BOOST_CHECK(mesh.points()[7] == point_t<>(0.5f, 1.5f, 2.5f));
BOOST_REQUIRE(mesh.number_of_triangles() == 12);
BOOST_CHECK(mesh.triangles()[ 0].x == 1);
BOOST_CHECK(mesh.triangles()[ 0].y == 4);
BOOST_CHECK(mesh.triangles()[ 0].z == 2);
BOOST_CHECK(mesh.triangles()[ 1].x == 1);
BOOST_CHECK(mesh.triangles()[ 1].y == 2);
BOOST_CHECK(mesh.triangles()[ 1].z == 0);
BOOST_CHECK(mesh.triangles()[ 2].x == 2);
BOOST_CHECK(mesh.triangles()[ 2].y == 6);
BOOST_CHECK(mesh.triangles()[ 2].z == 3);
BOOST_CHECK(mesh.triangles()[ 3].x == 2);
BOOST_CHECK(mesh.triangles()[ 3].y == 3);
BOOST_CHECK(mesh.triangles()[ 3].z == 0);
BOOST_CHECK(mesh.triangles()[ 4].x == 3);
BOOST_CHECK(mesh.triangles()[ 4].y == 5);
BOOST_CHECK(mesh.triangles()[ 4].z == 1);
BOOST_CHECK(mesh.triangles()[ 5].x == 3);
BOOST_CHECK(mesh.triangles()[ 5].y == 1);
BOOST_CHECK(mesh.triangles()[ 5].z == 0);
BOOST_CHECK(mesh.triangles()[ 6].x == 5);
BOOST_CHECK(mesh.triangles()[ 6].y == 7);
BOOST_CHECK(mesh.triangles()[ 6].z == 4);
BOOST_CHECK(mesh.triangles()[ 7].x == 5);
BOOST_CHECK(mesh.triangles()[ 7].y == 4);
BOOST_CHECK(mesh.triangles()[ 7].z == 1);
BOOST_CHECK(mesh.triangles()[ 8].x == 4);
BOOST_CHECK(mesh.triangles()[ 8].y == 7);
BOOST_CHECK(mesh.triangles()[ 8].z == 6);
BOOST_CHECK(mesh.triangles()[ 9].x == 4);
BOOST_CHECK(mesh.triangles()[ 9].y == 6);
BOOST_CHECK(mesh.triangles()[ 9].z == 2);
BOOST_CHECK(mesh.triangles()[10].x == 6);
BOOST_CHECK(mesh.triangles()[10].y == 7);
BOOST_CHECK(mesh.triangles()[10].z == 5);
BOOST_CHECK(mesh.triangles()[11].x == 6);
BOOST_CHECK(mesh.triangles()[11].y == 5);
BOOST_CHECK(mesh.triangles()[11].z == 3);
}
BOOST_AUTO_TEST_SUITE_END()
}; /* namespace test */
}; /* namespace raptor_convex_decomposition */ | true |
8114e1acc7d0e523ee549b8051c23e584aab7b5c | C++ | juanmard/juegocpp | /Clases/Nombres.h | UTF-8 | 3,253 | 3.71875 | 4 | [] | no_license | ///
/// @file Nombres.cpp
/// @brief Fichero de implementación de la clase "Nombres".
/// @author Juan Manuel Rico
/// @date Noviembre 2015
/// @version
/// - 1.0.0 Noviembre 2015
///
#ifndef _NOMBRES_H_
#define _NOMBRES_H_
#include <string>
#include <iostream>
/// Clase que reúne todos los nombres de objetos del juego.
///
/// @todo Permitir añadir nombres en tiempo de ejecución.
/// Para ello una variable global debería llevar la cuenta de los códigos generados por
/// la clase y emparejar con la cadena 'string' que se le pase por referencia.
/// @code
/// Nombre::codigo = AñadirNombre ("Pelota");
/// @endcode
/// El codigo sería el mismo para todos los actores del mismo tipo, luego sería una variable
/// estática de la clase ("Pelota", "Paleta", etc...)
/// @code
/// if (who->getCodigo() == Pelota::codigo) {} else {};
/// @endcode
/// @attention Igual es más conveniente utilizar una clase STL como 'map' para modelar los nombres.
///
class Nombres
{
public:
/// Código de cada actor del juego.
enum codigo {
pelota, ///< Pelota que rebota por pantalla.
paleta, ///< Paleta que golpea a la pelota y la desvía.
herny, ///< Troglodita de prueba.
jugador, ///< Jugador de prueba.
enemigo, ///< Enemigo de prueba.
ladrillo, ///< Ladrillo para ser golpeado por la pelota.
mago, ///< Prueba simple sin desarrollar.
ben, ///< Prueba de un personaje completo con Ben10.
camello, ///< Un actor de prueba más.
plataforma ///< Actor de prueba con movimiento automático.
};
public:
/// Constructor.
///
Nombres ();
/// Destructor.
///
~Nombres ();
/// Convierte el código de un nombre en una cadena imprimible de caracteres.
/// @todo Utilizar un operador de conversión de tipos para este método.
/// En lugar de usar el 'switch' utilizar una estructura 'stl' tipo 'map'.
/// Esto mismo se hizo para referenciar los punteros y los nombres de los Bitmaps en la clase 'Almacen'.
///
static std::string& Imprimir (const codigo cod_nombre)
{
std::string &cadena = *new std::string();
switch (cod_nombre)
{
case pelota: cadena = "Pelota"; break;
case paleta: cadena = "Suelo"; break;
case herny: cadena = "Herny"; break;
case jugador: cadena = "Jugador"; break;
case enemigo: cadena = "Enemigo"; break;
case ladrillo: cadena = "Ladrillo"; break;
case mago: cadena = "Mago"; break;
case ben: cadena = "Ben"; break;
case camello: cadena = "Camello"; break;
case plataforma: cadena = "Plataforma"; break;
default: cadena = "Sin nombre"; break;
}
return cadena;
};
/// Obtiene cadena representativa del objeto como un insertor en el flujo.
/// @todo Cambiar por herencia con PrintableObject
///
friend std::ostream& operator<< (std::ostream& os, const Nombres::codigo cod);
};
#endif
| true |
97fc8b49cc21639fb787f17fe0e846ccf8b2f2dd | C++ | AlicKaufmann/hovercraft_cpp | /src/mylibrary/src/create_integrator.cpp | UTF-8 | 2,265 | 2.625 | 3 | [] | no_license | // creates an integrator for non-autonomous ODE, also returning the cost
#include <casadi/casadi.hpp>
#include <create_integrator.hpp>
#include <iostream>
//#include <casadi_limits.hpp>
using namespace std;
using namespace casadi;
Function create_integrator_cost(Function f /*transition map*/ , int M /*number of integration steps*/, Function g /*guadrature*/)
{
MX Ts = MX::sym("Ts");
MX u = MX::sym("u", 2);
MX t0 = MX::sym("t0");
MX t = t0;
MX x0 = MX::sym("x0",6);
MX x = x0;
// create the "augmented" transition map
Function fg = Function("fg", {x, u, t}, {f(MXVector{x,u})[0], g(MXVector{x,u,t})[0]}, {"x", "u", "t"}, {"k_x", "k_q"});
MX dt = Ts/M;
MX q = MX::zeros(1,1);
for(int i=1; i<=M; i++)
{
MXDict k1 = fg(MXDict{{"x", x}, {"u", u}, {"t", t}});
MXDict k2 = fg(MXDict{{"x", x + k1["k_x"] * dt/2}, {"u", u}, {"t", t+dt/2}});
MXDict k3 = fg(MXDict{{"x", x + k2["k_x"] * dt/2}, {"u", u}, {"t", t+dt/2}});
MXDict k4 = fg(MXDict{{"x", x + k3["k_x"] * dt}, {"u", u}, {"t", t+dt}});
t = t + dt;
x = x + dt/6 * (k1["k_x"] + 2 * k2["k_x"] + 2 * k3["k_x"] + k4["k_x"]);
q = q + dt/6 * (k1["k_q"] + 2 * k2["k_q"] + 2 * k3["k_q"] + k4["k_q"]);
}
return Function("fgd", {x0, Ts, u, t0}, {x, q}, {"x0", "Ts", "u", "t0"}, {"xf", "qf"});
}
// integrator for autonomous ODE which doesn't return cost but more efficient computation
Function create_integrator_rk4(Function f /*transition map*/ , int M /*number of integration steps*/)
{
MX Ts = MX::sym("Ts");
MX t = MX::sym("t");
MX u = MX::sym("u", 2);
MX px= MX::sym("px");
MX py = MX::sym("py");
MX theta = MX::sym("theta");
MX vx = MX::sym("vx");
MX vy = MX::sym("vy");
MX omega = MX::sym("omega");
MX dt = Ts/M;
MX x0 = MX::sym("x0",6);
MX x = x0;
for(int i=1; i<=4; i++)
{
cout << f << endl;
cout << f(MXVector{x,u}) << endl;
vector<MX> k1 = f(MXVector{x, u});
vector<MX> k2 = f(MXVector{x + k1[0] * dt/2, u});
vector<MX> k3 = f(MXVector{x + k2[0] * dt/2, u});
vector<MX> k4 = f(MXVector{x + k3[0] * dt, u});
x = x + dt/6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0]);
}
//cout << "k1 vaut : " << k1[0] << endl;
return Function("fd", {x0, Ts, u}, {x});
}
| true |
18d9a42fe6c9c3501972c7e352eb2da2a423e65a | C++ | oktomus/cpp-closest-point-on-mesh | /src/core/scene.h | UTF-8 | 500 | 2.90625 | 3 | [] | no_license | #pragma once
#include "mesh.h"
#include "rasterized_mesh.h"
#include <vector>
namespace core
{
/**
* @brief Store multiple meshes and everything required to render them.
*/
class Scene
{
public:
Scene(const std::vector<Mesh>& meshes);
std::size_t get_mesh_count() const;
const Mesh& get_mesh(const std::size_t index) const;
void render() const;
private:
const std::vector<Mesh> m_meshes;
std::vector<RasterizedMesh> m_drawing_meshes;
};
} // namespace core
| true |
94a3efba61e556fd825a54ba4e2074a28fa4ef08 | C++ | Ajay7545/AllDataStructure | /arrarysort012.cpp | UTF-8 | 1,374 | 3.375 | 3 | [] | no_license | #include<iostream>
#include<bits/stdc++.h>
#include<assert.h>
using namespace std;
void printarr(int *a,int n);
int main()
{
/*
Invariant: At each index, at 0th index count 0s ,at 1th index 1s count 2s count at index 2.
Pre-condition:vaues shoud not be other than 0,1,2
Post-condition: a the eemnt in an array had stored 0,1,2 count ony.
*/
int t;
cout<<"Nmbr of testcase:";
cin>>t;
for(int i=0;i<t;i++)
{
int n;
cout<<"enter array size:";
cin>>n;
int av[n];
cout<<"enter values in array 0,1,2:";
for(int k=0;k<n;k++)
{ int val;
cin>>val;
assert(val>=0); //PRE CONDITION INPUT VALUES SHOULD BE 0,1,2, IN AN ARRAY
assert(val<=2);
av[k]=val;
}
printarr(av,n);
}
}
void printarr(int *a,int n) //ROUTINES
{
int b[3]={0,0,0};
for(int j=0;j<n;j++)
{
if(a[j]==0)
b[a[j]]++;
else if(a[j]==1)
b[a[j]]++;
else
b[a[j]]++;
}
int aa=b[0],bb=b[1],cc=b[2];
while(aa>0)
{cout<<0<<" ";
aa--;}
while(bb>0)
{cout<<1<<" ";
bb--;}
while(cc>0)
{cout<<2<<" ";
cc--;}
cout<<endl;
}
| true |
5eed547b245db972797a91c5bc5f7ac774bf47b6 | C++ | marinov98/CSCI-335 | /tests/project1Tests/main.cpp | UTF-8 | 1,319 | 3.25 | 3 | [] | no_license | /******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
bool isCorrectPosition(int pos) {
return (pos == 1 || pos == 4 || pos == 7 || pos == 8 || pos == 10 || pos == 25 || pos == 26
|| pos == 30 || pos == 38 || pos == 39);
}
vector<string> split(string const& in) {
int pos = 1;
vector<string> result;
string s = "";
for (int i = 0; i < in.size(); i++) {
if (in[i] != ',' && isCorrectPosition(pos)) {
s += in[i];
}
else {
if (isCorrectPosition(pos)) {
result.push_back(s);
s = "";
}
pos++;
}
}
if (!s.empty()) {
result.push_back(s);
}
return result;
}
int main() {
ifstream parser;
parser.open("testcsv.txt");
string reader;
vector<string> extractor;
while (getline(parser, reader)) {
extractor.push_back(reader);
}
vector<string> tester = split(extractor[0]);
int i = 0;
for (string s : tester) {
cout << " index:" << i++ << " value:" << s << '\n';
}
return 0;
}
| true |
7704f93c14324bc3321187311e5126ec2a9c7ac8 | C++ | dkarlo2/PlayerDetectionTracking | /src/min_edge_cover.cpp | UTF-8 | 10,536 | 2.765625 | 3 | [] | no_license | #include "min_edge_cover.h"
#include "time_measurement.h"
#include <queue>
#undef min
#undef max
// mostly copied from
// https://www.topcoder.com/community/data-science/data-science-tutorials/assignment-problem-and-hungarian-algorithm/
// ###############################################################################################################################
#define INF 100000000 //just infinity
int max_match; //n workers and n jobs
double *lx, *ly; //labels of X and Y parts
int *xy; //xy[x] - vertex that is matched with x,
int *yx; //yx[y] - vertex that is matched with y
bool *S, *T; //sets S and T in algorithm
double *slack; //as in the algorithm description
int *slackx; //slackx[y] such a vertex, that
// l(slackx[y]) + l(y) - w(slackx[y],y) = slack[y]
int *prev; //array for memorizing alternating paths
void init_labels(int n, double **cost)
{
memset(lx, 0, n * sizeof(*lx));
memset(ly, 0, n * sizeof(*ly));
for (int x = 0; x < n; x++)
for (int y = 0; y < n; y++)
lx[x] = std::max(lx[x], cost[x][y]);
}
void update_labels(int n)
{
int x, y;
double delta = INF; //init delta as infinity
for (y = 0; y < n; y++) //calculate delta using slack
if (!T[y])
delta = std::min(delta, slack[y]);
for (x = 0; x < n; x++) //update X labels
if (S[x]) lx[x] -= delta;
for (y = 0; y < n; y++) //update Y labels
if (T[y]) ly[y] += delta;
for (y = 0; y < n; y++) //update slack array
if (!T[y])
slack[y] -= delta;
}
void add_to_tree(int x, int prevx, int n, double **cost)
//x - current vertex,prevx - vertex from X before x in the alternating path,
//so we add edges (prevx, xy[x]), (xy[x], x)
{
S[x] = true; //add x to S
prev[x] = prevx; //we need this when augmenting
for (int y = 0; y < n; y++) //update slacks, because we add new vertex to S
if (lx[x] + ly[y] - cost[x][y] < slack[y])
{
slack[y] = lx[x] + ly[y] - cost[x][y];
slackx[y] = x;
}
}
void augment(int n, double **cost) //main function of the algorithm
{
if (max_match == n) return; //check wether matching is already perfect
int x, y, root; //just counters and root vertex
int *q = new int[n];
int wr = 0, rd = 0; //q - queue for bfs, wr,rd - write and read
//pos in queue
memset(S, false, n * sizeof(*S)); //init set S
memset(T, false, n * sizeof(*T)); //init set T
memset(prev, -1, n * sizeof(*prev)); //init set prev - for the alternating tree
for (x = 0; x < n; x++) //finding root of the tree
if (xy[x] == -1)
{
q[wr++] = root = x;
prev[x] = -2;
S[x] = true;
break;
}
for (y = 0; y < n; y++) //initializing slack array
{
slack[y] = lx[root] + ly[y] - cost[root][y];
slackx[y] = root;
}
//second part of augment() function
while (true) //main cycle
{
while (rd < wr) //building tree with bfs cycle
{
x = q[rd++]; //current vertex from X part
for (y = 0; y < n; y++) //iterate through all edges in equality graph
if (cost[x][y] == lx[x] + ly[y] && !T[y])
{
if (yx[y] == -1) break; //an exposed vertex in Y found, so
//augmenting path exists!
T[y] = true; //else just add y to T,
q[wr++] = yx[y]; //add vertex yx[y], which is matched
//with y, to the queue
add_to_tree(yx[y], x, n, cost); //add edges (x,y) and (y,yx[y]) to the tree
}
if (y < n) break; //augmenting path found!
}
if (y < n) break; //augmenting path found!
update_labels(n); //augmenting path not found, so improve labeling
wr = rd = 0;
for (y = 0; y < n; y++)
//in this cycle we add edges that were added to the equality graph as a
//result of improving the labeling, we add edge (slackx[y], y) to the tree if
//and only if !T[y] && slack[y] == 0, also with this edge we add another one
//(y, yx[y]) or augment the matching, if y was exposed
if (!T[y] && slack[y] == 0)
{
if (yx[y] == -1) //exposed vertex in Y found - augmenting path exists!
{
x = slackx[y];
break;
}
else
{
T[y] = true; //else just add y to T,
if (!S[yx[y]])
{
q[wr++] = yx[y]; //add vertex yx[y], which is matched with
//y, to the queue
add_to_tree(yx[y], slackx[y], n, cost); //and add edges (x,y) and (y,
//yx[y]) to the tree
}
}
}
if (y < n) break; //augmenting path found!
}
if (y < n) //we found augmenting path!
{
max_match++; //increment matching
//in this cycle we inverse edges along augmenting path
for (int cx = x, cy = y, ty; cx != -2; cx = prev[cx], cy = ty)
{
ty = xy[cx];
yx[cy] = cx;
xy[cx] = cy;
}
augment(n, cost); //recall function, go to step 1 of the algorithm
}
delete q;
}//end of augment() function
int* hungarian(int n, double **cost)
{
lx = new double[n];
ly = new double[n];
xy = new int[n];
yx = new int[n];
S = new bool[n];
T = new bool[n];
slack = new double[n];
slackx = new int[n];
prev = new int[n];
int a[6];
max_match = 0; //number of vertices in current matching
memset(xy, -1, n * sizeof(*xy));
memset(yx, -1, n * sizeof(*yx));
init_labels(n, cost); //step 0
augment(n, cost); //steps 1-3
delete[] prev;
delete[] slackx;
delete[] slack;
delete[] T;
delete[] S;
delete[] yx;
delete[] ly;
delete[] lx;
return xy;
}
// ###############################################################################################################################
static int nodeIdGenerator = 0;
Node::Node(bool T, int TI) : id(nodeIdGenerator++), type(T), typeIndex(TI) {}
void Graph::updateNeisCount() {
neisCount.clear();
for (int i = 0; i < nodes.size(); i++) {
neisCount[nodes[i]] = 0;
for (int j = 0; j < nodes.size(); j++) {
if (edges[i][j] != non_exist) {
neisCount[nodes[i]]++;
}
}
}
}
static void decreaseTableElement(double &element, double d) {
if (element != non_exist) {
element -= d;
if (element < 1e-5) {
element = 0;
}
}
}
static void increaseTableElement(double &element, double d) {
if (element != non_exist) {
element += d;
}
}
static void dumpTable(double **table, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (table[i][j] == non_exist) {
std::cout << "- ";
}
else {
std::cout << table[i][j] << ' ';
}
}
std::cout << std::endl;
}
system("pause");
}
std::map<Node, std::set<Node>> findMinimalEdgeCover(Graph &g) {
std::vector<Node> nodes = g.getNodes();
double** edges = g.getEdges();
int n = nodes.size();
std::vector<int> nodeMapping;
for (int i = 0; i < nodes.size(); i++) {
if (g.isEmpty(nodes[i])) {
n--;
} else {
nodeMapping.push_back(i);
}
}
std::cerr << "Number of non empty nodes: " << n << std::endl;
if (n == 0) {
return std::map<Node, std::set<Node>>();
}
std::vector<int> minWeightNodes;
MyTime mt;
mt.start();
// create a table representing the expanded graph
double **table = new double*[n];
for (int i = 0; i < n; i++) {
table[i] = new double[n];
}
for (int i = 0; i < n; i++) {
double d = std::numeric_limits<double>::max();
int minDIndex = -1;
for (int j = 0; j < n; j++) {
table[i][j] = edges[nodeMapping[i]][nodeMapping[j]];
if (table[i][j] != non_exist && table[i][j] < d) {
d = table[i][j];
minDIndex = j;
}
}
if (minDIndex != -1) {
table[i][i] = 2 * d;
minWeightNodes.push_back(minDIndex);
} else {
std::cerr << "Was" << std::endl;
throw "";
}
}
// check
for (int i = 0; i < n; i++) {
Node ni = nodes[nodeMapping[i]];
for (int j = 0; j < n; j++) {
Node nj = nodes[nodeMapping[j]];
if (table[i][j] != non_exist && i != j && (ni.isType() && nj.isType() || !ni.isType() && !nj.isType())) {
std::cerr << "should not happen" << std::endl;
throw "";
}
}
}
// dumpTable(table, n);
// convert from minimal to maximal weight perfect matching problem
double d = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (table[i][j] != non_exist) {
d = std::max(d, table[i][j]);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (table[i][j] != non_exist) {
table[i][j] = d - table[i][j];
} else {
table[i][j] = -std::numeric_limits<double>::max();
}
}
}
// dumpTable(table, n);
std::cerr << "Init table: " << mt.time() << std::endl;
mt.start();
int *assignments = hungarian(n, table);
std::cerr << "Hungarian: " << mt.time() << std::endl;
std::map<Node, std::set<Node>> cover;
for (int i = 0; i < n; i++) {
Node ni = nodes[nodeMapping[i]];
cover[ni] = std::set<Node>();
}
for (int i = 0; i < n; i++) {
if (assignments[i] == -1) {
continue;
}
Node ni = nodes[nodeMapping[i]];
int j = assignments[i];
if (i == j) {
Node n = nodes[nodeMapping[minWeightNodes[i]]];
cover[ni].insert(n);
cover[n].insert(ni);
if (n.isType() && ni.isType() || !n.isType() && !ni.isType()) {
std::cerr << ":o" << std::endl;
system("pause");
}
} else {
Node n = nodes[nodeMapping[j]];
cover[ni].insert(n);
cover[n].insert(ni);
if (n.isType() && ni.isType() || !n.isType() && !ni.isType()) {
std::cerr << ":o2" << std::endl;
system("pause");
}
}
}
for (int i = 0; i < n; i++) {
delete[] table[i];
}
delete[] table;
delete assignments;
return cover;
}
void testFindMinimalEdgeCover() {
Graph g(5);
Node a(true, 0);
Node b(true, 1);
Node c(true, 2);
Node x(false, 0);
Node y(false, 1);
g.addNode(a);
g.addNode(b);
g.addNode(c);
g.addNode(x);
g.addNode(y);
g.init();
g.addEdge(a, x, 10);
g.addEdge(b, x, 1);
g.addEdge(b, y, 3);
g.addEdge(c, y, 5);
g.updateNeisCount();
std::map<Node, std::set<Node>> cover = findMinimalEdgeCover(g);
for (std::map<Node, std::set<Node>>::iterator it = cover.begin(); it != cover.end(); it++) {
if (it->first.isType()) {
for (std::set<Node>::iterator jt = it->second.begin(); jt != it->second.end(); jt++) {
if (jt->isType()) {
std::cerr << "should not happen" << std::endl;
throw "";
}
int measurementIndex = it->first.getTypeIndex();
int trackIndex = jt->getTypeIndex();
std::cout << "Match: " << measurementIndex << ' ' << trackIndex << std::endl;
}
}
}
system("pause");
}
| true |
61674029382c398626d076c1f1566c00174c6d1d | C++ | FancyKings/SDUSTOJ_ACCode | /Code_by_runid/2430668.cc | UTF-8 | 2,352 | 3.484375 | 3 | [
"Apache-2.0"
] | permissive | #include <bits/stdc++.h>
using namespace std;
const double PI = 3.14;
class Shape
{
public:
static int NumOfShapes;
double r;
Shape(double x):r(x){
NumOfShapes++;
cout << "A shape is created!" << endl;
};
virtual ~Shape(){
cout << "A shape is erased!" << endl;
};
static int getNumOfShapes()
{
return NumOfShapes;
}
virtual double getArea() = 0;
};
class Circle:public Shape
{
public:
static int NumOfCircles;
double l;
Circle(double x):l(x),Shape(x){
NumOfCircles++;
cout << "A circle is created!" << endl;
};
~Circle(){
cout << "A circle is erased!" << endl;
};
double getArea()
{
return (l*l*PI);
}
static int getNumOfCircles()
{
return (NumOfCircles);
}
};
class Square:public Shape
{
public:
static int NumOfSquares;
double r;
Square(double x):r(x),Shape(x){
NumOfSquares++;
cout << "A square is created!" << endl;
};
~Square(){
cout << "A square is erased!" << endl;
};
double getArea()
{
return (r*r);
}
static int getNumOfSquares()
{
return (NumOfSquares);
}
};
int Shape::NumOfShapes = 0;
int Circle::NumOfCircles = 0;
int Square::NumOfSquares = 0;
int main()
{
int cases;
char type;
double data;
Shape *shape;
cin>>cases;
cout<<"numOfShapes = "<<Shape::getNumOfShapes();
cout<<", numOfCircles = "<<Circle::getNumOfCircles();
cout<<", numOfSquares = "<<Square::getNumOfSquares()<<endl;
for (int i = 0; i < cases; i++)
{
cin>>type>>data;
switch(type)
{
case 'C':
shape = new Circle(data);
break;
case 'S':
shape = new Square(data);
break;
}
cout<<"Area = "<<setprecision(2)<<fixed<<shape->getArea()<<endl;
delete shape;
}
cout<<"numOfShapes = "<<Shape::getNumOfShapes();
cout<<", numOfCircles = "<<Circle::getNumOfCircles();
cout<<", numOfSquares = "<<Square::getNumOfSquares()<<endl;
}
/**************************************************************
Problem: 1810
User: 201701060705
Language: C++
Result: Accepted
Time:8 ms
Memory:1272 kb
****************************************************************/
| true |
9f5666bda0ff306003b3e9d14ad898319e023ac3 | C++ | BhanujaAggarwal/LeetCode | /#1408.cpp | UTF-8 | 534 | 2.71875 | 3 | [] | no_license | class Solution {
public:
vector<string> stringMatching(vector<string>& words) {
set<string> ans;
vector<string> a;
for(int i=0;i<words.size()-1;i++){
for(int j=i+1;j<words.size();j++){
if(words[i].find(words[j])!=-1){
ans.insert(words[j]);
}
if(words[j].find(words[i])!=-1){
ans.insert(words[i]);
}
}
}
for(auto i:ans) a.push_back(i);
return a;
}
}; | true |
9d21e90a10f0d7ca96f9b844725a191c9ac26464 | C++ | serialphotog/emu64 | /libemu64/rom.cpp | UTF-8 | 761 | 2.734375 | 3 | [] | no_license | #include "emu64/rom.h"
#include <algorithm>
#include <fstream>
#include <vector>
#include <stdio.h>
#include <iostream>
namespace Emu64
{
Rom::Rom()
{
}
Rom::~Rom()
{
if (m_data != nullptr) delete m_data;
}
void Rom::Read(std::string path)
{
// TODO: Error handling!
FILE* fp = fopen(path.c_str(), "rb");
if (fp == NULL)
{
std::cout << "[ERROR]: Failed to load ROM " << path << std::endl;
exit(1);
}
fseek(fp, 0L, SEEK_END);
m_size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
m_data = (unsigned char*)malloc(m_size);
fread(m_data, m_size, 1, fp);
fclose(fp);
}
} | true |
91b85deb5a23474888d73ce57a739b2fb2dc02c1 | C++ | vikas0o7/important_cpp_questions | /trie.cpp | UTF-8 | 1,208 | 3.53125 | 4 | [] | no_license | #include<bits/stdc++.h>
#define io ios_base::sync_with_stdio(false)
#define mp make_pair
#define pb push_back
using namespace std;
class Trie{
public:
bool isendofword;
unordered_map<char,Trie*> map;
};
Trie* newTrie(){
Trie* temp= new Trie;
temp->isendofword=false;
return temp;
}
void insert(Trie* &root, string s){
if(root==NULL) root=newTrie();
Trie* temp=root;
for(int i=0;i<s.length();i++){
if(temp->map.find(s[i])==(temp->map).end()){
temp->map[s[i]]= newTrie();
temp= temp->map[s[i]]; //map[s[i]] will be trie*; see the struct;
}
}
temp->isendofword=true; // temp will be at last letter of string s;
}
bool search(Trie* &root, string s){
if(root==NULL) return false;
Trie* temp=root;
for(int i=0;i<s.length();i++){
if(temp->map.find(s[i])== temp->map.end()) return false;
temp= temp->map[s[i]];
}
return true;
}
int main()
{
Trie* root = nullptr;
insert(root, "geeks");
cout << search(root, "geeks") << " ";
insert(root, "for");
cout << search(root, "for") << " ";
cout << search(root, "geekk") << " ";
insert(root, "gee");
cout << search(root, "gee") << " ";
insert(root, "science");
cout << search(root, "sciences") << endl;
return 0;
}
| true |
5d3dad482af4cea609ed5546869e8ef900b6acdf | C++ | FunctionDou/Code | /Cc++/epoll_fifo_1_复用.cpp | UTF-8 | 3,907 | 2.703125 | 3 | [] | no_license | /*************************************************************************
> File Name: epoll.cpp
> Author: Function_Dou
> Mail: NOT
> Created Time: 2018年04月19日 星期四 20时25分45秒
epoll 函数:
// 创建一个 epoll 对象(epoll instance),同时返回该对象的描述符。
int epoll_create(int size);
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);
epoll_event 结构体:
typedef union epoll_data
{
void *ptr;
int fd;
uint32_t u32;
uint64_t u64;
} epoll_data_t;
struct epoll_event
{
uint32_t events; // Epoll 事件
epoll_data_t data; // 用户数据
};
events :
EPOLLIN 监听 fd 是否可读
EPOLLOUT 监听 fd 是否可写
EPOLLRDHUP Linux 2.6.17 后可用。监听流式套接字对象是否关闭或半关闭
EPOLLPRI 监听是否有紧急数据可读
EPOLLET 表示设置关联的描述符 IO 事件触发模式
op 方法:
EPOLL_CTL_ADD 将参数 fd 指定的描述符添加到 epoll 对象中,同时将其关联到一个 epoll 事件对象——即参数 event 所指定的值
EPOLL_CTL_MOD 修改描述符 fd 所关联的事件对象 event,前提是该 fd 已经添加到了 epoll 对象中
EPOLL_CTL_DEL 将描述符 fd 从 epoll 对象中移除,此时参数 event 被忽略,也可指定为 NULL
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#define N 64
#define NUM 2
int create_fifo(const char *);
void sig_sigint(int);
void write_error(const char *);
int read_fd(int);
int Write(const char *);
int Write(const char *s)
{
int n;
n = write(STDOUT_FILENO, s, strlen(s));
return n;
}
int read_fd(int fd)
{
int n;
// 验证边沿触发和水平缓冲的区别, 所以将 buf 设置为 4
char buf[4], line[N];
// 水平缓冲使用, 边沿触发使用就能看出区别
n = read(fd, buf, sizeof(buf));
if(n > 0)
{
sprintf(line, "%d say : %s\n", fd, buf);
puts(line);
}
if(n == 0)
{
sprintf(line, "%d is close\n", fd);
return 0;
}
if(n < 0)
write_error("read error\n");
return n;
}
void write_error(const char *s)
{
Write(s);
exit(EXIT_FAILURE);
}
void sig_sigint(int)
{
unlink("a.fifo");
unlink("b.fifo");
exit(EXIT_FAILURE);
}
int create_fifo(const char *s)
{
int fifo;
if((fifo = mkfifo(s, 0644)) < 0)
return -1;
return 0;
}
int main()
{
if(create_fifo("a.fifo") == -1)
write_error("create mkfifo error\n");
if(create_fifo("b.fifo") == -1)
write_error("create mkfifo error\n");
struct sigaction action;
action.sa_handler = sig_sigint;
if(sigaction(SIGINT, &action, NULL) == -1)
write_error("sigaction error");
int fd[NUM];
fd[0] = open("a.fifo", O_RDONLY);
fd[1] = open("b.fifo", O_RDONLY);
int epfd;
if((epfd = epoll_create(3)) == -1)
write_error("epoll error");
for(int i = 0; i < NUM; i++)
{
struct epoll_event epoll;
epoll.data.fd = fd[i];
// 水平触发模式 : 缓冲区有数据就会输出, 直到缓冲区读取完毕.
// epoll.events = EPOLLIN;
epoll.events = EPOLLIN | EPOLLET;
// 边沿触发 : 当缓冲区有改变的时侯才会立马触发 epoll_wait(), 而不用等到把值写到缓冲区中.
if(epoll_ctl(epfd, EPOLL_CTL_ADD, fd[i], &epoll) == -1)
write_error("epoll_ctl error");
}
int n;
struct epoll_event re_event[NUM];
while(1)
{
// 这里的等待数量一定是最大的描述符 + 1
if((n = epoll_wait(epfd, re_event, NUM + 1, -1)) == -1)
write_error("epoll wait erro");
for(int i = 0; i < NUM; i++)
{
if(re_event[i].events == EPOLLIN)
read_fd(re_event[i].data.fd);
}
}
exit(EXIT_SUCCESS);
}
| true |
5a529dc751027fa0c712c26b46396384cefcb7e6 | C++ | ConnorShore/Candle3D | /Candle3D/Camera.h | UTF-8 | 1,061 | 2.75 | 3 | [] | no_license | #pragma once
#include "glm\glm.hpp"
#include "InputManager.h"
#include "Window.h"
enum Translate
{
FORWARD, BACK, LEFT, RIGHT
};
struct CameraTransform
{
glm::vec3 position, direction, right, up;
float pitch, yaw, roll, sensitivity;
};
struct Viewing
{
glm::mat4 viewMatrix, projectionMatrix;
float fov, zNear, zFar;
};
class Camera
{
public:
Camera();
~Camera();
void init(Window& window, int screenWidth, int screenHeight);
void update(InputManager& inputManager);
void resetCamera();
void resetView();
void showCursor();
void hideCursor();
void translate(Translate direction, float speed);
void setMouseLook(bool look) { _mouseLook = look; }
//--------------------//
CameraTransform transform;
Viewing viewing;
private:
const float MAX_ANGLE = 85.0f;
const float MIN_ANGLE = -85.0f;
Window _window;
int _screenWidth, _screenHeight;
bool _mouseLook;
//--------------------//
glm::mat4 updateViewMatrix();
glm::mat4 updateProjectionMatrix();
void lookCalculations();
void mouseLook(InputManager& inputManager);
};
| true |
aa46a0bdf9abc00d2d8ae79b8e197b1bbcb08226 | C++ | robini/LeetCode | /LinkedList/92. Reverse Linked List II.cpp | UTF-8 | 659 | 3.296875 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (m == n)
return head;
ListNode p(0);
p.next = head;
n -= m - 1;
ListNode* ph = &p;
ListNode* before = &p;
while (--m)
{
ph = ph->next;
before = before->next;
}
ph = ph->next;
ListNode* pre = nullptr;
ListNode* next = nullptr;
while (n--)
{
next = ph->next;
ph->next = pre;
pre = ph;
ph = next;
}
before->next->next = next;
before->next = pre;
return p.next;
}
}; | true |
840ea3aea29e2eeecd6216592f0fd0029174690c | C++ | iloveooz/podbelsky | /04/p4-04.cpp | UTF-8 | 787 | 3.4375 | 3 | [] | no_license | //p4-04.cpp - оператор break в переключателе
#include <iostream>
using namespace std;
int main()
{
int ic;
cout << "\nВведите восьмеричную цифру: ";
cin >> ic;
cout << '\n' << ic;
switch (ic)
{
case 0: cout << " - Ноль ";break;
case 1: cout << " - Один"; break;
case 2: cout << " - Два"; break;
case 3: cout << " - Три"; break;
case 4: cout << " - Четыре"; break;
case 5: cout << " - Пять"; break;
case 6: cout << " - Шесть"; break;
case 7: cout << " - Семь"; break;
default: cout << "\nОшибка! Это не восьмеричная цифра!";
}
cout << "\nКонец выполнения программы" << endl;
return 0;
}
| true |
6dff0d9d59523d6e49208d89e28d8de7c2ff93c0 | C++ | IonUreche/VulkanApp | /src/GUI/window.cpp | UTF-8 | 4,483 | 2.5625 | 3 | [] | no_license | #include "window.h"
#include <QTimer>
#include "Utils/Camera.h"
Window::Window(int width, int height) : m_width(width), m_height(height),
m_time(0.0f)
{
SetFocus(reinterpret_cast<HWND>(this->winId()));
m_camera = new utils::Camera(width, height);
m_vulkanWindow = new VulkanWindow(m_width, m_height, static_cast<uint32_t>(this->winId()));
m_moveDirMask = 0;
QTimer* graphics_timer = new QTimer;
graphics_timer->setInterval(15);
connect(graphics_timer, &QTimer::timeout, this, &Window::update);
graphics_timer->start();
m_startTime = std::chrono::high_resolution_clock::now();
}
//======================================================================================
Window::~Window()
{
delete m_vulkanWindow;
}
//======================================================================================
void Window::update()
{
auto currentTime = std::chrono::high_resolution_clock::now();
float deltaTime = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - m_startTime).count();
m_startTime = currentTime;
m_time += deltaTime;
m_camera->SetMoveDirection(m_moveDirMask);
m_camera->Update(deltaTime);
m_vulkanWindow->SetView(m_camera->GetView());
m_vulkanWindow->SetProjection(m_camera->GetProjection());
m_vulkanWindow->DrawFrame();
}
//======================================================================================
bool Window::event(QEvent *ev)
{
//if (ev->type() == QEvent::Show)
//{
//}
return QWindow::event(ev);
}
//======================================================================================
void Window::keyPressEvent(QKeyEvent* ev)
{
QWindow::keyPressEvent(ev);
if (ev->key() == Qt::Key::Key_W)
{
m_moveDirMask |= utils::MoveDirectionMasks::k_forward;
}
if (ev->key() == Qt::Key::Key_S)
{
m_moveDirMask |= utils::MoveDirectionMasks::k_backwards;
}
if (ev->key() == Qt::Key::Key_D)
{
m_moveDirMask |= utils::MoveDirectionMasks::k_right;
}
if (ev->key() == Qt::Key::Key_A)
{
m_moveDirMask |= utils::MoveDirectionMasks::k_left;
}
if (ev->key() == Qt::Key::Key_E)
{
m_moveDirMask |= utils::MoveDirectionMasks::k_up;
}
if (ev->key() == Qt::Key::Key_Q)
{
m_moveDirMask |= utils::MoveDirectionMasks::k_down;
}
if (ev->key() == Qt::Key::Key_Shift)
{
m_camera->SetFastSpeedMode(true);
}
}
//======================================================================================
void Window::keyReleaseEvent(QKeyEvent* ev)
{
if (ev->key() == Qt::Key::Key_W)
{
m_moveDirMask &= ~utils::MoveDirectionMasks::k_forward;
}
if (ev->key() == Qt::Key::Key_S)
{
m_moveDirMask &= ~utils::MoveDirectionMasks::k_backwards;
}
if (ev->key() == Qt::Key::Key_D)
{
m_moveDirMask &= ~utils::MoveDirectionMasks::k_right;
}
if (ev->key() == Qt::Key::Key_A)
{
m_moveDirMask &= ~utils::MoveDirectionMasks::k_left;
}
if (ev->key() == Qt::Key::Key_E)
{
m_moveDirMask &= ~utils::MoveDirectionMasks::k_up;
}
if (ev->key() == Qt::Key::Key_Q)
{
m_moveDirMask &= ~utils::MoveDirectionMasks::k_down;
}
if (ev->key() == Qt::Key::Key_Shift)
{
m_camera->SetFastSpeedMode(false);
}
}
//======================================================================================
void Window::mouseMoveEvent(QMouseEvent* ev)
{
QPointF currentMousePos = ev->screenPos();
if (m_mouseLeftPressed)
{
QPointF delta = currentMousePos - m_lastMousePos;
float dXf = static_cast<float>(delta.x()) / static_cast<float>(m_width);
float dYf = static_cast<float>(delta.y()) / static_cast<float>(m_height);
m_camera->OnMouseMoveX(dXf);
m_camera->OnMouseMoveY(-dYf);
}
m_lastMousePos = currentMousePos;
}
//======================================================================================
void Window::mousePressEvent(QMouseEvent* ev)
{
if (ev->button() == Qt::MouseButton::LeftButton)
{
m_mouseLeftPressed = true;
m_leftClickPos = ev->screenPos();
}
if (ev->button() == Qt::MouseButton::RightButton)
{
m_mouseRightPressed = true;
m_rightClickPos = ev->screenPos();
}
}
//======================================================================================
void Window::mouseReleaseEvent(QMouseEvent* ev)
{
if (ev->button() == Qt::MouseButton::LeftButton)
{
m_mouseLeftPressed = false;
}
if (ev->button() == Qt::MouseButton::RightButton)
{
m_mouseRightPressed = false;
}
}
//======================================================================================
//====================================================================================== | true |
566c46a4bf4bd13c69f91e4f45360eac9e5d4b4d | C++ | pvaibhavv12/Coding | /coding_interview/merge.cpp | UTF-8 | 1,842 | 3.515625 | 4 | [] | no_license | #include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct node{
int element;
struct node* next;
} node;
typedef struct list{
node* head;
} list;
void add_ele(list* list,int ele){
node* temp = (node*)malloc(sizeof(node*));
temp->element = ele;
temp->next = NULL;
if(list->head == NULL)
{
list->head = temp;
}else{
node* pre = list->head;
while(pre->next != NULL)
pre = pre->next;
pre->next = temp;
}
}
list* list_init(){
list* temp = (list*)malloc(sizeof(list*));
temp->head = NULL;
return temp;
}
void list_display(list* list){
node* temp = list->head;
while(temp != NULL)
{
cout << temp->element << endl;
temp = temp->next;
}
}
node* merge(node* a,node* b){
node* temp = NULL;
if(a == NULL)
return a;
if(b == NULL)
return b;
if(a->element < b->element)
{
temp = a;
temp->next = merge(a->next,b);
}else
{
temp = b;
temp->next = merge(a,b->next);
}
return temp;
}
int main(){
list* test1,*test2;
test1 = list_init();
add_ele(test1,1);
add_ele(test1,1);
add_ele(test1,2);
add_ele(test1,5);
add_ele(test1,6);
add_ele(test1,7);
//cout << "done 1\n";
test2 = list_init();
add_ele(test2,1);
add_ele(test2,2);
add_ele(test2,3);
add_ele(test2,4);
add_ele(test2,4);
add_ele(test2,9);
node* temp = merge(test1->head,test2->head);
temp->element = 6;
while(temp != NULL)
{
printf("%d \n",temp->element);
temp = temp->next;
}
cout << "/////////////////////////////////\n";
list_display(test1);
cout << "/////////////////////////////////\n";
list_display(test2);
}
| true |
7356fe6740de6602b8b192b6d2764e280e00532f | C++ | FUKUDA87/OneWaySurvivor | /OneWaySurvivor/SourceFolder/Source/GameSource/Count/Count.cpp | UTF-8 | 586 | 2.578125 | 3 | [] | no_license | #include "Count.h"
#include"../Judgment.h"
C_Count::C_Count(const int * Start)
{
//‰Šú‰»
CountStart = *Start;
StartFlg = true;
}
bool C_Count::Update(void)
{
SetNow();
CountDownNow--;
if (CountDownNow <= 0)StartFlg = true;
return StartFlg;
}
bool C_Count::Update_Count(void)
{
SetNow();
CountDownNow--;
if (CountDownNow <= 0)StartFlg = true;
Judg judg;
return judg.ReverseFlg2(&StartFlg);
}
void C_Count::UpCount(void)
{
CountDownNow++;
}
void C_Count::SetNow(void)
{
if (StartFlg != true)return;
CountDownNow = CountStart;
StartFlg = false;
} | true |
62872538c54bd8250e2c4341cd5cb478cceb59fc | C++ | hitochan777/programming | /cf/Rockethon2015/513B1.cpp | UTF-8 | 730 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int n,m,cnt = 0;
int f(vector<int>& v){
int val = 0;
for(int i = 0;i< n;++i){
for(int j = i;j<n;++j){
int minval = 100;
for(int k = i;k<=j;++k){
if(minval>v[k]){
minval = v[k];
}
}
val += minval;
}
}
return val;
}
int main(){
int maxval = 0;
cin>>n>>m;
vector<int> v(n),ans(n);
for(int i =0 ;i<n;++i){
v[i] = i+1;
}
do {
int fp = f(v);
// cout<<fp<<endl;
if(fp > maxval){
cnt = 1;
maxval = fp;
ans = v;
}
else if(fp==maxval){
if(cnt<m){
cnt++;
ans = v;
}
}
} while(next_permutation(v.begin(), v.end()));
for(int i = 0;i<n;++i){
cout<<ans[i]<<" ";
}
return 0;
}
| true |
9e3f34720e31429a5b36ac95fd16ccd9ecd26d8f | C++ | Sage-of-Mirrors/Booldozer | /include/DOM/DoorDOMNode.hpp | UTF-8 | 1,762 | 2.640625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "BGRenderDOMNode.hpp"
struct LStaticDoorData;
class LRoomDOMNode;
enum class EDoorOrientation : uint8_t
{
Front_Facing = 1,
Side_Facing,
No_Fade = 4
};
enum class EDoorType : uint8_t
{
Door,
Viewport,
Window
};
enum class EDoorModel : uint8_t
{
None,
Square_Mansion_Door,
Round_Topped_Mansion_Door,
Parlor_Double_Door,
Anteroom_Door,
Lab_Door,
Gallery_Door,
Nursery_Door,
Twins_Door,
Wooden_Door,
Basement_Hallway_Door,
Hearts_Double_Door,
Clubs_Door,
Diamonds_Door,
Spades_Door
};
class LDoorDOMNode : public LBGRenderDOMNode
{
EDoorOrientation mOrientation;
EDoorType mDoorType;
int32_t mJmpId;
EDoorModel mModel;
int32_t mDoorEntryNumber;
glm::vec3 mViewportSize;
int32_t mNextEscape;
int32_t mCurrentEscape;
std::weak_ptr<LRoomDOMNode> mWestSouthRoom;
std::weak_ptr<LRoomDOMNode> mEastNorthRoom;
public:
typedef LBGRenderDOMNode Super;
LDoorDOMNode(std::string name);
virtual std::string GetName() override;
virtual void RenderDetailsUI(float dt) override;
bool Load(const LStaticDoorData& source);
bool Save(LStaticDoorData& dest);
void PostProcess();
void PreProcess();
void AssignJmpIdAndIndex(std::vector<std::shared_ptr<LDoorDOMNode>> doors);
bool HasRoomReference(std::shared_ptr<LRoomDOMNode> room);
int32_t GetJmpId() const { return mJmpId; }
int32_t GetIndex() const { return mDoorEntryNumber; }
EDoorModel GetModel() { return mModel; }
EDoorOrientation GetOrientation() { return mOrientation; }
/*=== Type operations ===*/
// Returns whether this node is of the given type, or derives from a node of that type.
virtual bool IsNodeType(EDOMNodeType type) const override
{
if (type == EDOMNodeType::Door)
return true;
return Super::IsNodeType(type);
}
};
| true |
8e68d0f13d2779cc18bbe3aa6772b588a48f618e | C++ | shivam-72/Data-Structure | /OPERATIONS ON ARRAY/delete.cpp | UTF-8 | 1,000 | 3.65625 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int n, length, index, i, x;
int A[n];
cout << "enter the size of array" << endl;
cin >> n;
cout << "no. of element you want to insert:" << endl;
cin >> length;
if (length <= n)
{
cout << "elements of array" << endl;
for (i = 0; i < length; i++)
{
cin >> A[i];
}
cout << "at which index want to delete the value";
cin >> index;
if (index >= 0 || index < length){
cout << "the value i deleted is : ";
cout<< A[index];
cout << "new array is"<<endl;
for (i = index; i < length - 1; i++)
{
A[i] = A[i + 1];
}
length--;
for (i = 0; i < length; i++)
{
cout << A[i]<<endl;
} }
}
else
{
cout << "length is more reduce ur length length cant be more than size of array";
}
return 0;
} | true |
069f9659cbd96a32c522cdd65ec36abb0a589c12 | C++ | fosheus/ManvsMen | /ManvsMen/MapGenerator.h | UTF-8 | 1,243 | 2.59375 | 3 | [] | no_license | #pragma once
#include <cstdlib>
#include <SFML\Graphics.hpp>
#include "Point.h"
#include "AVL.h"
#include "Utils.h"
#include "ImageManager.h"
class MapGenerator
{
public :
enum Cell_Type {
WALL = 0,
PATH = 1,
CONCRETE = 2
};
private :
int **matrix;
size_t height;
size_t width;
size_t blocWidth;
size_t blocHeight;
AVL tree;
std::vector<nodeptr> roots;
int** openMatrix(int** matrix, int multiplier);
int** closeMatrix(int** matrix, int multiplier);
void fillAVL();
void addAdjToSameTree(int x, int y, int **visitedMatrix, int currentTree);
std::vector<Point> getNeighbours(Point point);
void removeDiagonal();
void optimizeRendering();
public:
MapGenerator(size_t height, size_t width, size_t blocWidth, size_t blocHeight);
int** getMatrix() { return matrix; }
size_t getWidth() { return width; }
size_t getHeight() { return height;}
size_t getBlockSize() { return blocWidth; }
Point getWorldPosition(Point mapPosition);
Point getMapPosition(Point worldPosition);
Point getRandomPathPoint();
Point getRandomPathPointInRange(int range,Point point);
Point getRandomPathPointOutRange(int range, Point point);
bool isPositionAPath(Point p);
Point getFirstPathCellTopLeft();
~MapGenerator();
};
| true |
9bd21163d0d14292aff70f9bb62931260942a8dd | C++ | mdpabel/CPP | /14. vector/04.cpp | UTF-8 | 1,171 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main()
{
// Fast I/O
ios_base::sync_with_stdio(false);
cin.tie(NULL);
vector<int> v = {10, 12, 3, 14, 51, 6, 7, 7, 12, 12, 10, 10, 4, 3, 3, 3, 3};
// vector<int>::iterator it;
// for (it = v.begin(); it != v.end(); it++)
// {
// cout << *it << " ";
// }
// sort(v.begin(), v.end());
// sort(v.begin(), v.end(), greater<int>());
// sort(v.rbegin(), v.rend());
// reverse(v.begin(), v.end());
// v.erase(v.begin(), v.begin() + 4);
// v.erase(v.begin(), v.end() - 2);
// vector<int>::iterator it;/
// int it = unique(v.begin(), v.end()) - v.begin();
// // v.resize(distance(v.begin(), it));
// for (int i = 0; i < it; i++)
// {
// cout << v[i] << " ";
// }
// vector<int>::iterator it = max_element(v.begin(), v.end());
// int n = max_element(v.begin(), v.end()) - v.begin();
// cout << n << endl;
vector<int>::iterator it = min_element(v.begin(), v.end());
int n = min_element(v.begin(), v.end()) - v.begin();
cout << *it << endl;
cout << n << endl;
return 0;
} | true |
a38863352829d0d4386e8a99f74eaf468dbbcb49 | C++ | workshopbot/ProjectEuler | /20-FactorialDigitSum.cpp | UTF-8 | 835 | 2.9375 | 3 | [] | no_license | #include<iostream>
// #include<fstream>
#include"gmp.h"
using namespace std;
int main()
{
int SIZE = 0, Sum = 0;
unsigned long int num = 100;
mpz_t factorial;
mpz_init(factorial);
mpz_fac_ui(factorial, num);
gmp_printf(" 100! is , \n%Zd\n", factorial);
SIZE = __gmpz_sizeinbase(factorial, 10);
cout << "Number of digits == " << SIZE << "\n";
char* numString;
int Digits[SIZE] = {0};
numString = new char[SIZE];
mpz_get_str(numString, 10 ,factorial);
for(int i = 0 ; i < SIZE ; i++)
{
Digits[i] = numString[i] - '0';
if(Digits[i] == -48)
{
break;
}
// cout << Digits[i] << "\n";
Sum = Sum + Digits[i];
}
cout << "The sum is, "<< Sum <<endl;
cout << "\nExecuted Successfully\n";
} | true |
c14a72b637a1a5b419db8467c38143994c9ffabc | C++ | Psingh12354/C-STL | /Inserter.cpp | UTF-8 | 354 | 3.46875 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<list>
using namespace std;
int main()
{
vector<int> ar={1,2,3,4,5,6};
vector<int>::iterator p1=ar.begin();
advance(p1,3);
copy(ar.begin(),ar.end(),inserter(ar,p1));
cout << "The new vector after inserting elements is : ";
for (int &x : ar)
cout << x << " ";
return 0;
}
| true |
230c7789549d6963eff7884803cd2e29f9b75453 | C++ | NeoGameEngineProject/SDK | /Neo2D/include/KeyboardShortcuts.h | UTF-8 | 882 | 2.765625 | 3 | [] | no_license | #ifndef NEO_KEYBOARDSHORTCUTS_H
#define NEO_KEYBOARDSHORTCUTS_H
#include <Widget.h>
#include <vector>
#include <map>
namespace Neo2D
{
namespace Gui
{
class NEO2D_EXPORT Shortcut
{
private:
std::map<unsigned int, bool> status;
std::vector<Neo::INPUT_KEYS> keys;
std::function<void(void*)> callback;
void* data;
public:
Shortcut(const std::vector<Neo::INPUT_KEYS>& keys, std::function<void(void*)> callback, void* data) :
callback(callback),
data(data),
keys(keys)
{}
bool update(unsigned int key, bool value);
};
class NEO2D_EXPORT KeyboardShortcuts : public Widget
{
std::vector<Shortcut> shortcuts;
public:
KeyboardShortcuts(const shared_ptr<Widget>& parent = nullptr);
virtual bool handle(const Event& e) override;
virtual void init() override;
void addShortcut(const Shortcut& s)
{
shortcuts.push_back(s);
}
};
}
}
#endif //NEO_KEYBOARDSHORTCUTS_H
| true |
7d8f5f674723391ad3c8239e3a8c0b0a5e7a8487 | C++ | nmlgc/ReC98 | /th01/math/str_val.cpp | UTF-8 | 869 | 3.15625 | 3 | [] | no_license | #include "th01/math/str_val.hpp"
void pascal str_right_aligned_from_uint16(
char *str, uint16_t val, uint16_t width
)
{
uint16_t divisor = 10000;
unsigned int i = width;
bool past_leading_zeroes = false;
while(i < 5) {
divisor /= 10;
i++;
}
for(i = 0; i < width; i++) {
if(val / divisor) {
past_leading_zeroes = true;
}
if(past_leading_zeroes) {
str[i] = (val / divisor) + '0';
} else {
str[i] = ' ';
}
val %= divisor;
divisor /= 10;
}
str[width] = '\0';
}
void pascal str_from_positive_int16(char *str, int16_t val)
{
int16_t divisor = 10000;
int i;
unsigned int str_p = 0;
bool past_leading_zeroes = false;
for(i = 0; i < 5; i++) {
if(val / divisor) {
past_leading_zeroes = true;
}
if(past_leading_zeroes) {
str[str_p++] = (val / divisor) + '0';
}
val %= divisor;
divisor /= 10;
}
str[str_p] = '\0';
}
| true |
ac040517dc7e66ccb28fa7be0ad55242028f8692 | C++ | onnoo/Online-Judge | /Baekjoon/17363.cpp | UTF-8 | 666 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
char mapping[125];
int a[] = {46, 79, 45, 124, 47, 92, 94, 60, 118, 62};
char b[] = {'.', 'O', '|', '-', '\\', '/', '<', 'v', '>', '^'};
int main(void)
{
ios::sync_with_stdio(0);
cin.tie(0);
int N, M;
cin >> N >> M;
cin.ignore();
for (int i = 0; i < 10; i++)
mapping[a[i]] = b[i];
char arr[N][M + 1];
for (int i = 0; i < N; i++)
{
cin.getline(arr[i], M + 1);
}
for (int j = M - 1; j >= 0; j--)
{
for (int i = 0; i < N; i++)
{
cout << mapping[arr[i][j]];
}
cout << '\n';
}
return 0;
} | true |
71dfb7bd9efd31baad0698ae46087b28a5200618 | C++ | sereslorant/logan_engine | /LoganEngine/src/lExample/lPacMan/lPM_Model/lPM_Agents/lPM_PacMan.h | UTF-8 | 1,362 | 2.671875 | 3 | [
"MIT"
] | permissive | #ifndef LPM_PAC_MAN_H
#define LPM_PAC_MAN_H
#include "lPM_Agent.h"
#include "../../lPM_Controller/liPM_AgentController.h"
class lPM_PacMan : public lPM_Agent, public liPM_PacMan
{
protected:
unsigned int Reward = 0;
liPM_AgentController *AgentControl;
std::list<liPM_PacManObserver *> PacManObservers;
public:
virtual void Visit(liPM_Coin *coin) override
{
if(!coin->IsEaten())
{
coin->Eat();
Reward++;
for(liPM_PacManObserver *Observer : PacManObservers)
{
Observer->RewardReceived(Reward);
}
}
}
virtual void Accept(liPM_Visitor *visitor) override
{
visitor->Visit((liPM_PacMan *)this);
lPM_Agent::Accept(visitor);
}
virtual void Subscribe(liPM_PacManObserver *pac_man_observer) override
{
PacManObservers.push_back(pac_man_observer);
//
pac_man_observer->RewardReceived(Reward);
}
virtual void Update() override
{
dX = 0;
dY = 0;
if(AgentControl != nullptr)
{
AgentControl->Think();
if(AgentControl->GetUp())
{dY -= 1;}
if(AgentControl->GetDown())
{dY += 1;}
if(AgentControl->GetRight())
{dX += 1;}
if(AgentControl->GetLeft())
{dX -= 1;}
}
}
lPM_PacMan(int x,int y,liPM_AgentController *agent_control = nullptr)
:lPM_Agent(x,y,false),AgentControl(agent_control)
{
//Üres
}
virtual ~lPM_PacMan() override
{
//Üres
}
};
#endif // LPM_PAC_MAN_H
| true |
35f616f706a3ad623d7d7402d4a388354d35d3c6 | C++ | GrinPlusPlus/GrinPlusPlus | /src/P2P/Messages/TransactionKernelMessage.h | UTF-8 | 1,428 | 2.875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Message.h"
#include <Crypto/Models/Hash.h>
class TransactionKernelMessage : public IMessage
{
public:
//
// Constructors
//
TransactionKernelMessage(Hash&& kernelHash)
: m_kernelHash(std::move(kernelHash))
{
}
TransactionKernelMessage(const Hash& kernelHash)
: m_kernelHash(kernelHash)
{
}
TransactionKernelMessage(const TransactionKernelMessage& other) = default;
TransactionKernelMessage(TransactionKernelMessage&& other) noexcept = default;
//
// Destructor
//
virtual ~TransactionKernelMessage() = default;
//
// Operators
//
TransactionKernelMessage& operator=(const TransactionKernelMessage& other) = default;
TransactionKernelMessage& operator=(TransactionKernelMessage&& other) noexcept = default;
//
// Clone
//
IMessagePtr Clone() const final { return IMessagePtr(new TransactionKernelMessage(*this)); }
//
// Getters
//
MessageTypes::EMessageType GetMessageType() const final { return MessageTypes::TransactionKernelMsg; }
const Hash& GetKernelHash() const { return m_kernelHash; }
//
// Deserialization
//
static TransactionKernelMessage Deserialize(ByteBuffer& byteBuffer)
{
Hash kernelHash = byteBuffer.ReadBigInteger<32>();
return TransactionKernelMessage(std::move(kernelHash));
}
protected:
void SerializeBody(Serializer& serializer) const final
{
serializer.AppendBigInteger<32>(m_kernelHash);
}
private:
Hash m_kernelHash;
}; | true |
ac5f5f0353636166ea6f7be73b5f8c04154a69ba | C++ | sillsdev/WorldPad | /Bin/src/AutoCheckin/Checkin.cpp | UTF-8 | 19,826 | 2.65625 | 3 | [] | no_license | /*
Auto-Checkin - a utility to perform the entire Perforce check-in process
unattended. The steps taken are:
Waiting for the CheckIn_History.txt file to become available;
Acquiring the CheckIn_History.txt file (no longer locking token file);
Re-syncing all files to the local machine;
Rebuilding FW with tests;
Appending a comment to the CheckIn_History.txt file
Submitting files to Perforce.
The program accepts the user's check-in comment passed on the command
line or, if not supplied, will pop up a dialog asking for it.
Possible gotchas that you need to be aware of:
If the Perforce sync results in inability to "clobber writable
files", the auto-checkin will abort;
If any files need resolving, the auto-checkin will abort;
Subversion files are not synchronized;
Any build or test failure will prevent a check-in.
*/
#include <windows.h>
#include <stdio.h>
#include "Dialogs.h"
#include "resource.h"
#include "Globals.h"
const char * pszWorkSpaceFileName = "C:\\__AutoCheckinWorkspace.txt";
const char * pszWorkSpace2FileName = "C:\\__AutoCheckinWorkspace2.txt";
const char * pszDepotFw = NULL; // "//depot/fw/";
const char * pszCheckinTokenFile = "CheckIn_History.txt";
const char * pszChagelistSpecFileName = "C:\\__AutoCheckinChagelist.txt";
static bool fTimedOut = false;
void RevertTokenFile();
void FatalError(const char * Msg)
{
static bool fRevertingOnError = false;
printf("Fatal error: %s\r\n", Msg);
if (!fRevertingOnError)
{
fRevertingOnError = true;
RevertTokenFile();
fRevertingOnError = false;
}
MessageBox(NULL, Msg, "Auto-checkin: fatal error", MB_ICONSTOP | MB_OK);
exit(1);
}
/* This function has been replaced with a call to system(), because redirection
of standard output to a file was not possible with ExecCmd().
However, it has not been rigorously established whether the return values from
system() are the same as those from ExecCmd(). Basically, we are assuming zero
means success, and non-zero means an error of some sort.
// Executes the command in the given string and waits for the launched process to exit.
DWORD ExecCmd(LPCTSTR pszCmd)
{
// Set up data for creating new process:
BOOL bReturnVal = false;
STARTUPINFO si;
DWORD dwExitCode = 0;
PROCESS_INFORMATION process_info;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
// Launch new process:
bReturnVal = CreateProcess(NULL, (LPTSTR)pszCmd, NULL, NULL, false, 0, NULL,
NULL, &si, &process_info);
if (bReturnVal)
{
CloseHandle(process_info.hThread);
WaitForSingleObject(process_info.hProcess, INFINITE);
GetExitCodeProcess(process_info.hProcess, &dwExitCode);
CloseHandle(process_info.hProcess);
}
else
{
return (DWORD)-1;
}
return dwExitCode;
}
*/
// Advance character pointer beyond tabs and spaces:
const char * SkipWhiteSpace(const char * pch)
{
if (!pch)
return NULL;
while (*pch == ' ' || *pch == '\t')
pch++;
return pch;
}
// Remove whitespace and newlines from end of string:
void ChopWhiteSpaceAndNewlines(char * psz)
{
if (!psz)
return;
if (*psz == 0)
return;
psz += strlen(psz) - 1;
while (*psz == ' ' || *psz == '\t' || *psz == '\n' || *psz == '\r')
*(psz--) = 0;
}
bool FileIsEmpty(const char * pszFilePath)
{
FILE * file = fopen(pszFilePath, "rt");
if (!file)
return true;
char szLine[2];
bool fEmpty = false;
if (fgets(szLine, 2, file) == NULL)
fEmpty = true;
fclose(file);
return fEmpty;
}
// Get Perforce to give us the Client name, User name and Root path:
void GetClientAndUser()
{
gpszClient = NULL;
gpszUser = NULL;
char szCmd[100];
sprintf(szCmd, "p4 client -o >%s", pszWorkSpaceFileName);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Could not get client details from Perforce.");
// We are looking for text after "Client:", text after "Owner:" and text after "Root:"
FILE * file = fopen(pszWorkSpaceFileName, "rt");
if (!file)
FatalError("Could not open workspace file for client details.");
char szLine[200];
while (!gpszClient || !gpszUser || !pszDepotFw)
{
if (fgets(szLine, 200, file) == NULL)
FatalError("Workspace file does not contain full client details.");
if (strncmp(szLine, "Client:", 7) == 0)
{
// We have the client name:
gpszClient = strdup(SkipWhiteSpace(&szLine[7]));
ChopWhiteSpaceAndNewlines(gpszClient);
continue;
}
if (strncmp(szLine, "Owner:", 6) == 0)
{
// We have the user name:
gpszUser = strdup(SkipWhiteSpace(&szLine[6]));
ChopWhiteSpaceAndNewlines(gpszUser);
continue;
}
if (strncmp(szLine, "View:", 5) == 0)
{
while (!pszDepotFw)
{
if (fgets(szLine, 200, file) == NULL)
FatalError("Workspace file does not contain full client details.");
char * psz = strstr(szLine, gpszClient);
if (psz != NULL)
{
psz = strstr(szLine, "//depot/");
if (psz != NULL)
{
char * psz2 = strstr(psz, "/... //");
if (psz != NULL)
{
*(psz2+1) = 0;
pszDepotFw = strdup(psz);
}
}
}
}
}
}
fclose(file);
}
// Make a list of changelists that the user has pending.
// The default list is always implicit.
void GetAvailableChangeLists()
{
gpnChangeLists = NULL;
gppszChangeListsComments = NULL;
gcclChangeLists = 0;
char szCmd[200];
sprintf(szCmd, "p4 changes -s pending -u %s >%s", gpszUser, pszWorkSpaceFileName);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Could not see which changelists are pending.");
// Collect changelist numbers:
FILE * file = fopen(pszWorkSpaceFileName, "rt");
if (!file)
return;
char szLine[400];
while (fgets(szLine, 400, file) != NULL)
{
// Find start of changelist number:
char * pszStartNumber = szLine;
while (!isdigit(*pszStartNumber))
{
pszStartNumber++;
if (*pszStartNumber == 0)
break;
}
// Find end of changelist number:
char * pszEndNumber = strstr(pszStartNumber, " on");
if (pszEndNumber)
{
*pszEndNumber = 0;
}
if (pszStartNumber && pszEndNumber)
{
// Add changelist number to list:
int * nTemp = new int [1 + gcclChangeLists];
char ** pszTemp = new char * [1 + gcclChangeLists];
for (int i = 0; i < gcclChangeLists; i++)
{
nTemp[i] = gpnChangeLists[i];
pszTemp[i] = gppszChangeListsComments[i];
}
delete[] gpnChangeLists;
gpnChangeLists = nTemp;
gpnChangeLists[gcclChangeLists++] = atoi(pszStartNumber);
delete[] gppszChangeListsComments;
gppszChangeListsComments = pszTemp;
// Collect comment for this changelist:
pszEndNumber++;
char *pszCommentStart = strchr(pszEndNumber, '\'');
if (pszCommentStart)
{
pszCommentStart++;
char * pszCommentEnd = strrchr(pszCommentStart, '\'');
if (pszCommentEnd)
{
*pszCommentEnd = 0;
ChopWhiteSpaceAndNewlines(pszCommentStart);
gppszChangeListsComments[gcclChangeLists - 1] = strdup(pszCommentStart);
}
}
}
}
fclose(file);
}
// See if anyone has the token file.
bool TokenFileIsFree()
{
char szCmd[200];
sprintf(szCmd, "p4 opened -a %s%s >%s", pszDepotFw, pszCheckinTokenFile,
pszWorkSpaceFileName);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Could not see if token file is checked out.");
// Looking for empty file:
return FileIsEmpty(pszWorkSpaceFileName);
}
// Get up to date token file:
void SyncTokenFile()
{
char szCmd[200];
sprintf(szCmd, "p4 sync %s%s", pszDepotFw, pszCheckinTokenFile);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Could not sync token file from Perforce.");
}
// Open token file for edit.
void OpenTokenFileForEdit()
{
char szCmd[200];
if (!gnCheckinChangeList)
sprintf(szCmd, "p4 edit %s%s", pszDepotFw, pszCheckinTokenFile); // Default changelist
else
sprintf(szCmd, "p4 edit -c %d %s%s", gnCheckinChangeList, pszDepotFw, pszCheckinTokenFile);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Could not open token file for edit from Perforce.");
}
// Lock token file:
/* No longer used.
void LockTokenFile()
{
char szCmd[200];
sprintf(szCmd, "p4 lock %s%s", pszDepotFw, pszCheckinTokenFile);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Could not lock token file on Perforce.");
}*/
// Relinquish the token file.
void RevertTokenFile()
{
char szCmd[200];
sprintf(szCmd, "p4 revert %s%s", pszDepotFw, pszCheckinTokenFile);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Could not revert token file on Perforce.");
}
// See if we have the token file exclusively:
bool TokenFileExclusivelyMine()
{
char szCmd[200];
sprintf(szCmd, "p4 opened -a %s%s >%s", pszDepotFw, pszCheckinTokenFile,
pszWorkSpaceFileName);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Could not see if token file is checked out.");
// Looking for our client name in first line, and only one line:
FILE * file = fopen(pszWorkSpaceFileName, "rt");
if (!file)
return false;
char szLine[400];
if (fgets(szLine, 400, file) == NULL)
{
// Nobody has the file! Could be an error...
fclose(file);
return false;
}
char * pszClientInLine = strstr(szLine, gpszClient);
if (pszClientInLine == NULL)
{
// Somebody else has the file!
fclose(file);
return false;
}
/* // Make sure our client has the file locked:
char * pszRestOfLine = pszClientInLine + strlen(gpszClient);
if (strncmp(pszRestOfLine, " *locked*", 9) != 0)
{
// It wasn't really us!
fclose(file);
return false;
}
*/
// Make sure no other lines exist in report:
if (fgets(szLine, 400, file) != NULL)
{
// Somebody else has the file!
fclose(file);
return false;
}
fclose(file);
return true;
}
// Sync all files.
void SyncAllFiles()
{
char szCmd[200];
// Perforce:
sprintf(szCmd, "p4 sync %s...", pszDepotFw);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Could not completely sync to files on Perforce.");
// Subversion:
//TODO...
}
// Return true if any files in the selected changelist need resolving.
bool FilesNeedResolving()
{
// Firstly, use the p4 opened command to get a list of files in the selected changelist:
char szCmd[200];
if (!gnCheckinChangeList)
sprintf(szCmd, "p4 opened -c default >%s", pszWorkSpaceFileName); // Default changelist
else
sprintf(szCmd, "p4 opened -c %d >%s", gnCheckinChangeList, pszWorkSpaceFileName);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Could not check if files need resolving.");
// Now examine listed files:
FILE * file = fopen(pszWorkSpaceFileName, "rt");
if (!file)
FatalError("Could not open workspace file for files in selected changelist.");
char szLine[200];
bool fFilesNeedResolving = false;
while (fgets(szLine, 200, file) != NULL)
{
// Get current file:
char * pszFile = strdup(szLine);
// Remove revision and status description:
char * pszStatus = strrchr(pszFile, '#');
if (pszStatus)
*pszStatus = 0;
if (strlen(pszFile) == 0)
break; // End of list reached.
// See if current file needs resolving. If user opted for auto-resolve, try that:
if (gfAutoResolve)
sprintf(szCmd, "p4 resolve -am \"%s\" >%s", pszFile, pszWorkSpace2FileName);
else
sprintf(szCmd, "p4 resolve -n \"%s\" >%s", pszFile, pszWorkSpace2FileName);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Could not see if file needed resolving.");
// Look for empty file:
if (!FileIsEmpty(pszWorkSpace2FileName))
{
// File is not empty, but if auto-resolve was attempted, we can see if it worked:
if (gfAutoResolve)
{
// If the resolve failed, the phrase "resolve skipped" will appear in the report:
FILE * file2 = fopen(pszWorkSpace2FileName, "rt");
if (file2)
{
char szLine2[400];
while (fgets(szLine2, 400, file2) != NULL)
{
if (strstr(szLine2, "resolve skipped"))
{
printf("File '%s' has conflicts.\n", pszFile);
fFilesNeedResolving = true;
break;
}
}
fclose(file2);
remove(pszWorkSpace2FileName);
}
}
else
{
printf("File '%s' needs resolving.\n", pszFile);
fFilesNeedResolving = true;
}
}
}
fclose(file);
return fFilesNeedResolving;
}
// Rebuild all.
void RebuildAll()
{
char szCmd[300];
sprintf(szCmd, "%s\\bin\\nant\\bin\\nant.exe -buildfile:%s\\bld\\FieldWorks.build remakefw "
"remakefw-failOnError", gpszRoot, gpszRoot);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Build failed.");
// just run tests:
// c:\FW\bin\nant\bin\nant.exe -buildfile:c:\FW\bld\FieldWorks.build test all remakefw-failOnError
}
// Prepare changelist specification.
void MakeChangelistSpec()
{
// Get current changelist specification:
char szCmd[200];
if (!gnCheckinChangeList)
sprintf(szCmd, "p4 change -o >%s", pszWorkSpaceFileName); // Default changelist
else
sprintf(szCmd, "p4 change -o %d >%s", gnCheckinChangeList, pszWorkSpaceFileName);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Cannot get Changelist specification from Perforce.");
// Make copy of file. If any line contains "<enter description here>",
// replace it with user's comment:
FILE * input = fopen(pszWorkSpaceFileName, "rt");
if (!input)
FatalError("Cannot open original Changelist specification file.");
FILE * output = fopen(pszChagelistSpecFileName, "wt");
if (!output)
{
fclose(input);
FatalError("Cannot open new Changelist specification file.");
}
char szLine[400];
bool fDescriptionActive = false;
while (fgets(szLine, 400, input) != NULL)
{
if (fDescriptionActive)
{
// Replace current line with comment:
fprintf(output, "\t%s\r\n", gpszCheckinComment);
fDescriptionActive = false;
}
else
{
fprintf(output, szLine);
if (strncmp(szLine, "Description:", 12) == 0)
fDescriptionActive = true;
}
}
fclose(input);
fclose(output);
}
// Edit token file to add user's comment of changes.
void EditTokenFile()
{
char szTokenFileName[300];
sprintf(szTokenFileName, "%s\\%s", gpszRoot, pszCheckinTokenFile);
// Check if last comment has a newline at the end:
FILE * fileToken = fopen(szTokenFileName, "rt");
if (!fileToken)
FatalError("Cannot open token file.");
char szLine[400];
while (fgets(szLine, 400, fileToken) != NULL)
;
fclose(fileToken);
fileToken = NULL;
bool fNewLineFound = false;
int nLen = strlen(szLine);
if (nLen == 0)
fNewLineFound = true;
else
{
int iEnd = nLen - 1;
if (szLine[iEnd] == '\n' || szLine[iEnd] == '\r')
fNewLineFound = true;
}
// Append user's check-in details:
fileToken = fopen(szTokenFileName, "at");
if (!fileToken)
FatalError("Cannot append to token file.");
if (!fNewLineFound)
fprintf(fileToken, "\r\n");
fprintf(fileToken, "%s (auto), %s. %s\r\n", gpszCheckinUser, gpszCheckinDate,
gpszCheckinComment);
fclose(fileToken);
}
// Submit changes:
void P4Submit()
{
char szCmd[200];
if (!gnCheckinChangeList)
sprintf(szCmd, "p4 submit -i <%s", pszChagelistSpecFileName); // Default changelist
else
sprintf(szCmd, "p4 submit -c %d -i <%s", gnCheckinChangeList, pszChagelistSpecFileName);
int nResult = system(szCmd);
if (nResult != 0)
FatalError("Cannot submit changes to Perforce.");
}
DWORD WINAPI TimeOutCheck(LPVOID)
{
// Sleep for 2 hours before signalling time-out:
Sleep(2 * 60 * 60 * 1000);
fTimedOut = true;
FatalError("Timed out. Two hours have passed, and I don't know why I haven't finished.");
return 0;
}
int main(int argc, char * argv[])
{
printf("Please wait while initial details are downloaded from Perforce server...\n");
gpszClient = NULL;
gpszUser = NULL;
gpszRoot = NULL;
gpszCheckinUser = NULL;
gpszCheckinDate = NULL;
gpszCheckinComment = NULL;
gnCheckinChangeList = 0;
pszDepotFw = NULL;
// Get client name and user name (and root path):
GetClientAndUser();
printf("client = '%s'; user = '%s'...\n", gpszClient, gpszUser);
// Get available changelist numbers:
GetAvailableChangeLists();
// Get root path:
const int kcchBuf = 100;
char szBuf[kcchBuf] = "";
GetEnvironmentVariable("fwroot", szBuf, kcchBuf);
gpszRoot = strdup(szBuf);
// Get default value for date:
SYSTEMTIME SystemTime;
GetSystemTime(&SystemTime);
sprintf(szBuf, "%d-%02d-%02d", SystemTime.wYear, SystemTime.wMonth, SystemTime.wDay);
gpszCheckinDate = strdup(szBuf);
printf("...Done.\n");
// There are two ways to run the program:
// 1) from the command line, with free text (as the checkin comment) forming the rest of the
// command line;
// 2) with no command line arguments, in which case all details are collected in a dialog
// box.
// In the case of (1), all other variables take default values: Default changelist, Perforce
// user name, date format etc.
// Check if user entered text:
if (argc < 2)
{
if (DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_DIALOG_USER_INFO), NULL,
DlgProcUserInfo) == 0)
{
exit(0);
}
}
else
{
// Get user's checkin comment from the command line:
const char * pszCommandLine = GetCommandLine();
// The position of the what the system thinks is the first of the command line arguments
// is the start of the comment:
gpszCheckinComment = strdup(strstr(pszCommandLine, argv[1]));
// Use Perforce user name as default checkin name:
gpszCheckinUser = strdup(gpszUser);
}
printf("Attempting to acquire check-in token file...\n");
// Loop until we get exclusive access to token file:
while (true)
{
// See if anyone has the token file:
if (TokenFileIsFree())
{
// Get up to date token file:
SyncTokenFile();
// Open token file for edit:
OpenTokenFileForEdit();
// Lock token file:
// LockTokenFile();
// See if anyone else has the token file as well as us:
if (TokenFileExclusivelyMine())
{
// We have the token file exclusively, so we can proceed:
break;
}
else
{
// Someone else got it at the same time as us! We'll revert:
RevertTokenFile();
}
}
// Sleep for 10 seconds before trying again:
Sleep(10000);
}
printf("...Done.\n");
// Now that we have the token file, create a new thread to monitor if we take too long
// to complete the task:
DWORD nThreadId; // MSDN says you can pass NULL instead of this, but you can't on Win98.
HANDLE hThread = CreateThread(NULL, 0, TimeOutCheck, NULL, 0, &nThreadId);
printf("Synchronizing files with Perforce server...\n");
// Sync all files:
SyncAllFiles();
if (fTimedOut)
Sleep(INFINITE);
printf("...Done.\n");
printf("Checking if any files need resolving...\n");
// See if any files need resolving:
if (FilesNeedResolving())
FatalError("One or more files need resolving. No point in attempting build, as check-in will fail anyway.");
if (fTimedOut)
Sleep(INFINITE);
printf("...Done.\n");
printf("\n");
printf("******************************************************************************\n");
printf("Initialization complete. About to start build. You can leave your machine now!\n");
printf("******************************************************************************\n");
printf("\n");
Sleep(4000);
// Rebuild all - does not return if build fails:
RebuildAll();
if (fTimedOut)
Sleep(INFINITE);
// Prepare Chagelist spec file:
MakeChangelistSpec();
if (fTimedOut)
Sleep(INFINITE);
// Edit CheckIn_History.txt file to add user's description of changes.
EditTokenFile();
if (fTimedOut)
Sleep(INFINITE);
// Submit changes:
P4Submit();
printf("Auto-checkin completed!\r\n");
TerminateThread(hThread, 0);
delete[] pszDepotFw;
delete[] gpszClient;
delete[] gpszUser;
delete[] gpszRoot;
delete[] gpszCheckinUser;
delete[] gpszCheckinDate;
delete[] gpszCheckinComment;
for (int i = 0; i < gcclChangeLists; i++)
delete[] gppszChangeListsComments[i];
delete[] gppszChangeListsComments;
delete[] gpnChangeLists;
remove(pszWorkSpaceFileName);
remove(pszChagelistSpecFileName);
return 0;
}
| true |
793feedcca763412eb3abfdfa51e4c58d13567a0 | C++ | jeanyvesb9/GS | /visitview.cpp | UTF-8 | 7,594 | 2.546875 | 3 | [] | no_license | #include "visitview.h"
#include "ui_visitview.h"
VisitView::VisitView(QWidget *parent, int visit) :
QDialog(parent),
ui(new Ui::VisitView),
visit{visit}
{
ui->setupUi(this);
this->setWindowIcon(QIcon(iconsPath->absolutePath().append("/Open_Icon.png")));
QStringList list {"Bueno", "Regular", "Malo", "Muy Malo"};
ui->GeneralStatus->addItems(list);
loadVisit(visit);
setEdit(false);
}
VisitView::VisitView(QWidget *parent, QString id) :
QDialog(parent),
ui(new Ui::VisitView),
id{id}
{
ui->setupUi(this);
ui->Godson_ID->setText(id);
ui->Date->setDate(QDate::currentDate());
dateCheckAvail = false;
QStringList list {"Bueno", "Regular", "Malo", "Muy Malo"};
ui->GeneralStatus->addItems(list);
setEdit(true);
ui->Ok->setText("Crear");
ui->Ok->setIcon(QIcon(iconsPath->absolutePath().append("/Ok_Icon.png")));
ui->VisitNumber->setText(QString::number(getVisitNumber(QDate::currentDate())));
this->setWindowTitle("Crear Visita");
disconnect(ui->Edit, 0, 0, 0);
connect(ui->Ok, SIGNAL(clicked()), this, SLOT(createVisit_Clicked()));
//TODO emit signal when closed, no creation
disconnect(ui->Ok, 0, 0, 0);
connect(ui->Edit, SIGNAL(clicked()), this, SLOT(close()));
}
VisitView::~VisitView()
{
delete ui;
}
int VisitView::getVisitNumber(QDate date)
{
query.clear();
query.prepare("SELECT Visits.Date FROM Visits WHERE Visits.ID_GodsonCode LIKE :id");
query.bindValue(":id", id);
query.exec();
QList<QDate> dateList;
while (query.next())
{
dateList.append(QDate::fromString(query.value("Date").toString(), "yyyy/MM/dd"));
}
qSort(dateList);
if (dateCheckAvail && date == this->date && dateList.contains(date))
{
int i = 0;
for(; dateList[i] != date; i++);
return i + 1;
}
else if (dateList.contains(date))
return -1;
int i = 0;
for(; i < dateList.size(); i++)
{
if (dateList[i] > date)
{
return i + 1;
}
}
return i + 1;
}
void VisitView::loadVisit(int visit)
{
query.clear();
query.prepare("SELECT Visits.ID_GodsonCode, Visits.Date, Visits.Meeting, Visits.GeneralStatus, Visits.Comment FROM Visits WHERE Visits.ID_Visit = :id");
query.bindValue(":id", visit);
query.exec();
query.next();
ui->Godson_ID->setText(query.value("ID_GodsonCode").toString());
id = query.value("ID_GodsonCode").toString();
ui->Date->setDate(QDate::fromString(query.value("Date").toString(), "yyyy/MM/dd"));
ui->Meeting->setChecked(query.value("Meeting").toBool());
ui->GeneralStatus->setCurrentIndex(query.value("GeneralStatus").toInt());
ui->Comment->setPlainText(query.value("Comment").toString());
dateCheckAvail = true;
canSave = true;
date = QDate::fromString(query.value("Date").toString(), "yyyy/MM/dd");
ui->VisitNumber->setText(QString::number(getVisitNumber(date)));
}
void VisitView::saveVisit()
{
query.clear();
query.prepare("UPDATE Visits SET Date = :date, Meeting = :meeting, GeneralStatus = :gs, Comment = :comment WHERE Visits.ID_Visit = :id");
query.bindValue(":id", visit);
query.bindValue(":date", ui->Date->date().toString("yyyy/MM/dd"));
query.bindValue(":meeting", ui->Meeting->isChecked());
query.bindValue(":gs", ui->GeneralStatus->currentIndex());
query.bindValue(":comment", ui->Comment->toPlainText());
query.exec();
}
void VisitView::createVisit()
{
query.clear();
query.prepare("INSERT INTO Visits(ID_GodsonCode, Date, Meeting, GeneralStatus, Comment) VALUES (:id, :date, :meeting, :gs, :comment)");
query.bindValue(":id", id);
query.bindValue(":date", ui->Date->date().toString("yyyy/MM/dd"));
query.bindValue(":meeting",ui->Meeting->isChecked());
query.bindValue(":gs", ui->GeneralStatus->currentIndex());
query.bindValue(":comment", ui->Comment->toPlainText());
query.exec();
}
void VisitView::edit_Clicked()
{
setEdit(!editStatus);
}
void VisitView::createVisit_Clicked()
{
if (canSave)
{
createVisit();
this->close();
dateCheckAvail = true;
date = ui->Date->date();
emit update();
return;
}
QMessageBox *message = new QMessageBox;
message->setWindowIcon(QIcon(iconsPath->absolutePath().append("/Warning_Icon.png")));
message->setText("La fecha ingresada corresponde a una visita existente, o supera la fecha del Sistema. Por favor corrobore la configuración de Windows.");
message->show();
}
void VisitView::saveEdit_Clicked()
{
if (canSave)
{
saveVisit();
setEdit(false);
date = ui->Date->date();
emit update();
return;
}
QMessageBox *message = new QMessageBox;
message->setWindowIcon(QIcon(iconsPath->absolutePath().append("/Warning_Icon.png")));
message->setText("La fecha ingresada corresponde a una visita existente, o supera la fecha del Sistema. Por favor corrobore la configuración de Windows.");
message->show();
}
void VisitView::cancelEdit_Clicked()
{
setEdit(false);
loadVisit(visit);
canSave = 1;
}
void VisitView::dateChanged(QDate date)
{
int dateNumber = getVisitNumber(date);
if (dateNumber == -1 || date > QDate::currentDate())
{
ui->Date->setStyleSheet("QDateEdit { color : red; }");
ui->VisitNumber->setText("-");
canSave = 0;
}
else
{
ui->Date->setStyleSheet("QDateEdit { color : black; }");
ui->VisitNumber->setText(QString::number(dateNumber));
canSave = 1;
}
}
void VisitView::setEdit(bool status)
{
editStatus = status;
ui->VisitNumber->setReadOnly(true);
ui->Godson_ID->setReadOnly(true);
ui->Date->setReadOnly(!status);
ui->Meeting->setEnabled(status);
ui->GeneralStatus->setEnabled(status);
ui->Comment->setReadOnly(!status);
if (status)
{
ui->Date->setButtonSymbols(QAbstractSpinBox::UpDownArrows);
disconnect(ui->Edit, 0, 0, 0);
connect(ui->Edit, SIGNAL(clicked()), this, SLOT(cancelEdit_Clicked()));
ui->Edit->setText("Cancelar");
ui->Edit->setIcon(QIcon(iconsPath->absolutePath().append("/Warning_Icon.png")));
disconnect(ui->Ok, 0, 0, 0);
connect(ui->Ok, SIGNAL(clicked()), this, SLOT(saveEdit_Clicked()));
ui->Ok->setText("Guardar");
ui->Ok->setIcon(QIcon(iconsPath->absolutePath().append("/Save_Icon.png")));
this->setWindowTitle("Editar Visita");
connect(ui->Date, SIGNAL(dateChanged(QDate)), this, SLOT(dateChanged(QDate)));
}
else
{
ui->Date->setButtonSymbols(QAbstractSpinBox::NoButtons);
ui->Date->setStyleSheet("QDateEdit { color : black; }");
disconnect(ui->Edit, 0, 0, 0);
connect(ui->Edit, SIGNAL(clicked()), this, SLOT(edit_Clicked()));
ui->Edit->setText("Editar");
ui->Edit->setIcon(QIcon(iconsPath->absolutePath().append("/Edit_Icon.png")));
disconnect(ui->Ok, 0, 0, 0);
connect(ui->Ok, SIGNAL(clicked()), this, SLOT(close()));
ui->Ok->setText("Ok");
ui->Ok->setIcon(QIcon(iconsPath->absolutePath().append("/Ok_Icon.png")));
this->setWindowTitle("Ver Visita");
disconnect(ui->Date, 0, 0, 0);
}
}
| true |
252edb53f5542d4e64c06c14fae33ddfc5cf8602 | C++ | cwlseu/Source | /lib/Seu/Cose/Test/NewArrayTest.cpp | UTF-8 | 436 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include "../Util/newArray.h"
using namespace Seu::Cose;
using namespace std;
void test()
{
int ndim=2;
int* arr = new int[2]{1,2};
int init =3;
int*** p = new3DimArray(4,4,4,init);
print3DimArray(p,4,4,4);
delete3DimArray(p,4,4,4);
std::cout<<sizeof(p)<<"";
reAlloc(arr,2,100);
for (int i = 0; i <100; ++i)
{
std::cout<<arr[i]<<"\t";
if(i%5==0)std::cout<<"\n";
}
}
int main()
{
test();
return 0;
} | true |
70c02ca7d085f4a1ed257cc17705a0b98e039007 | C++ | nssk1999/Edabit-Solutions | /1. Very Easy/sumOfTwoNumbers.cpp | UTF-8 | 505 | 3.65625 | 4 | [
"MIT"
] | permissive | /* this program will add two numbers
* Problem : https://edabit.com/challenge/SFzHtm63XT6EYNHWY
*/
#include <iostream>
using namespace std;
int addition(int a, int b) {
if (b > 0) {
while (b > 0) {
a++;
b--;
}
}
if (b < 0) { // when 'b' is negative
while (b < 0) {
a--;
b++;
}
}
}
int main() {
int num1,num2;
cin>>num1>>num2;
cout << addition(num1, num2) << endl;
return 0;
}
| true |
fa9462ff0ae04912e4933e4e5a6d10858d15a234 | C++ | sipe9/PerforceAssist | /P4Library/Utils/StringUtil.cpp | UTF-8 | 3,306 | 3.203125 | 3 | [
"MIT"
] | permissive |
#include "StringUtil.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
namespace VersionControl
{
bool StringUtil::endsWith(const std::string &from, const std::string &what)
{
if (from.length() < what.length())
return false;
std::string::const_reverse_iterator i1 = from.rbegin();
std::string::const_reverse_iterator i2 = what.rbegin();
for (; i2 != what.rend(); i2++, i1++)
{
if (*i1 != *i2)
return false;
}
return true;
}
bool StringUtil::startsWith(const std::string &from, const std::string &what)
{
if (from.length() < what.length())
return false;
std::string::const_iterator i1 = from.begin();
std::string::const_iterator i2 = what.begin();
for (; i2 != what.end(); i2++, i1++)
{
if (*i1 != *i2)
return false;
}
return true;
}
std::string StringUtil::SplitByLastOf(const std::string &s, const char lastOf, bool keepFirst)
{
size_t splitpos = s.find_last_of(lastOf);
if (splitpos == std::string::npos)
return s;
if (keepFirst)
return s.substr(0, splitpos);
else
return s.substr(splitpos + 1, s.length() - splitpos - 1);
}
std::string StringUtil::SplitByFirstOf(const std::string &s, const char firstOf, bool keepFirst)
{
size_t splitpos = s.find_first_of(firstOf);
if (splitpos == std::string::npos)
return s;
if (keepFirst)
return s.substr(0, splitpos);
else
return s.substr(splitpos + 1, s.length() - splitpos - 1);
}
bool StringUtil::Contains(const std::string &s, const std::string &string)
{
return (s.find(string) != std::string::npos);
}
std::string StringUtil::TrimEnd(const std::string &str, char c)
{
std::string::size_type i1 = str.length() - 1;
while (i1 >= 0 && str[i1] == c)
{
--i1;
}
if (i1 < 0)
return "";
return str.substr(0, i1 + 1);
}
std::string StringUtil::TrimStart(const std::string &str, char c)
{
std::string::size_type iend = str.length();
std::string::size_type i1 = 0;
while (i1 < iend && str[i1] == c)
{
++i1;
}
if (i1 >= iend)
return "";
return str.substr(i1);
}
std::string StringUtil::Trim(const std::string &str, char c)
{
return TrimStart(TrimEnd(str, c), c);
}
void StringUtil::Split(std::string &s, const char delim, std::vector<std::string> &out)
{
std::string::size_type lastPos = s.find_first_not_of(delim, 0);
std::string::size_type pos = s.find_first_of(delim, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
out.push_back(s.substr(lastPos, pos - lastPos));
lastPos = s.find_first_not_of(delim, pos);
pos = s.find_first_of(delim, lastPos);
}
}
bool StringUtil::IsPositiveNumber(const std::string &s)
{
return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit);
}
bool StringUtil::startsWithAndAssign(const std::string &line, const char *prefix, std::string &dest, bool trim)
{
if (StringUtil::startsWith(line, prefix))
{
dest = line.substr(strlen(prefix));
if (trim)
{
dest = TrimStart(dest, ' ');
dest = TrimStart(dest, '\t');
}
return true;
}
return false;
}
std::string StringUtil::Substring(const std::string &s, int start, int length)
{
if ((start + length) > static_cast<int>(s.length()))
return s;
return s.substr(start, length);
}
} | true |
3839a4feafe318aae6502b5d5f0b3c05591cb6be | C++ | rsrs2013/Optimizing-Single-Source-Shortest-Path-Algorithm-to-parallelize-on-a-GPU | /codeSample/entry_point.cpp | UTF-8 | 8,415 | 2.53125 | 3 | [] | no_license | #include <cstring>
#include <stdexcept>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
#include "utils.h"
#include "cuda_error_check.cuh"
#include "initial_graph.hpp"
#include "parse_graph.hpp"
#include "opt.cu"
#include "impl2.cu"
#include "impl1.cu"
#define SSSP_INF 1073741824
enum class ProcessingType {Push, Neighbor, Own, Unknown};
enum SyncMode {InCore, OutOfCore};
enum SyncMode syncMethod;
enum SmemMode {UseSmem, UseNoSmem};
enum SmemMode smemMethod;
enum EdgeListMode {input=0,source=1,destination=2};
enum EdgeListMode edge_list_mode;
// Open files safely.
template <typename T_file>
void openFileToAccess( T_file& input_file, std::string file_name ) {
input_file.open( file_name.c_str() );
if( !input_file )
throw std::runtime_error( "Failed to open specified file: " + file_name + "\n" );
}
int source_order_compare( edge_list a , edge_list b ) {
return a.srcIndex < b.srcIndex;
}
int destination_order_compare( edge_list a , edge_list b ) {
return a.destIndex < b.destIndex;
}
// Execution entry point.
int main( int argc, char** argv )
{
std::string usage =
"\tRequired command line arguments:\n\
Input file: E.g., --input in.txt\n\
Block size: E.g., --bsize 512\n\
Block count: E.g., --bcount 192\n\
Output path: E.g., --output output.txt\n\
Processing method: E.g., --method bmf (bellman-ford), or tpe (to-process-edge), or opt (one further optimizations)\n\
Shared memory usage: E.g., --usesmem yes, or no \n\
Sync method: E.g., --sync incore, or outcore\n\
Edge List Order Mode : E.g., --edgeListMode input,source,destination\n";
try {
std::ifstream inputFile;
std::ofstream outputFile;
int selectedDevice = 0;
int bsize = 0, bcount = 0;
int vwsize = 32;
int threads = 1;
long long arbparam = 0;
bool nonDirectedGraph = false; // By default, the graph is directed.
ProcessingType processingMethod = ProcessingType::Unknown;
syncMethod = OutOfCore;
/********************************
* GETTING INPUT PARAMETERS.
********************************/
for( int iii = 1; iii < argc; ++iii )
if ( !strcmp(argv[iii], "--method") && iii != argc-1 ) {
if ( !strcmp(argv[iii+1], "bmf") )
processingMethod = ProcessingType::Push;
else if ( !strcmp(argv[iii+1], "tpe") )
processingMethod = ProcessingType::Neighbor;
else if ( !strcmp(argv[iii+1], "opt") )
processingMethod = ProcessingType::Own;
else{
std::cerr << "\n Un-recognized method parameter value \n\n";
exit;
}
}
else if ( !strcmp(argv[iii], "--sync") && iii != argc-1 ) {
if ( !strcmp(argv[iii+1], "incore") )
syncMethod = InCore;
if ( !strcmp(argv[iii+1], "outcore") )
syncMethod = OutOfCore;
else{
std::cerr << "\n Un-recognized sync parameter value \n\n";
exit;
}
}
else if ( !strcmp(argv[iii], "--usesmem") && iii != argc-1 ) {
if ( !strcmp(argv[iii+1], "yes") )
smemMethod = UseSmem;
if ( !strcmp(argv[iii+1], "no") )
smemMethod = UseNoSmem;
else{
std::cerr << "\n Un-recognized usesmem parameter value \n\n";
exit;
}
}
else if ( !strcmp(argv[iii], "--edgeListMode") && iii != argc-1 ) {
if ( !strcmp(argv[iii+1], "input") )
edge_list_mode = input;
else if ( !strcmp(argv[iii+1], "source") )
edge_list_mode = source;
else if ( !strcmp(argv[iii+1], "destination") )
edge_list_mode = destination;
else{
std::cerr << "\n Un-recognized usesmem parameter value \n\n";
exit;
}
}
else if( !strcmp( argv[iii], "--input" ) && iii != argc-1 /*is not the last one*/)
openFileToAccess< std::ifstream >( inputFile, std::string( argv[iii+1] ) );
else if( !strcmp( argv[iii], "--output" ) && iii != argc-1 /*is not the last one*/)
openFileToAccess< std::ofstream >( outputFile, std::string( argv[iii+1] ) );
else if( !strcmp( argv[iii], "--bsize" ) && iii != argc-1 /*is not the last one*/)
bsize = std::atoi( argv[iii+1] );
else if( !strcmp( argv[iii], "--bcount" ) && iii != argc-1 /*is not the last one*/)
bcount = std::atoi( argv[iii+1] );
if(bsize <= 0 || bcount <= 0){
std::cerr << "Usage: " << usage;
exit;
throw std::runtime_error("\nAn initialization error happened.\nExiting.");
}
if( !inputFile.is_open() || processingMethod == ProcessingType::Unknown ) {
std::cerr << "Usage: " << usage;
throw std::runtime_error( "\nAn initialization error happened.\nExiting." );
}
if( !outputFile.is_open() )
openFileToAccess< std::ofstream >( outputFile, "out.txt" );
CUDAErrorCheck( cudaSetDevice( selectedDevice ) );
std::cout << "Device with ID " << selectedDevice << " is selected to process the graph.\n";
/********************************
* Read the input graph file.
********************************/
std::cout << "Collecting the input graph ...\n";
std::vector<initial_vertex> parsedGraph( 0 );
std::vector<edge_list> edgeList( 0 );
uint nEdges = parse_graph::parse(inputFile,parsedGraph,edgeList,arbparam,nonDirectedGraph);
std::cout << "Input graph collected with " << parsedGraph.size() << " vertices and " << nEdges << " edges.\n";
/********************************
* Sort the edge list.
********************************/
switch(edge_list_mode) {
case 0:
break;
case 1:
std::sort(edgeList.begin(),edgeList.end(),source_order_compare);
break;
case 2:
std::sort(edgeList.begin(),edgeList.end(),destination_order_compare);
break;
}
for( int i = 0 ; i < std::min(nEdges,(uint)20) ; i++ ) {
std::cout << "Edge i : " << i << " ( " << edgeList[i].srcIndex << " , " << edgeList[i].destIndex << ") , weight : " << edgeList[i].weight << " \n";
}
std::cout<<"Arranging for the Bellman-Ford\n";
uint vertices = parsedGraph.size();
uint edges = nEdges;
//std::vector<double> distance;
uint distance[vertices];
setTime();
std::cout<<"The number of vertices are:"<< vertices<<std::endl;
std::fill_n(distance,vertices,SSSP_INF);
/*for(int i=0;i<vertices;i++){
distance[i] = 0;
}*/
//distance[0] = 0;
std::cout<<"Starting the bellman-ford\n";
for(uint i = 0 ; i < vertices ; i++ ) {
bool change = false;
for(uint j = 0 ; j < edges ; j++ ){
int source = edgeList[j].srcIndex;
int destination = edgeList[j].destIndex;
int weight = edgeList[i].weight;
if(distance[source] + weight < distance[destination]) {
distance[destination] = distance[source] + weight;
change = true;
}
}
if( !change )
break;
}
std::cout << "Sequential Bellman-Ford Takes " << getTime() << "ms.\n";
/* Process the graph.
********************************/
switch(processingMethod){
case ProcessingType::Push:
puller(&parsedGraph, bsize, bcount, &edgeList,syncMethod,smemMethod);
break;
case ProcessingType::Neighbor:
neighborHandler(&parsedGraph, bsize, bcount);
break;
default:
own(&parsedGraph, bsize, bcount);
}
/********************************
* Do the comparision b/w parallel and sequential
********************************/
int num_of_diff = 0;
for(int i = 0 ; i < vertices ; i++ ) {
if( parsedGraph[i].vertexValue.distance != distance[i]) {
std::cout << "Sequential Distance for v " << i << " is : " << distance[i] << " and parallel gave : " << parsedGraph[i].vertexValue.distance << " \n.";
num_of_diff++;
}
}
if( num_of_diff == 0 ) {
std::cout << "Good Job! Serial and Parallel versions match.\n";
}
else {
std::cout << "Warning!!! Serial and Parallel mismatch " << num_of_diff << " distance values.\n";
}
/********************************
* It's done here.
********************************/
CUDAErrorCheck( cudaDeviceReset() );
std::cout << "Done.\n";
return( EXIT_SUCCESS );
}
catch( const std::exception& strException ) {
std::cerr << strException.what() << "\n";
return( EXIT_FAILURE );
}
catch(...) {
std::cerr << "An exception has occurred." << std::endl;
return( EXIT_FAILURE );
}
}
| true |
f73669a6ea841f6649c274665365e0e29425ac4a | C++ | veedee2000/Competitive-Programming | /Leetcode/MATH/Smallest_Range_1.cpp | UTF-8 | 306 | 2.671875 | 3 | [] | no_license | class Solution {
public:
int smallestRangeI(vector<int>& a, int k) {
int mmin = a[0], mmax = a[0];
for(auto x:a){
mmin = min(mmin, x);
mmax = max(mmax, x);
}
if(mmax - mmin - 2 * k > 0) return mmax - mmin - 2 * k;
else return 0;
}
};
| true |
88f5dbf9f408bfff6e3d735be97180f653c05d31 | C++ | C-Elegans/d16-cc2 | /src/MachineInstruction.hpp | UTF-8 | 957 | 2.59375 | 3 | [] | no_license | //
// MachineInstruction.hpp
// d16-cc2
//
// Created by Michael Nolan on 7/3/16.
// Copyright © 2016 Michael Nolan. All rights reserved.
//
#ifndef MachineInstruction_hpp
#define MachineInstruction_hpp
#include <cstdint>
#include <stdio.h>
#include <memory>
#include <vector>
typedef enum _Op_Type{
NOP=0,
ADD,
SUB,
PUSH,
POP,
MOVB,
MOV=0x0D,
AND,
OR,
XOR,
NOT,
NEG,
LD,
ST,
CMP,
JMP,
CALL,
SPEC,
SHL,
SHR,
ROL,
RCL,
LDCP,
STCP,
ADC,
SBB,
SET,
ADDI=0x81,
SUBI=0x82,
PUSHI=0x83,
MOVI=0x8D,
ANDI=0x8e,
ORI=0x8f,
XORI=0x90,
LDI=0x93,
STI=0x94,
CMPI=0x95,
JMPI=0x96,
CALLI=0x97,
SHLI=0x99,
SHRI=0x9a,
ROLI=0x9b,
RCLI=0x9c,
ADCI=0x9f,
SBBI=0xA0
} OpType;
class MachineInstruction {
public:
OpType type;
public:
virtual void assemble(uint16_t** data) = 0;
virtual void print() = 0;
void printType();
};
typedef std::vector<std::unique_ptr<MachineInstruction>> instruction_vec;
#endif /* MachineInstruction_hpp */
| true |
47b648bdc8c15547bdb8d18eb654b4416a065396 | C++ | sindreij/TDT4102 | /Oving1/del3b.cpp | UTF-8 | 319 | 3.5 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main() {
double tall1;
double tall2;
cout << "Skriv inn et tall: ";
cin >> tall1;
cout << "Skriv inn enda et tall: ";
cin >> tall2;
if (tall1 > tall2) {
cout << tall1 << " er størst" << endl;
} else {
cout << tall2 << " er størst" << endl;
}
}
| true |
78f6b307ae80bb58ab96e771416ee03fa78cadc7 | C++ | RdlP/space-invader | /include/Juego.h | UTF-8 | 2,924 | 3.1875 | 3 | [] | no_license | #ifndef Juego_h
#define Juego_h
/**
* Clase que representa al jeugo.
*
* Esta clase representa al juego, almacenando diversos atributos,
* como por ejemplo la puntuación, el nivel en el que se encuentra
* el juego, el nombre del jugador, si el juego ha terminado o no, etc...
*
* @author Ángel Luis Perales Gómez
* @version 0.1.1
* @section LICENCIA
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details at
* http://www.gnu.org/copyleft/gpl.html
*/
class Juego
{
public:
/**
* Constructor de la clase Juego.
*
* Constructor de la clase Juego que se encarga de inicializar
* la puntuación a 0, el nivel a 1, y terminado como false.
*/
Juego(int vidas);
/**
* Función que devuelve la puntación del juegador.
*
* @return Devuelve la puntación del juegador.
*/
int getPuntuacion();
/**
* Función que incrementa la puntuación del juegador.
*
* @param incremento Indica la cantidad en la que se
* va a aumentar la puntuación.
*/
void incrementarPuntuacion(int incremento);
/**
* Función que devuelve el nombre del juegador.
*
* @return Devuelve el nombre del jugador.
*/
char* getNombre();
/**
* Función que devuelve el nivel en que se encuentra el jugador.
*
* @return Devuelve el nivel en el que se encuentra el jugador.
*/
int getNivel();
/**
* Función que devuelve si el juego a terminado o no.
*
* @return Devuelve True si el juego ha terminado y falso en caso contrario.
*/
bool isTerminado();
/**
* Función para establecer si el juego a terminado o no.
*
* @param cond True para acabar el juego y False en caso contrario.
*/
void setTerminado(bool cond);
/**
* Función que devuelve las vidas que le quedan al jugador.
*
* @return Devuelve las vidas que le quedan al jugador.
*/
int getVidas();
/**
* Función usada para decrementar las vidas cuando
* el juegador muere.
*
* @param vidas Indica las vidas que le quedan al jugador.
*/
void setVidas(int vidas);
protected:
private:
int puntuacion;
char* nombre;
int nivel;
int vidas;
bool terminado;
};
#endif // Juego_h
| true |
2bfe2414fba45ad50e06518eac608f4191503a0c | C++ | rems4e/Projet2MIC | /Projet2MIC/src/Personnage.h | UTF-8 | 2,998 | 2.734375 | 3 | [] | no_license | //
// Personnage.h
// Projet2MIC
//
// Créé par Marc Promé et Rémi Saurel.
// Ce fichier et son contenu sont librement distribuables, modifiables et utilisables pour toute œuvre non commerciale, à condition d'en citer les auteurs.
//
#ifndef Projet2MIC_Personnage_h
#define Projet2MIC_Personnage_h
#include "EntiteMobile.h"
class Inventaire;
class ObjetInventaire;
class TiXmlElement;
class Personnage : public EntiteMobile {
public:
enum competences_t {premiereCompetence, force = premiereCompetence, agilite, endurance, nbCompetences};
class Competences {
public:
Competences();
int operator[](competences_t c) const;
int &operator[](competences_t c);
bool operator==(Competences const &c) const;
bool operator<(Competences const &c) const;
bool operator<=(Competences const &c) const;
bool operator>(Competences const &c) const;
bool operator>=(Competences const &c) const;
TiXmlElement *sauvegarde() const;
void restaurer(TiXmlElement *);
private:
int _valeurs[nbCompetences];
};
static Unichar nomCompetence(competences_t c);
enum positionTenue_t {premierePositionTenue, brasG = premierePositionTenue, brasD, casque, armure, gants, bottes, nbPositionsTenue};
virtual ~Personnage();
virtual void animer();
virtual bool interagir(Personnage *p, bool test) = 0;
virtual bool attaquer(Personnage *p);
virtual glm::vec2 origine() const;
virtual bool centrage() const;
// Le coefficient multiplicateur de la vitesse de déplacement de l'entité
virtual double vitesse() const;
int vieActuelle() const;
virtual void modifierVieActuelle(int delta);
virtual int vieTotale() const;
virtual bool definirAction(action_t a);
virtual Niveau::couche_t couche() const;
ObjetInventaire const *tenue(positionTenue_t p) const;
ObjetInventaire *tenue(positionTenue_t p);
void definirTenue(positionTenue_t p, ObjetInventaire *o);
Inventaire *inventaire();
Inventaire const *inventaire() const;
Competences const &competences() const;
Competences &competences();
void definirCompetences(Competences const &c);
virtual bool peutEquiperObjet(ObjetInventaire *objet);
virtual bool peutEquiperObjet(ObjetInventaire *objet, positionTenue_t pos);
void definirNiveau(Niveau *n);
protected:
Personnage(bool decoupagePerspective, Niveau *n, uindex_t index, ElementNiveau::elementNiveau_t, Inventaire *inventaire);
Personnage(Personnage const &);
Personnage &operator=(Personnage const &);
Personnage *interagir(bool test);
virtual void mourir();
virtual void jeterObjets() = 0;
private:
int _vieActuelle;
double _vitesse;
struct DelaisAction {
horloge_t _cooldown;
horloge_t _cdAbsolu;
};
DelaisAction _delaisAction[nbActions];
Inventaire *_inventaire;
ObjetInventaire *_tenue[nbPositionsTenue];
Competences _competences;
Personnage *_cibleAttaque;
};
Personnage::positionTenue_t &operator++(Personnage::positionTenue_t &p);
Personnage::competences_t &operator++(Personnage::competences_t &p);
#endif
| true |
1f81bf4962a140a39878d98f445262c3ab9204b6 | C++ | 15831944/TRiAS | /TRiAS/TRiAS/TRiAS/Obsolete (Win16 etc.)/IRISOPEN.HXX | ISO-8859-1 | 1,135 | 2.625 | 3 | [] | no_license | // Dialogfensterklasse fr DB erffnen
// File: IRISOPEN.HXX
#if !defined(_IRISOPEN_HXX)
#define _IRISOPEN_HXX
// OpenDialogfenster
class OpenDBDialog : public DialogWindow {
// Buttons
PushButton OKButton, CancelButton;
CheckBox ROCheckBox;
// FileListBoxes
FileListBox FileList;
// EditFenster
SingleLineEdit SLE_DBName, SLE_UserName, SLE_PassWord;
// Lokale Routinen
void SelectFile (void); // ListBox fllen
// EventHandler
void ListBoxSel (ControlEvt);
void ListBoxClk (ControlEvt);
void ButtonClick (ControlEvt);
// Textfelder fr eingelesene Strings
char _DBName[PATHLEN+1];
char _UserName[USERLEN+1];
char _PassWord[PASSWDLEN+1];
Bool _ReadOnlyFlag;
public:
// Konstruktor (Initialisierung des Dialogfensters)
OpenDBDialog (pWindow);
// Memberfunktionen
char *GetFileSpec (char *pc = NULL, short = 0) const; // liefert FileNamen
char *GetUserName (char *pc = NULL, short = 0) const; // liefert UserNamen
char *GetPassWord (char *pc = NULL, short = 0) const; // liefert Password
Bool GetROMode (void) { return _ReadOnlyFlag; }
};
#endif // _IRISOPEN_HXX
| true |
db06ff792afbd43114e25f2c690e01b31821c21e | C++ | shgalus/shg | /include/shg/rng.h | UTF-8 | 9,186 | 3.140625 | 3 | [
"MIT"
] | permissive | /**
* \file include/shg/rng.h
* Random number generator.
* \date Created on 11 December 2011.
*/
#ifndef SHG_RNG_H
#define SHG_RNG_H
#include <iostream>
#include <shg/vector.h>
namespace SHG {
/**
* \defgroup random_number_generator Random number generator
*
* Random number generator.
*
* \{
*/
/**
* A base class for defining random number generators. A derived class
* should define operator() to get random numbers uniformly
* distributed on [0, 1] and write(), read() methods to save and load
* generator states using binary streams.
*/
class RNG {
public:
/**
* Random number uniformly distributed on [0, 1].
*/
virtual double operator()() = 0;
/**
* Random number uniformly distributed on (0, 1].
*/
double unipos();
/**
* Random number uniformly distributed on (0, 1).
*/
double uniopen();
/**
* Random integer uniformly distributed on [0, b).
*
* \exception SHG::Invalid_argument unless b > 0
*/
int uni(int b);
/**
* Random integer uniformly distributed on [a, b).
*
* \exception SHG::Invalid_argument unless a < b
*/
int uni(int a, int b);
/**
* Random number exponentially distributed. The probability
* density function of the exponential distribution is defined as
* \f[f(x) = \exp(-x) \; \mbox{for $x \geq 0$}.\f]
*
* \implementation See \cite knuth-2002b, p. 141.
*/
double exponential();
/**
* Random point uniformly distributed on the surface of a
* simplex. The simplex is defined as \f[ \{(x_1, \ldots, x_n)
* \colon x_1 + \ldots + x_n = 1, x_i \geq 0 \}. \f] n is read as
* x.size().
*
* \exception SHG::Invalid_argument unless x.size() > 0
*
* \implementation See \cite wieczorkowski-zielinski-1997, p.
* 104.
*/
void simplex_surface(Vecdouble& x);
/**
* Random number generated from a discrete distribution.
* Probability function of the distribution is defined as \f[
* \Pr(X = k) = p_k, 0 \leq k < n. \f] \f$n\f$ is read as
* p.size(). There should be p.size() > 0 and p[0] + ... + p[n -
* 1] = 1.
*
* \exception SHG::Invalid_argument unless p.size() > 0
*
* \implementation See \cite knuth-2002b, p. 127,
* \cite wieczorkowski-zielinski-1997, p. 66.
*/
int finite(const Vecdouble& p);
/**
* Random number normally distributed with mean 0 and variance 1.
*
* \implementation See \cite wieczorkowski-zielinski-1997, p. 48,
* algorithm 3.2.
*/
double normal();
/**
* Random sample of n from N numbers 0, 1,..., N - 1, 0 < n <= N.
* Each subset of n elements is equally probable. Sample is
* increasingly ordered.
*
* \exception SHG::Invalid_argument unless n > 0 and n <= N
*
* \implementation See \cite knuth-2002b, section 3.4.2,
* algorithm S.
*/
void random_sample(int n, int N, Vecint& x);
/**
* Random number from logarithmic series distribution.
* Logarithmic series distribution with parameter 0 < p < 1 has
* the probability function \f[ \Pr(X = i) = (a / i)p^i, \; i =
* 1, 2, 3, \ldots, \; a = -\frac{1}{\log(1 - p)}.\f] The
* expected value and variance are \f[ EX = ap / (1 - p), \; D^2X
* = ap(1 - ap) / (1 - p)^2. \f]
*
* \exception SHG::Invalid_argument unless p > 0 and p < 1.0
*
* \exception std::overflow_error if the result exceeds
* std::numeric_limits<unsigned long>::max(), what may happen for
* p close to 1
*
* \implementation Kemp's second accelerated generator,
* \cite devroye-1986, p. 548. See also <a href =
* "http://luc.devroye.org/errors.pdf">an on-line errata</a>.
*/
unsigned long logarithmic(double p);
/**
* Random number from geometric distribution. Geometric
* distribution has the probability function \f[\Pr(X = n) = (1 -
* p)^{n - 1}p, \; n = 1, 2, \ldots, \; 0 < p \leq 1.\f]
*
* \exception SHG::Invalid_argument unless p > 0.0 and p <= 1.0
*
* \exception std::overflow_error if the generated number exceeds
* std::numeric_limits<unsigned long>::max(), what may happen for
* p close to 0
*
* \implementation See \cite knuth-2002b, p. 145.
*/
unsigned int geometric(double p);
/**
* Random number from gamma distribution. Gamma distribution has
* the probability density function \f[ f(x) = \left\{
* \begin{array} {ll} b^a / \Gamma(a) x^{a - 1} \exp(-bx) &
* \mbox{for $x > 0$} \\ 0 & \mbox{for $x \leq 0$} \end{array}
* \right.\f] where \f$b\f$ and \f$a\f$ are positive parameters.
*
* \exception SHG::Invalid_argument unless a > 0.0 and b > 0.0
*
* \implementation See \cite knuth-2002b, p. 142-143 and solution
* to exercise 16 on p. 633. See also <a href =
* "http://www.gnu.org/software/gsl/">GNU Scientific Library</a>,
* version 1.15, file gsl-1.15/randist/gamma.c.
*/
double gamma(double a = 1.0, double b = 1.0);
/**
* Random number from beta distribution. Beta distribution has
* the probability density function \f[ f(x) = \left\{
* \begin{array} {ll} \frac{1}{B(a, b)}x^{a - 1}(1 - x)^{b - 1} &
* \mbox{for $0 < x < 1$} \\ 0 & \mbox{for $x \leq 0$ or $x \geq
* 1$} \end{array} \right.\f] where \f$a\f$ and \f$b\f$ are
* positive parameters and \f$B(a, b) = \Gamma(a)\Gamma(b) /
* \Gamma(a + b)\f$ (see \cite fisz-1969, p. 167).
*
* \exception SHG::Invalid_argument unless a > 0.0 and b > 0.0
*
* \implementation See \cite knuth-2002b, p. 143. See also <a
* href = "http://www.gnu.org/software/gsl/">GNU Scientific
* Library</a>, version 1.15, file gsl-1.15/randist/beta.c.
*/
double beta(double a, double b);
/**
* Random number from binomial distribution. Binomial
* distribution has the probability function \f[ \Pr(X = k) =
* \frac{n!}{k!(n - k)!}p^k(1 - p)^{n - k}, \; k = 0, 1, \ldots,
* n, \; 0 \leq p \leq 1.\f]
*
* \exception SHG::Invalid_argument unless p >= 0.0 and p <= 1.0
*
* \implementation See \cite knuth-2002b, p. 143. See also <a
* href = "http://www.gnu.org/software/gsl/">GNU Scientific
* Library</a>, version 1.15, file gsl-1.15/randist/binomial.c.
*/
unsigned int binomial(double p, unsigned int n);
/**
* Random number from Poisson distribution. Poisson distribution
* has the probability function \f[ \Pr(X = n) = \frac{\mu^n}{n!}
* \exp(-\mu), \; n = 0, 1, 2, \ldots, \f] where \f$\mu > 0\f$ is
* the mean.
*
* \exception SHG::Invalid_argument unless mu > 0.0
*
* \implementation See \cite knuth-2002b, p. 145-146. See also <a
* href = "http://www.gnu.org/software/gsl/">GNU Scientific
* Library</a>, version 1.15, file gsl-1.15/randist/poisson.c.
*/
unsigned int poisson(double mu);
/**
* Random number from negative binomial distribution. Negative
* binomial distribution has the probability function \f[ \Pr(X =
* n) = {{t - 1 + n} \choose {n}} p^t(1 - p)^n, \; n = 0, 1, 2,
* \ldots,\f] where \f$t > 0\f$ and \f$0 < p < 1\f$.
*
* \exception SHG::Invalid_argument unless t > 0.0 and p > 0.0
* and p < 1.0
*
* \implementation See \cite knuth-2002b, p. 149 (exercise 19)
* and p. 633-634. See also <a href =
* "http://www.gnu.org/software/gsl/">GNU Scientific Library</a>,
* version 1.15, file gsl-1.15/randist/nbinomial.c.
*/
unsigned int negative_binomial(double t, double p);
/**
* Random number from Laplace distribution. Laplace distribution
* has the probability density function \f[f(x) =
* \frac{1}{2\lambda} \exp \left(-\frac{|x - \mu|}{\lambda}
* \right).\f] It is asserted that \f$\lambda > 0\f$.
*
* \exception SHG::Invalid_argument unless lambda > 0.0
*
* \implementation The method of inverse transform sampling is
* used \cite wieczorkowski-zielinski-1997, p. 41.
*/
double laplace(double mu, double lambda);
/**
* Saves the generator state in a stream. The stream should be
* open in binary mode. After a call, the state of the stream
* should be tested: if f.fail() returns true, an error has
* occured.
*/
virtual void write(std::ostream& f) const = 0;
/**
* Loads the generator state from a stream. The stream should be
* open in binary mode. After a call, if f.fail() returns true,
* the operation failed and the state remains the same as before
* the call.
*/
virtual void read(std::istream& f) = 0;
virtual ~RNG();
private:
double gamma_int(unsigned int a);
double gamma_large(double a);
double gamma_frac(double a);
};
/** \} */ /* end of group random_number_generator */
} // namespace SHG
#endif
| true |
e78cbc09314cf9eac18833acd457cffec10be91a | C++ | FRCTeam1073-TheForceTeam/preseason2012 | /CS Lectures on OOP/RookieOOP/RookieOOP/AnimalDemo.cpp | UTF-8 | 1,598 | 3.25 | 3 | [] | no_license | //
// main.cpp
// RookieOOP
//
// Created by Irfan Ugur on 11/4/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#include <iostream>
#include <string>
#include "Animal.h"
#include "Fish.h"
#include "Quadrupedal.h"
#include "Dog.h"
#include "Beagle.h"
#include "Cat.h"
void printAnimalInfo(Animal* inputAnimal){
//this code will pull information from your animal as it is defined in the class...
cout << ("\n\nSpecies:\t" + inputAnimal->getSpecies());
cout << ("\nName:\t" + inputAnimal->getName());
cout << "\nNumber of legs:\t";
cout << inputAnimal->getLegNumber();
cout << ("\nBreed\t" + inputAnimal->getBreed());
//this code will do a unique noise OR any other code you wrote for that matter in your animal class.
cout << ("\nSay something, " + inputAnimal->getName() + "!\n");
inputAnimal->makeNoise();
cout << "\n";
}
int mainddddd (int argc, const char * argv[])
{
Fish* nemo = new Fish("Nemo");
Fish* dory = new Fish("Dory");
Cat* kitty = new Cat("Kitty");
Dog* spot = new Dog("Spot");
Beagle* max = new Beagle("Max");
/* Let's print out their info with the function I declared at the top! Notice how the function takes Animals, yet we're passing in Dogs, Fish, Cats, etc.
printAnimalInfo(nemo);
printAnimalInfo(dory);
printAnimalInfo(kitty);
printAnimalInfo(spot);
printAnimalInfo(max);
*/
//The animals are casuing mischief!
spot->chaseCat(kitty);
kitty->eatAFish(nemo);
kitty->eatAFish(dory);
return 0;
}
| true |
aaee83118374861e55b0000fadae21facdb850fa | C++ | TTilenB/Programiranje1 | /naloga04e.cpp | UTF-8 | 438 | 3 | 3 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
int main ()
{
int n, m = 1, a;
cout << "Vnesite število za dimenzijo: " << endl;
cin >> n;
cout << "\n" << endl;
a = n + 7;
for(int i = n; i >= 1; --i)
{
cout << a;
a = a - 2;
for(int j = 1; j <= i; ++j)
{
cout << "+ ";
}
cout << m << endl;
m = m + 2;
}
return 0;
}
| true |
294d83fe18e43bb6c570ce21ecb78bd7021454dc | C++ | sagregas/Leetcode | /CPP_Solutions/PalindromeNumber.cpp | UTF-8 | 447 | 3.203125 | 3 | [] | no_license | class Solution {
public:
bool isPalindrome(int x) {
if(x < 0) return false;
if(x / 10 == 0) return true;
std::stack<int> stk;
int num = x;
while(num != 0){
stk.push(num%10);
num = num/10;
}
while(x != 0){
if(stk.top() != x%10){
return false;
}
else{
x = x/10;
stk.pop();
}
}
return true;
}
};
| true |
9f4e6d7d2dce078f31dde50033df9ef2cf30af39 | C++ | AdeelZafar907/math.h-library-complete-calculator- | /math.h/Matrix.h | UTF-8 | 473 | 2.8125 | 3 | [] | no_license | #pragma once
class matrix
{
int row;
int column;
public:
void set_row(int);
void set_col(int);
int get_row();
int get_col();
void get_additionOfMatrix(int**,int**,int,int);
void get_subtractionOfMatrix(int**, int**,int,int);
void get_multiplicationOfMatrix(int**, int**,int,int,int);
void get_determinantInMatrix(int**,int,int);
void get_transpose(int**,int,int);
matrix(int,int);
matrix();
matrix(matrix&);
void display();
~matrix();
}; | true |
c1689905a8bf38a822b5c46f3a51e62bacf5d9e2 | C++ | hvvka/ncurses-threading | /src/learning/2cpp/main.cpp | UTF-8 | 355 | 2.609375 | 3 | [] | no_license | #include <ncurses.h>
using namespace std;
int main(int argc, char** argv)
{
initscr();
int x, y;
x = y = 10;
// moves the cursor to the specified location
move(y, x);
printw("Hello move!");
refresh();
int c = getch();
// clears the screen
clear();
mvprintw(0, 0,"%d", c);
refresh();
getch();
endwin();
return 0;
}
| true |
17f2bd25a76087b34a783e54e50a4e420e7bedd8 | C++ | SimonGido/Dot_Engine | /Dot_Engine/src/Dot/PhysicsEngine/PhysicsSystem.cpp | UTF-8 | 1,238 | 2.890625 | 3 | [
"Apache-2.0"
] | permissive | #include "stdafx.h"
#include "PhysicsSystem.h"
namespace Dot {
void PhysicsSystem::Update(float dt)
{
for (int i = 0; i < m_Entities.size(); ++i)
{
auto transform = &ECSManager::Get()->GetComponent<Transform>(m_Entities[i]);
auto& rigidBody = ECSManager::Get()->GetComponent<RigidBody>(m_Entities[i]);
transform->pos += rigidBody.velocity * dt;
transform->UpdateModel();
}
}
void PhysicsSystem::Add(Entity entity)
{
LOG_INFO("Entity with ID %d added",entity);
m_Entities.push_back(entity);
}
void PhysicsSystem::Remove(Entity entity)
{
std::sort(m_Entities.begin(), m_Entities.end());
int position = binarySearch(0, (int)m_Entities.size() - 1, entity);
if (position != -1 && !m_Entities.empty())
{
LOG_INFO("Entity with ID %d removed",entity);
m_Entities[position] = m_Entities[m_Entities.size() - 1];
m_Entities.erase(m_Entities.end() - 1);
}
}
int PhysicsSystem::binarySearch(int start, int end, Entity entity)
{
if (end >= start)
{
int mid = start + (end - start) / 2;
if (m_Entities[mid] == entity)
return mid;
if (m_Entities[mid] > entity)
return binarySearch(start, mid - 1, entity);
return binarySearch(mid + 1, end, entity);
}
return -1;
}
}
| true |
916cc16f17d33472fb6114863d5da31897381484 | C++ | wwuhn/wwuhn.github.io | /witisoPC/32cpp/贺利坚/overall/自定义顺序栈解决迷宫问题.cpp | GB18030 | 3,397 | 3.140625 | 3 | [] | no_license | #include <iostream> // Զ˳ջԹ
#include <iomanip>
#include <cstdlib>
using namespace std;
#define MaxSize 100
int maze[10][10] = //һԹ0ʾͨ1ʾǽ
{
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,1,0,0,1,0,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,0,0,1},
{1,0,1,1,1,0,1,1,0,1},
{1,1,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
struct Try //һջ·
{
int i; //ǰк
int j; //ǰ㳡к
int d; //diһ߷λķλ
} path[MaxSize]; //ջ
int top = -1; //ʼջָ
void findPath(int xb, int yb, int xe, int ye) //·Ϊ(xb,yb)(xe,ye)
{
int i, j, d, find, k;
top++; //ʼջ
path[top].i = xb;
path[top].j = yb;
path[top].d = -1;
maze[xb][yb] = -1;
while(top>-1) //ջΪʱѭ
{
i = path[top].i;
j = path[top].j;
d = path[top].d;
if(i==xe && j==ye) //ҵ˳ڣ·
{
cout << "Թ·£\n";
for(k=0; k<=top; k++)
{
cout << "\t(" << path[k].i << "," << path[k].j << ")";
if((k+1)%5==0) cout << endl; //ÿһ
}
cout << endl;
return;
}
find = 0;
while(d<4 && find==0) //һߵĵ
{
d++;
switch(d)
{
case 0: //
i = path[top].i-1;
j = path[top].j;
break;
case 1: //
i = path[top].i;
j = path[top].j+1;
break;
case 2: //
i = path[top].i+1;
j = path[top].j;
break;
case 3: //
i = path[top].i;
j = path[top].j-1;
break;
}
if(maze[i][j]==0) find = 1; //ҵͨ·
}
if(find==1) //ҵһ߷
{
path[top].d = d; //ԭջԪصdֵ
top++; //һ߷ջ
path[top].i = i;
path[top].j = j;
path[top].d = -1;
maze[i][j] = -1; //ظߵ
//cout << "\t(" << path[top].i << "," << path[top].j << ")"; //ʾ̽
}
else //û·ߣջ
{
maze[path[top].i][path[top].j] = 0; //øλñ·߷
top--;
}
}
cout << "ûп·\n";
}
int main()
{
findPath(1,1,8,8); //(1,1)룬(8,8)
while(1);
return 0;
} | true |
874bf479fe91818d401eee8222fe15549a200127 | C++ | visvasuthar/CMPE152-Project1 | /Word.cpp | UTF-8 | 492 | 2.890625 | 3 | [] | no_license | //
// Created by Luis on 2/7/2020.
//
#include <iostream>
#include "Word.h"
#include "Tag.h"
#include "Token.h"
using namespace std;
Word::Word(){
*AND = Word("&&", tag.AND);
*OR = Word("||", tag.OR);
*eq = Word("==", tag.EQ);
*ne = Word("!=", tag.NE);
*le = Word("<=", tag.LE);
*ge = Word(">=", tag.GE);
*minus = Word("minus", tag.MINUS);
*True = Word("true", tag.TRUE);
*False = Word("false", tag.FALSE);
*temp = Word("t", tag.TEMP);
} | true |
93013dbe7582b5e2451df911eb9c1652070d4657 | C++ | Dev-LucasReis/Estruturada-de-Dados-C- | /Atividades/ParPos.cpp | UTF-8 | 657 | 3.53125 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <stdlib.h>
using namespace std;
class PosPar{
public:
int n;
void entrada(){
cout <<"Digite um numero:" <<"\n";
cin >> n ;
}
bool VerificaPosPar(){
if(n >= 0 && n % 2 == 0){
return true;
}else{
return false;
}
}
int cont(){
int aux = 1;
while(VerificaPosPar() == true){
entrada();
aux = aux + 1;
}if(VerificaPosPar() == false){
aux = aux - 1;
}
return aux;
}
};
int main(){
PosPar obj;
obj.entrada();
cout<<"\n";
cout<< obj.VerificaPosPar() << "\n";
cout << "Quantidade de numeros pares e positivos: " << "\n" <<obj.cont();
return 0;
}
| true |
83d7fd7346aebfe08ac5cc4944462009e23795a0 | C++ | xRiveria/Amethyst | /Amethyst/Source/RHI/RHI_DescriptorSetLayoutCache.cpp | UTF-8 | 6,380 | 2.703125 | 3 | [] | no_license | #include "Amethyst.h"
#include "RHI_DescriptorSetLayoutCache.h"
#include "RHI_Shader.h"
#include "RHI_Pipeline.h"
#include "RHI_DescriptorSetLayout.h"
namespace Amethyst
{
RHI_DescriptorSetLayoutCache::RHI_DescriptorSetLayoutCache(const RHI_Device* rhi_Device)
{
m_RHI_Device = rhi_Device;
//Set the descriptor set capacity to an initial value.
SetDescriptorSetCapacity(16); // Creates the descriptor pool.
}
void RHI_DescriptorSetLayoutCache::SetPipelineState(RHI_PipelineState& pipelineState)
{
//Retrieve pipeline descriptors.
RetrieveDescriptors(pipelineState, m_Descriptors);
//Compute a hash for the descriptors for comparison.
uint32_t hash = 0;
for (const RHI_Descriptor& descriptor : m_Descriptors)
{
Utility::HashCombine(hash, descriptor.ComputeHash(false));
}
//If there is no descriptor set layout for this particular hash, create one.
auto it = m_DescriptorSetLayouts.find(hash);
if (it == m_DescriptorSetLayouts.end()) //Cannot find...
{
//Create a name for the descriptor set layout - this is very uswful for Vulkan debugging.
std::string name = "Compute Shader: " + (pipelineState.m_ComputeShader ? pipelineState.m_ComputeShader->RetrieveName() : "Null");
name += "Vertex Shader: " + (pipelineState.m_VertexShader ? pipelineState.m_VertexShader->RetrieveName() : "Null");
name += "Pixel Shader: " + (pipelineState.m_PixelShader ? pipelineState.m_PixelShader->RetrieveName() : "Null");
//Emplace a new descriptor set layout.
it = m_DescriptorSetLayouts.emplace(std::make_pair(hash, std::make_shared<RHI_DescriptorSetLayout>(m_RHI_Device, m_Descriptors, name.c_str()))).first;
}
//Retrieve the descriptor set layout we will be using.
m_DescriptorSetLayoutCurrent = it->second.get();
m_DescriptorSetLayoutCurrent->NeedsToBind();
}
bool RHI_DescriptorSetLayoutCache::SetConstantBuffer(const uint32_t slot, RHI_ConstantBuffer* constantBuffer)
{
AMETHYST_ASSERT(m_DescriptorSetLayoutCurrent != nullptr);
return m_DescriptorSetLayoutCurrent->SetConstantBuffer(slot, constantBuffer);
}
void RHI_DescriptorSetLayoutCache::SetSampler(const uint32_t slot, RHI_Sampler* sampler)
{
AMETHYST_ASSERT(m_DescriptorSetLayoutCurrent != nullptr);
m_DescriptorSetLayoutCurrent->SetSampler(slot, sampler);
}
void RHI_DescriptorSetLayoutCache::SetTexture(const uint32_t slot, RHI_Texture* texture, const bool storage)
{
AMETHYST_ASSERT(m_DescriptorSetLayoutCurrent != nullptr);
m_DescriptorSetLayoutCurrent->SetTexture(slot, texture, storage);
}
bool RHI_DescriptorSetLayoutCache::RetrieveDescriptorSet(RHI_DescriptorSet*& descriptorSet)
{
AMETHYST_ASSERT(m_DescriptorSetLayoutCurrent != nullptr);
return m_DescriptorSetLayoutCurrent->RetrieveDescriptorSet(this, descriptorSet);
}
void RHI_DescriptorSetLayoutCache::GrowIfNeeded()
{
//If there is room for at least one more descriptor set (hence +1), we don't need to re-allocate yet.
const uint32_t requiredCapacity = RetrieveDescriptorSetCount() + 1;
//If we are over budget, re-allocate the descriptor pool with double its current size.
if (requiredCapacity > m_DescriptorSetCapacity)
{
SetDescriptorSetCapacity(m_DescriptorSetCapacity * 2);
}
}
uint32_t RHI_DescriptorSetLayoutCache::RetrieveDescriptorSetCount() const
{
/*
Instead of updating dewsceripots to not reference it, the RHI_Texture2D destructor resets the descriptor set layout cache.
As this can happen from another thread, we thus do the wait here. Ideally, ~RHI_Texture2D() is made to work right.
*/
while (m_AreDescriptorSetLayoutsBeingCleared)
{
AMETHYST_INFO("Waiting for descriptor set layouts to be cleared...");
std::this_thread::sleep_for(std::chrono::milliseconds(16));
}
uint32_t descriptorSetCount = 0;
for (const std::pair<size_t, std::shared_ptr<RHI_DescriptorSetLayout>>& descriptorSetsLayout : m_DescriptorSetLayouts)
{
descriptorSetCount += descriptorSetsLayout.second->RetrieveDescriptorSetCount();
}
return descriptorSetCount;
}
void RHI_DescriptorSetLayoutCache::RetrieveDescriptors(RHI_PipelineState& pipelineState, std::vector<RHI_Descriptor>& descriptors)
{
if (!pipelineState.IsPipelineStateValid())
{
AMETHYST_ERROR("Invalid pipeline state.");
descriptors.clear();
return;
}
bool descriptorsAcquired = false;
if (pipelineState.IsComputePipeline())
{
//Wait for compilation.
pipelineState.m_ComputeShader->WaitForCompilation();
//Retrieve computer shader descriptors.
descriptors = pipelineState.m_ComputeShader->RetrieveDescriptors();
descriptorsAcquired = true;
}
else if (pipelineState.IsGraphicsPipeline())
{
//Wait for compilation.
pipelineState.m_VertexShader->WaitForCompilation();
//Retrieve vertex shader descriptors.
descriptors = pipelineState.m_VertexShader->RetrieveDescriptors();
descriptorsAcquired = true;
//If there is a pixel shader, merge it's resources into our map as well.
if (pipelineState.m_PixelShader)
{
//Wait for compilation.
pipelineState.m_PixelShader->WaitForCompilation();
for (const RHI_Descriptor& descriptorReflected : pipelineState.m_PixelShader->RetrieveDescriptors())
{
//Assume that the descriptor has been created in the vertex shader and only try to update its shader stage.
bool updatedExisting = false;
for (RHI_Descriptor& descriptor : descriptors)
{
//If the descriptor is the same...
if ((descriptor.m_DescriptorType == descriptorReflected.m_DescriptorType) && (descriptor.m_Slot == descriptorReflected.m_Slot))
{
descriptor.m_Stage |= descriptorReflected.m_Stage;
updatedExisting = true;
break;
}
}
//If no updating took place, this descriptor is new, so we add it.
if (!updatedExisting)
{
descriptors.emplace_back(descriptorReflected);
}
}
}
}
//Change constant buffers to dynamic if requested.
if (descriptorsAcquired)
{
for (uint32_t i = 0; i < g_RHI_MaxConstantBufferCount; i++)
{
for (RHI_Descriptor& descriptor : descriptors)
{
if (descriptor.m_DescriptorType == RHI_Descriptor_Type::ConstantBuffer)
{
if (descriptor.m_Slot == pipelineState.m_DynamicConstantBufferSlots[i] + g_RHI_ShaderShiftBuffer)
{
descriptor.m_IsDynamicConstantBuffer = true;
}
}
}
}
}
}
} | true |
99f37ae3edf349104cbbe6370dbbc1ffd9313312 | C++ | mdross95/Tic-Tac-Toe | /test.cpp | UTF-8 | 7,436 | 2.859375 | 3 | [] | no_license | #include <vector>
#include "AIPlayer.hpp"
#include "Board.hpp"
#include "CreatePlayers.hpp"
#include "Game.hpp"
#include "InputOutput.hpp"
#include "HumanPlayer.hpp"
#include "Player.hpp"
#include "SetupGame.hpp"
#include "Spot.hpp"
using namespace std;
void testBoard()
{
Board board;
Player* p1ptr = new HumanPlayer('X', 1);
Player* p2ptr = new HumanPlayer('O',1);
//getBoardSize
assert(board.getBoardSize() == 9);
//takeSpot
vector<Spot> testVec1(9, Spot());
testVec1[0].setIsTaken();
testVec1[0].setTakenBy(p1ptr);
board.takeSpot(p1ptr, 0);
assert(board.getBoardVec()[0] == testVec1[0]);
assert(!(board.getBoardVec()[1] == testVec1[0]));
//availableSpots
board.takeSpot(p1ptr, 1);
board.takeSpot(p2ptr, 2);
board.takeSpot(p2ptr, 3);
vector<Spot>testVec2;
for (int i = 4; i < 9; i++)
{
testVec2.push_back(Spot(i, false, nullptr));
}
assert(testVec2.size() == board.availableSpots().size());
for(int i = 0; i < 5; i++)
{
assert(testVec2[i].getLocation() == board.availableSpots()[i].getLocation());
}
//checkWin
board = Board();
assert(!board.checkWin(p1ptr));
board.takeSpot(p1ptr, 0);
board.takeSpot(p1ptr, 3);
board.takeSpot(p1ptr, 6);
assert(board.checkWin(p1ptr));
board = Board();
board.takeSpot(p1ptr, 1);
board.takeSpot(p1ptr, 4);
board.takeSpot(p1ptr, 7);
assert(board.checkWin(p1ptr));
board = Board();
board.takeSpot(p1ptr, 2);
board.takeSpot(p1ptr, 5);
board.takeSpot(p1ptr, 8);
assert(board.checkWin(p1ptr));
board = Board();
board.takeSpot(p1ptr, 0);
board.takeSpot(p1ptr, 1);
board.takeSpot(p1ptr, 2);
assert(board.checkWin(p1ptr));
board = Board();
board.takeSpot(p1ptr, 3);
board.takeSpot(p1ptr, 4);
board.takeSpot(p1ptr, 5);
assert(board.checkWin(p1ptr));
board = Board();
board.takeSpot(p1ptr, 6);
board.takeSpot(p1ptr, 7);
board.takeSpot(p1ptr, 8);
assert(board.checkWin(p1ptr));
board = Board();
board.takeSpot(p1ptr, 0);
board.takeSpot(p1ptr, 4);
board.takeSpot(p1ptr, 8);
assert(board.checkWin(p1ptr));
board = Board();
board.takeSpot(p1ptr, 2);
board.takeSpot(p1ptr, 4);
board.takeSpot(p1ptr, 6);
assert(board.checkWin(p1ptr));
//checkTie
board = Board();
assert(!board.checkTie());
//checkTie checks for no available spots
for (int i = 0; i < board.getBoardSize(); i++)
{
board.takeSpot(p1ptr, i);
}
assert(board.checkTie());
delete p1ptr;
delete p2ptr;
}
void testCreatePlayers()
{
//createPlayers()
CreatePlayers cp;
Player* p1ptr;
Player* p2ptr;
Player* firstplayerptr;
Player* secondplayerptr;
cp.createPlayers(2, 'X', 'O', 1, p1ptr, p2ptr, firstplayerptr, secondplayerptr);
assert(p1ptr->getSymbol() == 'X');
assert(p2ptr->getSymbol() == 'O');
assert(firstplayerptr == p1ptr);
assert(secondplayerptr == p2ptr);
assert(p1ptr->isHuman());
assert(!p2ptr->isHuman());
assert(p1ptr->getOtherPlayer() == p2ptr);
assert(p2ptr->getOtherPlayer() == p1ptr);
assert(p1ptr->getShouldPickRandomly() == false);
assert(p2ptr->getShouldPickRandomly() == true);
}
void testInputOutput()
{
InputOutput io;
//checkTerminate
string test = "notquit";
assert(!io.checkTerminate(test));
test = "quit";
assert(io.checkTerminate(test));
}
void testPlayer()
{
Board board;
Player* p1ptr = new HumanPlayer('X', 1);
Player* p2ptr = new AIPlayer('O',1);
p1ptr->setOtherPlayer(p2ptr);
p2ptr->setOtherPlayer(p1ptr);
//isHuman
assert(p1ptr->isHuman());
assert(!p2ptr->isHuman());
//getSymbol
assert(p1ptr->getSymbol() == 'X');
assert(p2ptr->getSymbol() == 'O');
//getOtherPlayer/setOtherPlayer
assert(p1ptr->getOtherPlayer() == p2ptr);
assert(p2ptr->getOtherPlayer() == p1ptr);
//get/setShouldPickRandomly
assert(!p1ptr->getShouldPickRandomly());
assert(p2ptr->getShouldPickRandomly());
p2ptr->setShouldPickRandomly(false);
assert(!p2ptr->getShouldPickRandomly());
delete p1ptr;
delete p2ptr;
}
void testSpot()
{
Player* p1ptr = new HumanPlayer('X', 1);
Player* p2ptr = new AIPlayer('O',1);
Spot spot1(0, false, nullptr);
Spot spot2(0, false, nullptr);
//getIsTaken/setters
assert(!spot1.getIsTaken());
spot1.setIsTaken();
spot1.setTakenBy(p1ptr);
assert(spot1.getIsTaken());
//getTakenBy/setters
assert(spot2.getTakenBy() == nullptr);
spot2.setIsTaken();
spot2.setTakenBy(p2ptr);
assert(spot2.getTakenBy() == p2ptr);
//Spot==Spot
assert(!(spot1==spot2));
spot2.setTakenBy(p1ptr);
assert(spot1==spot2);
delete p1ptr;
delete p2ptr;
}
void testValidate()
{
Validate vldt;
//validateFirstPlayer
string firstPlayerInput = "wrong";
assert(vldt.validateFirstPlayer(firstPlayerInput) == vldt.getFirstPlayerFailToken());
firstPlayerInput = "3";
assert(vldt.validateFirstPlayer(firstPlayerInput) == vldt.getFirstPlayerFailToken());
firstPlayerInput = "1";
assert(vldt.validateFirstPlayer(firstPlayerInput) == 1);
firstPlayerInput = "2";
assert(vldt.validateFirstPlayer(firstPlayerInput) == 2);
//validateGameType
string gameTypeInput = "wrong";
assert(vldt.validateGameType(gameTypeInput) == vldt.getGameTypeFailToken());
gameTypeInput = "4";
assert(vldt.validateGameType(gameTypeInput) == vldt.getGameTypeFailToken());
gameTypeInput = "1";
assert(vldt.validateGameType(gameTypeInput) == 1);
gameTypeInput = "2";
assert(vldt.validateGameType(gameTypeInput) == 2);
gameTypeInput = "3";
assert(vldt.validateGameType(gameTypeInput) == 3);
//validateSymbols
string symbolsInput = "wrong";
assert(vldt.validateSymbols(symbolsInput) == vldt.getSymbolFailToken());
symbolsInput = "D >";
assert(vldt.validateSymbols(symbolsInput) == vldt.getSymbolFailToken());
symbolsInput = "D D";
assert(vldt.validateSymbols(symbolsInput) == vldt.getSymbolFailToken());
symbolsInput = "X O";
assert(vldt.validateSymbols(symbolsInput) == std::make_pair('X', 'O'));
Board board;
Player* p1ptr = new HumanPlayer('X', 1);
//validateMove
string moveInput = "wrong";
assert(vldt.validateMove(moveInput, board) == vldt.getMoveFailToken());
moveInput = "100";
assert(vldt.validateMove(moveInput, board) == vldt.getMoveFailToken());
moveInput = "0";
assert(vldt.validateMove(moveInput, board) == 0);
board.takeSpot(p1ptr, 0);
assert(vldt.validateMove(moveInput, board) == vldt.getMoveFailToken());
delete p1ptr;
}
int main()
{
testBoard();
cout << "Board functions passed!" << endl;
testCreatePlayers();
cout << "CreatePlayers functions passed!" << endl;
testInputOutput();
cout << "InputOutput functions passed!" << endl;
testPlayer(); //tests Player as well as AIPlayer and HumanPlayer
cout << "Player functions passed!" << endl;
testSpot();
cout << "Spot function passed!" << endl;
testValidate();
cout << "Validate function passed!" << endl;
cout << "ALL FUNCTIONS PASSED" << endl;
return 0;
}
| true |
167fe48134820edaf323b27db733d7484f69b869 | C++ | necros0/battletanks | /BattleTanks/Menu.cpp | UTF-8 | 1,100 | 2.984375 | 3 | [] | no_license | #include "Menu.h"
#include "Game.h"
#include "Vec2.h"
#include <iostream>
Menu::Menu(std::string title) :
mTitle(title, *Game::Font().get("resources/font/Ubuntu-M.ttf"), 50)
{
mTitle.setOrigin(Vec2(mTitle.getLocalBounds().width * 0.5f, mTitle.getLocalBounds().height * 0.5f));
Vec2 labelOrigin = Vec2(WINDOW_WIDTH * 0.5f, WINDOW_HEIGHT - MENU_TOP);
//labelOrigin.x = labelOrigin.x - (mTitle.getLocalBounds().width * 0.5f);
//labelOrigin.y = labelOrigin.y + (mTitle.getLocalBounds().height * 0.5f);
mTitle.setPosition(labelOrigin.toScreenVec());
}
Menu::~Menu(void)
{
while(!mItems.empty())
{
delete(mItems.back());
mItems.pop_back();
}
}
void Menu::addItem(MenuItem* item)
{
mItems.push_back(item);
}
float Menu::getNextItemHeight()
{
return WINDOW_HEIGHT - (mItems.size() * 70) - MENU_TOP - 150.0f;
}
void Menu::draw(sf::RenderTarget& target)
{
target.draw(mTitle);
for (auto it = mItems.begin(); it != mItems.end(); it++)
{
(*it)->draw(target);
}
}
void Menu::setActive(bool b)
{
for (auto it = mItems.begin(); it != mItems.end(); it++)
{
(*it)->setActive(b);
}
}
| true |
cee5fe9f7aa1a3d05ece9b96b70f0b90dd877e72 | C++ | MasterHoracio/Uva | /10013/10013.cpp | UTF-8 | 776 | 2.5625 | 3 | [] | no_license | #include <cstdio>
using namespace std;
int n1[1000000];
int n2[1000000];
int re[1500000];
int main()
{
int cases, len, carry, sum;
scanf("%d",&cases);
while(cases--){
scanf("%d",&len);
for(int i = 0; i < len; i++)
scanf("%d %d",&n1[i],&n2[i]);
carry = 0;
for(int i = len - 1; i >= 0; i--){
sum = n1[i] + n2[i] + carry;
if(sum > 9){
re[i] = sum % 10;
carry = 1;
}else{
re[i] = sum;
carry = 0;
}
}
for(int i = 0; i < len; i++)
printf("%d",re[i]);
printf("\n");
if(cases != 0)
printf("\n");
}
return 0;
}
| true |
9a9628268f2e393852ff61f671ae5f2b83993134 | C++ | Elendeer/homework | /operating_system/process_scheduling_algorithm/round_robin_scheduling.cpp | UTF-8 | 4,676 | 3.421875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <list>
using namespace std;
// ===== =====
class Process {
private:
string _name;
int _arrival_time, _served_time, _priority;
// _time_tarting = -1 by default, means haven't start yet.
int _time_remaining, _time_starting;
public:
Process(string name,
int arrival_time, int served_time, int priority);
~Process();
// Return true if the process is end.
bool isEnd();
// Schedule this process.
// Return -1 if schedule is not succeed (already end).
// Return the actual schedule time if succeed.
// e.g.
// _time_remaining = 1
// schedule(3);
// will return 1;
int schedule(int schedule_time);
string getName() const;
int getArrivalTime() const;
int getPriority() const;
int getStartTime() const;
int getServedTime() const;
void setStartTime(int start_time);
void print() const;
};
Process::Process(string name,
int arrival_time, int served_time, int priority) :
_name(name),
_arrival_time(arrival_time),
_served_time(served_time),
_priority(priority) {
_time_remaining = _served_time;
_time_starting = -1;
}
Process::~Process() {}
bool Process::isEnd() {
if (_time_remaining) return false;
return true;
}
int Process::schedule(int schedule_time) {
if (isEnd()) return -1;
if (schedule_time <= _time_remaining) {
_time_remaining -= schedule_time;
return schedule_time;
}
else {
int tmp = _time_remaining;
_time_remaining = 0;
return tmp;
}
}
string Process::getName() const {
return _name;
}
int Process::getArrivalTime() const {
return _arrival_time;
}
int Process::getPriority() const {
return _priority;
}
int Process::getStartTime() const {
return _time_starting;
}
int Process::getServedTime() const {
return _served_time;
}
void Process::setStartTime(int start_time) {
_time_starting = start_time;
}
void Process::print() const {
cout << "Process name: " << _name
<< "\tarrival time: " << _arrival_time
<< "\tserved time: " << _served_time
<< "\tstarting time: " << _time_starting;
}
// ===== =====
class Processor {
private:
// start from 0.
int _current_time;
// sor by arrival time.
list<Process> _coming_list;
list<Process> _processing_list;
public:
Processor();
~Processor();
// Return true if all lists are empty.
bool isEmpty();
void push(Process process);
// Run the processor;
void run();
};
Processor::Processor() : _current_time(0) {}
Processor::~Processor() {}
bool Processor::isEmpty() {
if (_coming_list.empty() &&
_processing_list.empty()) return true;
return false;
}
void Processor::push(Process process) {
_coming_list.push_back(process);
_coming_list.sort([](Process p1, Process p2) {
return p1.getArrivalTime() < p2.getArrivalTime();
});
}
void Processor::run() {
while (!isEmpty()) {
// add to processing list by time.
if (_current_time == _coming_list.front().getArrivalTime()) {
Process p = _coming_list.front();
p.setStartTime(_current_time);
_processing_list.push_back(p);
_coming_list.erase(_coming_list.begin());
}
if (!_processing_list.empty()) {
Process p = _processing_list.front();
_processing_list.erase(_processing_list.begin());
int time = p.schedule(1);
cout << "t : " << _current_time << "schedule : " << p.getName() << endl;
// haven't end
if (time != -1) {
_current_time += 1;
}
else {
p.print();
int t = p.getStartTime();
int turnaround_time = _current_time - t;
double powered_turnaround_time = turnaround_time / p.getServedTime();
cout << "\tfinishing time: " << _current_time
<< "\tturnaround time: " << turnaround_time
<< "\tpowered turnaround time: " << powered_turnaround_time
<< endl;
continue;
}
// add to processing list by time.
if (_current_time == _coming_list.front().getArrivalTime()) {
Process p = _coming_list.front();
p.setStartTime(_current_time);
_processing_list.push_back(p);
_coming_list.erase(_coming_list.begin());
}
time = p.schedule(1);
// haven't end
if (time != -1) {
_processing_list.push_back(p);
_current_time += 1;
}
else {
p.print();
int t = p.getStartTime();
int turnaround_time = _current_time - t;
double powered_turnaround_time = turnaround_time / p.getServedTime();
cout << "\tfinishing time: " << _current_time
<< "\tturnaround time: " << turnaround_time
<< "\tpowered turnaround time: " << powered_turnaround_time
<< endl;
}
}
}
}
// ===== =====
// ===== =====
// ===== =====
int main() {
Processor p;
p.push({"A", 0, 5, 12});
p.push({"B", 1, 3, 31});
p.push({"C", 2, 2, 21});
p.push({"D", 3, 1, 10});
p.run();
return 0;
} | true |