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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
bf8377b144a8200f4d142d02d61f87e8cd9e0bd5 | C++ | priyananda/projects | /pixelx/src/PxPhysics/src/PxVector4d.cpp | UTF-8 | 2,016 | 3 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////////////////////
// PxVector4d.cpp
// Function definitions for 4d vector class
// You may use this code however you wish, but if you do, please credit me and
// provide a link to my website in a readme file or similar
// Downloaded from: www.paulsprojects.net
// Created: 20th July 2002
// Modified: 15th August 2002 - prevent divide by zero in operator PxVector()
// Modified: 8th November 2002 - Changed Constructor layout
// - Some speed Improvements
// - Corrected Lerp
//////////////////////////////////////////////////////////////////////////////////////////
#include "PxVector4d.h"
void PxVector4d::RotateX(double angle)
{
(*this)=GetRotatedX(angle);
}
PxVector4d PxVector4d::GetRotatedX(double angle) const
{
PxVector v3d(x, y, z);
v3d.RotateX(angle);
return PxVector4d(v3d.x, v3d.y, v3d.z, w);
}
void PxVector4d::RotateY(double angle)
{
(*this)=GetRotatedY(angle);
}
PxVector4d PxVector4d::GetRotatedY(double angle) const
{
PxVector v3d(x, y, z);
v3d.RotateY(angle);
return PxVector4d(v3d.x, v3d.y, v3d.z, w);
}
void PxVector4d::RotateZ(double angle)
{
(*this)=GetRotatedZ(angle);
}
PxVector4d PxVector4d::GetRotatedZ(double angle) const
{
PxVector v3d(x, y, z);
v3d.RotateZ(angle);
return PxVector4d(v3d.x, v3d.y, v3d.z, w);
}
void PxVector4d::RotateAxis(double angle, const PxVector & axis)
{
(*this)=GetRotatedAxis(angle, axis);
}
PxVector4d PxVector4d::GetRotatedAxis(double angle, const PxVector & axis) const
{
PxVector v3d(x, y, z);
v3d.RotateAxis(angle, axis);
return PxVector4d(v3d.x, v3d.y, v3d.z, w);
}
PxVector4d operator*(float scaleFactor, const PxVector4d & rhs)
{
return rhs*scaleFactor;
}
bool PxVector4d::operator==(const PxVector4d & rhs) const
{
if(x==rhs.x && y==rhs.y && z==rhs.z && w==rhs.w)
return true;
return false;
}
PxVector4d::operator PxVector()
{
if(w==0.0f || w==1.0f)
return PxVector(x, y, z);
else
return PxVector(x/w, y/w, z/w);
}
| true |
b9e5e2790d1baf0ade4358c60895d9af280f352e | C++ | Akrakas/Custom_Neural_Network | /Sources/Database_class.cpp | UTF-8 | 627 | 2.859375 | 3 | [] | no_license | #include "Database_class.h"
Database_class::Database_class()
{
Sequences = NULL;
}
Database_class::~Database_class()
{
if(Sequences!=NULL){
for(int i=0 ; i<number_of_categories ; i++)
{
for(int j=0 ; j<number_of_sequences ; j++)
{
Sequences[i][j].~Sequence();
}
free(Sequences[i]);
}
free(Sequences);
Sequences = NULL;
}
}
void Database_class::Clear_Database()
{
if(Sequences!=NULL){
for(int i=0 ; i<number_of_categories ; i++)
{
for(int j=0 ; j<number_of_sequences ; j++)
{
Sequences[i][j].~Sequence();
}
free(Sequences[i]);
}
free(Sequences);
Sequences = NULL;
}
}
| true |
0332a4c7df17f21b88390f4c2ff094a26e411d46 | C++ | tsintermax/algorithms_and_data_structures | /cpp/mergsort.cpp | UTF-8 | 1,390 | 3.578125 | 4 | [] | no_license | #include<stdio.h>
#include <cstdlib>
#define ARRAY_LENGTH(array) (sizeof(array) / sizeof(array[0]))
void merge(int array[],int start, int partition, int end){
int i = start;
int j = partition + 1;
int index_sorted = start;
int tmp_arr[end - start];
while (i <= partition && j <= end )
{
if( j > end){
tmp_arr[index_sorted] = array[i];
i++;
index_sorted++;
}
else if( i > partition ){
tmp_arr[index_sorted] = array[j];
j++;
index_sorted++;
}else if(array[i] <= array[j]){
tmp_arr[index_sorted] = array[i];
i++;
index_sorted++;
}else{
tmp_arr[index_sorted] = array[j];
j++;
index_sorted++;
};
}
for ( i = start; i <= end; i++)
{
array[i] = tmp_arr[i];
}
}
void mergesort(int array[],int start, int end){
int partition = (start + end) / 2;
if (start < end)
{
mergesort(array,start,partition);
mergesort(array,partition + 1,end);
merge(array,start,partition,end);
};
}
int main(void) {
int array[] = {3,2,6,5,4,9,8,3};
int array_length = ARRAY_LENGTH(array);
mergesort(array,0,array_length);
for(int i=0;i<array_length;++i){
printf("%d\n", array[i]);
}
return 0;
} | true |
d4a36701f3bcf6b9ed07cbe34e9ca5931e34e77f | C++ | tangodown1934/Algorithm-judge | /20150710/locker.cpp | UHC | 800 | 2.796875 | 3 | [] | no_license | /*
VC, GCC
*/
#include <stdio.h>
int main()
{
int itr;
int nCount; /* Ʈ ̽ */
int n, k;
int i, j, mul, temp;
int locker[100];
scanf("%d", &nCount); /* Ʈ ̽ Է */
for (itr = 0; itr<nCount; itr++)
{
printf("#testcase%d\n", itr + 1);
scanf("%d %d", &n, &k);
for (i = 0; i < 100; i++){
locker[i] = 1;
}
for (i = 2; i <= n; i++){
j = i;
mul = 1;
temp = j*mul;
while (temp-1 < 100){
locker[temp-1] = !locker[temp-1];
// printf("count i : %d / j : %d, mul : %d, locker[%d] : %d\n", i, j, mul, temp-1, temp);
mul++;
temp = j*mul;
}
// printf("\n");
}
printf("%d\n", locker[k-1]);
}
// system("pause");
return 0; /* ݵ return 0 ּžմϴ. */
} | true |
7ef853f6ef0d108be03819475537964db15f0ccb | C++ | jeremtop/CatchMe | /Catch_me.cpp | UTF-8 | 13,820 | 3.296875 | 3 | [] | no_license | /**
* \file Catch_me.cpp
* \author Mathis Garcia, Arnaud Sanchez, Jérémy Topalian, Loïc Vigne.
* \version 2.0
* \date 17 Decembre 2013
* \brief Jeu "Catch me if you can".
*
*/
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <utility>
#include <cstdlib>
#include <fstream>
using namespace std;
/** \namespace catch_me
*
* namespace grouping tools components
* game's gameplay
*/
namespace catch_me
{
typedef vector <char> CVLine; /** \typedef Vector \brief a type representing a row of the matrix */
typedef vector <CVLine> CMatrix; /** \typedef \brief Vector: a type representing the matrix */
typedef pair <unsigned, unsigned> CPosition; /** \typedef \brief pair: a type representing a position in the matrix */
const string KReset ("0"); /** \fn \brief String: a type to return to the original color */
const string KRouge ("31"); /** \fn \brief String: a type to set a string in red */
const string KVert ("32"); /** \fn \brief String: a type to set a string in green */
const string KJaune ("33"); /** \fn \brief String: a type to set a string in jaune */
const string KBleu ("34"); /** \fn \brief String: a type to set a string in bleu */
const char KTokenPlayer1 = 'X'; /** \var \brief Char: a type representing the red player */
const char KTokenPlayer2 = 'O'; /** \var \brief Char: a type representing the blue player */
const char KEmpty = ' '; /** \var \brief Char: a type representing empty squares */
const char KWall = '#'; /** \var \brief Char: a type representing walls */
const char KFood = 'f'; /** \var \brief Char: a type representing food */
unsigned scorebleu=0; /** \var \brief a type representing the blue player score */
unsigned scorerouge=0; /** \var \brief a type representing the red player score */
/**
* \fn ClearScreen ()
* \brief function to clear the display
*/
void ClearScreen ()
{
cout << "\033[H\033[2J";
}//ClearScreen()
/**
* \fn Couleur (const string & coul)
* \brief function to change the color of the display.
*
*\param coul : Colors
*/
void Couleur (const string & coul)
{
cout << "\033[" << coul <<"m";
}//Couleur()
/**
* \fn InitMat(CMatrix & Mat, unsigned Msize)
* \brief function to create the map where the game take place.
*
*\param Mat : Matrix
*\param Msize : Size of the matrix
*/
void InitMat(CMatrix & Mat, unsigned Msize)
{
srand(time(NULL));
Mat.resize(Msize);
for(unsigned i=0;i<Msize;++i)
{
Mat[i].resize(Msize);
}
for(unsigned i=0;i<Mat.size();++i)
{
for(unsigned j=0;j<Mat.size();++j)
{
Mat[i][j]=KEmpty;
}
}
//wall generation
for(unsigned i=0;i<(Mat.size()/3)+1;++i)
{
Mat[i][Msize/2]=KWall;
}
for(unsigned i=0;i<Mat.size()/3;++i)
{
Mat[Msize/4][i]=KWall;
}
Mat[1][Msize-2]=KWall;
for(unsigned i=0;i<Mat.size()/4;++i)
{
Mat[Msize/2-1][i]=KWall;
}
for(unsigned i=0;i<(Mat.size()/2)+1;++i)
{
Mat[Msize-1][i]=KWall;
}
Mat[Msize/2][Msize-2]=KWall;
Mat[Msize/2+1][Msize/2-1]=KWall;
Mat[Msize/2+1][Msize-2]=KWall;
Mat[(Msize/2)+1][(Msize/3)-1]=KWall;
//fin wall generation
for(unsigned i=0;i<Mat.size();++i)
{
for(unsigned j=0;j<Mat.size();++j)
{
unsigned rando=rand() %8;
if(rando == 0 && Mat[i][j] != KWall)
{
// Mat[i][j]=KFood;
}
}
}
}//InitMat()
/**
* \fn ShowMat (CMatrix & Mat, pair<unsigned,unsigned> PosRouge, pair<unsigned,unsigned> PosBleu)
* \brief function used to display the matrix who is composed by players, food, walls and empty squares.
*
*\param Mat : Matrix
*\param PosRouge : Red Player position
*\param PosBleu : Blue Player position
*/
void ShowMat (CMatrix & Mat, pair<unsigned,unsigned> PosP1, pair<unsigned,unsigned> PosP2)
{
ClearScreen();
for(unsigned i=0;i<Mat.size();++i)
{
for(unsigned j=0;j<Mat.size();++j)
{
if(i==PosP1.first && j==PosP1.second)
{
Couleur(KRouge);
Mat[i][j]=KTokenPlayer1;
}
else if(i==PosP2.first && j==PosP2.second)
{
Couleur(KBleu);
Mat[i][j]=KTokenPlayer2;
}
else if(Mat[i][j]==KFood)
{
Couleur(KJaune);
}
else if(Mat[i][j]==KWall)
{
Couleur(KVert);
}
else
{
Couleur(KReset);
}
cout<<setw(4)<<'['<<Mat[i][j]<<']';
}
Couleur(KReset);
cout<<endl<<endl<<endl;
}
}//ShowMat()
/**
* \fn NoFood(CMatrix & Mat)
* \brief function to know if there are food.
*
*\param Mat : Matrix
*/
bool NoFood(CMatrix & Mat)
{
unsigned ComptFood = 0;
for(;;)
{
for(unsigned i=0;i<Mat.size();++i)
{
for(unsigned j=0;j<Mat.size();++j)
{
if (Mat[i][j]==KFood)
ComptFood = ComptFood+1;
}
}
if (ComptFood==0)
{
cout<< "Il n'y a plus de petits pains. Le joueur ";
Couleur(KRouge);
cout<< "rouge ";
Couleur(KReset);
cout<< "gagne la partie."<<endl<<endl;
// affichage score
scorerouge=scorerouge+1;
cout<<"Score :"<<endl;
cout<<"Joueur";
Couleur(KBleu);
cout<< " bleu ";
Couleur(KReset);
cout<< ":" << scorebleu <<endl;
cout<<"Joueur";
Couleur(KRouge);
cout<< " rouge ";
Couleur(KReset);
cout<< ":" << scorerouge <<endl<<endl;
// affichage options
cout<<"Tapez Q pour quitter."<<endl;
cout<<"Tapez R pour recommencer."<<endl;
return true;
break;
}
else return false;
}
}//NoFood()
/**
* \fn MoveToken(CMatrix & Mat,char & Move, CPosition & Pos, unsigned Msize)
* \brief Function used to move your token in different directions
*
*\param Mat : Matrix
*\param Move : Movemement
*\param Pos : Position
*\param Msize : Size of the matrix
*
*Z: The token moves one square up
*S: The token moves one square down
*Q: The token moves one space to the left
*D: The token moves one space to the right
* Note: If a token attempts to exit the map, an error message appears
*/
void MoveToken(CMatrix & Mat,char & Move, CPosition & Pos, unsigned Msize)
{
unsigned P1=get<0>(Pos);// ancienne position
unsigned P2=get<1>(Pos);// ancienne position
while(true)
{
cin>>Move;
Move=toupper(Move);
switch (Move)
{
case 'Z':
if(Mat[Pos.first] != Mat[0])
{
if (Mat[Pos.first-1][Pos.second]!=KWall)
{
--Pos.first;
break;
}
}
else
cout<<"Erreur, restez dans la carte."<<endl;
continue;
case 'S':
if(Mat[Pos.first] != Mat[Msize-1])
{
if (Mat[Pos.first+1][Pos.second]!=KWall)
{
++Pos.first;
break;
}
}
else
cout<<"Erreur, restez dans la carte."<<endl;
continue;
case 'Q':
if(Mat[Pos.first][Pos.second] != Mat[Pos.first][0])
{
if (Mat[Pos.first][Pos.second-1]!=KWall)
{
--Pos.second;
break;
}
}
else
cout<<"Erreur, restez dans la carte."<<endl;
continue;
case 'D':
if(Mat[Pos.first][Pos.second] != Mat[Pos.first][Msize-1])
{
if (Mat[Pos.first][Pos.second+1]!=KWall)
{
++Pos.second;
break;
}
}
else
cout<<"Erreur, restez dans la carte."<<endl;
continue;
default:
cout<<"Erreur, mouvement incorrect."<<endl;
continue;
}
break;
}
Mat[P1][P2]=KEmpty;//KEmpty sur l'ancienne position
}//MoveToken()
/**
* \fn Menu()
* \brief function used to display the menu.
*
*/
void Menu()
{
ifstream titre;
titre.open("./titre.txt");
if(titre) //Si le fichier existe
{
while(titre) //Tant qu'on n'est pas a la fin
{
string ligne;
getline(titre, ligne); //On lit une ligne
Couleur(KJaune);
cout << ligne << endl; //Et on l'affiche dans la console
Couleur(KReset);
}
}
else //Si le fichier n'existe pas
{
cout << "ERREUR: Le fichier n'est pas disponible." << endl;
}
cout<<"Bienvenue gamer, tu es sur le point de commencer une partie de \"CATCH ME IF YOU CAN !\" avec un autre être humain !"<<endl<<endl;
ifstream menu;
menu.open("./menu.txt");
if(menu)
{
while(menu)
{
string ligne;
getline(menu, ligne);
cout << ligne << endl;
}
}
else
{
cout << "ERREUR: Le fichier texte contenant le menu n'est pas disponible." << endl;
}
}// Menu()
/**
* \fn int Game(void)
* \brief function of the game.
*
*/
int Game(void)
{
CMatrix Mat;
unsigned Msize;
CPosition PosP1,PosP2;
char Move;
ifstream config;
config.open("./config.txt");
if(config)
{
string ligne;
unsigned temp;
unsigned temp2;
config>>ligne>>temp;
cout<<temp<<'*';
Msize=temp;//taille matrice du fichier
config>>ligne>>temp;
config>>ligne>>temp2;
if(temp==Msize || temp2==Msize)
//on peut ecrire postion 4 en prenant en compte que le vector commence a l'indice 0 ou on peut dire aussi 5 si l'on ne prend pas en compte que le vector commence a l'indice 0
{
temp=temp-1;
temp2=temp2-1;
}
PosP1=make_pair(temp,temp2);
config>>ligne>>temp;
config>>ligne>>temp2;
if(temp==Msize || temp2==Msize)
//on peut ecrire postion 4 en prenant en compte que le vector commence a l'indice 0 ou on peut dire aussi 5 si l'on ne prend pas en compte que le vector commence a l'indice 0
{
temp=temp-1;
temp2=temp2-1;
}
PosP2=make_pair(temp,temp2);
}
else
{
cout << "ERREUR: Le fichier config.txt n'est pas disponible." << endl;
}
InitMat(Mat,Msize);
ShowMat(Mat,PosP1,PosP2);
while(true)
{
//joueur rouge
if(NoFood(Mat) == true) break;
cout<<endl<<"Deplacez-vous joueur ";
Couleur(KRouge);
cout<<"rouge";
Couleur(KReset);
cout<<':'<<'\n';
MoveToken(Mat,Move,PosP1,Msize);
ShowMat(Mat,PosP1,PosP2);
// si les deux joueurs sont sur la même case, alors le joueur bleu gagne la partie
if (PosP1==PosP2)
{
cout<< "Le joueur ";
Couleur(KBleu);
cout<< "bleu ";
Couleur(KReset);
cout<< "gagne la partie."<<endl<<endl;
// affichage score
scorebleu=scorebleu+1;
cout<<"Score :"<<endl;
cout<<"Joueur";
Couleur(KBleu);
cout<< " bleu ";
Couleur(KReset);
cout<< ":" << scorebleu <<endl;
cout<<"Joueur";
Couleur(KRouge);
cout<< " rouge ";
Couleur(KReset);
cout<< ":" << scorerouge <<endl<<endl;
// affichage options
cout<<"Tapez Q pour quitter."<<endl;
cout<<"Tapez R pour recommencer."<<endl;
break;
}
//joueur bleu
if(NoFood(Mat) == true) break;
cout<<endl<<"Deplacez-vous joueur ";
Couleur(KBleu);
cout<<"bleu";
Couleur(KReset);
cout<<':'<<'\n';
MoveToken(Mat,Move,PosP2,Msize);
ShowMat(Mat,PosP1,PosP2);
if (PosP1==PosP2)
{
cout<< "Le joueur ";
Couleur(KBleu);
cout<< "bleu ";
Couleur(KReset);
cout<< "gagne la partie."<<endl<<endl;
// affichage score
scorebleu=scorebleu+1;
cout<<"Score :"<<endl;
cout<<"Joueur";
Couleur(KBleu);
cout<< " bleu ";
Couleur(KReset);
cout<< ":" << scorebleu <<endl;
cout<<"Joueur";
Couleur(KRouge);
cout<< " rouge ";
Couleur(KReset);
cout<< ":" << scorerouge <<endl<<endl;
// affichage options
cout<<"Tapez Q pour quitter."<<endl;
cout<<"Tapez R pour recommencer."<<endl;
break;
}
}
return 0;
}//game()
/**
* \fn int Run(void)
* \brief main function that runs when launching the game
*
* \return 0 - Normal program termination.
*/
int Run(void)
{
char NavMenu;
ifstream regles;
ifstream credit;
while(true)
{
ClearScreen();
Menu();
cin>>NavMenu;
switch (NavMenu)
{
case '1':
Game();
char option;
while(true)
{
cin>>option;
option=toupper(option);
if(option=='Q')
break;
else if(option=='R')
Game();
}
ClearScreen();
break;
case '2':
ClearScreen();
regles.open("./regles.txt");
if(regles) //Si le fichier existe
{
while(regles) //Tant qu'on n'est pas a la fin
{
string ligne;
getline(regles, ligne); //On lit une ligne
cout << ligne << endl; //Et on l'affiche dans la console
}
regles.close();
while(true)
{
cin>>NavMenu;
NavMenu=toupper(NavMenu);
if(NavMenu=='M')
{
ClearScreen();
break;
}
else
continue;
}
continue;
}
else //Si le fichier n'existe pas
{
cout << "ERREUR: Le fichier n'est pas disponible." << endl;
break;
}
case '3':
ClearScreen();
credit.open("./credit.txt");
if(credit) //Si le fichier existe
{
while(credit) //Tant qu'on n'est pas a la fin
{
string ligne;
getline(credit, ligne); //On lit une ligne
cout << ligne << endl; //Et on l'affiche dans la console
}
credit.close();
cout<<endl<<"Tapez M pour revenir au menu."<<endl;
while(true)
{
cin>>NavMenu;
NavMenu=toupper(NavMenu);
if(NavMenu=='M')
{
ClearScreen();
break;
}
else
continue;
}
continue;
}
else //Si le fichier n'existe pas
{
ClearScreen();
cout << "ERREUR: Le fichier n'est pas disponible." << endl;
break;
}
case '4':
ClearScreen();
break;
default:
cout<<"Erreur, saisissez une commande valable. (1,2,3,4)"<<endl;
continue;
}
break;
}
return 0;
}
}
/**
* \fn int main()
* \brief Program input.
*
* \return 1 - Program Bug.
* \return 0 - Normal program termination.
*/
int main()
{
try
{
return catch_me::Run();
}
catch(...)
{
cerr<<"bug"<<endl;
return 1;
}
return 0;
}//int main()
| true |
81c19fa612105ca4c452e1164e9dbde83c8f0d48 | C++ | karnkittik/AlgorithmDesign | /inversion.cpp | UTF-8 | 297 | 2.796875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int n;cin>>n;
int a[n];
for(int i=0;i<n;i++){
int x;cin>>x;
a[i]=x;
}
int inv = 0;
for(int i =0;i<n;i++){
for(int j=i+1;j<n;j++){
if(a[j]<a[i]) inv+=1;
}
}
cout<<inv;
} | true |
50ed915f17d02dccc2d605009bdceed3aeedc3db | C++ | DmytroHaponov/searchTextInWeb | /scannerinline.h | UTF-8 | 866 | 2.5625 | 3 | [] | no_license | #pragma once
#include <QObject>
#include <QRegularExpression>
namespace search {
class ScannerInLine
{
public:
explicit ScannerInLine(const QString& target_text);
/**
* @brief searches target text in a single line
* @param line in which search is implemented
* @return list of positions of found targets
*/
QStringList search_target_in_line(const QString& line);
/**
* @brief searches url pattern in a single line
* @param line in which search for URLs is implemented
* @return list of found URLs
*/
QStringList search_urls_in_line(const QString& line);
private:
//! regexp to search target text
QRegularExpression m_target_text_expr;
//! regexp to search URL
QRegularExpression m_url_expr;
//! pattern to search URL in text
static const QString url_pattern;
};
} //search
| true |
1369348fd73e852c8b16774e256155b62ceda3fc | C++ | again1943/zoj-solution | /src/1496.cpp | UTF-8 | 1,204 | 2.96875 | 3 | [] | no_license | #include<cstdio>
#include<utility>
#include<cstdlib>
#include<algorithm>
#include<numeric>
using namespace std;
#define PI 3.14159
int f[3];
int r[9];
double diameter,target;
#define eps 1e-10
inline double myabs( double t )
{
if( t > eps )
return t;
else if( t < -eps )
return -t;
else
return 0;
}
double do_work( int* f,int* r,double diameter,double target,pair<int,int>& ret )
{
int i,j;
double value;
double min_v = 10000000;
for( i = 0; i < 3; i++ )
for( j = 0; j < 9; j++ )
{
value = myabs(((double)f[i]/r[j])*diameter*PI-target);
if( min_v > value )
{
ret.first = f[i];
ret.second = r[j];
min_v = value;
}
}
return ((double)ret.first/ret.second)*diameter*PI;
}
int main()
{
int n,i,j;
double result;
pair<int,int> ret;
scanf("%d",&n);
for( i = 0; i < n; i++ )
{
if( i != 0 )
printf("\n");
for( j = 0; j < 3; j++ )
scanf("%d",&f[j]);
for( j = 0; j < 9; j++ )
scanf("%d",&r[j]);
scanf("%lf%lf",&diameter,&target);
result = do_work(f,r,diameter,target,ret);
printf("A gear selection of %d/%d produces a gear size of %0.3lf.\n",
ret.first,ret.second,result);
}
return 0;
}
| true |
72f6484198d65962f66c1c072e2ac39a17bb9db2 | C++ | comerje/PillarVendingAlt | /VendingAlternate/Display.cpp | UTF-8 | 604 | 2.578125 | 3 | [] | no_license |
#include "Display.h"
#include <iostream>
#include "MessageData.h"
void WriteToStdOut(std::string& msg)
{
std::cout << msg << std::endl;
}
Display::Display(AbstractConductor& machine)
:Component(machine),
DisplayCallback(&WriteToStdOut)
{
}
Display::~Display()
{
}
void Display::Notify(eNotifyMessageType msgType, MessageData* msg)
{
if(eNotifyMessageType::DisplayMessage == msgType)
{
std::auto_ptr<MessageData> data;
data.reset(msg);
HandleNotification(msg);
}
}
void Display::HandleNotification(MessageData* msg)
{
DisplayCallback(msg->m_message);
}
| true |
2be87346797275de0656f4a6e56e2a1dd7cfcc93 | C++ | monsterbasher/Multicraft | /Aurora/Aurora/System/touch/TouchSystemManager.h | UTF-8 | 1,411 | 2.546875 | 3 | [] | no_license | #ifndef TOUCHSYSTEMMANAGER_H
#define TOUCHSYSTEMMANAGER_H
#include <Aurora/System/SystemManager.h>
#include <Aurora/Math/Vector2.h>
#include <vector>
using namespace Key;
namespace Aurora
{
namespace System
{
class Touch
{
public:
int hash;
float positionX,positionY,previouspositionX,previouspositionY;
};
class TouchSystemManager : public SystemManager
{
private:
bool _keyStates[Key::Count];
std::vector<Touch> _touches;
bool virtualPads;
bool movePad;
int moveHash;
Math::Vector2 movePoint;
Math::Vector2 movePadPos;
bool rotatePad;
int rotateHash;
Math::Vector2 rotatePoint;
Math::Vector2 rotatePadPos;
public:
TouchSystemManager();
void Update();
bool keyPressed(Key::Code keyCode);
bool keyHold(Key::Code keyCode);
bool mouseButtonDown(Mouse::Button buttonNumber);
int getMouseX();
int getMouseY();
float getAnalogX();
float getAlanogY();
public:
void TouchesBegan(int hash,float x,float y);
void TouchesMoved(int hash,float newX,float newY,float lastX,float lastY);
void TouchesEnded(int hash,float x,float y);
};
}
}
#endif
| true |
3cda83214ed4f6a3e11d94610a3f67342b1eed1e | C++ | xiangbai/Homework | /08_IO/08_09/file_in.cpp | UTF-8 | 1,825 | 3.171875 | 3 | [] | no_license | /*************************************************************************
> File Name: file_in.cpp
> Author: wang
> Mail:xiangbai@qq.com
> Created Time: Sat 12 Apr 2014 07:05:27 PM CST
************************************************************************/
#include<iostream>
#include<string>
#include<vector>
#include<fstream>
#include<sstream>
#include<stdexcept>
void getwords(std::vector<std::string> &words , const std::string &line)
{
std::istringstream sin(line) ; //字符串流
std::string word ;
while(sin>>word)
{
words.push_back(word);
}
sin.clear();
}
int fileToVector(std::string filename , std::vector<std::string> &svec , std::vector<std::string> &words)
{
std::ifstream fin ;
fin.open(filename.c_str());
if(!fin)
{
return 1 ;
}
std::string line;
while(getline(fin , line))
{
svec.push_back(line);
getwords(words , line);
}
fin.close();
if(fin.eof())
{
return 4 ;
}
if(fin.bad())
{
return 2 ;
}
if(fin.fail())
{
return 3 ;
}
}
int main(int argc , char *argv[])
{
std::vector<std::string> svec ;
std::vector<std::string> words ;
std::string filename;
std::cout<<"Enter filename :"<<std::endl;
std::cin>>filename ;
int fileflag = fileToVector(filename,svec,words);
switch(fileflag)
{
case 1:
std::cout<<"error:can not open file: "<<filename<<std::endl ;
break ;
case 2:
std::cout<<"error system failturn"<<std::endl;
break;
case 3:
std::cout<<"error:read failure"<<std::endl;
break;
}
std::cout<<"Vector :" << std::endl;
for(std::vector<std::string>::iterator iter = svec.begin() ; iter != svec.end() ; ++iter)
{
std::cout<<*iter<<std::endl;
}
std::cout<<"words :"<<std::endl;
for(std::vector<std::string>::iterator iter = words.begin() ; iter != words.end() ; ++iter)
{
std::cout<<*iter<<std::endl;
}
return 0 ;
}
| true |
4130c68343bdfdcb0fed2c5e7a810f554e371f16 | C++ | shaaker-ma/Advanced-Programming | /CA 4/Task.cpp | UTF-8 | 648 | 2.84375 | 3 | [] | no_license | #include <string>
#include <vector>
#include "Task.hpp"
using namespace std;
Task::Task(string nameNew, unsigned int estimatedTimeNew, unsigned int priorityNew, string descriptionNew){
name = nameNew;
estimatedTime = estimatedTimeNew;
priority = priorityNew;
description = descriptionNew;
isDone= false;
isAssigned = false;
}
void Task::updateTaskFeatures(unsigned int estimatedTimeNew, unsigned int priorityNew, string descriptionNew){
estimatedTime = estimatedTimeNew;
priority = priorityNew;
description = descriptionNew;
}
void Task::updateStatusToDone(){
isDone= true;
}
void Task::updateToAssigned(){
isAssigned = true;
}
| true |
e7113ae9df01e15bb615aa675054d61f7c7d4b0a | C++ | nschaech/nickschaecher_comp2 | /NODE.h | UTF-8 | 4,595 | 3.953125 | 4 | [] | no_license | #ifndef NODE
#define NODE
#include <iostream>
using namespace std;
//binary node template class to create binaryNodes
template<class T>
class binaryNode {
public:
T data;
binaryNode<T >*left;
binaryNode<T> *right;
binaryNode(T d)
:data(d),left(nullptr),right(nullptr){}
};
//binarySearhtree class to initialize binaryNodes and add the needed functions
template<class T>
class binarySearchTree {
private:
binaryNode<T>* root;
int numberOfNodes;
//insert function
void insert(T item, binaryNode<T>*& t)
{
//Insert nodes at the edge of the list
if (t == nullptr)
{
t = new binaryNode<T>(item);
numberOfNodes++;
}
//traverse list by comparing the new item with a given item
//if the new item is less the given item traverse left
else if (item < t->data)
{
insert(item, t->left);
}
//if the new item is greater than the given item traverse right
else if (item > t->data)
{
insert(item, t->right);
}
}
//find functions
binaryNode<T>* find(T item, binaryNode<T>* t, long long int& compare)
{
//If the item is not found return nullptr
if (t == nullptr)
{
return nullptr;
}
//traverse list by recursively calling find function like in insert to determine where the item is
else if (item < t->data)
{
compare++;
return find(item, t->left,compare);
}
else if (item > t->data)
{
compare++;
return find(item, t->right,compare);
}
//if item when compared is not greater or less than the checked data the item must be equal to the data being checked.
else
{
compare++;
return t;
}
}
//function to traverse a list and delete along the way
void elements(T &data)
{
//if the list is empty return
if (root->left == nullptr)
{
return;
}
else
{
//top node is what is returned
data = root->left->data;
//remove top node to get anothe node in the list to return
remove(root->left->data,root->left);
return;
}
}
public:
//constructor to set initial value to root
binarySearchTree() : root(nullptr), numberOfNodes(0) {}
//destructor needed to deallocate allocated memory
~binarySearchTree() {
clear(root->left);
}
//Find min function traverses the binary tree to the far left to find the least valuable element
binaryNode<T>* findMin(binaryNode<T>* t)
{
if (t == nullptr)
{
return nullptr;
}
else if (t->left == nullptr)
{
return t;
}
return findMin(t->left);
}
//remove function deallocates a given node
void remove(T item, binaryNode<T> *&t)
{
//traverse binary tree
if (t == nullptr)
{
return;
}
if (item < t->data)
{
remove(item, t->left);
}
else if (item > t->data)
{
remove(item, t->right);
}
else
{
binaryNode<T>* oldNode;
//if the node to the left of the node to be removed is a nullptr set node that will replace the deleted node to the right node
if (t->left == nullptr)
{
oldNode = t;
t = t->right;
delete oldNode;
numberOfNodes--;
return;
}
//If right node to the node to be deleted is nullptr set the node to replace the deleted node to the left node of the deleted node
else if (t->right == nullptr)
{
oldNode = t;
t = t->left;
delete oldNode;
numberOfNodes--;
return;
}
//Set the node to replace the deleted node to the minimum node if none of the above conditions is true
oldNode = findMin(t->right);
t->data = oldNode->data;
//recursively call this function to meet a condition that will delete the node that is desired to be deleted
remove(t->data, t->right);
}
}
//public insert to call private insert since only the element of type T is being passed in cpp
void insert(T item)
{
insert(item, root);
}
//public find for compars that are passed and given item called in cpp
binaryNode<T>* find(T item,long long int& compare)
{
return find(item, root,compare);
}
//clear function to deallocate memory upon when the desctructor is called
void clear(binaryNode<T>* t)
{
if (t == nullptr)
{
return;
}
else {
clear(t->left);
clear(t->right);
delete(t);
numberOfNodes--;
}
}
//T elements returns data at the given top node of the binary tree
T elements()
{
T data;
elements(data);
return data;
}
//int get size returns teh number of nodes in the tree which was iterated in insert function above.
int getNumberOfNodes() { return numberOfNodes; }
};
#endif
| true |
cdc4ace92b661ed9813a79bfedc5e6e79fea3850 | C++ | AbrahamFB/Programaci-n-en-C-B-sico---Intermedio---Avanzado- | /Funciones/Ejercicio22.cpp | UTF-8 | 410 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <conio.h>
using namespace std;
int escribeNum(int ini, int fin){
if(ini == fin){
return ini;
}
else{
return escribeNum(ini, fin-1);
}
}
int main(){
int ini, fin;
cout << "Ingresa un Inicio:" << endl;
cin >> ini;
cout << "Ingresa un Final:" << endl;
cin >> fin;
for(int i = ini; i <= fin; i++){
cout << escribeNum(i, fin) << " ";
}
getch();
return 0;
}
| true |
ec9740bc418eb951f68a26b4372dad63ebdf860d | C++ | SpeedZhang/1071-C-Progrmming | /w012/3%knightTour.cpp | UTF-8 | 3,378 | 3.265625 | 3 | [] | no_license | #include<stdio.h>
struct Pos
{
int row;
int col;
};
Pos KnightTour(int access[][8],int row,int col)
{
Pos pos;
int min=9;
int minrow=-1,mincol=-1,nextrow,nextcol;
int h[8]= {2,1,-1,-2,-2,-1,1,2};
int v[8]= {-1,-2,-2,-1,1,2,2,1};
access[row][col]=0;
for(int i=0; i<8; i++)
{
nextrow=row+v[i];
nextcol=col+h[i];
if(nextrow>=0 && nextrow<=7 && nextcol>=0 && nextcol<=7 && access[nextrow][nextcol]>0)
{
access[nextrow][nextcol]--;
if(access[nextrow][nextcol]<min)
{
min=access[nextrow][nextcol];
minrow=nextrow;
mincol=nextcol;
}
}
}
pos.row=minrow;
pos.col=mincol;
return pos;
}
void prArr(int m[][8])
{
for(int i=0;i<8;i++)
{
printf("|---|---|---|---|---|---|---|---|\n");
for(int j=0;j<8;j++)
{
printf("%c%3d",'|',m[i][j]);
}
printf("%c\n",'|');
}
printf("|---|---|---|---|---|---|---|---|\n");
}
void prArrTwo(int n[][8])
{
for(int i=0;i<8;i++)
{
printf("|---|---|---|---|---|---|---|---|\n");
for(int j=0;j<8;j++)
{
printf("%c%3d",'|',n[i][j]);
}
printf("%c",'|');
printf("\n");
}
printf("|---|---|---|---|---|---|---|---|\n");
}
int main()
{
Pos pos;
int choice,m[8][8]={0};
int row,col,moves=1;
int n[8][8]={0};
int access[8][8]=
{
2, 3, 4, 4, 4, 4, 3, 2,
3, 4, 6, 6, 6, 6, 4, 3,
4, 6, 8, 8, 8, 8, 6, 4,
4, 6, 8, 8, 8, 8, 6, 4,
4, 6, 8, 8, 8, 8, 6, 4,
4, 6, 8, 8, 8, 8, 6, 4,
3, 4, 6, 6, 6, 6, 4, 3,
2, 3, 4, 4, 4, 4, 3, 2
};
while(choice!=3)
{
printf("1. Knight Tour by entering position\n");
printf("2. Check 64 cases\n");
printf("3. Exit\n");
printf("=> choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
moves=1;
printf("Enter row and col for number 1:");
scanf("%d %d",&row,&col);
m[row][col]=1;
printf("The board for this test is:\n");
for(int i=2;i<=64;i++)
{
pos=KnightTour(access,row,col);
row=pos.row;
col=pos.col;
m[row][col]=i;
moves++;
}
prArr(m);
printf("The tour ended with %d moves.\n",moves);
printf("This was a full tour!\n");
break;
case 2:
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
moves=1;
row=i;
col=j;
for(int k=1; k<64; k++)
{
m[row][col]=k;
pos=KnightTour(access,row,col);
moves++;
row=pos.row;
col=pos.col;
}
if(moves==64)
{
n[i][j]=64;
}
else
{
n[i][j]=0;
}
}
}
prArrTwo(n);
break;
}
}
return 0;
}
| true |
1c485221f94e9b617861eea7d1d9d80ee508d43d | C++ | ElexandroTorres/hashTable | /include/hashtbl.h | UTF-8 | 11,482 | 3.5 | 4 | [] | no_license | /*
* Autoria: Elexandro Torres Tavares
* T.I, 2019.
*/
#ifndef HASHTBL_H
#define HASHTBL_H
#include <forward_list>
#include <cmath>
// Namespace
namespace ac {
/// Classe HashEntry. Representa um item de tabela.
template<class KeyType, class DataType>
class HashEntry {
public:
KeyType m_key; //<! Amazena uma chave para uma entrada.
DataType m_data; //<! Armazena o dado para uma entrada.
/// Construtor padrão.
HashEntry() {/* Vazio*/}
/// Construtor com inicialização.
HashEntry(KeyType key_, DataType data_) : m_key(key_), m_data(data_) {/* Empty */}
};
/// Classe HashTbl
template<typename KeyType, typename DataType, typename KeyHash = std::hash<KeyType>, typename KeyEqual = std::equal_to<KeyType>>
class HashTbl {
public:
// Definições de tipo:
using Entry = HashEntry<KeyType, DataType>;
// Construtores:
/*!
* Construtor padrão. Caso não informado o tamanho a tabela será iniciada com o tamanho "DEFAULT_SIZE".
*/
HashTbl(size_t tbl_size_ = DEFAULT_SIZE) {
m_tableSize = nextPrime(tbl_size_); // Define o tamanho da tabela como sendo o primo >= a tbl_size.
m_data_table = new std::forward_list<Entry>[m_tableSize]; // Cria uma tabela de listas encadeadas.
}
/*!
* Construtor copia.
*/
HashTbl(const HashTbl &other) {
m_tableSize = other.m_tableSize;
m_count = other.m_count;
m_data_table = new std::forward_list<Entry>[m_tableSize]; // Cria uma tabela de listas encadeadas.
// Copiar todas as listas para a nova tabela.
for(auto i = 0u; i < m_tableSize; i++) {
m_data_table[i] = other.m_data_table[i];
}
}
/*!
* Construtor a partir de outra lista.
*/
HashTbl(std::initializer_list<Entry> ilist) {
m_tableSize = nextPrime(ilist.size());
m_data_table = new std::forward_list<Entry>[m_tableSize]; // Cria uma tablea de listas encadeadas.
// Inserir cada item da lista inicializadora na tabela.
for(auto it = ilist.begin(); it != ilist.end(); it++) {
insert(it->m_key, it->m_data);
}
}
/*!
* Destrutor.
*/
virtual ~HashTbl() {
delete[] m_data_table;
}
/*!
* Operador de atribuição a partir de outra tabela.
*/
HashTbl &operator=(const HashTbl &other) {
//antes limpar a lista caso ela tenha elementos.
if(this->m_count > 0) {
clear();
}
m_tableSize = other.m_tableSize;
m_count = other.m_count;
delete[] m_data_table;
m_data_table = new std::forward_list<Entry>[m_tableSize]; // Cria uma tablea de listas encadeadas.
// Copiar todas as listas para a nova tabela.
for(auto i = 0u; i < m_tableSize; i++) {
m_data_table[i] = other.m_data_table[i];
}
return *this;
}
/*!
* Operador de atribuição a partir de uma lista inicializadora.
*/
HashTbl &operator=(std::initializer_list<Entry> ilist) {
if(this->m_count > 0) {
clear();
}
m_tableSize = nextPrime(ilist.size());
delete[] m_data_table;
m_data_table = new std::forward_list<Entry>[m_tableSize];
//inserir os novos itens na lista.
for(auto it = ilist.begin(); it != ilist.end(); it++) {
insert(it->m_key, it->m_data);
}
return *this;
}
/*!
* Insere um novo elemento na tabela. Caso a chave ja esteja na tabela, subistituir o valor associado a ela.
* @param k_ Chave do novo elemento.
* @param d_ Dado associado a chave.
* @return true caso seja possivel inserir o novo elemento e false caso contrario.
*/
bool insert(const KeyType &k_, const DataType &d_) {
Entry new_entry(k_, d_); // Cria um novo item de tabela com os valores passados.
auto address(hashFunc(k_) % m_tableSize); // Calcula o endereço a qual o valor será adicionado.
// Varrer toda a lista para verificar se há algum item com a mesma chave.
for(auto it = m_data_table[address].begin(); it != m_data_table[address].end(); it++) {
// Caso encontre algum item com a mesma chave faz a substuição do dado associado a ela.
if(equalFunc(new_entry.m_key, it->m_key)) {
it->m_data = d_;
return false;
}
}
// Verifica o fator para caso seja necessario de uma tabela com mais espaços.
if((m_count/m_tableSize) > 1) {
rerash();
address = hashFunc(k_) % m_tableSize; // Calcula o endereço a qual o valor será adicionado.
}
// Caso seja a primeira vez de um item com essa chave, inserir ele na tabela.
m_data_table[address].push_front(new_entry);
++m_count;
return true;
}
bool erase(const KeyType &k_) {
auto address(hashFunc(k_) % m_tableSize); // Calcula o endereço a qual o valor será removido.
auto it = m_data_table[address].begin();
// Caso especial, lista vazia.
if(it == m_data_table[address].end()) {
return false;
}
// Caso especial, para caso o item removido seja o primeiro elemento.
if(equalFunc(k_, it->m_key)) {
m_data_table[address].erase_after(m_data_table[address].before_begin());
--m_count; // Diminuí a quantidade de elementos presentes na tabela.
return true;
}
auto itPrev = it; // Posição anterior ao it para nos permitir fazer a inserção.
it++; // Avança o iterator.
// Verificar o resto da lista.
while(it != m_data_table[address].end()) {
// Caso encontre um item com a mesma chave, iremos remove-lo.
if(equalFunc(k_, it->m_key)) {
m_data_table[address].erase_after(itPrev); // Remove o elemento após o itPrev, ou seja, o que achamos a igualdade entre as chaves.
--m_count;
return true;
}
++itPrev; // ItPrev sempre vai está uma posição antes do it para assim permitir a inserção.
++it;
}
return false;
}
/*!
* Dado uma chave verifica o elemento associado a ela e o atribui a uma variavel.
* @param k_ Chave para o elemento.
* @param d_ Referencia para onde será armazenado o valor associado a chave.
* @return true caso estejam associados e false caso contrario.
*/
bool retrieve(const KeyType &k_, DataType &d_) const {
auto address(hashFunc(k_) % m_tableSize);
for(auto it = m_data_table[address].begin(); it != m_data_table[address].end(); it++) {
if(equalFunc(k_, it->m_key)) {
d_ = it->m_data;
return true;
}
}
return false;
}
/*!
* Limpa a tabela, liberando o espaço de todas as listas associadas a ela.
*/
void clear(void) {
// Iremos limpar todas as listas. Porem a tabela ainda continuará com o mesmo tamanho.
for(auto i = 0u; i < m_tableSize; i++) {
m_data_table[i].clear();
}
m_count = 0;
}
/*!
* Verifica se a tabela está vazia.
* @return true Caso esteja vazia e false caso contrario.
*/
bool empty(void) const {
return m_count == 0;
}
/*!
* Retorna a quantidade de elementos presentes na tabela.
* @return Quantidade de elementos na tabela.
*/
size_t size(void) const {
return m_count;
}
/*!
* Retorna a quantidade de elementos presentes na lista de colisão do elemento da chave dada.
* @param k Chave para um determinado elemento na tabela.
* @return Quantidade de elementos presentes na lista de colisão em que k_ pertence.
*/
size_t count(const KeyType &k_) const {
auto address(hashFunc(k_) % m_tableSize); //Representa o endereço.
unsigned int cont = 0; // Contador para verificar quantos elementos existem no mesmo "ramo" da chave dada.
// Varrer toda a lista até o seu final.
for(auto it = m_data_table[address].begin(); it != m_data_table[address].end(); it++) {
++cont;
}
return cont;
}
/*!
* Retorna uma referencia para o dado associado a chave dada.
* Caso a chave não exista na tabela, retorna uma exceção.
* @param k_ Chave do elemento desejado.
* @return Uma referencia para o dado associado a chave dada ou uma exceção std::out_of_range caso não exista.
*/
DataType &at(const KeyType &k_) {
auto address(hashFunc(k_) % m_tableSize);
for(auto it = m_data_table[address].begin(); it != m_data_table[address].end(); it++) {
if(equalFunc(k_, it->m_key)) {
return it->m_data;
}
}
// Caso a chave não seja encontrada é lançada uma exceção.
throw std::out_of_range("Key is not in table");
}
/*!
* Retorna uma referencia para o dado associado a chave dada.
* Caso a chave não exista ela será adicionada na tabela.
* @param k_ Chave do elemento desejado.
* @return Uma referencia para o dado associado a chave dada.
*/
DataType &operator[](const KeyType &k_) {
auto address(hashFunc(k_) % m_tableSize);
for(auto it = m_data_table[address].begin(); it != m_data_table[address].end(); it++) {
if(equalFunc(k_, it->m_key)) {
return it->m_data;
}
}
//Caso a chave não esteja presente.
insert(k_, DataType());
return m_data_table[address].begin()->m_data;
}
/*!
* Sobrecarga do operador << para permitir a impressão da tabela de maneira pratica.
*/
friend std::ostream &operator<<(std::ostream &out, const HashTbl &tbl) {
for(auto i = 0u; i < tbl.m_tableSize; i++) {
out << i << ": ";
for(auto it = tbl.m_data_table[i].begin(); it != tbl.m_data_table[i].end(); it++) {
out << it->m_data << " ";
}
out << std::endl;
}
return out;
}
private:
KeyHash hashFunc; //<! Função hash.
KeyEqual equalFunc; //<! Função de igualdade.
unsigned int m_tableSize; //<! Armazena o tamanho da tabela..
unsigned int m_count = 0; //<! Quantidade de elementos na tabela.
std::forward_list<Entry> *m_data_table; //<! Poneiro para tabela de listas de Entry.
static const short DEFAULT_SIZE = 11; // Tamanho padrão da tabela.
// Metodos privados:
/*!
* Aumenta o tamanho da tabela e reorganiza os elementos da tabela anterior com novas posições de acordo com
* a função hash.
*/
void rerash() {
unsigned int newTableSize = nextPrime(2*m_tableSize);
std::forward_list<Entry> *newTable;
newTable = new std::forward_list<Entry>[newTableSize];
// Varrer toda a tabela anterior.
for(auto i = 0u; i < m_tableSize; i++) {
// Varrer cada posição da lista e adicionar os elementos na nova tabela em novas posições.
for(auto it = m_data_table[i].begin(); it != m_data_table[i].end(); it++) {
auto address(hashFunc(it->m_key) % newTableSize);
newTable[address].push_front(*it);
}
}
delete[] m_data_table; // Apaga a memoria associada a tabela anterior.
m_data_table = newTable;
m_tableSize = newTableSize;
}
/*!
* Verifica se um determinado numero é primo.
* @param number Numero a ser verificado.
* @return true caso seja primo e false caso contrario.
*/
bool is_prime(size_t &number) {
for(size_t i = 2; i <= sqrt(number); i++) {
if(number % i == 0) {
return false;
}
}
return true;
}
/*!
* Dado um numero calcular o primo que é igual ou o segue.
* @param number Numero a qual iremos calcular.
* @return O numero primo igual ou seguinte ao numero dado.
*/
size_t nextPrime(size_t number) {
if(number <= 1) {
return 1;
}
// Enquanto não achar um primo vai testando para o proximo valor.
while(is_prime(number) == false) {
number++;
}
return number;
}
}; // Fim da Classe hashTbl
} // Fim do Namespace
#endif
| true |
3b55ea78ae4c19c26d2422a395644bc26a6bafe5 | C++ | andyyhchen/coursera-cpp | /ch5-lec.cpp | UTF-8 | 600 | 3.390625 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Bug{
private:
int nLegs; int nColor;
public:
int nType;
Bug(int legs, int color)
{
nLegs = legs;
nColor = color;
}
void PrintBug(){
cout << "Bug with nLegs " << nLegs <<" and color " << nColor << endl;
}
};
class FlyBug: public Bug{
int nWings;
public:
FlyBug(int legs, int color, int wings);
void PrintFlyBug(){
cout << "FlyBug with nLegs " << nLegs <<" and color " << nColor << endl;
}
};
FlyBug::FlyBug(int legs, int color, int wings):Bug(legs, color){
nWings = wings;
}
int main()
{
Bug b(4, 1);
FlyBug fb(3,3,5);
} | true |
9a9e54386f40b5f219ed396ebad5fb802252e11a | C++ | nags5454/1SI16CS068_SIT_CSE_OOPLAB | /to find area FuncOverload.cpp | UTF-8 | 973 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
void fnVol(int);
void fnVol(double);
void fnVol(double, int);
void fnVol(int, int, int);
int main()
{
int iSide, iL, iB, iH;
double dRad;
cout << "\nEnter side length of cube" << endl;
cin >> iSide;
fnVol(iSide);
cout << "\nEnter radius of sphere" << endl;
cin >> dRad;
fnVol(dRad);
cout << "\nEnter side lengths of cuboid" << endl;
cin >> iL >> iB >> iH;
fnVol(iL, iB, iH);
cout << "\nEnter radius and height of cylinder" << endl;
cin >> dRad >> iH;
fnVol(dRad, iH);
return 0;
}
void fnVol(int iS)
{
cout << "\nVolume of Cube is : " << iS*iS*iS << " units." << endl;
}
void fnVol(double dR)
{
cout << "\nVolume of Sphere is : " << 4.0/3.0*M_PI*dR*dR*dR << " units." << endl;
}
void fnVol(double dR, int iH)
{
cout << "\nVolume of Cylinder is : " << M_PI*dR*dR*iH << " units." << endl;
}
void fnVol(int iL, int iB, int iH)
{
cout << "\nVolume of Cuboid is : " << iL*iB*iH << " units." << endl;
}
| true |
155bdccf80d82831c8ee2769ed23987adf982b4e | C++ | tetraa-coder/tetra | /produits.cpp | UTF-8 | 2,522 | 2.671875 | 3 | [] | no_license | #include "produits.h"
produits::produits(){
nbr=0;
id=0;
nom_type="";
nom_produit="";
}
produits::produits(int n,int i,std::string t,std::string p){
nbr=n;
id=i;
nom_type=t;
nom_produit=p;
}
int produits::get_nbr(){return nbr;}
int produits::get_id(){return id;}
std::string produits::get_nom_type(){return nom_type;}
std::string produits::get_nom_produit(){return nom_produit;}
produits::~produits()
{
}
bool produits::ajouter_produit()
{
QSqlQuery query;
query.prepare("INSERT INTO tab_produit (nbr,id,nom_type,nom_produit)""VALUES(:nbr,:id,:nom_type,:nom_produit)");
query.bindValue(":id",id);
query.bindValue(":nbr",nbr);
query.bindValue(":nom_produit",QString::fromStdString (nom_produit));
query.bindValue(":nom_type",QString::fromStdString(nom_type));
return query.exec();
}
QSqlQueryModel * produits::afficher_produit()
{
QSqlQueryModel *model = new QSqlQueryModel();
QSqlDatabase db = QSqlDatabase::database();
model->setQuery("select nbr,ID,NOM_type,NOM_produit FROM tab_produit",db);
model->setHeaderData(0,Qt::Horizontal,QObject::tr("NBR"));
model->setHeaderData(1,Qt::Horizontal,QObject::tr("ID"));
model->setHeaderData(2,Qt::Horizontal,QObject::tr("NOM_type"));
model->setHeaderData(3,Qt::Horizontal,QObject::tr("NOM_produit"));
return model;
}
bool produits::supprimer_produit(int id)
{
QSqlQuery query;
query.prepare("DELETE FROM tab_produit WHERE ID= :id");
query.bindValue(":id",id);
return query.exec();
}
bool produits::modifier_produit(int id,int nbr,QString nom_produit,QString nom_type)
{
QSqlQuery query;
query.prepare("UPDATE tab_produit SET nbr= :nbr, nom_type= :nom_type , nom_produit= :nom_produit WHERE id= :id");
query.bindValue(":id",id);
query.bindValue(":nbr",nbr);
query.bindValue(":nom_type",nom_type);
query.bindValue(":nom_produit",nom_produit);
return query.exec();
}
QSqlQueryModel * produits::recherche_produit(const QString &id)
{
QSqlQueryModel * model = new QSqlQueryModel();
model->setQuery("select * from tab_produit where(id LIKE '"+id+"%')");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("NBR"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("NOM_TYPE"));
model->setHeaderData(3, Qt::Horizontal, QObject::tr("NOM_PRODUIT"));
return model;
}
| true |
853933147d0a143b60742652d1500f55036a54e5 | C++ | kedumuc1712/INT2002 | /Tuan 2/BT ThayKhoi/BT02.cpp | UTF-8 | 167 | 2.8125 | 3 | [] | no_license | # include <iostream>
# include <cmath>
using namespace std;
int main(){
float x;
int y;
cin >> x >> y;
float hat = pow(x,y);
cout << hat <<endl;
return 0;
}
| true |
50780ae5def7f0a2ad8c26b9bddc6afb34a5c1f6 | C++ | cpatrasciuc/nine-men-morris | /src/console_game/ai_player.cc | UTF-8 | 1,211 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright (c) 2013 Cristian Patrasciuc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "console_game/ai_player.h"
#include <memory>
#include <sstream>
#include <string>
#include "ai/ai_algorithm.h"
#include "game/game.h"
#include "game/player_action.h"
namespace console_game {
AIPlayer::AIPlayer(const std::string& name,
std::auto_ptr<ai::AIAlgorithm> algorithm)
: Player(name), algorithm_(algorithm.release()) {
}
std::string AIPlayer::GetNextAction(game::Game* game_model) {
const game::PlayerAction action(algorithm_->GetNextAction(*game_model));
game_model->ExecutePlayerAction(action);
std::ostringstream msg;
msg << name() << " ";
switch (action.type()) {
case game::PlayerAction::MOVE_PIECE:
msg << "moved from " << action.source() << " to " << action.destination();
break;
case game::PlayerAction::REMOVE_PIECE:
msg << "removed a piece from " << action.source();
break;
case game::PlayerAction::PLACE_PIECE:
msg << "placed a piece to " << action.destination();
break;
}
msg << ".";
return msg.str();
}
} // namespace console_game
| true |
52cde0e3d2d8e37dfbaa9c0a5a3679ca815989af | C++ | ouchiminh/ouchitest | /include/ccol.hpp | UTF-8 | 1,791 | 2.890625 | 3 | [] | no_license | #pragma once
#ifdef __linux__
#include <cstdio>
namespace ouchi::test {
class ccol {
public:
enum color_code : unsigned short {
foreground_blue = 34,
foreground_green = 32,
foreground_red = 31,
background_blue = 44,
background_green = 42,
background_red = 41,
};
friend color_code operator|(color_code c1, color_code c2) noexcept { return (color_code)((unsigned short)c1 | (unsigned short)c2); }
ccol() = default;
ccol(const ccol&) = delete;
~ccol()
{
restore();
}
void set_color(color_code c) const noexcept
{
std::printf("\x1b[%dm", c);
}
void restore() const noexcept
{
std::printf("\x1b[0m");
}
};
}
#else
// impl for windows
#include <Windows.h>
namespace ouchi::test {
/// <summary>
/// console color for cmd.exe
/// </summary>
class ccol {
HANDLE stdout_;
CONSOLE_SCREEN_BUFFER_INFO csbi_;
public:
enum color_code : WORD {
foreground_blue = FOREGROUND_BLUE,
foreground_green = FOREGROUND_GREEN,
foreground_red = FOREGROUND_RED,
background_blue = BACKGROUND_BLUE,
background_green = BACKGROUND_GREEN,
background_red = BACKGROUND_RED,
};
friend color_code operator|(color_code c1, color_code c2) noexcept { return (color_code)((WORD)c1 | (WORD)c2); }
ccol()
: stdout_{GetStdHandle(STD_OUTPUT_HANDLE)}
{
GetConsoleScreenBufferInfo(stdout_, &csbi_);
}
ccol(const ccol&) = delete;
~ccol()
{
restore();
}
void set_color(color_code c) const noexcept
{
SetConsoleTextAttribute(stdout_, (WORD)c);
}
void restore() const noexcept
{
SetConsoleTextAttribute(stdout_, csbi_.wAttributes);
}
};
}
#endif
| true |
eb8de2e1bf4a876df087174eafe312fd63f2a758 | C++ | whitead/WordModel | /lib/simple_model.cpp | UTF-8 | 2,874 | 2.71875 | 3 | [] | no_license | #include "simple_model.hpp"
wordmodel::SimpleModel::SimpleModel(){
std::string delims(TOKENIZER_DELIMS);
for(unsigned int i = 0; i < delims.size(); i++) {
delimiters_.push_back(delims.substr(i,1));
}
}
wordmodel::SimpleModel::SimpleModel(const char* delimiters[], int dlength){
for(int i = 0; i < dlength; i++) {
delimiters_.push_back(delimiters[i]);
}
}
wordmodel::SimpleModel::SimpleModel(SimpleModel&& sm) :
parser_(std::move(sm.parser_)),
word_modes_(std::move(sm.word_modes_)),
delimiters_(std::move(sm.delimiters_)){
}
wordmodel::SimpleModel::~SimpleModel() {
}
void wordmodel::SimpleModel::write_summary(std::ostream& out) {
out << "Simple Word Model:" << std::endl;
out << "Word : Mode " << std::endl;
for ( auto it = word_modes_.begin(); it != word_modes_.end(); ++it )
out << " [" << it->first << "] : [" << it->second << "] " << std::endl;
out << std::endl;
}
bool wordmodel::SimpleModel::putc(char c) {
//end of stream for now
if(c == '\x00')
return detected_interface_;
else if(c == '\b') { //backspace
if(input_string_.size() > 0) {
input_string_.erase(input_string_.size() - 1);
} else
return detected_interface_;
} else {
input_string_ += c;
}
detected_interface_ = false;
//If there are no delimiters, we always return an interface
if(delimiters_.size() == 0)
detected_interface_ = true;
//check over all the delimiters
for(auto const &d : delimiters_) {
if(!input_string_.compare(d)) {
detected_interface_ = true;
break;
}
}
return detected_interface_;
}
const std::string& wordmodel::SimpleModel::get_prediction(unsigned int* prediction_id) {
//assign reference
if(prediction_id != NULL)
last_prediction_id_ = *prediction_id;
return prediction_;
}
bool wordmodel::SimpleModel::detected_interface() const {
return detected_interface_;
}
void wordmodel::SimpleModel::interface(bool interface) {
if(interface && input_string_.size() > 0) {
parser_.add_word(input_string_);
do_train();
prediction_ = word_modes_[input_string_];
//store weight if needed
last_prediction_weight_ = parser_.count(input_string_, prediction_);
//clear the stream
input_string_.clear();
}
}
void wordmodel::SimpleModel::do_train() {
//build word_modes_
unsigned int count;
std::string word_i, word_j;
for(size_t i = 0; i < parser_.get_word_number(); ++i) {
count = 0;
for(auto j: parser_.iterate_pairs(i)) {
if(parser_.count(i,j) > count) {
parser_.get_word(i, &word_i);
parser_.get_word(j, &word_j);
word_modes_[word_i] = word_j;
count = parser_.count(i,j);
}
}
}
}
double wordmodel::SimpleModel::get_prediction_weight(unsigned int* prediction_id) const {
if(*prediction_id == last_prediction_id_)
return last_prediction_weight_;
return 0;
}
| true |
ac050fa28cef611862e087ee2b15611b29a438b5 | C++ | LuannMateus/c-exercises | /repetition-structure/01 - Exercícios - Desafio/exer02.cpp | UTF-8 | 1,996 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <string.h>
using namespace std;
int main(){
setlocale(LC_ALL, "Portuguese");
string resp;
double rendaP, rendaF,totA = 0, totO = 0, acumula1 = 0, acumula2 = 0, acumula3 = 0, porcem1, porcem2, porcem3;
int totD = 0, totR = 0, tot = 0;
cout << "==========================================================\n";
cout << "<-- Tabela de Informações -->\n";
cout << "<-- Para parar o código digite [0] para renda pessoal -->\n";
while(1){
tot += 1;
cout << "==========================================================\n";
cout << "Informe sua renda pessoal R$: ";
cin >> rendaP;
if(rendaP == 0)
break;
cout << "Informe sua renda familiar R$: ";
cin >> rendaF;
cout << "Informe o total gasto com alimentação R$: ";
cin >> totA;
cout << "Informe o total gasto com outras despesas R$: ";
cin >> totO;
if(totO > 200){
totD += 1;
}
if(rendaP > rendaF){
totR += 1;
}
acumula1 += rendaP + rendaF;
acumula2 += totA;
acumula3 += totO;
}
if(tot == 1 && rendaP == 0){
porcem1 = 0;
porcem2 = 0;
porcem3 = 0;
} else {
tot -= 1;
porcem1 = (totD * 100) / tot;
porcem2 = (acumula2 * 100) / acumula1;
porcem3 = (acumula3 * 100) / acumula1;
}
cout << "=======================\n";
cout << "<-- Resultados Gerais -->\n";
cout << "=======================\n";
cout << "Porcentagem dos alunos que gastam acima de R$200 reais com outras despesas: " << porcem1 << "%";
cout << "\nNúmero total de alunos com renda pessoal maior que a renda familiar: " << totR;
cout << "\nPorcentagem de gastos com alimentação: " << porcem2 << "%";
cout << "\nPorcentagem de gastos com outras despesas: " << porcem3 << "%";
cout << "\n\n";
return 0;
} | true |
c8241bb3c22b3c218dd7a02d9f7a25ef62d17410 | C++ | alisson2000rj/SE | /02 - Exercicios SE/exercicio-03-Blink-alisson-1touch-always/exercicio-03-Blink-alisson-1touch-always.ino | UTF-8 | 2,594 | 3.25 | 3 | [] | no_license | /*
* Versao by alisson
* modificado 12 set 2018
* utilizada com referencia o exemplo blink existente na IDE do arduino
* http://www.arduino.cc/en/Tutorial/Blink
* Blink - 1touch-always
Utiliza o pino 13 como saida para fornecer sinal positivo ao LED.
O estado do pino 13 muda conforme e alterado o estado do pino 7, que esta ligado a uma chave pushbutton. Ao pressionar a chave, o pino 7
recebe sinal negativo, e consequentemente o sinal HIGH e fixado no pino 13.
Descrição:
+ O circuito de alimentacao do LED e baseado no circuito Pull UP. Onde, o pinos de controle do LED estão sempre recebendo sinal HIGH do pino de +5v ate que a chave pushbutton seja pressionada.
Entao, os pinos de controle do LED passam a receber sinal LOW do GND.
- O algoritmo utilizado e adaptado utilizava o circuito de pull down. Onde, o pino de controle do LED estava sempre recebendo sinal LOW do pino GND ate que a chave pushbutton fosse pressionada.
Entao, os pinos de controle do LED passavam a receber sinal HIGH do pino de +5v.
*/
#define spd 1000
unsigned long lasttempoled = 0; // acumula o tempo
// bloco setup roda uma unica vez quando pressionado reset ou ligado a placa pela primeira vez
void setup()
{
// ativa o uso da ferramenta serial monitor. Esta ferramenta ajuda no debug do codigo fonte.
Serial.begin(9600);
// inicializa os pinos: pino 13 como saida de dados e o pino 7 como entrada de dados
pinMode(13, OUTPUT);
pinMode(7, INPUT);
}
// bloco roda eternamente, loop constante
void loop()
{
int btn = digitalRead(7); // realiza leitura do sinal enviado para o pino 7 e armazena seu valor na variavel btn
Serial.print("btn: ");
Serial.println(btn);
// bloco 1 - responsavel por fixar LED aceso.
// utiliza uma negação pois o o circuito utilizado e o PULL UP, que mantem o pino 7 alimentado com sinal HIGH.
if(!btn)
{
digitalWrite(13, HIGH); // envia sinal para o led de acordo com o valor armazenado na variavel btn
while(1);
}
// bloco 2 - responsavel pela frequencia com que o LED pisca.
// Referencia - site brincando com ideas - video aula programacao com arduino - aula 13 - delay e millis
if((millis() - lasttempoled) < spd) // tempo menor que 1000ms retorna LED apagado
{
digitalWrite(13, LOW);
}
if((millis() - lasttempoled) >= spd) // tempo maior que 1000ms retorna LED aceso
{
digitalWrite(13, HIGH);
}
if((millis() - lasttempoled) >= spd*2) // tempo maior que 2000ms registra o tempo em lastempoled para uso na proxima rodada
{
lasttempoled = millis();
}
}
| true |
5c466360370d13f5b3777eb98ba3827cd4961717 | C++ | tusharchopratech/mouse_project | /wearablecode/windows/src/modules/stm32/SerialPort.cpp | UTF-8 | 3,615 | 2.828125 | 3 | [] | no_license | /*
* Author: Manash Kumar Mandal
* Modified Library introduced in Arduino Playground which does not work
* This works perfectly
* LICENSE: MIT
*/
#include "SerialPort.h"
SerialPort::SerialPort()
{
// char *portName;
comPort += getSerialCOMport();
cout << comPort.c_str() << endl;
this->connected = false;
this->handler = CreateFileA(static_cast<LPCSTR>(comPort.c_str()),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (this->handler == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_FILE_NOT_FOUND)
{
printf("ERROR: Handle was not attached. Reason: %s not available\n", comPort.c_str());
}
else
{
printf("ERROR!!!");
}
}
else
{
DCB dcbSerialParameters = {0};
if (!GetCommState(this->handler, &dcbSerialParameters))
{
printf("failed to get current serial parameters");
}
else
{
dcbSerialParameters.BaudRate = 256000;
dcbSerialParameters.ByteSize = 8;
dcbSerialParameters.StopBits = ONESTOPBIT;
dcbSerialParameters.Parity = NOPARITY;
// dcbSerialParameters.fDtrControl = DTR_CONTROL_ENABLE;
if (!SetCommState(handler, &dcbSerialParameters))
{
printf("ALERT: could not set Serial port parameters\n");
}
else
{
this->connected = true;
PurgeComm(this->handler, PURGE_RXCLEAR | PURGE_TXCLEAR);
}
}
}
}
SerialPort::~SerialPort()
{
if (this->connected)
{
this->connected = false;
CloseHandle(this->handler);
}
}
string SerialPort::getSerialCOMport()
{
cout << "Available serial ports :-" << endl;
string portName = "";
char lpTargetPath[5000]; // buffer to store the path of the COMPORTS
for (int i = 0; i < 255; i++) // checking ports from COM0 to COM255
{
std::string str = "COM" + std::to_string(i); // converting to COM0, COM1, COM2
DWORD test = QueryDosDevice(str.c_str(), lpTargetPath, 5000);
// Test the return value and error if any
if (test != 0) //QueryDosDevice returns zero if it didn't find an object
{
std::cout << str << " : " << lpTargetPath << std::endl;
portName = str;
}
}
cout << "Connecting to Port " << portName << " !" << endl;
return portName;
}
int SerialPort::readSerialPort(unsigned char *buffer, unsigned int buf_size)
{
DWORD bytesRead;
unsigned int toRead = 0;
//ClearCommError(this->handler, &this->errors, &this->status);
if (ReadFile(this->handler, buffer, buf_size, &bytesRead, NULL))
{
PurgeComm(this->handler, PURGE_RXCLEAR);
return bytesRead;
}
return 0;
}
bool SerialPort::writeSerialPort(unsigned char *buffer, unsigned int buf_size)
{
DWORD bytesSend;
if (!WriteFile(this->handler, (void *)buffer, buf_size, &bytesSend, 0))
{
ClearCommError(this->handler, &this->errors, &this->status);
return false;
}
else
return true;
}
bool SerialPort::isConnected()
{
if (!ClearCommError(this->handler, &this->errors, &this->status))
this->connected = false;
return this->connected;
}
// Close Connection
void SerialPort::closeSerial()
{
CloseHandle(this->handler);
}
| true |
1800d70eff7912dc887174fcebc84cac33caf85d | C++ | amrzakii2000/Snake-and-Ladder-Roll-Dice-Game | /CardTen.h | UTF-8 | 750 | 2.71875 | 3 | [] | no_license | #pragma once
#include "Card.h"
#include"Player.h"
class CardTen : public Card
{
static int price;
static int fees;
static bool flag_P_F;
static Player* owner;
static bool flag_owner;
static Player* Passer;
public:
class CardTen(const CellPosition& pos); // A Constructor takes card position
virtual void ReadCardParameters(Grid* pGrid); // Reads the parameters of CardOne which is: walletAmount
bool SetPrice(int p); //Ziad: Get Price, if invalid will return false, !! constant
bool SetFees(int f); //Ziad: Get fees, if invalid will return false !! constant
void SetFlagpF(bool pf);
static int GetPrice();
static int GetFees();
virtual void Apply(Grid* pGrid, Player* pPlayer);
virtual ~CardTen(); // A Virtual Destructor
};
| true |
9849ef20cb9464e3ceba1541ecaa5c77f99176c2 | C++ | tallbl0nde/Aether | /source/utils/Utils.cpp | UTF-8 | 3,032 | 3.03125 | 3 | [
"MIT"
] | permissive | #include <filesystem>
#include "Aether/utils/Utils.hpp"
namespace Aether::Utils {
std::string buttonToCharacter(const Button b) {
switch (b) {
case Button::A:
return "\uE0E0";
break;
case Button::B:
return "\uE0E1";
break;
case Button::X:
return "\uE0E2";
break;
case Button::Y:
return "\uE0E3";
break;
case Button::LSTICK:
return "\uE104";
break;
case Button::RSTICK:
return "\uE105";
break;
case Button::L:
return "\uE0E4";
break;
case Button::R:
return "\uE0E5";
break;
case Button::ZL:
return "\uE0E6";
break;
case Button::ZR:
return "\uE0E7";
break;
case Button::PLUS:
return "\uE0EF";
break;
case Button::MINUS:
return "\uE0F0";
break;
case Button::DPAD_LEFT:
return "\uE0ED";
break;
case Button::DPAD_UP:
return "\uE0EB";
break;
case Button::DPAD_RIGHT:
return "\uE0EE";
break;
case Button::DPAD_DOWN:
return "\uE0EC";
break;
case Button::SL_LEFT:
case Button::SR_LEFT:
return "\uE0E8";
break;
case Button::SL_RIGHT:
case Button::SR_RIGHT:
return "\uE0E9";
break;
default:
break;
}
return "";
};
bool fileExists(std::string path) {
return std::filesystem::exists(path);
}
uint16_t getUTF8Char(const std::string & str, unsigned int & pos) {
uint16_t c = 0;
// One byte
if ((str.length() - pos) >= 1) {
if ((str[0 + pos] & 0b10000000) == 0) {
c = str[0 + pos];
pos += 1;
}
}
// Two bytes
if (c == 0 && (str.length() - pos) >= 2) {
if ((str[0 + pos] & 0b11100000) == 0b11000000) {
c = (str[0 + pos] & 0b00011111) << 6;
c = (c | (str[1 + pos] & 0b00111111));
pos += 2;
}
}
// Three bytes
if (c == 0 & (str.length() - pos) >= 3) {
if ((str[0 + pos] & 0b11110000) == 0b11100000) {
c = (str[0 + pos] & 0b00001111) << 12;
c = (c | ((str[1 + pos] & 0b00111111) << 6));
c = (c | (str[2 + pos] & 0b00111111));
pos += 3;
}
}
return c;
}
Button SDLtoButton(uint8_t k) {
return (Button)k;
}
}; | true |
80f8bdd848093ff94a6faeedf0c848ff936c8524 | C++ | m0rjjj/plant-watering-device | /src/main.cpp | UTF-8 | 6,813 | 2.546875 | 3 | [] | no_license | #include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const uint8_t PUMP_PIN = D0;
const uint8_t SOLENOID_1_PIN = D1;
const uint8_t SOLENOID_2_PIN = D2;
const uint8_t plants[] = {SOLENOID_1_PIN, SOLENOID_2_PIN};
// Connect to the WiFi
const char *ssid = "****";
const char *password = "****";
// topics
const char *waterPlantsTopic = "pwd-water-plants";
const char *configurePumpDelay = "pwd-configure-pump-delay";
const char *configureSolenoid1Duraion = "pwd-configure-solenoid-1-duration";
const char *configureSolenoid2Duraion = "pwd-configure-solenoid-2-duration";
const char *outputTopic = "pwd-output";
const char *outputStatusTopic = "pwd-status-output";
// timers
bool pumpState = false;
int pumpNumber = 1;
int pumpCounter = 0;
bool solenoid1State = false;
int solenoid1Number = 20;
int solenoid1Counter = 0;
bool solenoid2State = false;
int solenoid2Number = 20;
int solenoid2Counter = 0;
// actions
String actionWaterPlantsStart("start");
// state
byte stateBusy = 1;
byte stateFree = 0;
byte state = stateFree;
const IPAddress mqttServerIp(192, 168, 1, 101);
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi()
{
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char *topicData, byte *payloadData, unsigned int length)
{
String payload;
for (unsigned int i = 0; i < length; i++)
{
payload.concat((char)payloadData[i]);
}
String topic(topicData);
if (state == stateBusy)
{
Serial.println("Busy");
client.publish(outputTopic, "{\"error\":\"busy\"}");
return;
}
if (topic.equals(waterPlantsTopic))
{
if (payload.equals(actionWaterPlantsStart))
{
state = stateBusy;
Serial.println("Watering Plants Started");
client.publish(outputTopic, "{\"success\":\"watering-plants-started\"}");
return;
}
Serial.print("Unrecognized action: ");
Serial.println(payload);
client.publish(outputTopic, "{\"error\":\"unrecognized-message\"}");
return;
}
if (topic.equals(configurePumpDelay))
{
const int delay = payload.toInt();
if (payload.toInt() > 0)
{
pumpNumber = delay;
Serial.printf("Pump delay changed to: %d seconds\n", delay);
client.publish(outputTopic, "{\"success\":\"pump-delay-changed\"}");
return;
}
Serial.print("Wrong delay: ");
client.publish(outputTopic, "{\"error\":\"wrong-delay\"}");
Serial.println(payload);
return;
}
if (topic.equals(configureSolenoid1Duraion))
{
const int delay = payload.toInt();
if (payload.toInt() > 0)
{
solenoid1Number = delay;
Serial.printf("Solenoid 1 duration changed to: %d seconds\n", delay);
client.publish(outputTopic, "{\"success\":\"solenoid-1-duration-changed\"}");
return;
}
Serial.print("Wrong duration: ");
client.publish(outputTopic, "{\"error\":\"wrong-duration\"}");
Serial.println(payload);
return;
}
if (topic.equals(configureSolenoid2Duraion))
{
const int delay = payload.toInt();
if (payload.toInt() > 0)
{
solenoid2Number = delay;
Serial.printf("Solenoid 2 duration changed to: %d seconds\n", delay);
client.publish(outputTopic, "{\"success\":\"solenoid-2-duration-changed\"}");
return;
}
Serial.print("Wrong duration: ");
client.publish(outputTopic, "{\"error\":\"wrong-duration\"}");
Serial.println(payload);
return;
}
}
void reconnect()
{
while (!client.connected())
{
Serial.println("Attempting MQTT connection...");
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str()))
{
Serial.println("connected");
client.subscribe(waterPlantsTopic);
client.subscribe(configurePumpDelay);
client.subscribe(configureSolenoid1Duraion);
client.subscribe(configureSolenoid2Duraion);
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup()
{
Serial.begin(57600);
pinMode(PUMP_PIN, OUTPUT);
pinMode(SOLENOID_1_PIN, OUTPUT);
pinMode(SOLENOID_2_PIN, OUTPUT);
digitalWrite(PUMP_PIN, HIGH);
digitalWrite(SOLENOID_1_PIN, HIGH);
digitalWrite(SOLENOID_2_PIN, HIGH);
setup_wifi();
client.setServer(mqttServerIp, 1883);
client.setCallback(callback);
}
unsigned long previousMillis = millis();
unsigned long currentMillis;
int stage = 0;
void loop()
{
currentMillis = millis();
if (state == stateBusy && stage == 0)
{
stage = 1;
pumpState = true;
digitalWrite(PUMP_PIN, LOW);
Serial.println("Pump on");
client.publish(outputStatusTopic, "{\"stage\":\"1\",\"status\":\"pump-on\"}");
}
if (pumpCounter == pumpNumber && stage == 1)
{
stage = 2;
solenoid1State = true;
digitalWrite(SOLENOID_1_PIN, LOW);
Serial.println("Solenoid 1 on");
client.publish(outputStatusTopic, "{\"stage\":\"2\",\"status\":\"solenoid-1-on\"}");
}
if (solenoid1Counter == solenoid1Number && stage == 2)
{
stage = 3;
solenoid1Counter = 0;
solenoid1State = false;
digitalWrite(SOLENOID_1_PIN, HIGH);
Serial.println("Solenoid 1 off");
client.publish(outputStatusTopic, "{\"stage\":\"3\",\"status\":\"solenoid-1-off\"}");
solenoid2State = true;
digitalWrite(SOLENOID_2_PIN, LOW);
Serial.println("Solenoid 2 on");
client.publish(outputStatusTopic, "{\"stage\":\"3\",\"status\":\"solenoid-2-on\"}");
}
if (solenoid2Counter == solenoid2Number && stage == 3)
{
stage = 0;
state = stateFree;
solenoid2Counter = 0;
solenoid2State = false;
digitalWrite(SOLENOID_2_PIN, HIGH);
Serial.println("Solenoid 2 off");
client.publish(outputStatusTopic, "{\"stage\":\"4\",\"status\":\"solenoid-2-off\"}");
pumpCounter = 0;
pumpState = false;
digitalWrite(PUMP_PIN, HIGH);
Serial.println("Pump off");
client.publish(outputStatusTopic, "{\"stage\":\"4\",\"status\":\"pump-off\"}");
}
if (currentMillis - previousMillis > 1000)
{
if (pumpState)
{
pumpCounter++;
}
if (solenoid1State)
{
solenoid1Counter++;
}
if (solenoid2State)
{
solenoid2Counter++;
}
if (state == stateBusy)
{
Serial.println(".");
}
previousMillis = millis();
}
if (!client.connected())
{
reconnect();
}
client.loop();
} | true |
22d99e71443f4f446dc01cb9d6939c0786928ea4 | C++ | jhy156456/python-algorithm | /이전/백준/(백준)DFS-단지짓기.cpp | WINDOWS-1252 | 1,166 | 2.703125 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<queue>
using namespace std;
int n;
int answerCount = 1;
vector<vector<int>>problems;
vector<vector<int>>visited;
vector<int> answers;
int dy[4] = {-1,1,0,0};//,,,
int dx[4] = {0,0,-1,1};
void dfs(int y, int x) {
visited[y][x] = true;
for (int i = 0; i < 4; i++) {
int goY = y + dy[i];
int goX = x + dx[i];
if (goY<0 || goX<0 || goX>=n || goY>=n) continue;
if (!visited[goY][goX]
&&problems[goY][goX]==1) {
answerCount++;
dfs(goY, goX);
}
}
}
int main() {
cin >> n;
problems = vector<vector<int>>(n, vector<int>(n, 0));
visited = vector<vector<int>>(n, vector<int>(n, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
char a;
cin >> a;
problems[i][j] = a - '0';
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (visited[i][j] == 0 && problems[i][j] == 1) {
dfs(i, j);
answers.push_back(answerCount);
answerCount = 1;
}
}
}
sort(answers.begin(), answers.end());
cout << answers.size() << endl;
for (int i = 0; i < answers.size(); i++)cout << answers[i] << endl;
} | true |
76345f1349ccfe451f9cfcf6f899392e3b483716 | C++ | slagusev/CrossPlatformEngine | /Engine/CQuaternion.cpp | WINDOWS-1252 | 6,773 | 2.78125 | 3 | [] | no_license | ///////////////////////////////////////////////////////////////////////////////
// Icarus Game Engine
// Copyright 2011 Timothy Leonard
///////////////////////////////////////////////////////////////////////////////
#include "CQuaternion.h"
#include "CVector3.h"
#include "CVector4.h"
#include "CMatrix3.h"
#include "CMatrix4.h"
#include "CString.h"
using namespace Engine::Math;
CQuaternion::CQuaternion()
{
X = 0;
Y = 0;
Z = 0;
W = 0;
}
CQuaternion::CQuaternion(f32 x, f32 y, f32 z, f32 w)
{
X = x;
Y = y;
Z = z;
W = w;
}
void CQuaternion::Set(const f32 x, const f32 y, const f32 z, const f32 w)
{
X = x;
Y = y;
Z = z;
W = w;
}
void CQuaternion::Zero()
{
X = 0;
Y = 0;
Z = 0;
W = 0;
}
f32 CQuaternion::operator[](u32 index) const
{
switch (index)
{
case 0: return X;
case 1: return Y;
case 2: return Z;
default: return W;
}
}
f32 & CQuaternion::operator[](u32 index)
{
switch (index)
{
case 0: return X;
case 1: return Y;
case 2: return Z;
default: return W;
}
}
f32 CQuaternion::operator[](s32 index) const
{
switch (index)
{
case 0: return X;
case 1: return Y;
case 2: return Z;
default: return W;
}
}
f32 & CQuaternion::operator[](s32 index)
{
switch (index)
{
case 0: return X;
case 1: return Y;
case 2: return Z;
default: return W;
}
}
CQuaternion CQuaternion::operator-() const
{
return CQuaternion(-X, -Y, -Z, -W);
}
CQuaternion & CQuaternion::operator=(const CQuaternion& a)
{
X = a.X;
X = a.Y;
Z = a.Z;
W = a.W;
return *this;
}
CQuaternion CQuaternion::operator+(const CQuaternion& a) const
{
return CQuaternion(X + a.X, Y + a.Y, Z + a.Z, W + a.W);
}
CQuaternion CQuaternion::operator-(const CQuaternion& a) const
{
return CQuaternion(X - a.X, Y - a.Y, Z - a.Z, W - a.W);
}
CQuaternion CQuaternion::operator*(const CQuaternion& a) const
{
return CQuaternion(W * a.X + X * a.W + Y * a.Z - Z * a.Y,
W * a.Y + Y * a.W + Z * a.X - X * a.Z,
W * a.Z + Z * a.W + X * a.Y - Y * a.X,
W * a.W - X * a.X - Y * a.Y - Z * a.Z);
}
CVector3 CQuaternion::operator*(const CVector3& a) const
{
f32 xxzz = X * X - Z * Z;
f32 wwyy = W * W - Y * Y;
f32 xw2 = X * W * 2.0f;
f32 xy2 = X * Y * 2.0f;
f32 xz2 = X * Z * 2.0f;
f32 yw2 = Y * W * 2.0f;
f32 yz2 = Y * Z * 2.0f;
f32 zw2 = Z * W * 2.0f;
return CVector3((xxzz + wwyy) * a.X + (xy2 + zw2) * a.Y + (xz2 - yw2) * a.Z,
(xy2 - zw2) * a.X + (Y*Y + W*W - X*X - Z*Z) + (yz2 + xw2) * a.Z,
(xz2 + yw2) * a.X + (yz2 - xw2) * a.Y + (wwyy - xxzz) * a.Z);
}
CQuaternion CQuaternion::operator*(f32 a) const
{
return CQuaternion(X * a, Y * a, Z * a, W * a);
}
CQuaternion& CQuaternion::operator*=(f32 a)
{
*this = *this * a;
return *this;
}
CQuaternion CQuaternion::operator/(f32 a) const
{
f32 inv = 1.0f / a;
return *this * inv;
}
CQuaternion& CQuaternion::operator*=(const CQuaternion& a)
{
*this = *this * a;
return *this;
}
CQuaternion& CQuaternion::operator-=(const CQuaternion& a)
{
X -= a.X;
Y -= a.Y;
Z -= a.Z;
W -= a.W;
return *this;
}
CQuaternion& CQuaternion::operator+=(const CQuaternion& a)
{
X += a.X;
Y += a.Y;
Z += a.Z;
W += a.W;
return *this;
}
CQuaternion Engine::Math::operator*(const f32 a, const CQuaternion& b)
{
return b * a;
}
CVector3 Engine::Math::operator*(const CVector3 a, const CQuaternion& b)
{
return b * a;
}
bool CQuaternion::Compare(const CQuaternion & a) const
{
return (X == a.X && Y == a.Y && Z == a.Z && W == a.W);
}
bool CQuaternion::Compare(const CQuaternion & a, const f32 epsilon) const
{
return (Abs(X - a.X) <= EPSILON && Abs(X - a.X) <= EPSILON && Abs(Z - a.Z) <= EPSILON && Abs(W - a.W) <= EPSILON);
}
bool CQuaternion::operator==(const CQuaternion & a) const
{
return Compare(a);
}
bool CQuaternion::operator!=(const CQuaternion & a) const
{
return !Compare(a);
}
CQuaternion CQuaternion::Inverse() const
{
return CQuaternion(-X, -Y, -Z, W);
}
f32 CQuaternion::Length() const
{
f32 len = X * X + Y * Y + Z * Z + W * W;
return Math::Sqrt(len);
}
CQuaternion CQuaternion::Normalize() const
{
f32 len = Length();
if (len != 0.0f)
{
f32 ilen = 1.0f / len;
return CQuaternion(X * ilen, Y * ilen, Z * ilen, W * ilen);
}
return CQuaternion(X, Y, Z, W);
}
CQuaternion CQuaternion::Lerp(const CQuaternion& b, f32 delta)
{
if (delta <= 0.0f)
return *this;
else if (delta >= 1.0f)
return b;
else
{
return *this + delta * (b - *this);
}
}
CQuaternion CQuaternion::Slerp(const CQuaternion& to, f32 delta)
{
CQuaternion temp;
f32 omega, cosom, sinom, scale0, scale1;
if (delta <= 0.0f)
return CQuaternion(*this);
else if (delta >= 0.0f)
return CQuaternion(to);
else if (*this == to)
return CQuaternion(to);
else
{
cosom = X * to.X + Y * to.Y + Z * to.Z + W * to.W;
if (cosom < 0.0f)
{
temp = -to;
cosom = -cosom;
}
else
{
temp = to;
}
if ((1.0f - cosom) > 1e-6f)
{
scale0 = 1.0f - cosom * cosom;
sinom = Math::InvSqrt(scale0);
omega = Math::ATan2(scale0 * sinom, cosom);
scale0 = Math::Sin((1.0f - delta) * omega) * sinom;
scale1 = Math::Sin(delta * omega) * sinom;
}
else
{
scale0 = 1.0f - delta;
scale1 = delta;
}
return CQuaternion(scale0 * *this) + (scale1 * temp);
}
}
Engine::Containers::CString CQuaternion::ToString()
{
return S("(%f,%f,%f,%f)").Format(X, Y, Z, W);
}
bool CQuaternion::FromString(Engine::Containers::CString str, CQuaternion& a)
{
if (str.Length() <= 0 || // Needs a string :3
str[0] != '(' || str[str.Length() - 1] != ')' || // Needs the braces around it.
str.Count(',') != 3) // Needs exactly 1 seperating comma.
return false;
str = str.Trim("() ");
s32 idx = str.IndexOf(',');
s32 idx2 = str.IndexOf(',', idx + 1);
s32 idx3 = str.IndexOf(',', idx2 + 1);
Engine::Containers::CString x = str.SubString(0, idx).Trim();
Engine::Containers::CString y = str.SubString(idx + 1, (idx2 - idx) - 1).Trim();
Engine::Containers::CString z = str.SubString(idx2 + 1, (idx3 - idx2) - 1).Trim();
Engine::Containers::CString w = str.SubString(idx3 + 1).Trim();
a.Set(x.ToFloat(), y.ToFloat(), z.ToFloat(), w.ToFloat());
return true;
}
CMatrix3 CQuaternion::ToMatrix3() const
{
CMatrix3 mat;
f32 wx, wy, wz;
f32 xx, yy, yz;
f32 xy, xz, zz;
f32 x2, y2, z2;
x2 = X + X;
y2 = Y + Y;
z2 = Z + Z;
xx = X * x2;
xy = X * y2;
xz = X * z2;
yy = Y * y2;
yz = Y * z2;
zz = Z * z2;
wx = W * x2;
wy = W * y2;
wz = W * z2;
mat[0][0] = 1.0f - ( yy + zz );
mat[0][1] = xy - wz;
mat[0][2] = xz + wy;
mat[1][0] = xy + wz;
mat[1][1] = 1.0f - ( xx + zz );
mat[1][2] = yz - wx;
mat[2][0] = xz - wy;
mat[2][1] = yz + wx;
mat[2][2] = 1.0f - ( xx + yy );
return mat;
}
CMatrix4 CQuaternion::ToMatrix4() const
{
return ToMatrix3().ToMatrix4();
}
| true |
51dad55802bf90f5485257db348a095c96f2b45c | C++ | igonzalezb/EDA-TP8 | /COMPRESOR+DESCOMPRESOR/Tile.h | UTF-8 | 333 | 2.78125 | 3 | [] | no_license | #pragma once
#include <string>
using namespace std;
class Tile
{
public:
Tile() { ; }
Tile(string path);
~Tile();
void select();
void deselect();
void toggleSelection();
bool isSelected();
string getFilePath();
int getLength();
void setLength(int length);
private:
string filePath;
bool selected;
int length;
};
| true |
d881d3b13c2f904fa40460fa2a231bdf49a2ca23 | C++ | andrzej0szczepanczyk0muzyk/rekrutacja-techocean | /MergeSortTest/MergeSortTest/Source.cpp | WINDOWS-1250 | 2,308 | 3.1875 | 3 | [] | no_license | #define RAPORT "raport.txt"
#include <stdlib.h> /* malloc, free, rand */
#include <iostream>
#include <string>
#include <stdio.h>
#include <cstring>
#include <vector>
#include <cstdio>
#include <ctime>
#include <fstream>
using namespace std;
typedef vector<int> V;
//sortuje rosnco tablic pod referencj &K uywajc podziau tablicy na P czci przy jednej iteracji
void mergesort(vector<int> &K, int P)
{
if (K.size() <= 1) return;
vector<int>::iterator k = K.begin();
int s = K.size();
vector<vector<int>> slice(P);
for (int i = 0; i < P; i++)
{
slice[i] = vector<int>(k + s*i / P, k + s*(i + 1) / P);
mergesort(slice[i], P);
}
{
vector<int> it(slice.size(), 0);
int mval = 0;
int ik = 0;
int i;
int mi;
bool end = false;
while (end == false)
{
end = true;
mval = 0x7FFFFFFF;
for (i = 0; i < slice.size(); i++)
{
if (it[i] < slice[i].size())
{
if (mval > slice[i][it[i]]) { mval = slice[i][it[i]]; mi = i; }
end = false;
}
}
if (end == false)
{
K[ik++] = mval; it[mi]++;
}
}
}
}
void wyswietl(V k)
{
for (int u = 0; u < k.size(); u++) cout << k[u] << " "; cout << endl;
}
V wygenerujTablice(int k, int size)
{
int c = 31;
V tab(size);
for (int u = 0; u < tab.size(); u++)
{
//ustawienie 1 -> generuje tablic malejc
//ustawienie 0 -> generuje tablic wedug problemu Collatza
if (1)
{
c = tab.size() - u;
}
else
{
//Problem Collatza
if (c % 2 == 0) c = c / 2;
else c = 3 * c + 1;
}
tab[u] = c;
}
return tab;
}
int main()
{
clock_t start;
clock_t stop;
fstream f;
f.open(RAPORT, ios::out);
//wspczynnik > 1 -> maksymalna liczba podziaw w jednej iteracji w danym tecie wiksza, ni rozmiar tablicy
//wspczynnik < 1 -> w przeciwnym przypadku
const float wspolczynnik = 1.2;
const int ROZMIAR_T=100;
for (int u = 2; u < ROZMIAR_T*wspolczynnik; u++)
{
V A = wygenerujTablice(1,ROZMIAR_T);
start = clock();
mergesort(A, u);
stop = clock();
wyswietl(A);
cout << "czas wykonania si programu dla "<<u<<" podzialow: " << stop-start << endl;
f << u << "\t" << stop - start << "\n";
}
f.close();
} | true |
529dc8acf86419dd60d857e5001a84ffbe03e493 | C++ | kcaHder/Secrets | /histograph.cpp | UTF-8 | 575 | 2.984375 | 3 | [] | no_license | //
// histograph.cpp
//
//
// Created by Michele Iannello on 13/11/17.
//
//
#include "histogram.cpp"
#include "graph.cpp"
using namespace std;
void histograph()
{
bool again = 1;
while(again)
{
//Histogram or Graph?
bool choice;
cout << "Vuoi fare un istogramma (0) o un grafico (1)?" << endl;
cin >> choice;
//Histogram
if(!choice)
{
cin.get();
histogram();
}
//Graph
else
{
cin.get();
graph();
}
//Again?
cout << "Vuoi fare un altro grafico o istogramma (1) oppure no (0)?" << endl;
cin >> again;
}
}
| true |
7571ae82748952d7343fb5c30edaabda7d2a21a0 | C++ | yonasadiel/cp | /FacebookHackerCup/2018_1_A_EthanTraversesATree.cpp | UTF-8 | 1,379 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int n, k;
int a[2005];
int b[2005];
vector<int> pre;
vector<int> post;
vector<int> adj[2005];
int label[2005];
void traverse(int node) {
pre.push_back(node);
if (a[node]) { traverse(a[node]); }
if (b[node]) { traverse(b[node]); }
post.push_back(node);
}
void dfs(int node, int l) {
label[node] = l;
for (int a : adj[node])
if (label[a] == -1) dfs(a, l);
}
void solve(int tc) {
pre.clear();
post.clear();
for (int i=0; i<2005; i++) adj[i].clear();
memset(label, -1, sizeof label);
scanf("%d%d", &n, &k);
for (int i=1; i<=n; i++) {
scanf("%d%d", &a[i], &b[i]);
}
traverse(1);
// for (int a : pre) printf(" %2d", a); printf("\n");
// for (int a : post) printf(" %2d", a); printf("\n");
for (int i=0; i<pre.size(); i++) {
adj[pre[i]].push_back(post[i]);
adj[post[i]].push_back(pre[i]);
}
int l = 1;
for (int i=1; i<=n; i++) {
if (label[i] == -1) {
dfs(i, l);
l++;
}
}
printf("Case #%d:", tc);
if (l > k) {
for (int i=1; i<=n; i++) { printf(" %d", ((label[i] - 1) % k) + 1); }
printf("\n");
} else {
printf(" Impossible\n");
}
}
int main() {
int t;
scanf("%d", &t);
for (int i=1; i<=t; i++) {
solve(i);
}
} | true |
939e97a1d1a4770fd7f3a2fcf53daa87bf8b261b | C++ | zh880517/GMServer | /CoreLib/LibActor/Message/ValueMessage.h | UTF-8 | 850 | 2.875 | 3 | [] | no_license | #pragma once
#include <LibActor/Message/IMessage.h>
namespace ActorLite
{
template <class ValueType>
class ValueMessage : public IMessage
{
public:
explicit ValueMessage(const Detail::Address& from, bool bUdp):IMessage(from, false, bUdp){ }
explicit ValueMessage(const Detail::Address& from, ValueType value, bool bUdp) :IMessage(from, false, bUdp), m_Value(value){ }
ValueType& Value(){ return m_Value; }
const ValueType& Value()const { return m_Value; }
const char* TypeName() const { return MessageTraits<ValueType>::TYPE_NAME; }
virtual uint32_t TypeID() const override { return MessageTraits<ValueType>::TYPE_ID; }
private:
ValueType m_Value;
private:
ValueMessage(const ValueMessage &other);
ValueMessage &operator=(const ValueMessage &other);
public:
~ValueMessage(){}
};
} | true |
ca7d385e39720c2f49926b278324e4c195c62c64 | C++ | Radziu1202/AISD | /problem plecakowy/Rucksack.cpp | UTF-8 | 9,645 | 2.90625 | 3 | [] | no_license | #include "stdlib.h"
#include "time.h"
#include <Windows.h>
#include "math.h"
#include "random"
#include "stdio.h"
#include "iostream"
#include "algorithm"
#include <fstream>
using namespace std;
double PCFreq = 0.0;
__int64 CounterStart = 0;
void StartCounter()
{
LARGE_INTEGER li;
if (!QueryPerformanceFrequency(&li))
printf("QueryPerformanceFrequency failed!\n");
PCFreq = double(li.QuadPart);
QueryPerformanceCounter(&li);
CounterStart = li.QuadPart;
}
double GetCounter()
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return double(li.QuadPart - CounterStart) / PCFreq;
} //chronometr
void print_matrix(int**K, int n, int n1)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n1; j++)
{
cout<<K[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
struct item
{
int waga;
int wartosc;
};
struct item* tab_itemy(int n)
{
struct item *tablica_itemow=new struct item[n];
for (int i = 0; i < n; i++)
{
struct item IT;
IT.waga=rand() % 100 + 1;
IT.wartosc=rand() % 100 + 1;
tablica_itemow[i]=IT;
}
return tablica_itemow;
}
double **new_part(int n)
{
double** part = new double*[n];
for (int i = 0; i < n; i++)
{
part[i] = new double[3];
}
return part;
}
int **new_matrix(int n,int n1)
{
int **K = new int*[n + 1];
for (int i = 0 ; i<(n+1) ; i++)
{
K[i]=new int[n1+1]();
}
return K;
}
void items(int **K, int n, int n1, struct item *itemy)
{
cout<<"Dynamic numery Przedmiotow: ";
int g = n, g1 = n1;
int waga = 0;
int M = -1, maksymalna = -1;
while (M != 0)
{
for (int i = 0; i < g; i++)
{
for (int j = 0; j < g1; j++)
{
if (K[i][j] > maksymalna)
{
maksymalna = K[i][j];
M = i;
}
}
}
g = M;
g1 -= itemy[M - 1].waga;
maksymalna = -1;
if(M>=1)
waga += itemy[M - 1].waga;
if(M)
cout<<M<<" ";
}
cout<<endl<<"waga przdmiotow dynamic: "<<waga<<endl;
}
int dynamic(int**K, int W, struct item *itemy, int n)
{
for (int i = 1; i < n+1; i++)
{
for (int w = 1; w < W+1; w++)
{
if (itemy[i-1].waga <= w)
K[i][w] = max(itemy[i-1].wartosc+ K[i - 1][w - itemy[i-1].waga], K[i - 1][w]);
else
K[i][w] = K[i - 1][w];
}
}
print_matrix(K, n + 1, W + 1);
items(K, n + 1, W + 1, itemy);
cout<<"Dynamic Wartosc "<<K[n][W]<<endl;
return K[n][W];
}
bool sort_by_first(double* A, double* C)
{
return A[0] > C[0];
}
int greedy(double**part, int W, struct item* itemy, int n)
{
int res = 0;
for (int i = 0; i < n; i++)
{
part[i][1] = itemy[i].wartosc;
part[i][2] = itemy[i].waga;
part[i][0] = (part[i][1]/part[i][2]);
}
sort(part, part + n, sort_by_first);
int k = 0;
while (k < n)
{
if (W - part[k][2] < 0)
{
k++;
continue;
}
res += part[k][1];
W -= part[k++][2];
}
return res;
}
//-------------------BRUTE FORCE----------------
bool check_candidate(vector<struct item> candidate,int b)
{
int whole_weight=0;
for (int i=0; i<candidate.size(); i++)
{
whole_weight+=candidate[i].waga;
}
if (whole_weight<=b)
return true;
return false;
}
int evalue_candidate(vector<struct item> candidate)
{
int whole_value=0;
for (int i =0; i<candidate.size(); i++)
{
whole_value+=candidate[i].wartosc;
}
return whole_value;
}
vector<struct item> gen_solution(struct item* items, int n, int N)
{
vector<struct item> solution_vec;
int k;
for(int i = 0; i < N; i++)
{
k = pow(2,i);
if(n & k)
{
solution_vec.push_back(items[i]);
}
}
/*
cout<< "--------" << n <<endl;
for(int i=0;i< solution_vec.size();i++)
cout << solution_vec[i] << " ";
cout << endl;
*/
return solution_vec;
}
int brute_force(struct item* items, int n,int b)
{
int pn = (int) pow(2, n);
int maksymalna=0;
vector<struct item>best_combination;
vector<struct item>candidate;
for(int i = 0; i < pn; i++)
{
candidate=gen_solution(items, i, n);
if (check_candidate(candidate,b))
{
int temp=evalue_candidate(candidate);
if(temp>maksymalna)
{
maksymalna=temp;
best_combination=candidate;
}
}
}
cout <<"wartosci BF: ";
for(int i=0; i< best_combination.size(); i++)
{
cout << best_combination[i].wartosc << " ";
}
cout<<endl<<"wagi BF: ";
for(int i=0; i< best_combination.size(); i++)
{
cout << best_combination[i].waga << " ";
}
cout << endl;
return maksymalna;
}
void execute_b(int b)
{
double suma_wynikow_dynamic=0.0,suma_wynikow_greedy=0.0;
double suma_czasow_greedy=0.0,suma_czasow_dynamic=0.0;
double suma_czasow_BF=0.0;
fstream zapis;
for (int n=1000;n<100000; n+=8000)
{
cout<<n<<endl;
for (int j =0; j<15; j++)
{
struct item* itemy=tab_itemy(n);
int** K = new_matrix(n,b);
StartCounter();
int wynik_dynamic = dynamic(K, b,itemy, n);
suma_czasow_dynamic+=GetCounter();
cout<<"dynamic wartosc: "<<wynik_dynamic<<endl;
suma_wynikow_dynamic+=wynik_dynamic;
for (int i =0;i<n;i++)
delete K[i];
delete[] K;
// StartCounter();
// int wynik=brute_force(itemy,n,b);
// suma_czasow_BF+=GetCounter();
// cout<<"BF wartosc "<<wynik<<endl<<endl<<endl;
double **part=new_part(n);
StartCounter();
int wynik_greedy = greedy(part, b, itemy, n);
suma_czasow_greedy+=GetCounter();
suma_wynikow_greedy+=wynik_greedy;
cout<<"Greedy wartosc: "<< wynik_greedy<<endl<<endl<<endl<<endl;
for (int i=0;i<3;i++)
{
delete part[i];
}
delete []part;
}
zapis.open("wyniki Knapsack.txt", ios::out | ios::app);
if(zapis.good() == true)
{
zapis<<suma_czasow_dynamic/15.0<<"\t"<<suma_czasow_greedy/15.0<<"\t"<<"wyniki dynamic:\t"<<suma_wynikow_dynamic/15.0<<"wyniki greedy:\t"<<suma_wynikow_greedy/15.0<<"\t"<<n <<endl;
zapis.close();
}
suma_czasow_dynamic=0.0;
suma_czasow_greedy=0.0;
suma_wynikow_dynamic=0.0;
suma_wynikow_greedy=0.0;
}
}
void execute_n(int n)
{
double suma_wynikow_dynamic=0.0,suma_wynikow_greedy=0.0;
double suma_czasow_greedy=0.0,suma_czasow_dynamic=0.0;
fstream zapis;
for (int b=100;b<2000; b+=100)
{
cout<<b<<endl;
for (int j =0; j<15; j++)
{
struct item* itemy=tab_itemy(n);
int** K = new_matrix(n,b);
StartCounter();
int wynik_dynamic = dynamic(K, b,itemy, n);
suma_czasow_dynamic+=GetCounter();
cout<<"dynamic wartosc: "<<wynik_dynamic<<endl;
suma_wynikow_dynamic+=wynik_dynamic;
for (int i =0;i<n;i++)
delete K[i];
delete[] K;
double **part=new_part(n);
StartCounter();
int wynik_greedy = greedy(part, b, itemy, n);
suma_czasow_greedy+=GetCounter();
suma_wynikow_greedy+=wynik_greedy;
cout<<"Greedy wartosc: "<< wynik_greedy<<endl<<endl<<endl<<endl;
for (int i=0;i<3;i++)
{
delete part[i];
}
delete []part;
}
zapis.open("wyniki Knapsack.txt", ios::out | ios::app);
if(zapis.good() == true)
{
zapis<<suma_czasow_dynamic/15.0<<"\t"<<suma_czasow_greedy/15.0<<"\t"<<"wyniki dynamic:\t"<<suma_wynikow_dynamic/15.0<<"wyniki greedy:\t"<<suma_wynikow_greedy/15.0<<"\t"<<n <<endl;
zapis.close();
}
suma_czasow_dynamic=0.0;
suma_czasow_greedy=0.0;
suma_wynikow_dynamic=0.0;
suma_wynikow_greedy=0.0;
}
}
void test(int b)
{
int n=5;
struct item *itemy= new item[n];
struct item IT;
IT.waga=4;
IT.wartosc=3;
itemy[0]=IT;
IT.waga=1;
IT.wartosc=5;
itemy[1]=IT;
IT.waga=4;
IT.wartosc=2;
itemy[2]=IT;
IT.waga=3;
IT.wartosc=7;
itemy[3]=IT;
IT.waga=12;
IT.wartosc=42;
itemy[4]=IT;
int** K = new_matrix(n,b);
dynamic(K, b,itemy, n);
double **part=new_part(n);
cout<<endl<<"Wartosc greedy: "<<greedy(part,b,itemy,n);
}
int main()
{
srand(time(NULL));
// test(12);
int b,n=20;
struct item *itemy=tab_itemy(n);
StartCounter();
int wynik=brute_force(itemy,n,b);
cout<<GetCounter()<<endl;;
// b= 80;
// execute_b(b);
// int n =50;
// execute_n(n);
return 0;
}
| true |
f2302d6bac52511e4a20e045f14c4a0411c6812e | C++ | corenel/ip-camera-ehome-server | /include/ices/util.h | UTF-8 | 1,381 | 3.140625 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
template <typename Ret, typename... Param0>
class Callback {
public:
virtual Ret invoke(Param0... param0) = 0;
};
template <typename Ret, typename... Param0>
class StaticFunctionCallback : public Callback<Ret, Param0...> {
private:
Ret (*func_)(Param0...);
public:
StaticFunctionCallback(Ret (*func)(Param0...)) : func_(func) {}
virtual Ret invoke(Param0... param0) { return (*func_)(param0...); }
};
template <typename Ret, typename T, typename Method, typename... Param0>
class MethodCallback : public Callback<Ret, Param0...> {
private:
void* object_;
Method method_;
public:
MethodCallback(void* object, Method method)
: object_(object), method_(method) {}
virtual Ret invoke(Param0... param0) {
T* obj = static_cast<T*>(object_);
return static_cast<void*>((obj->*method_)(param0...));
}
};
template <typename Ret, typename... Param0>
class Delegate {
private:
Callback<Ret, Param0...>* callback_;
public:
explicit Delegate(Ret (*func)(Param0...))
: callback_(new StaticFunctionCallback<Ret, Param0...>(func)) {}
template <typename T, typename Method>
Delegate(T* object, Method method)
: callback_(
new MethodCallback<Ret, T, Method, Param0...>(object, method)) {}
~Delegate() { delete callback_; }
Ret operator()(Param0... param0) { return callback_->invoke(param0...); }
};
| true |
380335ddb7de5936426adb3019e211f344c1294c | C++ | sydchen/leetcode | /best-time-to-buy-and-sell-stock.cpp | UTF-8 | 535 | 3.296875 | 3 | [] | no_license | #include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int maxProfit(vector<int> &prices) {
int minPrice = INT_MAX, bestProfit = 0, profit;
for(auto &price:prices) {
if(price < minPrice)
minPrice = price;
profit = price - minPrice;
if(profit > bestProfit)
bestProfit = profit;
}
return bestProfit;
}
};
int main()
{
vector<int> prices {1};
Solution s;
cout << s.maxProfit(prices);
}
| true |
72770058554d9fb5610d5a5fbf927a97af4bb957 | C++ | mgmourgos/juke-engine | /Files/Player.cpp | UTF-8 | 1,358 | 2.5625 | 3 | [] | no_license | #include "Player.h"
#include "PlayerConstants.h"
const int PLAYER_WIDTH = 25;
const int PLAYER_HEIGHT = 32;
Player::Player(Graphics& graphics, int x_, int y_) : Actor(x_, y_, PLAYER_WIDTH, PLAYER_HEIGHT, MOVEABLE)
{
sprite.reset(new Sprite(graphics, "Files/ghostSheet.bmp", 0, 0, width, height));
move_context_state = std::make_unique<OnGroundState>();
}
Player::~Player()
{
}
void Player::draw(const Graphics& graphics, int x_render_pos, int y_render_pos) const {
sprite->draw(graphics, x_render_pos, y_render_pos);
}
void Player::handleCommand(const Command& command) {
move_context_state->handleCommand(*this, command);
}
void Player::update(int elapsed_time_ms) {
double remaining_time_ms = elapsed_time_ms;
for (auto& collision : collision_vector)
{
setCollisionNormal(collision->normal);
}
Box result_box = physics.update(collision_vector, getBox(), move_context_state->getMaxVelocity(), elapsed_time_ms);
setBox(result_box);
collision_vector.clear();
move_context_state->update(*this, remaining_time_ms);
x_acc = 0;//Acceleration is only set actively(by commands)
//So we set it back to zero each frame
collision_normals.reset();
}
void Player::setMoveContextState(MoveContextState* new_state) {
move_context_state->onExit(*this);
move_context_state.reset(new_state);
move_context_state->onEntry(*this);
}
| true |
0870470bd5da1c3bf135291d9f1cfcd4d38bbbb7 | C++ | mojtabafazeli/competitive-programming | /07. Heap/4 [hackerearth] Roy and Trending Topics.cpp | UTF-8 | 2,017 | 3.265625 | 3 | [] | no_license | // Problem: Roy and Trending Topics
// Link: https://www.hackerearth.com/practice/data-structures/trees/heapspriority-queues/practice-problems/algorithm/roy-and-trending-topics-1/description/
// Solution: Mai Thanh Hiep
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
struct Record {
long long id;
long long change;
long long newScore;
};
struct greaterComparator {
bool operator() (const Record& r1, const Record& r2) const {
if (r1.change != r2.change)
return r1.change > r2.change;
else
return r1.id > r2.id;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
priority_queue<Record, vector<Record>, greaterComparator> minHeap;
long long topicId, currentScore, posts, likes, comments, shares;
long long newScore, change;
for (int i = 0; i < n; i++) {
cin >> topicId >> currentScore >> posts >> likes >> comments >> shares;
newScore = posts * 50 + likes * 5 + comments * 10 + shares * 20;
change = newScore - currentScore;
if (minHeap.size() < 5) {
minHeap.push((Record) {topicId, change, newScore});
}
// if we found a greater record, remove current min record, push new one to our minHeap
else if ((minHeap.top().change < change) || (minHeap.top().change == change && minHeap.top().id < topicId)) {
minHeap.pop();
minHeap.push((Record) {topicId, change, newScore});
}
}
// convert heap to vector for sorting
vector<Record> records;
while (!minHeap.empty()) {
records.push_back(minHeap.top());
minHeap.pop();
}
// Sort in decreasing by change, id
sort(records.begin(), records.end(), greaterComparator());
// print results
for (int i = 0; i < records.size(); i++) {
cout << records[i].id << " " << records[i].newScore << endl;
}
return 0;
}
| true |
b221b32330bbc89281ce8285d096414525356ca4 | C++ | ZhouAaron/PAT | /PAT A1076 Forwards on Weibo/PAT A1076 Forwards on Weibo/main.cpp | UTF-8 | 1,612 | 2.796875 | 3 | [] | no_license | //
// main.cpp
// PAT A1076 Forwards on Weibo
//
// Created by Aaron on 5/19/19.
// Copyright © 2019 周杰. All rights reserved.
//
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int MAXV = 1010;
struct Node{
int id;//节点编号
int layer;//层数
};
vector<Node> Adj[MAXV];//邻接表
bool inq[MAXV] = {false};
//starts为起始节点。L为层数上限
int BFS(int s,int L){
int numForward = 0;//转发数
queue<Node> q;
Node start;
start.id = s;
start.layer = 0;
q.push(start);
inq[start.id] = true;
while (!q.empty()) {
Node topNode = q.front();
q.pop();
int u = topNode.id;
for (int i = 0; i<Adj[u].size(); i++) {
Node next = Adj[u][i];
next.layer = topNode.layer + 1;
if (inq[next.id] == false && next.layer <= L) {
q.push(next);
inq[next.id] = true;
numForward++;
}
}
}
return numForward;
}
int main(int argc, const char * argv[]) {
Node user;
int n,L,numFollow,idFollow;
scanf("%d%d",&n,&L);
for (int i = 1; i<=n; i++) {
user.id = i;
scanf("%d",&numFollow);
for (int j = 0; j<numFollow; j++) {
scanf("%d",&idFollow);
Adj[idFollow].push_back(user);
}
}
int numQuery ,s;
scanf("%d",&numQuery);
for (int i = 0; i<numQuery; i++) {
memset(inq, false, sizeof(inq));
scanf("%d",&s);
int numForward = BFS(s, L);
printf("%d\n",numForward);
}
return 0;
}
| true |
79b9f88d2f6159d6f54a20fcaf814e32964db441 | C++ | SEOYEONGO/CPP | /함수 중복 작성 & 디폴트 매개변수/함수 중복 작성 + 디폴트 매개 변수/실습2-2 Person class 디폴트.cpp | UTF-8 | 429 | 3.75 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Person{
int id;
double weight;
string name;
public:
Person(int id=1, string name="Grace", double weight=20.5){
this->id=id;
this->name=name;
this->weight=weight;
}
void show() { cout<<id<<' '<<weight<<' '<<name<<endl;}
};
int main (){
Person grace, ashley(2, "Ashley"), helen(3, "Helen", 32.5);
grace.show();
ashley.show();
helen.show();
}
| true |
efdadf66e8a8915ab5fccb8cbfbe5b5ae9f2b548 | C++ | karthich/programming-contest | /spoj/cpp/Completed/Prime.cpp | UTF-8 | 1,847 | 3.0625 | 3 | [] | no_license | // Prime1.cpp : Defines the entry point for the console application.
//
#include<math.h>
#include<stdio.h>
#include<stdlib.h>
#define SIEVE_LIMIT 31627
#define TEST_CASES 10
#define PRIME_LIMIT 100001
#define LENGTH 100000
#define NUM_PRIMES 3402
using namespace std;
int primes[NUM_PRIMES];
void prime1(long a, long b);
void sieve();
int main()
{
int t,i,j;
scanf("%d",&t);
long a=0,b=0;
sieve();
for(i=0;i<t;i++)
{
scanf("%ld %ld",&a,&b);
prime1(a,b);
}
return 0;
}
void sieve()
{
int pr_count = 3,i,j,limit;
primes[0] = 2;
primes[1] = 3;
primes[2] = 5;
primes[3] = 7;
int isPrime = 1;
for(i=7;i<SIEVE_LIMIT;i+=2)
{
limit = (int)sqrtl(i);
for(j=0;primes[j]<=limit;j++)
{
if(i%primes[j]==0)
{
isPrime = 0;
break;
}
else
continue;
}
if(isPrime)
{
pr_count++;
primes[pr_count] = i;
}
isPrime = 1;
}
}
void prime1(long a,long b)
{
int range =(int) b- a + 1,limit,*prime,i,j,k;
prime = (int*) calloc(range, sizeof(int));
for(i=0;i<range;i++)
{
if(a+i==1)
{
prime[i] = 2;
continue;
}
if(a+i==2)
{
prime[i]=1;
printf("%ld\n",a+i);
continue;
}
else if((a+i)%2==0)
continue;
limit = (int) sqrtl(a+i);
for(j=0;primes[j]<=limit&&j<NUM_PRIMES;j++)
{
if(prime[i]!=2)
{
if((a+i)%primes[j]==0)
{
for(k=i;k<=range;k+=primes[j])
{
prime[k] = 2;
}
break;
}
else
continue;
}
}
if((a+i)==primes[j]||prime[i]==0)
{
prime[i]=1;
printf("%ld\n",a+i);
}
}
}
| true |
4138dda22bf86702b5ddb15bfa613970b3a36c62 | C++ | Schnee-B/SCAU_OJ | /Advanced Progreamming/Advanced Progreamming/17243 Huzi酱和他的俄罗斯套娃.cpp | UTF-8 | 595 | 2.71875 | 3 | [] | no_license | #include<cstdio>
#include<cstdlib>
#include<cstring>
int cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
int main()
{
int count, n, a[502], i, j;
while (scanf("%d", &n) != EOF)
{
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
qsort(a, n, sizeof(a[0]), cmp);
count = 0;
for (i = 0; i < n - 2; i++)
{
for (j = n / 2; j < n; j++)
{
if (a[i] != 0 && a[j] != 0 && a[j] / a[i] >= 3)
{
count++;
a[i] = a[j] = 0;
break;
}
}
}
for (i = 0; i < n; i++)
{
if (a[i] != 0)
count++;
}
printf("%d\n", count);
}
return 0;
} | true |
ac3cab0725074c95fce057d06b6e3986d5de086b | C++ | unisb-bioinf/TransitivityClusteringILP | /Distance.h | UTF-8 | 19,319 | 2.5625 | 3 | [] | no_license | /**
* Copyright (C) 2020 Tim Kehl <tkehl@bioinf.uni-sb.de>
* Kerstin Lenhof <klenhof@bioinf.uni-sb.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as
* published by the Free Software Foundation, either version 3 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
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the Lesser GNU General Public
* License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef TRANSITIVITY_CLUSTERING_ILP_STATISTIC_H
#define TRANSITIVITY_CLUSTERING_ILP_STATISTIC_H
#include <algorithm>
#include <cmath>
#include <numeric>
#include <tuple>
#include <vector>
#include <iostream>
#include <map>
#include <boost/math/special_functions/atanh.hpp>
#include "macros.h"
#include "DenseMatrix.h"
namespace TransitivityClusteringILP
{
/**
* A collection of mathematical operations.
*/
namespace Distance
{
/**
* This methods implements the squared distance.
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type
mean_difference(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator)
{
value_type n = (value_type)std::distance(first_begin, first_end);
value_type diff = 0;
for(; first_begin != first_end; ++first_begin, ++second_begin) {
diff += (*first_begin - *second_begin);
}
return diff / n;
}
/**
* This methods implements the squared distance.
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type
squared_distance(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator)
{
value_type n = (value_type)std::distance(first_begin, first_end);
value_type dist = 0;
for(; first_begin != first_end; ++first_begin, ++second_begin) {
value_type diff = (*first_begin - *second_begin);
dist += diff * diff;
}
return dist / n;
}
/**
* This methods implements the euclidean distance.
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type
euclidean_distance(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator second_end)
{
return std::sqrt(squared_distance<value_type, InputIterator>(first_begin, first_end, second_begin, second_end));
}
/**
* This methods implements the shifted euclidean distance.
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type
shifted_euclidean_distance_for_points(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator)
{
value_type n = (value_type)std::distance(first_begin, first_end);
value_type s = 0.0;
// Calculate optimal shift
InputIterator first = first_begin;
InputIterator second = second_begin;
for(; first != first_end; ++first, ++second) {
s += (*first - *second);
}
s = s / n;
value_type dist = 0.0;
//Calculate shifted distance
for(; first_begin != first_end; ++first_begin, ++second_begin) {
value_type diff = (*first_begin - s - *second_begin);
dist += diff * diff;
}
return std::sqrt(dist / n);
}
/**
* This methods implements the euclidean distance for gradients.
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type
euclidean_distance_for_gradients(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator second_end)
{
std::vector<value_type> fc_1;
fc_1.reserve(std::distance(first_begin, first_end));
for(; first_begin != (first_end-1); ++first_begin) {
fc_1.emplace_back(*(first_begin+1) - *first_begin);
}
std::vector<value_type> fc_2;
fc_2.reserve(std::distance(second_begin, second_end));
for(; second_begin != (second_end-1); ++second_begin) {
fc_2.emplace_back(*(second_begin+1) - *second_begin);
}
return euclidean_distance<value_type>(fc_1.begin(), fc_1.end(), fc_2.begin(), fc_2.end());
}
template <typename value_type>
value_type theta(value_type x1, value_type x2, value_type y1, value_type y2)
{
if(x1 == x2 && y1 == y2 && x1 == y1 && x2 == y2) {
return 0.0;
}
value_type cos_alpha = (x1*y1 + x2*y2)/(std::sqrt(x1*x1 + x2*x2) * std::sqrt(y1*y1 + y2*y2));
value_type theta = std::acos(cos_alpha) / 3.141593 * 180.0;
return theta;
}
/**
* This methods calculates the angles between ...
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
std::vector<value_type> calculate_angles(InputIterator begin, InputIterator end)
{
std::vector<value_type> angles;
angles.reserve(std::distance(begin, end));
for(; begin != (end-1); ++begin) {
angles.emplace_back(theta(*(begin), *(begin), *(begin), *(begin+1)));
}
return std::move(angles);
}
/**
* This methods implements the shifted euclidean distance.
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type
angle_distance(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator)
{
value_type sum = 0.0;
for(auto i=0; i<std::distance(first_begin, first_end)-1; ++i) {
double th = theta(1.0, *(first_begin+1+i) - *(first_begin+i), 1.0, *(second_begin+1+i) - *(second_begin+i));
sum += th;
}
return sum / (double)std::distance(first_begin, first_end);
}
/**
* This methods implements the shifted euclidean distance.
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type
normalized_angle_distance(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator)
{
value_type sum = 0.0;
for(auto i=0; i<std::distance(first_begin, first_end)-1; ++i) {
double fc1 = *(first_begin+1+i) - *(first_begin+i);
double fc2 = *(second_begin+1+i) - *(second_begin+i);
double th = theta(1.0, fc1, 1.0, fc2);
double th1 = theta(1.0, 0.0, 1.0, fc1);
double th2 = theta(1.0, 0.0, 1.0, fc2);
sum += th / (1.0 + th1 + th2);
}
return sum / (double)std::distance(first_begin, first_end);
}
/**
* This methods implements the shifted euclidean distance.
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type
shifted_euclidean_distance_for_angles(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator second_end)
{
std::vector<value_type> ang1 = calculate_angles<value_type>(first_begin, first_end);
std::vector<value_type> ang2 = calculate_angles<value_type>(second_begin, second_end);
return shifted_euclidean_distance_for_points<value_type>(ang1.begin(), ang1.end(), ang2.begin(), ang2.end());
}
/**
* This methods implements the shifted euclidean distance.
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type
shifted_euclidean_distance_for_gradients(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator second_end)
{
std::vector<value_type> fc_1;
fc_1.reserve(std::distance(first_begin, first_end));
for(; first_begin != (first_end-1); ++first_begin) {
fc_1.emplace_back(*(first_begin+1) - *first_begin);
}
std::vector<value_type> fc_2;
fc_2.reserve(std::distance(second_begin, second_end));
for(; second_begin != (second_end-1); ++second_begin) {
fc_2.emplace_back(*(second_begin+1) - *second_begin);
}
return shifted_euclidean_distance_for_points<value_type>(fc_1.begin(), fc_1.end(), fc_2.begin(), fc_2.end());
}
/**
* This methods implements the shifted euclidean distance.
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type
shifted_euclidean_distance_for_gradients_and_points(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator second_end)
{
return shifted_euclidean_distance_for_points<value_type>(first_begin, first_end, second_begin, second_end) +
shifted_euclidean_distance_for_gradients<value_type>(first_begin, first_end, second_begin, second_end);
}
/**
* This methods calculates the pairwise euclidean distance for all points in a given range.
*
* @param begin InputIterator corresponding to the start of the first group.
* @param end InputIterator corresponding to the end of the first group.
*
* @return Distance matrix
*/
template <typename value_type, typename InputIterator>
GeneTrail::DenseMatrix pairwise_distance(InputIterator begin, InputIterator end) {
std::vector<value_type> x(begin, end);
GeneTrail::DenseMatrix dist(x.size(), x.size());
for(size_t i=0; i<x.size(); ++i){
dist.set(i, i, 0.0);
for(size_t j=i+1; j<x.size(); ++j){
value_type diff = x[i] - x[j];
dist(i, j) = std::sqrt(diff*diff);
dist(j, i) = dist(i, j);
}
}
return std::move(dist);
}
/**
* This methods normalizes a distance matrix.
*
* @param begin InputIterator corresponding to the start of the first group.
* @param end InputIterator corresponding to the end of the first group.
*
* @return Normalized distance matrix
*/
GeneTrail::DenseMatrix normalize_distances(GeneTrail::DenseMatrix& A) {
double n = (double)A.rows();
double mean = 0.0;
std::vector<double> row_means(A.rows(), 0.0);
std::vector<double> col_means(A.cols(), 0.0);
for(size_t i=0; i<A.rows(); ++i){
for(size_t j=0; j<A.cols(); ++j){
mean += A(i,j);
row_means[i] += A(i,j);
col_means[j] += A(i,j);
}
}
mean /= n*n;
for(size_t i=0; i<n; ++i){
row_means[i] /= n;
col_means[i] /= n;
}
for(size_t i=0; i<A.rows(); ++i){
for(size_t j=0; j<A.cols(); ++j){
A(i,j) = A(i,j) - row_means[i] - col_means[j] + mean;
}
}
return A;
}
/**
* This methods implements the distance covariance.
*
* @param A Normalized distance matrix
* @param B Normalized distance matrix
*
* @return Distance
*/
template <typename value_type>
value_type distance_covariance(GeneTrail::DenseMatrix& A, GeneTrail::DenseMatrix& B)
{
double n = (double)A.rows();
value_type cov = 0.0;
for(size_t i=0; i<A.rows(); ++i){
for(size_t j=0; j<A.cols(); ++j){
cov += A(i,j)*B(i,j);
}
}
cov /= n*n;
return(std::sqrt(cov));
}
/**
* This methods implements the distance correlation.
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type distance_covariance(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator second_end)
{
GeneTrail::DenseMatrix A = pairwise_distance<value_type>(first_begin, first_end);
A = normalize_distances(A);
GeneTrail::DenseMatrix B = pairwise_distance<value_type>(second_begin, second_end);
B = normalize_distances(B);
return distance_covariance<value_type>(A, B);
}
/**
* This methods implements the distance correlation.
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type distance_correlation(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator second_end)
{
GeneTrail::DenseMatrix A = pairwise_distance<value_type>(first_begin, first_end);
A = normalize_distances(A);
GeneTrail::DenseMatrix B = pairwise_distance<value_type>(second_begin, second_end);
B = normalize_distances(B);
double cov = distance_covariance<value_type>(A, B);
double varA = distance_covariance<value_type>(A, A);
double varB = distance_covariance<value_type>(B, B);
return cov / std::sqrt(varA * varB);
}
/**
* This methods implements the Dynamic Time Warping Distance Measure.
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type dynamic_time_warping(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator second_end)
{
std::vector<double> x(first_begin, first_end);
std::vector<double> y(second_begin, second_end);
GeneTrail::DenseMatrix DTW(x.size(), y.size());
DTW(0,0) = 0.0;
for(size_t i=0; i<x.size(); ++i) {
for(size_t j=0; j<y.size(); ++j) {
double cost = std::abs(x[i]-y[j]);
if(i == 0 && j == 0) continue;
if(i == 0) {
DTW(i,j) = cost + DTW(i, j-1);
} else if(j == 0) {
DTW(i,j) = cost + DTW(i-1, j);
} else {
DTW(i,j) = cost + std::min(DTW(i-1, j), std::min(DTW(i, j-1), DTW(i-1, j-1)));
}
}
}
return DTW(x.size()-1, y.size()-1);
}
/**
* This methods implements the Dynamic Time Warping Distance Measure (for gradients).
*
* @param first_begin InputIterator corresponding to the start of the first group.
* @param first_end InputIterator corresponding to the end of the first group.
* @param second_begin InputIterator corresponding to the start of the second group.
* @param second_end InputIterator corresponding to the end of the second group.
*
* @return Distance
*/
template <typename value_type, typename InputIterator>
value_type dynamic_time_warping_for_gradients(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator second_end)
{
std::vector<double> x(first_begin, first_end);
std::vector<double> y(second_begin, second_end);
GeneTrail::DenseMatrix DTW(x.size()-1, y.size()-1);
DTW(0,0) = 0.0;
for(size_t i=0; i<x.size()-1; ++i) {
for(size_t j=0; j<y.size()-1; ++j) {
double cost = std::abs((x[i+1]-x[i])-(y[j+1]-y[j]));
if(i == 0 && j == 0) continue;
if(i == 0) {
DTW(i,j) = cost + DTW(i, j-1);
} else if(j == 0) {
DTW(i,j) = cost + DTW(i-1, j);
} else {
DTW(i,j) = cost + std::min(DTW(i-1, j), std::min(DTW(i, j-1), DTW(i-1, j-1)));
}
}
}
return DTW(x.size()-2, y.size()-2);
}
}
}
#endif // TRANSITIVITY_CLUSTERING_ILP_STATISTIC_H
| true |
8be0d1e31419136abddc099e61310a1a7faacbbd | C++ | numpad/snong | /Obstacles.cpp | UTF-8 | 974 | 2.875 | 3 | [] | no_license | #include "Obstacles.hpp"
Obstacles::Obstacles() {
Obstacles::array = std::vector<Obstacle>();
}
void Obstacles::add(Obstacle o) {
Obstacles::array.push_back(o);
}
void Obstacles::each(std::function<void (Obstacle &)> func) {
for (auto &o : Obstacles::array) {
func(o);
}
}
void Obstacles::update() {
}
void Obstacles::collide(Ball &ball, Background &background) {
Obstacles::each([&ball, &background](Obstacle &o){
if (c2AABBtoAABB(ball.getAABB(), o.getAABB())) {
c2Manifold collision;
c2AABBtoAABBManifold(ball.getAABB(), o.getAABB(), &collision);
if (fabs(collision.normal.x) == 1.0) {
ball.vel.x *= -1.0;
}
if (fabs(collision.normal.y) == 1.0) {
ball.vel.y *= -1.0;
}
ball.bounce();
ball.speed *= 1.02;
if (ball.speed > 14.5)
ball.speed = 14.5;
background.shake(c2Len(ball.vel) * 2.0);
}
});
}
void Obstacles::draw(sf::RenderTarget &target) {
for (auto &o : Obstacles::array) {
o.draw(target);
}
}
| true |
8ec9bc2f7c44a6012046c249fd877705d6b8c548 | C++ | Starname28/YellowBelt | /Console/Console.cpp | UTF-8 | 2,646 | 3.109375 | 3 | [] | no_license | // Console.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <typeinfo>
#include <tuple>
template<typename Collection>
std::string join(const Collection& col, char c)
{
std::stringstream ss;
bool flag = true;
for (const auto& p : col)
{
if (!flag)
{
ss << c;
}
flag = false;
ss << p;
}
return ss.str();
}
template<typename Key, typename Value>
std::ostream& operator<<(std::ostream& out, const std::pair<Key, Value>& p)
{
return out << '(' << p.first << ' ' << p.second << ')';
}
template<typename Type>
std::ostream& operator<<(std::ostream& out, const std::vector<Type>& vec)
{
return out << '[' << join(vec, ',') << ']';
}
template<typename Key, typename Value>
std::ostream& operator<<(std::ostream& out, const std::map<Key,Value>& map)
{
return out << '{' << join(map, ',') << '}';;
}
template <typename First, typename Second>
std::pair<First, Second> operator*(const std::pair<First, Second>& first,
const std::pair<First, Second>& second)
{
return { first.first * second.first, first.second * second.second };
}
template <typename T>
T getSqr(T arg)
{
return arg * arg;
}
int main()
{
std::map<int, int> Map = { {1,2.5},
{2,45.7 } };
std::cout << Map << std::endl;
auto p = std::make_pair(22, 5);
auto [key1, key2] = getSqr(p);
std::cout << key1 << " " << key2 << std::endl;
std::tuple tup(1, "string", 23);
auto tup1 = std::make_tuple(1, "wer", 3);
std::cout << std::get<1>(tup1) << std::endl;
std::shared_ptr<std::string> helloWorld = std::make_shared<std::string>("Hello World");
std::cout << *helloWorld << std::endl;
std::vector < std::string> vec /*= std::vector < std::string>(1)*/;
vec.emplace_back("First String");
std::cout << vec;;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
a8a3b181090736a0fcb850693caeaefbd5c321f9 | C++ | bruceding/leetcode | /algorithms/cpp/longest-common-prefix/main.cpp | UTF-8 | 1,339 | 3.453125 | 3 | [] | no_license | #include<string>
#include<iostream>
#include<vector>
using std::string;
using std::vector;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ret = "";
if (strs.size() == 0) {
return ret;
}
auto first_str = strs[0];
for (int i = 0; i < first_str.size(); i++) {
bool flag = true;
for (auto &str : strs) {
if (i >= str.size()) {
flag = false;
break;
}
if(first_str[i] != str[i]) {
flag = false;
break;
}
}
if (flag) {
ret += first_str[i];
} else {
break;
}
}
return ret;
}
};
int main() {
vector<string> strs {"flower","flow","flight"};
Solution sol;
string ret;
ret = sol.longestCommonPrefix(strs);
std::cout << ret << std::endl;
strs = {"dog","racecar","car"};
ret = sol.longestCommonPrefix(strs);
std::cout << ret << std::endl;
strs = {"dog"};
ret = sol.longestCommonPrefix(strs);
std::cout << ret << std::endl;
strs = { "dogdogdog", "dog"};
ret = sol.longestCommonPrefix(strs);
std::cout << ret << std::endl;
return 0;
}
| true |
f10fbaecfc2eeddf62d7ce65ec8de4bc3c26f51f | C++ | tmdghks9574/Algorithm | /C++/2864.cpp | UTF-8 | 733 | 2.765625 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<cstring>
char aa[10];
char bb[10];
using namespace std;
int main()
{
string a;
string b;
cin >> a >> b;
for(int i = 0; i < a.length(); i++)
aa[i] = a[i];
for(int i = 0; i < b.length(); i++)
bb[i] = b[i];
for(int i = 0; i < strlen(aa); i++)
if(aa[i] == '6')
aa[i] = '5';
for(int i = 0; i < strlen(bb); i++)
if(bb[i] == '6')
bb[i] = '5';
cout << atoi(aa)+atoi(bb) << " ";
for(int i = 0; i < strlen(aa); i++)
if(aa[i] == '5')
aa[i] = '6';
for(int i = 0; i < strlen(bb); i++)
if(bb[i] == '5')
bb[i] = '6';
cout << atoi(aa)+atoi(bb) << endl;
}
| true |
3efb2857ec899f9f2c009f92d6bf310b356dae4f | C++ | maobenz/qtnewForum | /forum/post.h | UTF-8 | 619 | 2.671875 | 3 | [] | no_license | #ifndef POST_H
#define POST_H
#include "header.h"
#include "string.h"
class Post
{
public:
Post(string a,string b,string c,string d,int e);
string getContents();
string getTitle(); //返回标题
string getTime(); //返回时间
void changeComments(int i); //增加评论
string getuserName(); //获取用户名
int getID(); //获取用户ID
vector<int> getComments(); //获取评论
void deleteComments(int id); //删除评论
private:
int id;
string userName;
string time;
string title;
string contents;
vector<int> comments;
};
#endif // POST_H
| true |
14375b5c47c24b44dff2667b5ee62356a95bb11a | C++ | MikolajKarpeta/JiPP | /Lab6/include/employee.h | UTF-8 | 577 | 3 | 3 | [] | no_license | #include <iostream>
#ifndef LAB6_EMPLOYEE_H
#define LAB6_EMPLOYEE_H
class Employee {
private:
std::string ID;
std::string Name;
std::string Surname;
std::string DepartmentID;
std::string Position;
public:
Employee(std::string NewID, std::string NewName, std::string NewSurname, std::string NewDepartmentID, std::string NewPosition);
Employee();
std::string getID();
std::string getName();
std::string getSurname();
std::string getDepartmentID();
std::string getPosition();
};
#endif //LAB6_EMPLOYEE_H
| true |
58dd645a2ed0a78fff689aed022401908d722c2e | C++ | TheLightWay/vaca | /vaca/Spinner.h | UTF-8 | 1,873 | 2.6875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2022 David Capello
//
// This file is distributed under the terms of the MIT license,
// please read LICENSE.txt for more information.
#ifndef VACA_SPINNER_H
#define VACA_SPINNER_H
#include "vaca/base.h"
#include "vaca/Widget.h"
#include "vaca/WidgetClass.h"
#include "vaca/Register.h"
#include "vaca/TextEdit.h"
#include "vaca/SpinButton.h"
namespace vaca {
/**
Represents the Win32 class used by Spinner.
*/
class SpinnerClass : public WidgetClass
{
public:
static WidgetClassName getClassName()
{ return WidgetClassName(L"Vaca.Spinner"); }
};
/**
A Spinner is a couple of Widgets: an Edit and a SpinButton at the
right side.
The default range is from 0 to 100. The default position is 0.
*/
class VACA_DLL Spinner : public Register<SpinnerClass>, public Widget
{
TextEdit m_edit;
SpinButton m_spin;
public:
struct Styles {
static constexpr Style Default =
Widget::Styles::Visible |
Widget::Styles::Container;
};
Spinner(Widget* parent,
Style spinStyle = SpinButton::Styles::Default,
Style style = Spinner::Styles::Default);
Spinner(int minValue, int maxValue, int value,
Widget* parent,
Style spinStyle = SpinButton::Styles::Default,
Style style = Spinner::Styles::Default);
virtual ~Spinner();
TextEdit& getTextEdit();
SpinButton& getSpinButton();
int getMinimum();
int getMaximum();
void getRange(int& minValue, int& maxValue);
void setRange(int minValue, int maxValue);
int getValue();
void setValue(int value);
int getBase();
void setBase(int base);
protected:
// Events
virtual void onPreferredSize(PreferredSizeEvent& ev);
virtual void onLayout(LayoutEvent& ev);
};
} // namespace vaca
#endif // VACA_SPINNER_H
| true |
b486c9efbf5e12e0f8366b08b5e158749b888547 | C++ | Petterf91/ScrapEscape-Game | /graphics/include/light_grid.hpp | UTF-8 | 748 | 2.734375 | 3 | [] | no_license | #ifndef LIGHT_GRID_HPP
#define LIGHT_GRID_HPP
#include <array>
#include <GL/glew.h>
#include "lights.hpp"
#include "camera.hpp"
namespace graphics
{
struct Sphere
{
glm::vec3 center;
float radius;
};
struct Plane
{
glm::vec3 normal;
float distance;
};
struct Frustum
{
Plane left;
Plane right;
Plane top;
Plane bottom;
};
struct light_grid_element
{
glm::ivec4 count;
glm::ivec4 indices[15];
};
class LightGrid
{
public:
LightGrid();
void calculate_grid(const Camera& camera);
void update(const Camera& camera, const std::array<PointLight, 32>& lights);
private:
GLuint ubo;
static constexpr int block_size = 12;
light_grid_element indices[block_size * block_size];
Frustum grid[block_size][block_size];
};
}
#endif | true |
ee972adb5c39ecf3dbe055ba809f3dc1489760a2 | C++ | WhiteCatFly/Student-Code-RUC | /The third Homework/张若琦-2017201981/DisposeStr.cc | UTF-8 | 2,921 | 2.71875 | 3 | [] | no_license | #include <string>
#include <set>
#include <queue>
#include "DisposeStr.h"
extern std :: set<string> url_set;
extern std :: queue<string> url_que;
bool URLS :: check_in_set() const
{
if (url_set.count(url_))
return true;
return false;
}
bool URLS :: check_out_site(const string & root_url) const
{
if (url_.substr(0,ROOT_URL_LEN) != root_url)
return true;
return false;
}
bool URLS :: check_php() const
{
if (url_.find(".php") != string :: npos)
return true;
return false;
}
bool URLS :: check_html() const
{
if (url_.find(".html") != string :: npos || url_.find(".htm") != string :: npos)
return true;
return false;
}
bool URLS :: check_css() const
{
int url_len = url_.size();
if (url_len >= 4 && url_.substr(url_len - 4,4).compare(".css") == 0)
return true;
return false;
}
bool URLS :: check_js() const
{
int url_len = url_.size();
if ((url_len >= 3 && url_.substr(url_len - 3,3).compare(".js") == 0) ||
(url_len >= 4 && url_.substr(url_len - 4,4).compare(".jsp") == 0))
return true;
return false;
}
bool URLS :: check_suf() const
{
if (check_css() || check_js() || (!check_html() && !check_php()))
return true;
return false;
}
bool URLS :: check_pre() const
{
int url_len = url_.size();
for (auto str : UrlPre)
if (url_len >= str.len && url_.substr(0,str.len) == str.pre)
return true;
return false;
}
void URLS :: filter_blank_character()
{
int url_len = url_.size();
for (int i = 0;i < url_len;i ++)
if (url_[i] == '\n' || url_[i] == '\r' || url_[i] == '\n')
{
url_.erase(i,1);
url_len --;
}
}
void URLS :: Get_whole_url(const string & root_url,string now_url)
{
int url_len = url_.size();
if (url_len > 1 && url_.substr(0,2) == "//") // //
{
url_.erase(0,2);
return;
}
if (url_[0] == '/') // / -> root
{
url_ = root_url + url_;
return;
}
if (url_len > 2 && url_.substr(0,3) == "../") // ../
{
int ret_opt_num = 0;
while (url_len > 2 && url_.substr(0,3) == "../")
{
url_len -= 3;
ret_opt_num ++;
url_.erase(0,3);
}
int now_url_len = now_url.size();
if (now_url[now_url_len - 1] == '/')
now_url.erase(-- now_url_len,1);
for (int i = 0;i < ret_opt_num;i ++)
{
int pos = now_url.rfind('/');
now_url.erase(pos,now_url_len - pos);
now_url_len = pos;
}
url_ = now_url + '/' + url_;
return;
}
if (url_len > 6 && url_.substr(0,7) == "http://")
{
url_.erase(0,7);
return;
}
if (url_len > 7 && url_.substr(0,8) == "https://")
{
url_.erase(0,8);
return;
}
if (url_len >= ROOT_URL_LEN && url_.substr(0,ROOT_URL_LEN) == root_url)
{
return;
}
int now_url_len = now_url.size();
if (now_url[now_url_len - 1] == '/')
now_url.erase(-- now_url_len,1);
int pos = now_url.rfind('/');
if (pos != string :: npos)
now_url.erase(pos,now_url_len - pos);
url_ = now_url + '/' + url_;
}
void URLS :: insert()
{
url_set.insert(url_);
}
void URLS :: push()
{
url_que.push(url_);
} | true |
35957f6df67907d891d118aaa0b4ffa2ce606ae6 | C++ | kenshindeveloper/lorena | /headers/vardeclarationglobal.hpp | UTF-8 | 622 | 2.53125 | 3 | [] | no_license | #ifndef VAR_DECLARATION_GLOBAL_HPP
#define VAR_DECLARATION_GLOBAL_HPP
#include "statement.hpp"
#include "identifier.hpp"
#include "expression.hpp"
namespace april
{
class VarDeclarationGlobal: public Statement
{
private:
Identifier* ident;
Identifier* type;
Expression* expr;
public:
VarDeclarationGlobal(Identifier* ident, Identifier* type, Expression* expr): ident(ident), type(type), expr(expr) {}
virtual ~VarDeclarationGlobal();
virtual Symbol* codeGen (CodeGenContext&);
};
}
#endif //VAR_DECLARATION_GLOBAL_HPP | true |
d4c3cc0347d8a4cf350c31a0e3d5e6faeb75bc25 | C++ | JohnathanLP/cmcppgroups | /cpptictactoe/window.cpp | UTF-8 | 4,936 | 3.328125 | 3 | [] | no_license | #include <SFML/Graphics.hpp>
#include <iostream>
#include "game.hpp"
//Size of the window
#define HIGH 600
#define WIDE 600
//Defines the positions of each row and collumn
#define POS1 28
#define POS2 228
#define POS3 428
int main()
{
Game myGame;
int mouseX, mouseY, moveX, moveY;
int turn = 0;
//Creates Window
sf::RenderWindow window(sf::VideoMode(WIDE,HIGH), "TicTacToe");
//Loads the texture for the board grid
sf::Texture boardTexture;
if(!boardTexture.loadFromFile("board.png"))
{
//Throws this error if texture load fails
std::cout << "Error loading textures" << std::endl;
return 0;
}
//Sprite for the board grid
sf::Sprite boardSprite;
boardSprite.setTexture(boardTexture);
boardSprite.setPosition(12,12);
//Loads the texture for the X and O
sf::Texture xandoTexture;
if(!xandoTexture.loadFromFile("xando.png"))
{
//Throws this error if the texture load fails
std::cout << "Error loading textures" << std::endl;
return 0;
}
//Sprite for the X
sf::Sprite xSprite;
xSprite.setTexture(xandoTexture);
xSprite.setTextureRect(sf::IntRect(0,0,160,160));
//Sprite for the O
sf::Sprite oSprite;
oSprite.setTexture(xandoTexture);
oSprite.setTextureRect(sf::IntRect(0,160,160,160));
//Loads the font for the victory message
sf::Font font;
if(!font.loadFromFile("raidercrusadershiftdown.ttf"))
{
//Throws this error if the font load fails
std::cout << "Error loading font!" << std::endl;
return 0;
}
//Text for the victory message
sf::Text text;
text.setFont(font);
text.setCharacterSize(48);
text.setColor(sf::Color::Black);
text.setPosition(WIDE/2,HIGH/2);
//Loops as long as window is open
while(window.isOpen())
{
//Loops through all events that have occurred since last loop
sf::Event event;
while(window.pollEvent(event))
{
if(event.type == sf::Event::Closed)
{
//Closes the window if a close event is received
window.close();
}
if(event.type == sf::Event::MouseButtonPressed)
{
//If mouse is clicked, checks if it was the left mouse button
if(event.mouseButton.button == sf::Mouse::Left)
{
//Loads in the x and y position of the mouse button at the time of the click
mouseX = event.mouseButton.x;
mouseY = event.mouseButton.y;
//figure out which collumn was clicked
if(POS1 <= mouseX && mouseX <= POS1+160)
{
moveX = 0;
}
if(POS2 <= mouseX && mouseX <= POS2+160)
{
moveX = 1;
}
if(POS3 <= mouseX && mouseX <= POS3+160)
{
moveX = 2;
}
//figure out which row was clicked
if(POS1 <= mouseY && mouseY <= POS1+160)
{
moveY = 0;
}
if(POS2 <= mouseY && mouseY <= POS2+160)
{
moveY = 1;
}
if(POS3 <= mouseY && mouseY <= POS3+160)
{
moveY = 2;
}
//If the move was legal, switch over the turn
if(myGame.makeMove(turn, moveY, moveX) == true)
{
turn++;
turn %= 2;
}
//Uncomment this line if you want it to print the board to the terminal (for debugging)
//myGame.printBoard();
}
}
}
//clears the window
window.clear(sf::Color::White);
//redraws all the X's and O's - loops through all 9 spaces
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
//reads character in space
char space = myGame.getSpace(i,j);
int xPos, yPos;
//If the space isn't blank, sets xPos and yPos
if(space != ' ')
{
if(i == 0)
{
xPos = POS1;
}
else if(i == 1)
{
xPos = POS2;
}
else if(i == 2)
{
xPos = POS3;
}
if(j == 0)
{
yPos = POS1;
}
else if(j == 1)
{
yPos = POS2;
}
else if(j == 2)
{
yPos = POS3;
}
}
//If the space is an X, print an X there
if(space == 'X')
{
xSprite.setPosition(yPos, xPos);
window.draw(xSprite);
}
//If the space is an O, print an O there
else if(space == 'O')
{
oSprite.setPosition(yPos, xPos);
window.draw(oSprite);
}
}
}
//Check for victory, prints a message
if(myGame.testForWin())
{
if(turn == 0)
{
text.setString("O Wins!");
}
else
{
text.setString("X Wins!");
}
window.draw(text);
}
//Draws the board, then updates the window
window.draw(boardSprite);
window.display();
}
}
| true |
478cb1e7dfd04990b76706834d3a1f358f0aaa1b | C++ | JannisN/BMA | /Crystal/src/Vertex.cpp | UTF-8 | 333 | 2.5625 | 3 | [] | no_license | #include "Vertex.h"
namespace Crystal
{
Vertex::Vertex()
{
}
Vertex::Vertex(Vec pos)
{
this->pos = pos;
}
Vertex::Vertex(Vec pos, Vec normal)
{
this->pos = pos;
this->normal = normal;
}
Vertex::Vertex(Vec pos, Vec normal, Vec uvCoord)
{
this->pos = pos;
this->normal = normal;
this->uvCoord = uvCoord;
}
} | true |
e83b68f50c3643b9312ada3ac3fa17c8b4b488ea | C++ | ndoxx/wcore | /source/tests/catch_bezier.cpp | UTF-8 | 1,477 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | #include <catch2/catch.hpp>
#include <iostream>
#include "catch_math_common.h"
#include "bezier.h"
static const float precision = 1e-4;
TEST_CASE("Bezier curve order 3 interpolation.", "[bez]")
{
Bezier curve(vec3(0.0,0.0,0.0),
vec3(1.0,0.2,0.0),
vec3(1.0,0.4,1.0),
vec3(0.0,0.6,1.0));
REQUIRE(VectorNear(vec3(0.0,0.0,0.0), curve.interpolate(0.0f), precision));
REQUIRE(VectorNear(vec3(0.0,0.6,1.0), curve.interpolate(0.9999999f), precision));
REQUIRE(VectorNear(vec3(0.0,0.6,1.0), curve.interpolate(1.0f), precision));
}
TEST_CASE("Update control point.", "[bez]")
{
Bezier curve(vec3(0.0,0.0,0.0),
vec3(1.0,0.2,0.0),
vec3(1.0,0.4,1.0),
vec3(0.0,0.6,1.0));
curve.update_control_point(3, vec3(0.5,1.2,1.0));
REQUIRE(VectorNear(vec3(0.5,1.2,1.0), curve.interpolate(1.0f), precision));
}
TEST_CASE("De Casteljau's algorithm.", "[bez]")
{
vec3 p = Bezier::interpolate(0.5,
vec3(0.0,0.0,0.0),
vec3(1.0,0.2,0.0),
vec3(1.0,0.4,1.0),
vec3(8.0,0.6,1.0));
Bezier curve(vec3(0.0,0.0,0.0),
vec3(1.0,0.2,0.0),
vec3(1.0,0.4,1.0),
vec3(8.0,0.6,1.0));
vec3 expect = curve.interpolate(0.5f);
REQUIRE(VectorNear(expect, p, precision));
}
| true |
4ff640d4b3daac7a9bce508f01c7003c0dfde621 | C++ | metrix/printatronic | /I2C_RGB_master_uno/I2C_RGB_master_uno.ino | UTF-8 | 1,736 | 3.015625 | 3 | [] | no_license | // Wire Master Writer
// by Nicholas Zambetti <http://www.zambetti.com>
// Demonstrates use of the Wire library
// Writes data to an I2C/TWI slave device
// Refer to the "Wire Slave Receiver" example for use with this
// Created 29 March 2006
// This example code is in the public domain.
#include <Wire.h>
#define AT_ADDR 0x05 // 7 bit I2C address for DS1621 temperature sensor
int led_pin = 1;
boolean red_on;
boolean grn_on;
boolean blu_on;
void setup()
{
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600);
pinMode(led_pin, OUTPUT);
red_on = false;
blu_on = false;
grn_on = false;
}
void loop()
{
if (Serial.available()) {
toggle_remote_led(Serial.read());
}
}
void toggle_remote_led(char color){
if (color == 'r') {
red_on = !red_on;
if (red_on) {
Wire.beginTransmission(AT_ADDR);
Wire.write(0x00);
Wire.write(0x01);
Wire.endTransmission();
} else {
Wire.beginTransmission(AT_ADDR);
Wire.write(0x00);
Wire.write(0x00);
Wire.endTransmission();
}
} else if (color == 'b') {
blu_on = !blu_on;
if (blu_on) {
Wire.beginTransmission(AT_ADDR);
Wire.write(0x01);
Wire.write(0x01);
Wire.endTransmission();
} else {
Wire.beginTransmission(AT_ADDR);
Wire.write(0x01);
Wire.write(0x00);
Wire.endTransmission();
}
} else if (color == 'g') {
grn_on = !grn_on;
if (grn_on) {
Wire.beginTransmission(AT_ADDR);
Wire.write(0x02);
Wire.write(0x01);
Wire.endTransmission();
} else {
Wire.beginTransmission(AT_ADDR);
Wire.write(0x02);
Wire.write(0x00);
Wire.endTransmission();
}
}
}
| true |
fcbf51f2f19460bea0938596369df58ed49379c8 | C++ | Shaniamoro/2143-OOP-Roberts | /Assignments/P04/ExtraFiles/main.cpp | UTF-8 | 12,054 | 3.34375 | 3 | [] | no_license | /**
* Course: CMPS 2143 - OOP
* Program: Program 2
*
* Purpose: Game of Life Solution
*
* @author Shania Roberts
* @version 1.1 10/08/18
* @github repo: https://github.com/Shaniamoro/2143-OOP-Roberts
*/
#include <string>
#include <iostream>
#include <fstream>
#include <cstring>
#include <exception>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
using namespace sf;
using namespace std;
/**
* Creates the data structure that has its own methods that works on the data golCell
*
* @param {None}
* @return {NULL}
*/
struct golCell {
bool isAlive;
int neighbors;
RectangleShape Rect;
int Width;
int Height;
/**
* Constrctor for GOL cell which contains the neighbours
* and if the cell is alive or not
*
* @param {None}
* @return {NULL}
*/
golCell() {
isAlive = 0;
neighbors = 0;
Width = 10;
Height = 10;
Rect.setSize(sf::Vector2f(Width, Height));
Rect.setFillColor(Color::Cyan);
Rect.setOutlineColor(Color::Black);
Rect.setOutlineThickness(1);
}
void setCellPos(int x, int y) {
Rect.setPosition(x*Width, y*Height);
}
void changeColor(Color nameOfColor) {
Rect.setFillColor(nameOfColor);
}
};
// Default
class GameOfLife {
private:
golCell* World;
int nums[10];
int id;
public:
golCell ** W;
int Width; // Width f a cell
int Height; // Height of a cell
int worldRows; // Row count in the world
int worldCols; // Column count in the World
int frameCount; // Used to count the frames
int frameRate; // the rate at which they are to be printed
RenderWindow Window;
string outfileName;
void printWorld(string);
bool onWorld(int, int);
int countNeighbors(int, int);
void changeState(int, int);
ifstream readFromFile(string);
golCell** buildArray(ifstream&);
void refreshGeneration(int);
void run(string, string, string);
~GameOfLife();
GameOfLife(int width, int height);
GameOfLife(int width, int height, int rate);
void drawWorld();
// How to make one cell change color if its alive or dead
};
/**
* Constructor which creates our game of life world.
* Creates a window
*
* @param {int} width: width of the Window
* height: height of the window
* @return {NULL}
*/
GameOfLife::GameOfLife(int width, int height) {
World = new golCell[height];
id = 0;
frameCount = 0;
frameRate = 50; // Game board will be printed ever 5th iteration
Width = width;
Height = height;
// Creating a window with the specifications
Window.create(VideoMode(Width, Height), "Game of Life");
for (int i = 0; i < height; i++) {
W[i] = new golCell[width];
for (int j = 0; j < width; j++) {
W[i][j].setCellPos(i, j);
}
}
}
/**
* Constructor which creates our game of life world.
* Creates a window
*
* @param {int} width: width of the Window
* height: height of the window
* rate: User inputs the rate for the iterations
* @return {NULL}
*/
GameOfLife::GameOfLife(int width, int height, int rate) {
Width = width;
Height = height;
frameCount = 0;
//Gameboard would be printed the number of iterations given
frameRate = rate;
Window.create(VideoMode(Width, Height), "Game of Life");
W = new golCell*[height];
id = 0;
for (int i = 0; i < height; i++) {
W[i] = new golCell[width];
for (int j = 0; j < width; j++) {
W[i][j].setCellPos(i, j);
}
}
}
/**
* Deconstructor
*
*
* @param {int}
* @return {NULL}
*/
GameOfLife::~GameOfLife() {
for (int i = 0; i < worldRows; i++) {
//deletes the elements of the rows
delete[]W[i];
}
//delete rows
delete[]W;
}
/**
* Prints the current state of the GOL world
* Both to the Console and to the SFML screen
*
* @param {None}
* @return {NULL}
*/
void GameOfLife::drawWorld() {
Window.clear();
// Printing to the window
for (int i = 0; i < worldRows; i++) {
for (int j = 0; j < worldCols; j++) {
Window.draw(W[i][j].Rect);
}
}
// Printing to the console
for (int i = 0; i < worldRows; i++) {
for (int j = 0; j < worldCols; j++) {
cout << *(&W[i][j].isAlive) << "";
}
cout << endl;
}
// Make the thread wait
sleep(milliseconds(500));
Window.display();
}
/**
* Prints the Final World to File
*
* @param {None}
* @return {NULL}
*/
void GameOfLife::printWorld(string outfilename) {
ofstream myfile;
myfile.open(outfilename);
myfile << " Shania Roberts" << endl;
myfile << " The 338th generation" << endl;
// Printing to the file
for (int i = 0; i < worldRows; i++) {
for (int j = 0; j < worldCols; j++) {
myfile << *(&W[i][j].isAlive) << "";
}
myfile << endl;
}
myfile.close();
}
/**
* Checks to see if a cell is on the World
*
* @param {object , int} row: row we're looking at col: column we're looking at
* @return {int} neighbors: sum of neighbours
*/
bool GameOfLife::onWorld(int row, int col) {
// Checks if the location is within the range of the matrix
if ((row >= 0 && row < worldRows) && (col >= 0 && col < worldCols)) {
return true;
//cout << "Pass " << "row" << row << "col" << col << endl;
}
else {
return false;
//cout << "Fail" << "row" << row << "col" << col << endl;
}
}
/**
* Counts the live neighbors for a given cell
*
* @param {int} r: row we're looking at c: column we're looking at
* @return {int} neighbors: sum of neighbours
*/
int GameOfLife::countNeighbors(int r, int c) {
int neighbors = 0;
if (onWorld(r - 1, c - 1) && W[r - 1][c - 1].isAlive) {
neighbors++;
}
if (onWorld(r - 1, c) && W[r - 1][c].isAlive) {
neighbors++;
}
if (onWorld(r - 1, c + 1) && W[r - 1][c + 1].isAlive) {
neighbors++;
}
if (onWorld(r, c - 1) && W[r][c - 1].isAlive) {
neighbors++;
}
if (onWorld(r, c + 1) && W[r][c + 1].isAlive) {
neighbors++;
}
if (onWorld(r + 1, c - 1) && W[r + 1][c - 1].isAlive) {
neighbors++;
}
if (onWorld(r + 1, c) && W[r + 1][c].isAlive) {
neighbors++;
}
if (onWorld(r + 1, c + 1) && W[r + 1][c + 1].isAlive) {
neighbors++;
}
return neighbors;
}
/**
* Apply rules to kill the cell or bring it to life
*
* @param {object , int} row: row we're looking at col: column we're looking at
* @return {NULL}
*/
void GameOfLife::changeState(int row, int col) {
W[row][col].neighbors;
// Any live cell with fewer than two live neighbors dies,as if caused by under-population.
if (W[row][col].isAlive == true && W[row][col].neighbors < 2) {
W[row][col].isAlive = false;
W[row][col].setCellPos(row, col);
W[row][col].changeColor(Color:: Black);
}
// Any live cell with more than three live neighbors dies, as if by overcrowding.
if (W[row][col].isAlive == true && W[row][col].neighbors > 3) {
W[row][col].isAlive = false;
W[row][col].setCellPos(row, col);
W[row][col].changeColor(Color::Black);
}
// Any live cell with two or three live neighbors lives on to the next generation.
if (W[row][col].isAlive == true && W[row][col].neighbors == 2 || W[row][col].neighbors == 3) {
W[row][col].isAlive = true;
W[row][col].setCellPos(row, col);
W[row][col].changeColor(Color::Magenta);
}
// Any dead cell with exactly three live neighbors becomes a live cell.
if (W[row][col].isAlive == false && W[row][col].neighbors == 3) {
W[row][col].isAlive = true;
W[row][col].setCellPos(row, col);
W[row][col].changeColor(Color::Magenta);
}
else {
W[row][col].isAlive = W[row][col].isAlive;
if (W[row][col].isAlive == true) {
W[row][col].setCellPos(row, col);
W[row][col].changeColor(Color::Magenta);
}
else if (W[row][col].isAlive == false) {
W[row][col].setCellPos(row, col);
W[row][col].changeColor(Color::Black);
}
}
}
/**
* Attempting to open the file
*
* @param {string} fileName: the name of the file to be read in
* @return {ifstream} infile: reference to the file we will be using
*/
ifstream GameOfLife::readFromFile(string fileName) {
ifstream infile;
//cout << "Our filename is :" << fileName << endl;
infile.open(fileName);
if (!infile) {
//cout << "Error, file couldn't be opened" << endl;
exit(1);
}
return infile;
}
/**
* Attempting to build our initial Array and print it to the screen
*
* @param {ifstream } infile: the file we will be using
* @return {object} W: initial world
*/
golCell** GameOfLife::buildArray(ifstream& infile) {
//Reading the initial state (generation 0) for our game to be played.
//Along with the number of rows and columns
infile >> worldRows >> worldCols;
W = new golCell*[worldRows];
for (int i = 0; i < worldRows; i++) {
W[i] = new golCell[worldCols];
}
//declaring array to store integer 2d array from char array
int** tempArray = new int *[worldRows];
for (int i = 0; i < worldRows; i++) {
tempArray[i] = new int[worldCols];
}
char x;
string myString = "";
//while the character is 1 or 0, concatenate to string
while (!infile.eof()) {
x = infile.get();
if (x == '1' || x == '0') {
myString = myString + x;
}
}
//convert string into character array
char * characterArray = new char[myString.length() + 1];
strcpy_s(characterArray, myString.length() + 1, myString.c_str());
//convert character array into int array
int k = 0;
for (int i = 0; i < worldRows; i++) {
for (int j = 0; j < worldCols; j++) {
tempArray[i][j] = (int)characterArray[k] - 48;
k++;
}
}
//convert int array to World array
for (int i = 0; i < worldRows; i++) {
for (int j = 0; j < worldCols; j++) {
W[i][j].isAlive = tempArray[i][j];
if (W[i][j].isAlive == true) {
W[i][j].setCellPos(i, j);
W[i][j].changeColor(Color::Magenta);
}
else if (W[i][j].isAlive == false) {
W[i][j].setCellPos(i, j);
W[i][j].changeColor(Color::Black);
}
}
}
drawWorld();
return W;
}
/**
* Refreshes the generations then prints the new generation.
*
* @param {int} runAmt: the number of times the program will run
* @return {Null}
*/
void GameOfLife::refreshGeneration(int runAmt) {
//Change the states x times
for (int x = 0; x < runAmt; x++) {
for (int i = 0; i < worldRows; i++) {
for (int j = 0; j < worldCols; j++) {
W[i][j].neighbors = countNeighbors(i, j);
}
}
for (int i = 0; i < worldRows; i++) {
for (int j = 0; j < worldCols; j++) {
changeState(i, j);
}
if (x == 337) {
printWorld(outfileName);
}
}
//Print the new world
cout << "Printing Array to Draw: " << endl;
cout << "This is the : " << x + 1 << " run" << endl;
drawWorld();
}
}
/**
* Driver for the Game of life program , accepts arguements
*
* @param {string} inputFileName: name of the file we're accessing
* numberOfRuns: the number of generations we will generate
* outputFileName: output file for the program
* @return {NULL}
*/
void GameOfLife::run(string inputFileName, string numberOfRuns, string outputFileName) {
outfileName = outputFileName;
// Exception Handling
ifstream fileStream;
try {
fileStream = readFromFile(inputFileName);
}
catch (exception& e) {
//cout << "Error reading from the file" << endl;
exit(1);
}
// Reading from the file
fileStream = readFromFile(inputFileName);
// Builds the Initial World
golCell** World = buildArray(fileStream);
// Converting to integer
int numOfGenerations = stoi(numberOfRuns);
// updating generations
refreshGeneration(numOfGenerations);
}
int main(int argc, char *argv[]) {
// goes to default constructer
// gameOfLife Gol(1000,1000);
//User inputs iterations
int rate = 10;
GameOfLife Gol(400, 500, rate);
//GameOfLife World;
string infileName;
string numOfGenerations;
string outFileName;
if (argc < 4) {
// We print argv[0] assuming it is the program name
cout << "usage: " << argv[0] << " <filename>\n";
}
else {
infileName = argv[1];
numOfGenerations = argv[2];
outFileName = argv[3];
// Runs the driver fuction of the program
//Gol.run(infileName, numOfGenerations, outFileName);
}
while (Gol.Window.isOpen()) {
Event event;
while (Gol.Window.pollEvent(event)) {
if (Gol.frameCount % Gol.frameRate == 0) {
//Gol.drawWorld();
Gol.run(infileName, numOfGenerations, outFileName);
}
//Gol.drawWorld();
if (event.type == Event::Closed) {
Gol.Window.close();
}
}
Gol.frameCount++;
}
return 0;
}
| true |
e24484ff336b8194841f85ffcdb851b4c93fd4ae | C++ | KamiGoku/Polysectoid | /CPG_Main3/cpg.cpp | UTF-8 | 1,252 | 2.609375 | 3 | [] | no_license | #include <math.h>
#include "brain.cpp"
extern Brain b;
class Actuator {
public:
//float weights[SIZE]; // Weights for neighboring arduinos (0-4 -> vertical connection) (5,6 -> horizontal connections)
//float int_freq; // Intrinsic Frequency
//float bias[SIZE]; // Bias for neighboring arduinos
//float tau; // Frequency parameter
float phase; // Current phase of this actuator
int index; // ID number of Oscillator
Actuator(){}
float update_phase(float neighbor_phases[]) {
float sum = 0.0;
for (int i = 0; i < SIZE; i++) {
double weight,bias;
bias = modf(b.weights_bias[index][i], &weight);
weight = weight/10000.0;
if(((index==1 || index==6 || index==11) && (i==0)) ||
((index==2 || index==7 || index==12) && (i==0 || i==1)) ||
((index==3 || index==8 || index==13) && (i==1 || i==2)) ||
((index==4 || index==9 || index==14) && (i==2 || i==3))){
bias *= -1;
}
sum += weight * sin((double) ((neighbor_phases[i] - phase) * 2 * M_PI - bias));
}
sum = ((2 * M_PI * int_freq[index]) + sum) / (2 * M_PI * tau);
double modVal = 1;
phase = modf(sum + phase, &modVal);
return (float) phase;
}
};
| true |
eb34cfca47a2ad2e0b219db4368583cb784088f1 | C++ | muhaiwang/buptsse-2018-study-materials | /算法分析与设计/算法导论实验/2016级算法实验/实验五/动态规划01背包.cpp | GB18030 | 1,696 | 3.375 | 3 | [] | no_license | /*
*
*ʵ ̬滮01
*
*BY TianYu
*
*2018 12 20
*
*
*/
#include<stdio.h>
int bag_w,num;
int goods_v[5],goods_w[5];
int bag_v[5][11];
void Start()
{
printf("뱳");
scanf("%d",&bag_w);
printf("ƷĿ");
scanf("%d",&num);
printf("ֱÿƷļֵ\n");
for(int i=1;i<=num;i++)
{
scanf("%d",&goods_v[i]);
}
printf("ֱÿƷ\n");
for(int j=1;j<=num;j++)
{
scanf("%d",&goods_w[j]);
}
}
void Max()
{
for(int i=1;i<=num;i++)
{
for(int j=1;j<=bag_w;j++)
{
if(j<goods_w[i])//װȥ
{
bag_v[i][j]=bag_v[i-1][j];
}
else //װ
{
//װֵ
if(bag_v[i-1][j]>bag_v[i-1][j-goods_w[i]]+goods_v[i])
{
bag_v[i][j]=bag_v[i-1][j];
}
//ǰi-1ƷŽiƷļֵ֮
else
{
bag_v[i][j]=bag_v[i-1][j-goods_w[i]]+goods_v[i];
}
}
}
}
}
int item[5];
void Find(int i,int j)
{
if(i>=0)
{
if(bag_v[i][j]==bag_v[i-1][j])//˵ûװ
{
item[i]=0;//ȫֱδѡ
Find(i-1,j);
}
else if(j-goods_w[i]>=0 && bag_v[i][j]==bag_v[i-1][j-goods_w[i]]+goods_v[i])
{
item[i]=1;//ѱѡ
Find(i-1,j-goods_w[i]);//صװ֮ǰλ
}
}
}
void Print()
{
printf("ֵΪ%d",bag_v[num][bag_w]);
printf("\nֱƷ\n");
for(int i=1;i<=num;i++)
{
if(item[i]!=0)
printf("%dƷ\n",i);
}
}
int main()
{
Start();
Max();
Find(num,bag_w);
Print();
return 0;
}
| true |
dc0b337064680f56200368c2b72f47003538b19e | C++ | sahilgoyals1999/GFG-Algorithms | /03. Greedy Algorithms/09. Job Sequencing Problem.cpp | UTF-8 | 808 | 2.953125 | 3 | [] | no_license | // https://practice.geeksforgeeks.org/problems/job-sequencing-problem-1587115620/1
// T.C => O(n^2)
bool comp(Job a, Job b) {
return a.profit > b.profit;
}
pair<int, int> JobScheduling(Job a[], int n) {
// sort in dec. order of profit
sort(a, a + n, comp);
vector<int> result(n); // To store result (Sequence of jobs)
vector<bool> slot(n, false); // To keep track of free time slots
for (int i = 0; i < n; ++i) {
// Find a free slot for this job (we startfrom the last possible slot)
for (int j = min(n, a[i].dead) - 1; j >= 0; --j) {
// Free slot found
if (!slot[j]) {
result[j] = i;
slot[j] = true;
break;
}
}
}
pair<int, int> ans(0, 0);
for (int i = 0; i < n; i++) {
if (slot[i]) {
++ans.first;
ans.second += a[result[i]].profit;
}
}
return ans;
} | true |
2bdada02cbfb7db7991967e00cf7fdb1a08bcd45 | C++ | prafullgangboir/cpptest | /Chapter11/Class.h | UTF-8 | 905 | 3.3125 | 3 | [] | no_license | // ClassAndConstructor.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Name
{
const char* s;
};
class Table
{
Name* p;
size_t sz;
public:
Table(size_t s=15) //Constructor
{
sz = s;
p = new Name[sz];
}
Table(const Table& t) //Copy constructor
{
sz = t.sz;
p = new Name[sz];
for(int i = 0; i< sz; i++) p[i] = t.p[i];
}
Table& operator= (const Table& t) //Assignment operator
{
if(this != &t) //Beware of self assignment t = t
{
delete[] p;
p = new Name[sz=t.sz];
for(int i = 0; i< sz; i++)
p[i]= t.p[i];
}
return *this;
}
~Table() //Destructor
{
delete[] p;
}
Name* lookup(const char*);
bool insert(Name*);
};
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Size of Name Class: "<<sizeof(Name)<<'\n';
cout<<"Size of Table Class: "<<sizeof(Table)<<'\n';
return 0;
}
| true |
9aa9712810d7b674c49500d1fe15daa701e8ffc7 | C++ | NEDJIMAbelgacem/Graphics_Engine | /Engine/Headers/2D/Camera_2D.h | UTF-8 | 2,573 | 2.890625 | 3 | [] | no_license | #pragma once
#include "Core/Common.h"
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "AbstractCamera.h"
class Camera_2D : public AbstractCamera {
private:
glm::vec2 camera_pos;
glm::vec2 camera_right = glm::vec2(-1.0f, 0.0f);
glm::vec2 camera_up = glm::vec2(0.0f, 1.0f);
float zoom_level = 1.0f;
float screen_width, screen_height;
public:
Camera_2D(float screen_width = WINDOW_WIDTH, float screen_height = WINDOW_HEIGHT, glm::vec2 position = glm::vec2(0.0f, 0.0f)) {
this->screen_height = screen_height;
this->screen_width = screen_width;
this->camera_pos = position;
}
void SetPosition(glm::vec2 pos) { this->camera_pos = pos; }
void ZoomIn(float zoom_factor) {
zoom_level *= zoom_factor;
}
void ZoomOut(float zoom_factor) {
zoom_level /= zoom_factor;
}
void MoveUp(float distance) {
camera_pos += camera_up * distance;
}
void MoveDown(float distance) {
camera_pos -= camera_up * distance;
}
void MoveRight(float distance) {
camera_pos += camera_right * distance;
}
void MoveLeft(float distance) {
camera_pos -= camera_right * distance;
}
inline glm::vec2 GetCameraPosition() {
// return glm::vec2(0.5f * screen_width + camera_pos.x, 0.5 * screen_height + camera_pos.y);
return this->camera_pos;
}
inline void SetScreenSize(float width, float height) { this->screen_width = width; this->screen_height = height; }
inline float GetScreenWidth() { return screen_width; }
inline float GetScreenHeight() { return screen_height; }
glm::mat4 GetViewMatrix() override {
glm::mat4 scale = glm::scale(glm::identity<glm::mat4>(), glm::vec3(1.0f / zoom_level, 1.0f / zoom_level, 1.0f));
glm::mat4 translation = glm::translate(glm::identity<glm::mat4>(), glm::vec3(camera_pos.x, camera_pos.y, 0.0f));
return translation * scale;
}
glm::mat4 GetProjectionMatrix() override {
glm::mat4 scale = glm::scale(glm::identity<glm::mat4>(), glm::vec3(2.0f / screen_width, -2.0f / screen_height, 1.0f));
glm::mat4 translation = glm::translate(glm::identity<glm::mat4>(), glm::vec3(-1.0f, 1.0f, 0.0f));
glm::mat4 m = translation * scale;
return m;
}
void FillShader(ShaderProgram& prg) override {
glm::mat4 view_m = this->GetViewMatrix();
glm::mat4 proj_m = this->GetProjectionMatrix();
prg.FillUniformMat4f("u_view", view_m);
prg.FillUniformMat4f("u_proj", proj_m);
}
}; | true |
7e08a065c6e73ac0b32c0074cd45338fec7ff739 | C++ | hellocomrade/happycoding | /leetcode/GameOfLife.cpp | UTF-8 | 4,938 | 3.6875 | 4 | [] | no_license | #include <vector>
#include <algorithm>
using namespace std;
//https://leetcode.com/problems/game-of-life/
/*
289. Game of Life
According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised
by the British mathematician John Horton Conway in 1970."
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its
eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
- Any live cell with fewer than two live neighbors dies, as if caused by under-population.
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by over-population..
- Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
Write a function to compute the next state (after one update) of the board given its current state.
The next state is created by applying the above rules simultaneously to every cell in the current state,
where births and deaths occur simultaneously.
Example:
Input:
[
[0,1,0],
[0,0,1],
[1,1,1],
[0,0,0]
]
Output:
[
[0,0,0],
[1,0,1],
[0,1,1],
[0,1,0]
]
Follow up:
- Could you solve it in-place? Remember that the board needs to be updated at the same time:
You cannot update some cells first and then use their updated values to update other cells.
- In this question, we represent the board using a 2D array. In principle, the board is infinite,
which would cause problems when the active area encroaches the border of the array. How would you address
these problems?
Observations:
This is a straight forward problem as long as you had experience before on how to reuse the input array to
keep the necessary info along with the result in each cell. Fancier version will probably use bitwise operation
to track status. As for the flip cases, 2 is used for "0 to 1" and -1 is for "1 to 0".
Another trick part is to figure out how to visit the surrounding cells safely when the central cell is on the boundary.
gameOfLife1 is my naive version, which simply iterates all 8 cases. Or, you could do:
for (int m = std::max(i - 1, 0); m < std::min(i + 2, rowCnt); ++m)
for (int n = std::max(j - 1, 0); n < std::min(j + 2, colCnt); ++n)
Using max and min to make sure no out of bound error. See gameOfLife.
*/
class SolutionGameOfLife {
public:
void gameOfLife(vector<vector<int>>& board) {
int rowCnt = board.size();
if (1 > rowCnt) return;
int colCnt = board[0].size();
if (1 > colCnt) return;
for (int i = 0; i < rowCnt; ++i)
for (int j = 0, cnt = 0; j < colCnt; cnt = 0, ++j) {
for (int m = std::max(i - 1, 0); m < std::min(i + 2, rowCnt); ++m)
for (int n = std::max(j - 1, 0); n < std::min(j + 2, colCnt); ++n)
cnt += (1 == std::abs(board[m][n])) ? 1 : 0;
if (1 == board[i][j]) --cnt;
if ((2 > cnt || 3 < cnt) && 1 == board[i][j]) board[i][j] = -1;
if (3 == cnt && 0 == board[i][j]) board[i][j] = 2;
}
for (int i = 0; i < rowCnt; ++i)
for (int j = 0, cnt = 0; j < colCnt; cnt = 0, ++j)
if (2 == board[i][j]) board[i][j] = 1;
else if (-1 == board[i][j]) board[i][j] = 0;
}
void gameOfLife1(vector<vector<int>>& board) {
int rowCnt = board.size();
if (1 > rowCnt) return;
int colCnt = board[0].size();
if (1 > colCnt) return;
for (int i = 0; i < rowCnt; ++i)
for (int j = 0, cnt = 0; j < colCnt; cnt = 0, ++j) {
if (-1 < i - 1 && -1 < j - 1) cnt += (1 == board[i - 1][j - 1] || -1 == board[i - 1][j - 1]) ? 1 : 0;
if (-1 < i - 1 && colCnt > j + 1) cnt += (1 == board[i - 1][j + 1] || -1 == board[i - 1][j + 1]) ? 1 : 0;
if (-1 < i - 1) cnt += (1 == board[i - 1][j] || -1 == board[i - 1][j]) ? 1 : 0;
if (rowCnt > i + 1 && -1 < j - 1) cnt += (1 == board[i + 1][j - 1] || -1 == board[i + 1][j - 1]) ? 1 : 0;
if (rowCnt > i + 1 && colCnt > j + 1) cnt += (1 == board[i + 1][j + 1] || -1 == board[i + 1][j + 1]) ? 1 : 0;
if (rowCnt > i + 1) cnt += (1 == board[i + 1][j] || -1 == board[i + 1][j]) ? 1 : 0;
if (-1 < j - 1) cnt += (1 == board[i][j - 1] || -1 == board[i][j - 1]) ? 1 : 0;
if (colCnt > j + 1) cnt += (1 == board[i][j + 1] || -1 == board[i][j + 1]) ? 1 : 0;
if (2 > cnt && 1 == board[i][j]) board[i][j] = -1;
if (3 < cnt && 1 == board[i][j]) board[i][j] = -1;
if (3 == cnt && 0 == board[i][j]) board[i][j] = 2;
}
for (int i = 0; i < rowCnt; ++i)
for (int j = 0, cnt = 0; j < colCnt; cnt = 0, ++j)
if (2 == board[i][j]) board[i][j] = 1;
else if (-1 == board[i][j]) board[i][j] = 0;
}
};
/*
Test cases:
[[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
[]
[[1]]
[[0]]
[[1,1]]
[[0,1,0]]
[[1,1,1,0],[0,0,1,1],[1,1,1,1],[1,0,1,0]]
[[1,0,0],[1,1,1],[0,1,1]]
Outputs:
[[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
[]
[[0]]
[[0]]
[[0,0]]
[[0,0,0]]
[[0,1,1,1],[0,0,0,0],[1,0,0,0],[1,0,1,1]]
[[1,0,0],[1,0,1],[1,0,1]]
*/ | true |
6748bc00bb360c9ac8def5592b37b63547783727 | C++ | hobbsben/wes237b | /Assignment_3/code/dct/src/student_dct.cpp | UTF-8 | 5,504 | 2.859375 | 3 | [] | no_license | #include "main.h"
//#define USE_BASELINE
//#define USE_BASELINE_WITH_LUT
//#define USE_1D_DCT
//#define USE_MM
#define USE_MM_BLOCK
using namespace cv;
Mat LUT_w;
Mat LUT_h;
// Helper function
float sf(int in){
if (in == 0)
return 0.70710678118; // 1 / sqrt(2)
return 1.;
}
// Initialize LUT
void initDCT(int WIDTH, int HEIGHT)
{
LUT_w = Mat(WIDTH, WIDTH, CV_32F);
LUT_h = Mat(HEIGHT, HEIGHT, CV_32F);
float scale = 2.f/sqrtf(HEIGHT*WIDTH);
float sqrt_scale = sqrtf(scale);
for(int j = 0; j < WIDTH; j++)
{
for(int i = 0; i < WIDTH; i++)
{
LUT_w.at<float>(i, j) =
sqrt_scale *
sf(i) *
cos(M_PI/((float)WIDTH)*(j+1./2.)*(float)i);
}
}
for(int j = 0; j < HEIGHT; j++)
{
for(int i = 0; i < HEIGHT; i++)
{
LUT_h.at<float>(i, j) =
sqrt_scale *
sf(i) *
cos(M_PI/((float)HEIGHT)*(j+1./2.)*(float)i);
}
}
}
// 1D DCT
#ifdef USE_1D_DCT
Mat dct_1d(Mat input, int len, bool is_row){
if(is_row){
Mat result = Mat(1, len, CV_32FC1);//row,col; 1xlen
float z;
for(int i=0; i<len; i++){
z = 0;
for(int j=0; j<len; j++){
z += input.at<float>(0, j) * cos(M_PI/((float)len)*(j+1./2.)*(float)i);
}
result.at<float>(0, i) = z*sf(i);
}
return result;
}else{
Mat result = Mat(len, 1, CV_32FC1);
float z;
for(int i=0; i<len; i++){
z = 0;
for(int j=0; j<len; j++){
z += input.at<float>(j, 0) * cos(M_PI/((float)len)*(j+1./2.)*(float)i);
}
result.at<float>(i, 0) = z*sf(i);
}
return result;
}
}
// Opt: O(N^3)
Mat student_dct(Mat input)
{
const int HEIGHT = input.rows;
const int WIDTH = input.cols;
float scale = 2./sqrt(HEIGHT*WIDTH);
Mat result = Mat(HEIGHT, WIDTH, CV_32FC1);
Mat rows = Mat(HEIGHT, WIDTH, CV_32FC1);
for(int x = 0; x < HEIGHT; x++)
{
Mat temp = input.row(x);//1xHEIGHT
Mat temp_dct = dct_1d(temp, HEIGHT, true);
temp_dct.copyTo(rows.row(x));
}
for(int y = 0; y < WIDTH; y++)
{
Mat temp = rows.col(y);//WIDTHx1
Mat temp_dct = dct_1d(temp, WIDTH, false);
temp_dct.copyTo(result.col(y));
}
return result*scale;
}
#endif // USE_1D_DCT
// Baseline: O(N^4)
#if defined(USE_BASELINE) || defined(USE_BASELINE_WITH_LUT)
Mat student_dct(Mat input)
{
const int HEIGHT = input.rows;
const int WIDTH = input.cols;
float scale = 2./sqrt(HEIGHT*WIDTH);
Mat result = Mat(HEIGHT, WIDTH, CV_32FC1);
float *LUT_h_ptr = LUT_h.ptr<float>();
float *LUT_w_ptr = LUT_w.ptr<float>();
float* result_ptr = result.ptr<float>();
float* input_ptr = input.ptr<float>();
for(int x = 0; x < HEIGHT; x++)
{
for(int y = 0; y < WIDTH; y++)
{
//result.at<float>(x, y) = 0;
float value = 0.f;
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < WIDTH; j++)
{
//result.at<float>(x, y) += input.at<float>(i, j)
//value += input.at<float>(i, j)
value += input_ptr[i * WIDTH + j]
#ifndef USE_BASELINE_WITH_LUT
* cos(M_PI/((float)HEIGHT)*(i+1./2.)*(float)x)
* cos(M_PI/((float)WIDTH)*(j+1./2.)*(float)y);
#else
//* LUT_h.at<float>(x, i)
//* LUT_w.at<float>(y, j); // Note: the LUT includes scaling
* LUT_h_ptr[x * HEIGHT + i]
* LUT_w_ptr[y * WIDTH + j];
#endif
}
}
#ifndef USE_BASELINE_WITH_LUT
//result.at<float>(x, y) = scale * sf(x) * sf(y) * result.at<float>(x, y);
value = scale * sf(x) * sf(y) * value;
#endif
result_ptr[x * WIDTH + y] = value;
}
}
return result;
}
#endif // USE_BASELINE*
#if defined(USE_MM) || defined(USE_MM_BLOCK)
// Matrix multiplication code
void naive_square_matmul(const float* A, const float* B, float* C, int size)
{
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
{
C[i * size + j] = 0;
for(int k = 0; k < size; k++)
{
C[i * size + j] += A[i * size + k] * B[k * size + j];
}
}
}
}
// Matrix multiplication with blocking
void matmul_block(const float* A, const float* B, float* C, int size, int bsize)
{
for(int jj = 0; jj < size; jj += bsize)
{
for(int kk = 0; kk < size; kk += bsize)
{
for(int i = 0; i < size; i++)
{
for(int j = jj; j < ((jj+bsize)>size?size:(jj+bsize)); j++)
{
float temp = 0;
for(int k = kk; k < ((kk+bsize)>size?size:(kk+bsize)); k++)
{
temp += A[i * size + k] * B[k * size + j];
}
C[i * size + j] += temp;
}
}
}
}
}
// DCT as matrix multiplication
Mat student_dct(Mat input)
{
// -- Works only for WIDTH == HEIGHT
assert(input.rows == input.cols);
// -- Matrix multiply with OpenCV
//return LUT_w * input * LUT_w.t();
// -- Student matrix multiply
Mat LUT_t = LUT_w.t();
Mat temp = Mat(input.size(), CV_32F, 0.f);
Mat output = Mat(input.size(), CV_32F, 0.f);
#ifndef USE_MM_BLOCK
naive_square_matmul(LUT_w.ptr<float>(), input.ptr<float>(), temp.ptr<float>(), input.rows);
naive_square_matmul(temp.ptr<float>(), LUT_t.ptr<float>(), output.ptr<float>(), input.rows);
#else
matmul_block(LUT_w.ptr<float>(), input.ptr<float>(), temp.ptr<float>(), input.rows, 32);
matmul_block(temp.ptr<float>(), LUT_t.ptr<float>(), output.ptr<float>(), input.rows, 32);
#endif
return output;
}
#endif // USE_MM
| true |
46d75da6e23de9e18012c8cb53b71ab6132ee1b6 | C++ | Kowsihan-sk/Codeforces-Solutions | /Contests/Codeforces 717 div2/B_AGAGA_XOOORRR.cpp | UTF-8 | 1,075 | 2.609375 | 3 | [] | no_license | /** Author : S Kowsihan **/
#include <bits/stdc++.h>
using namespace std;
#define fast \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
#define ll long long
#define f(a, b, c) for (ll i = a; i < b; i += c)
typedef vector<ll> vl;
#define fo(i, a, b, c) for (ll i = a; i < b; i += c)
int main()
{
fast;
ll TT;
cin >> TT;
while (TT--)
{
ll n;
cin >> n;
vl ar(n);
f(0, n, 1) cin >> ar[i];
ll flag = 0;
f(0, n - 1, 1)
{
ll x = 0, t = 0, f = 0;
fo(j, 0, i + 1, 1) x ^= ar[j];
fo(j, i + 1, n, 1)
{
t ^= ar[j];
if (x == t)
f = 1, t = 0;
}
if (t == 0 && f)
{
flag = 1;
break;
}
}
if (flag)
cout << "YES\n";
else
cout << "NO\n";
}
return 0;
} | true |
c874dc8c05f665a2ec8a85c1105373dc1f150b92 | C++ | qpding/slambook | /ch7/triangulation.cpp | UTF-8 | 2,296 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "vo1.h"
using namespace std;
using namespace cv;
int main(int argc, char const *argv[])
{
// Print usage information if wrong usage occured.
if( argc != 3 )
{
cout << "application usage: feature_extraction img1 img2" << endl;
return 1;
}
// Import images
Mat img1 = imread( argv[1], CV_LOAD_IMAGE_COLOR );
Mat img2 = imread( argv[2], CV_LOAD_IMAGE_COLOR );
// Extract features
vector<KeyPoint> keypoints1, keypoints2;
vector<DMatch> matches;
find_feature_matches(img1, img2, keypoints1, keypoints2, matches);
cout << matches.size() << " pairs of matches are found." << endl;
// Estimate motion between two images
Mat R, t;
pose_estimation_2d2d(keypoints1, keypoints2, matches, R, t);
// Triangulation
vector<Point3d> points;
triangulation(keypoints1, keypoints2, matches, R, t, points);
// Check reprojection of triangulated point and feature point
// Compute coordinates in normalized plane
Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );
for(int i = 0; i < matches.size(); i++)
{
// The first frame
// Convert feature point coordinate to normalized plane
Point2d pt1 = pixel2cam(keypoints1[matches[i].queryIdx].pt, K);
// Project 3D point on the normalized plane
Point2d pt1_3d( points[i].x / points[i].z,
points[i].y / points[i].z );
cout << "point in the first camera frame: " << pt1 << endl;
cout << "piont projected from 3d point: " << pt1_3d << endl;
// The second frame
// Convert feature point coordinate to normalized plane
Point2d pt2 = pixel2cam(keypoints2[matches[i].trainIdx].pt, K);
// Project 3D point on the normalized plane
Mat pt2_3d_trans = R * ( Mat_<double>(3, 1) << points[i].x, points[i].y, points[i].z ) + t;
pt2_3d_trans /= pt2_3d_trans.at<double>(2, 0);
cout << "point in the second camera frame: " << pt2 << endl;
cout << "piont projected from 3d point: " << pt2_3d_trans.t() << endl;
cout << "-----------------------------" << endl;
}
return 0;
}
| true |
31df3bce6978ec233e928da4cde4b288f7d3b030 | C++ | adityarev/online-judge | /TimusOJ/1313.cpp | UTF-8 | 1,325 | 3.5625 | 4 | [] | no_license | #include <algorithm>
#include <iostream>
#include <vector>
int N;
std::vector<std::vector<int> > arr;
void
run_input() {
std::cin >> N;
for (int i = 0; i < N; i++) {
std::vector<int> row;
for (int j = 0; j < N; j++) {
int x;
std::cin >> x;
row.push_back(x);
}
arr.push_back(row);
}
}
bool
is_in_range(int val) {
return (0 <= val && val < N);
}
std::vector<int>
get_diagonal_numbers(int i, int j) {
std::vector<int> numbers;
while (is_in_range(i) && is_in_range(j)) {
numbers.push_back(arr[i][j]);
i--;
j++;
}
return numbers;
}
std::vector<int>
get_ans() {
int i = 0;
int j = 0;
std::vector<int> ans;
bool move_down = true;
while (true) {
std::vector<int> diagonals = get_diagonal_numbers(i, j);
ans.insert(ans.end(), diagonals.begin(), diagonals.end());
i += (int)(move_down);
j += (int)(!move_down);
if (move_down && i == N) {
move_down = false;
j++;
}
if (j == N)
break;
i = std::min(N - 1, i);
j = std::min(N - 1, j);
}
return ans;
}
void
show_ans(std::vector<int> &ans) {
bool first = true;
for (int num: ans) {
if (first)
first = false;
else
std::cout << " ";
std::cout << num;
}
std::cout << std::endl;
}
int
main() {
run_input();
std::vector<int> ans = get_ans();
show_ans(ans);
return 0;
}
| true |
a43e3bd859269ea04d0d940d89fb039787f6f9c7 | C++ | LittleYoung/Leaning_Cpp | /Leaning_Cpp/7.7main.cpp | UTF-8 | 1,427 | 3.609375 | 4 | [] | no_license | #include <iostream>
using namespace std;
const int max = 5;
int main()
{
double m[max];
cout << "The following is to fill the array with numbers: " << endl;
double* x = fill_array(m, max);
show(m, x);
if (x == (m - 1))
cout << "You cannot convert because you have not entered a valid number." << endl;
else
{
cout << "Please enter the number of times you want to change the array as a whole:" << endl;
double size;
cin >> size;
if (!cin)
{
cout << "Input error, cannot change." << endl;
cin.clear();
cin.sync();
}
else if (size < 0)
cout << "The input is negative and cannot be converted." << endl;
else
revalue(m, x, size);
}
system("pause");
return 0;
}
double* fill_array(double*m, int max)
{
int i;
for (i = 0; i < max; i++)
{
cout << i + 1 << "# : ";
cin >> m[i];
if (!cin)
{
cin.clear();
cin.sync();
cout << "Input error, end of input..." << endl;
break;
}
else if (m[i]<0)
{
cout << "You entered a negative number, and the input ended..." << endl;
break;
}
}
double *a = &m[i - 1];
return a;
}
void show(double*m, double*x)
{
cout << endl << "Here you will show the numbers you entered:" << endl;
while (m != (x + 1))
{
int i = 0;
cout << ++i << "# = " << *m << endl;
m++;
}
}
void revalue(double*m, double*x, double a)
{
while (m != (x + 1))
{
int i = 0;
cout << ++i << "# = " << (*m *= a) << endl;
m++;
}
} | true |
d589d92a8baa71260c032245303c858655927a6e | C++ | Andres6936/Editogia | /Include/Editogia/Util/Container.hpp | UTF-8 | 2,034 | 3.578125 | 4 | [] | no_license | // Joan Andrés (@Andres6936) Github.
#ifndef EDITOGIA_CONTAINER_HPP
#define EDITOGIA_CONTAINER_HPP
#include <algorithm>
#include <type_traits>
/**
* Wrapper around of method that set all the values of a Container
* to the value send for parameter.
*
* @tparam Container The parameter must be of meet the requirements
* of Container, it is: A Container is an object used to store other
* objects and taking care of the management of the memory used by
* the objects it contains.
*
* @tparam Type The type of value that Container stored.
*
* @param container The container that store the values, the
* container must meet the requirement of Iterable.
*
* @param value The value used to reset the container.
*/
template<typename Container, typename Type>
void resetAt(Container& container, const Type& value)
{
// Verify that the type elements that stored the Container is the
// same type of value that trying assign.
static_assert(std::is_same<typename Container::value_type, Type>::value,
"The value of parameter not is same type that stored the Container");
std::fill(container.begin(), container.end(), value);
}
/**
*
* @tparam Container The parameter must be of meet the requirements
* of Container, it is: A Container is an object used to store other
* objects and taking care of the management of the memory used by
* the objects it contains.
*
* @tparam Callable A Callable type is a type for which the INVOKE
* operation (used by, e.g., std::function, std::bind, and
* std::thread::thread) is applicable. This operation may be performed
* explicitly using the library function std::invoke.
*
* @param container The container that store the values, the
* container must meet the requirement of Iterable.
*
* @param function Callable object to be invoked.
*/
template<typename Container, typename Callable>
void applyAt(Container& container, Callable&& function)
{
for (auto& item : container)
{
std::invoke(std::forward<Callable>(function), item);
}
}
#endif //EDITOGIA_CONTAINER_HPP
| true |
4afe267a94cafab66df51399bf8297408bbd5b72 | C++ | amirghx/Algorithms_Jupyter | /Covid Challenge/Round-0/judge/submissions/96105886/challenge.cpp | UTF-8 | 7,327 | 2.90625 | 3 | [] | no_license | //
// Created by Mahsa Sheikhi on 4/19/20.
//
#include <iostream>
#include <cstdio>
#include <random>
#include <algorithm>
#include <climits>
#include <deque>
#include <string>
using namespace std;
long long INF = 99999999;
#define SIZE 1000
struct Edge{
int u;
int v;
int cost;
};
Edge mstEdges[SIZE];
void shuffle_array(Edge arr[], int n)
{
// To obtain a time-based seed
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
// Shuffling our array
shuffle(arr+1, arr + n,
default_random_engine(seed));
// Printing our array
// for (int i = 1; i < n; ++i)
// cout << arr[i].cost << " ";
// cout << endl;
}
void prim(int parent[],int adj[SIZE][SIZE], int N){
bool inSet[SIZE] = {false};
int bestEdge[N];
for(int i = 0; i < N; i++){
bestEdge[i] = INF;
}
bestEdge[0] = 0;
parent[0] = -1;
int minCost = 0;
for(int i = 0; i < N ; i++){
int v = -1;
for(int j = 0; j < N; j++){
if(!inSet[j] && (v == -1 || bestEdge[v] > bestEdge[j])){
v = j;
}
}
minCost += bestEdge[v];
inSet[v] = true;
for(int u = 0; u < N; u++){
if(adj[v][u]!=0 && !inSet[u] && adj[v][u] < bestEdge[u]){
bestEdge[u] = adj[v][u];
mstEdges[u].u=u;
mstEdges[u].v=v;
mstEdges[u].cost=bestEdge[u];
parent[u] = v;
}
}
}
return;
}
int main(){
deque<string> result;
int n, m;
cin>>n;
cin>>m;
deque<int> cityStayCost;
int temp;
int cities[SIZE][SIZE]={0};
int visitsMatrix[SIZE][SIZE]={0};
deque<int> familyCurrentCity[n];
deque<int> familyBusy;
int familyLocArr[n];
for (int i = 0; i < n; ++i) {
cin>>temp;
cityStayCost.push_back(temp);
familyBusy.push_back(0);
familyCurrentCity[i].push_back(i);
familyLocArr[i]=i;
}
int temp1, temp2, temp3;
for (int j = 0; j < m ; ++j) {
cin>>temp1;
cin>>temp2;
cin>>temp3;
cities[temp1-1][temp2-1]=temp3;
cities[temp2-1][temp1-1]=temp3;
}
int p[SIZE] = {0};
prim(p,cities,n);
// for (int k = 1; k < m; ++k) {
// cout<<mstEdges[k].u<<endl;
// cout<<mstEdges[k].v<<endl;
// cout<<"-------"<<endl;
//
//
// }
// 3 3
// 4 8 9
// 1 2 6
// 2 3 11
// 1 3 3
int citiesVisited = 0;
int today = 0;
// shuffle_array(mstEdges, n);
// cout<<mstEdges[1].cost<<endl;
//
// shuffle_array(mstEdges, n);
// cout<<mstEdges[1].cost<<endl;
// shuffle_array(mstEdges, n);
// cout<<mstEdges[1].cost<<endl;
// shuffle_array(mstEdges, n);
// cout<<mstEdges[1].cost<<endl;
// shuffle_array(mstEdges, n);
// cout<<mstEdges[1].cost<<endl;
// shuffle_array(mstEdges, n);
// cout<<mstEdges[1].cost<<endl;
int currentSize =0;
while (citiesVisited < n * (n-1)){
shuffle_array(mstEdges, n);
//shuffle mstEdges
for (int i = 1; i <n ; ++i) {
if( familyLocArr[mstEdges[i].u]==mstEdges[i].u&&familyCurrentCity[mstEdges[i].v].size() > 0&& visitsMatrix[mstEdges[i].u][familyCurrentCity[mstEdges[i].v][0]] != 1)
{
// cout<<"aa "<< mstEdges[i].u<<endl;
if( familyBusy[mstEdges[i].u] == 0) {
// cout<<"s1"<<endl;
citiesVisited++;
visitsMatrix[mstEdges[i].u][familyCurrentCity[mstEdges[i].v][0]] = 1;
familyBusy[mstEdges[i].u] = 1;
familyBusy[mstEdges[i].v] = 0;
result.push_back(to_string(1) + " " + to_string(today) + " " + to_string(familyCurrentCity[mstEdges[i].v][0]+1) + " " +
to_string(mstEdges[i].u));
result.push_back(to_string(2) + " " + to_string(today) + " "+to_string(familyCurrentCity[mstEdges[i].v][0]) + " "+ to_string(mstEdges[i].u));
familyLocArr[familyCurrentCity[mstEdges[i].v][0]]=mstEdges[i].u;
familyCurrentCity[mstEdges[i].u].push_back(familyCurrentCity[mstEdges[i].v][0]);
familyCurrentCity[mstEdges[i].v].pop_front();
}
}
else if( familyLocArr[mstEdges[i].v]==mstEdges[i].v&& familyCurrentCity[mstEdges[i].u].size() > 0&& visitsMatrix[mstEdges[i].v][familyCurrentCity[mstEdges[i].u][0]] != 1){
// cout<<"bb"<<endl;
if( familyBusy[mstEdges[i].v] == 0) {
// cout<<"s2"<<endl;
citiesVisited++;
visitsMatrix[mstEdges[i].v][familyCurrentCity[mstEdges[i].u][0]] = 1;
familyBusy[mstEdges[i].v] = 1;
familyBusy[mstEdges[i].u] = 0;
result.push_back(to_string(1) + " " + to_string(today) + " " + to_string(familyCurrentCity[mstEdges[i].u][0]+1) + " " +
to_string(mstEdges[i].v));
result.push_back(to_string(2) + " " + to_string(today) + " "+to_string(familyCurrentCity[mstEdges[i].u][0]) + " "+ to_string(mstEdges[i].v));
familyLocArr[familyCurrentCity[mstEdges[i].u][0]]=mstEdges[i].v;
familyCurrentCity[mstEdges[i].v].push_back(familyCurrentCity[mstEdges[i].u][0]);
familyCurrentCity[mstEdges[i].u].pop_front();
}
}
else{
// cout<<"s3"<<endl;
// && cityStayCost[mstEdges[i].v] > mstEdges[i].cost + cityStayCost[mstEdges[i].v]
// && cityStayCost[mstEdges[i].v] > mstEdges[i].cost +cityStayCost[mstEdges[i].u]
if( familyCurrentCity[mstEdges[i].v].size() > 0 ){
result.push_back(to_string(1) + " " + to_string(today) + " " + to_string(familyCurrentCity[mstEdges[i].v][0]+1) + " " +
to_string(mstEdges[i].u));
familyLocArr[familyCurrentCity[mstEdges[i].v][0]]=mstEdges[i].u;
familyCurrentCity[mstEdges[i].u].push_back(familyCurrentCity[mstEdges[i].v][0]);
familyCurrentCity[mstEdges[i].v].pop_front();
}
else if( familyCurrentCity[mstEdges[i].u].size() > 0){
result.push_back(to_string(1) + " " + to_string(today) + " " + to_string(familyCurrentCity[mstEdges[i].u][0]+1) + " " +
to_string(mstEdges[i].v));
familyLocArr[familyCurrentCity[mstEdges[i].u][0]]=mstEdges[i].v;
familyCurrentCity[mstEdges[i].v].push_back(familyCurrentCity[mstEdges[i].u][0]);
familyCurrentCity[mstEdges[i].u].pop_front();
}
}
}
for (int j = 0; j < n; ++j) {
familyBusy[j] = 0;
}
if( result.size()>currentSize){
today++;
currentSize = result.size();
}
}
int num = result.size();
cout<<num<<endl;
for (int l = 0; l < num; ++l) {
cout<<result[l]<<endl;
}
return 0;
}
| true |
984f9f14b714578a25da79373dfa236688a10f84 | C++ | YOSSHUA/mechatronicsLaboratory | /practice2/p2_4_3/p2_4_3servo/p2_4_3servo.ino | UTF-8 | 763 | 2.875 | 3 | [] | no_license | #include <Servo.h>
#include <LiquidCrystal.h> // include the library code:
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // initialize the interface pins
int analogPin = A0;
Servo myservo; // create servo object to control a servo
int val = 0; // variable to read the value from the analog pin
float tot;
void setup() {
lcd.begin(16, 2); // set up the LCD's number of columns and rows:
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
val = analogRead(analogPin); // read the input pin
tot = 5.0*float(val)/1023.0;
float ang = tot*180/5 ;
myservo.write(int(ang));
lcd.setCursor(0,0);
lcd.write("A'ngulo");
String num = String(ang,4);
lcd.setCursor(0,1);
lcd.print(num);
}
| true |
0167d75612d25cc08ca275b83aa589ca8ff944fe | C++ | srod-prog-cwiczenia/CPlusPlus | /Przykladowe_Okruchy_Programistyczne/permutacje.cpp | UTF-8 | 1,148 | 3.65625 | 4 | [] | no_license | /*
liczba 10 cyfrowa złożona z 10 różnych cyfr,
liczba utworzona przez 2 pierwsze dzieli się przez 2
liczba utworzona przez 3 pierwsze dzieli się przez 3,
etc.
*/
#include <iostream>
using namespace std;
void uwzglednij(int t[], int max) {
if (!t[0]) return; //nie może być zera na początku liczby
bool jest = true;
for (int i = 2; i <= max; i++) {
long int utworzona = 0;
long int mnoznik = 1;
for (int j = i - 1; j >= 0; j--) {
utworzona += mnoznik * t[j];
mnoznik *= 10;
}
jest &= !(utworzona % i);
}
if (jest) {
for (int i = 0; i < max; i++)
cout << t[i] << " ";
cout << endl;
}
}
void permutacja(int t[], int rozmiar, int max) {
if (rozmiar == 1) {
uwzglednij(t, max);
return;
}
for (int i = 0; i < rozmiar; i++) {
permutacja(t, rozmiar - 1, max);
if (rozmiar % 2)
swap (t[0], t[rozmiar - 1]);
else
swap(t[i], t[rozmiar - 1]);
}
}
int main() {
for (int q = 2; q <= 10; q++) {
int tab[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
permutacja(tab, q, q);
}
return 0;
}
| true |
a026f07cc556061eb66015ea10c9bd95841a77db | C++ | jordsti/stigame | /StiGame/files/FileSystem.cpp | UTF-8 | 2,821 | 3.015625 | 3 | [
"MIT"
] | permissive | #include "FileSystem.h"
#ifdef _WIN32
#include "windows.h"
#endif
#ifdef __unix__
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#endif
#include <iostream>
namespace StiGame
{
namespace FS
{
FileSystem::FileSystem()
{
}
#ifdef __unix__
//POSIX implementation
std::vector<Entry*> FileSystem::ListDirectory(std::string m_path)
{
std::string unix_path;
if(m_path.length() == 0)
{
//current_dir
unix_path = ".";
}
else
{
unix_path = m_path;
}
std::vector<Entry*> root;
DIR *dir = opendir(unix_path.c_str());
if(dir)
{
dirent *ent;
while(ent)
{
std::string name (ent->d_name);
if(name != "." && name != ".." && name.size() > 0)
{
if(ent->d_type == DT_DIR)
{
//directory
Directory *_dir = new Directory(name, m_path);
root.push_back(_dir);
}
else
{
//file
File *_file = new File(name, m_path);
root.push_back(_file);
}
}
ent = readdir(dir);
}
closedir(dir);
}
return root;
}
void FileSystem::CreateDir(std::string d_path)
{
struct stat st = {0};
if (stat(d_path.c_str(), &st) == -1) {
mkdir(d_path.c_str(), 0755);
}
}
#endif
#ifdef _WIN32
//windows implementation
std::vector<Entry*> FileSystem::ListDirectory(std::string m_path)
{
std::string win32_path;
if(m_path.length() == 0)
{
//current_dir
win32_path = "./*";
}
else
{
//need to add a wildcard for win32
win32_path = m_path + "*";
}
std::vector<Entry*> root;
WIN32_FIND_DATA f;
HANDLE h = FindFirstFile(win32_path.c_str(), &f);
if(h != INVALID_HANDLE_VALUE)
{
do
{
if(f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
//dir
std::string name(f.cFileName);
if(name != "." && name != "..")
{
Directory *dir = new Directory(name, m_path);
root.push_back(dir);
}
}
else
{
//file
File *file = new File(f.cFileName, m_path);
root.push_back(file);
}
}
while(FindNextFile(h, &f));
}
return root;
}
void FileSystem::CreateDir(std::string d_path)
{
if (CreateDirectory(d_path.c_str(), NULL))
{
}
else if (ERROR_ALREADY_EXISTS == GetLastError())
{
}
else
{
//todo
//error message
}
}
#endif
}
}
| true |
ce710371aecb841e9c9a05cf1ba04d0de8fb1c26 | C++ | samiavasil/temporary | /src/frame_work/base/CProtocolPackFactory.cpp | UTF-8 | 7,994 | 2.53125 | 3 | [] | no_license | #include "base/CProtocolPackFactory.h"
#include "base/CPacket.h"
#include "base/CProtocolDb.h"
//#define ENABLE_VERBOSE_DUMP
#include "base/debug.h"
CProtocolPackFactory::CProtocolPackFactory(CProtocolDb *protDb ) {
m_pDB = NULL;
if( NO_ERR != attachProtocolDb( protDb ) ){
CRITICAL << "!!!Default ProtocolDB can't be attached to ProtocolPackFactory: Use attachProtocol()";
}
}
CProtocolPackFactory::~CProtocolPackFactory(){
if( m_pDB ){
delete m_pDB;
}
}
int CProtocolPackFactory::attachProtocolDb( CProtocolDb * pDB ) {
int ret = WRONG_PARAMS;
if( pDB ){
if( m_pDB ){
delete m_pDB;
}
m_pDB = pDB;
ret = NO_ERR;
}
return ret;
}
CPacket* CProtocolPackFactory::createPacket(const pack_id_t packId) {
CPacket * packet = NULL;
if( PKT_ID_INVALID < packId ){
return packet;
}
int payloadLenBits=0;
if( NO_ERR == m_pDB->packetPayloadBitLen(packId, &payloadLenBits )){
packet = new CPacket( packId,payloadLenBits + m_pDB->getProtocolHeaderLenBits() + m_pDB->getProtocolPostFixLenBits() );
int num;
if( ( NO_ERR == m_pDB->getPacketMessagesNumber( packId,&num ) )&&( 0 < num ) ){
msg_id_t msgArr[num];
if( NO_ERR == m_pDB->getPacketMessagesId( packId, msgArr, num ) ){
const u8 *data;
for( int i=0; i < num; i++ ){
if( NO_ERR != m_pDB->getMessage( msgArr[i], &data ) ){
CRITICAL << "Wrong Message Id[" << msgArr[i] << "] for Packet Id[" << packId << "]";
delete packet;
packet = NULL;
break;
}
if( NO_ERR != setPacketMessage( packet,msgArr[i], data ) ){
CRITICAL << "Can't set Message with Id[" << msgArr[i]
<< "] for Packet with Id[" << packId << "]";
delete packet;
packet = NULL;
break;
}
}
}
}
}
return packet;
}
CPacket* CProtocolPackFactory::createPacketFromData(const u8 * data) {
CPacket * packet = NULL;
if( NULL == data ){
return packet;
}
packet = new CPacket( getPacketTypeFromData(data), getPacketLenFromData(data) );
if( NO_ERR != packet->setData( data ) ){
CRITICAL << "Can't create packet from data";
delete packet;
packet = NULL;
}
if( NO_ERR != checkPacketConsistency( packet ) ){
delete packet;
packet = NULL;
CRITICAL << "Can't create packet: Data inconsistent.";
}
return packet;
}
int CProtocolPackFactory::setPacketMessage(CPacket * packet, msg_id_t msgId, const u8 * data) {
int ret = WRONG_PARAMS;
int msgLen;
int offset;
if( ( NULL == packet )||( NULL == data ) ){
return ret;
}
ret = m_pDB->getMessageBitOffsetInPack( packet->packType() ,msgId , &offset );
if( NO_ERR == ret ){
ret = m_pDB->getMessageBitLen( msgId, &msgLen );
if( NO_ERR == ret ){
ret = packet->setBits( offset, msgLen, data );
}
else{
CRITICAL << "Can't set Message bits in packet for msgID["<< msgId << "]";
}
}
else{
CRITICAL << "Can't get Message offset in packet for msgID[" << msgId << "]";
}
return ret;
}
int CProtocolPackFactory::getPacketMessage(CPacket * packet, msg_id_t msgId, u8 * retData) {
int ret;
int msgLen;
int offset;
if( ( NULL == packet )||( NULL == retData ) ){
return WRONG_PARAMS;
}
ret = m_pDB->getMessageBitOffsetInPack( msgId, packet->packType(), &offset );
if( NO_ERR == ret ){
ret = m_pDB->getMessageBitLen( msgId, &msgLen );
if( NO_ERR == ret ){
ret = packet->getBits( offset, msgLen, retData );
}
}
return ret;
}
int CProtocolPackFactory::getPacketHeader(CPacket * packet, u8 * header) {
if( ( NULL == packet )||( NULL == header ) ){
return WRONG_PARAMS;
}
return packet->getBits( 0, m_pDB->getProtocolHeaderLenBits(), header );
}
int CProtocolPackFactory::getPacketPostFix(CPacket * packet, u8 * retPostFix) {
int ret = WRONG_PARAMS;
int offset;
if( ( NULL == packet )||( NULL == retPostFix ) ){
return ret;
}
offset = packet->packLenBits() - m_pDB->getProtocolPostFixLenBits();
if( m_pDB->getProtocolHeaderLenBits() < offset ){
ret = packet->getBits( offset, m_pDB->getProtocolPostFixLenBits(), retPostFix );
}
else{
CRITICAL << "Not correct packet semantic";
ret = WRONG_DATA;
}
return ret;
}
| true |
144c3311d6f40986ff1029e4f7d2a5d523f47508 | C++ | zero4drift/Cpp-Primer-5th-Exercises | /chapter-15/15.24.cpp | UTF-8 | 169 | 2.546875 | 3 | [
"MIT"
] | permissive | // Base class and its derived class require a virtual destructor;
// a virtual destructor of class type should release the resource occupied by the object of that type.
| true |
cda1a4df998062f98efdde594289a9806f53fa4d | C++ | TJUMomonga/TheFifteenthGroup | /CAN信号测试用例/produceTestCase.cpp | GB18030 | 8,018 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <stdlib.h>
#include <algorithm>
#include <cmath>
using namespace std;
string chan10_2(int num,int ord,int le);//ʮת
string chan2_16(int * a2, int len_t);//תʮ
string chan10_16(string a10);//ʮתʮ
void zerosort(int * tar ,string x, int be,int le); //0+
int main(){
ifstream fin("data.in");
ofstream fout("data.txt");
ofstream foutphy("dataphy.txt");
ofstream foutnr("datanr.txt");
ofstream foutr("datar.txt");
string canm; //ĵ
string id_10; //10ID
int len_t; //data
string temp;
while(getline(fin,canm)){ //з
string mes = canm.substr(0,3);
if(mes == "BO_"){
string temp = canm.substr(4,1);
int len_ID; //ID
int i;
for(i = 4;'0'<= temp[0] && temp[0] <= '9' ;){
i++;
temp = canm.substr(i,1);
}
len_ID = i - 4;
id_10 = canm.substr(4,len_ID); //õ10ID
int col = 0; //ðŵλ
for(i = 0; ; i++){
if(canm[i] == ':'){
col = i;
break;
}
}
len_t = canm[col+2] - '0';//õdata
fout << canm << endl;
foutphy << canm << endl;
}
if(canm.substr(0,1) != ""){
mes = canm.substr(1,3);
}
if(mes == "SG_"){
int col = 0; //ðŵλ
int i;
for(i = 0; ; i++){
if(canm[i] == ':'){
col = i;
break;
}
}
int ver_1 = col; //һŵλ
for(i = col; ; i++){
if(canm[i] == '|'){
ver_1 = i;
break;
}
}
int at = col; //һ@λ
for(i = col; ; i++){
if(canm[i] == '@'){
at = i;
break;
}
}
int be,le; //beλʼleλ
be = atoi(canm.substr(col+2, ver_1-col-2).data());
le = atoi(canm.substr(ver_1+1,at-ver_1-1).data());
int ord; //С
temp = canm.substr(at+1,1);
ord = temp[0] - '0'; //ordС
double a,b,c,d;
int zuok = at;//
for(i = at; ; i++){
if(canm[i] == '('){
zuok = i;
break;
}
}
int dou = zuok;//
for(i = zuok; ; i++){
if(canm[i] == ','){
dou = i;
break;
}
}
int yuok = zuok;//
for(i = zuok; ; i++){
if(canm[i] == ')'){
yuok = i;
break;
}
}
int zuof = at;//
for(i = at; ; i++){
if(canm[i] == '['){
zuof = i;
break;
}
}
int colf = zuof;//
for(i = zuof; ; i++){
if(canm[i] == '|'){
colf = i;
break;
}
}
int yuof = zuof;//ҷ
for(i = zuof; ; i++){
if(canm[i] == ']'){
yuof = i;
break;
}
}
a = atof(canm.substr(zuok+1,dou-zuok-1).data());
b = atof(canm.substr(dou+1,yuok-dou-1).data());
c = atof(canm.substr(zuof+1,colf-zuof-1).data());
d = atof(canm.substr(colf+1,yuof-colf-1).data());
int mid = (d+c) / 2 + 1; //ȷֵ(ȡм)
int low = c - 1;//ͱֵ߽
int high = d + 1;//ֵ߽߱
int xm = (mid - b) / a;
int xl = (low - b) / a;
int xh = (high - b) / a;
if(ord == 1){
mid--;
xm = (mid - b) / a;
string xm_2 = chan10_2(xm,1,le);
int can_2[64];
for(int i = 0; i < 64; i++)
can_2[i] = 0;
for(int i = be; i < be+le && i-be < xm_2.length(); i++){
can_2[i] = xm_2[i-be]-'0';
}
fout << canm << endl;
fout << "phy:" << mid << endl;
foutphy << canm << endl;
foutphy << mid << endl;
fout <<'t'<< chan10_16(id_10)
<< len_t <<chan2_16(can_2,len_t) << endl << endl;
foutnr <<'t'<< chan10_16(id_10)
<< len_t <<chan2_16(can_2,len_t) << "\\r\\n" << endl << endl;
foutr <<'t'<< chan10_16(id_10)
<< len_t <<chan2_16(can_2,len_t) << "\\r" << endl << endl;
//
//1.Խ½
int xlow = (c-b)/a;
if(xlow > 0){
string xl_2 = chan10_2(xl,1,le);
int can_2l[64];
for(int i = 0; i < 64; i++)
can_2l[i] = 0;
for(int i = be; i < be+le && i-be < xl_2.length(); i++){
can_2l[i] = xl_2[i-be]-'0';
}
fout << "Խ½:" << endl;
fout <<'t'<< chan10_16(id_10)
<< len_t <<chan2_16(can_2l,len_t) << endl << endl;
}
//2.ԽϽ
int xhigh = (d-b)/a;
if(xhigh < pow(2,le)-1){
string xh_2 = chan10_2(xh,1,le);
int can_2h[64];
for(int i = 0; i < 64; i++)
can_2h[i] = 0;
for(int i = be; i < be+le && i-be < xh_2.length(); i++){
can_2h[i] = xh_2[i-be]-'0';
}
fout << "ԽϽ:" << endl;
fout <<'t'<< chan10_16(id_10)
<< len_t <<chan2_16(can_2h,len_t) << endl << endl;
}
}
if(ord == 0){
string xm_2 = chan10_2(xm,1,le);
cout << xm << ' ' << xm_2 << endl;
int can_2[64];
for(int i = 0; i < 64; i++)
can_2[i] = 0;
zerosort(can_2 ,xm_2,be,le);
for(int i = 0; i < 8; i++){
for(int j = i * 8 + 7 ; j >= i * 8; j--)
cout << can_2[j] <<' ';
cout << endl;
}
fout << canm << endl;
fout << "phy:" << mid << endl;
foutphy << canm << endl;
foutphy << mid << endl;
fout <<'t'<< chan10_16(id_10)
<< len_t <<chan2_16(can_2,len_t) << endl << endl;
foutnr <<'t'<< chan10_16(id_10)
<< len_t <<chan2_16(can_2,len_t) << "\\r\\n" << endl << endl;
foutr <<'t'<< chan10_16(id_10)
<< len_t <<chan2_16(can_2,len_t) << "\\r" << endl << endl;
//
//1.Խ½
int xlow = (c-b)/a;
if(xlow > 0){
string xl_2 = chan10_2(xl,1,le);
int can_2l[64];
for(int i = 0; i < 64; i++)
can_2l[i] = 0;
for(int i = be; i < be+le && i-be < xl_2.length(); i++){
can_2l[i] = xl_2[i-be]-'0';
}
fout << "Խ½:" << endl;
fout <<'t'<< chan10_16(id_10)
<< len_t <<chan2_16(can_2l,len_t) << endl << endl;
}
}
}
}
return 0;
}
//ʮת
string chan10_2(int num,int ord,int le){
string s="";
if(num < 0)
s+='1';
for(int a = num; a ;a = a/2)
{
s=s+(a%2?'1':'0');
}
if(ord == 0){
reverse(s.begin(),s.end());
}
if(s=="")
s=s+'0';
return s;
}
//תʮ
string chan2_16(int * a2, int len_t){
string s="";
len_t = len_t * 2;
char a = '0';
char b = '0';
for(int i = 0; i < len_t * 4; i=i+8){
int sum = a2[i+3]*8 + a2[i+2]*4 + a2[i+1]*2 + a2[i];
if(sum <= 9)
a = sum + '0';
else if(sum > 9)
a = 'A' + sum - 10;
sum = 0;
sum = a2[i+7]*8 + a2[i+6]*4 + a2[i+5]*2 + a2[i+4];
if(sum <= 9)
b = sum + '0';
else if(sum > 9)
b = 'A' + sum - 10;
s = s + b;
s = s + a;
}
return s;
}
//ʮתʮ
string chan10_16(string a10){
int n = 0;
n = atoi(a10.data());
string s = "";
if (n == 0)
s = "0";
while (n != 0)
{
if (n%16 >9 )
s += n%16 - 10 +'A';
else
s += n%16 + '0';
n = n / 16;
}
reverse(s.begin(), s.end());
return s;
}
void zerosort(int * tar,string x, int be,int le){
int dev[8]={8,16,24,32,40,48,56,64};
int first,last;
int i;
for(i = 0; i < 8; i++){
if(be < dev[i])
break;
}
first = i;
int first_len = be - dev[first] + 8 + 1;
if(first_len > le) //ֻһ
first_len = le;
int red = le - first_len;
cout << be << ' ' << le << endl;
int mid_len = red / 8;
int last_len = red % 8;
int guid = le - 1; //ָ
//һ
for(int i = 0; i < first_len; i++){
tar[be-i] = x[le - i - 1] - '0';
if(tar[be-i] < 0) tar[be-i] = 0;
guid--;
}
//м
for(int i = 0; i < mid_len ; i++){
int row = first + 1 + i;
for(int j = 7; j >= 0; j--){
tar[row * 8 + j] = x[guid] - '0';
guid--;
}
}
//һ
for(int i = 0; i < last_len; i++){
int loc = (first + mid_len + 2)*8-1-i;
tar[loc] = x[guid] - '0';
guid--;
}
return;
}
| true |
05eedd7d885a293c04a0af26c81b3004aa041a2a | C++ | yifeir33/cs4500 | /assignment3/part2/array.h | UTF-8 | 926 | 2.515625 | 3 | [] | no_license | // lang: CwC
#pragma once
#include <iostream>
#include <cstring>
#include "object.h"
#include "string.h"
#include "assert.h"
/**
* NOTE: Just use your implementations - our API makes no assumptions about this interface
* besides basic functionality.
*
* Authors: Neil Resnik (resnik.n@husky.neu.edu) & Yifei Wang (wang.yifei3@husky.neu.edu)
*/
/**
* An Array class to which elements can be added to and removed from.
*/
class ObjectArray : public Object {};
/**
* An Array class to which strings can be added to and removed from.
*/
class StringArray : public Object {};
/**
* An Array class to which booleans can be added to and removed from.
*/
class BoolArray : public Object {};
/**
* An Array class to which floats can be added to and removed from.
* author: chasebish */
class FloatArray : public Object {};
/**
* An Array class to which integers can be added to and removed from.
* author: chasebish */
class IntArray : public Object {};
| true |
d468ca8b195c7fc8bb8c9b8dc2da133317c9204d | C++ | demonsheart/C- | /rongyu/homework1/file/2018192045_1038_正确_337.cpp | UTF-8 | 679 | 2.765625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main ()
{
int m,t,i,a1,a2,a3,j,b1,b2,b3;
cin>>t;
while(t--)
{
char *ch1=new char[10];
char *ch2=new char[10];
char *ch3=new char[10];
cin>>ch1; cin>>ch2; cin>>ch3;
cin>>a1>>b1;
cin>>a2>>b2;
cin>>a3>>b3;
m=b1-a1+b2-a2+b3-a3+3;
char *New=new char[m];
for(i=0;i<=b1-a1;i++)
*(New+i)=*(ch1+a1-1+i);
for(i=b1-a1+1,j=0;i<=b1-a1+1+b2-a2;j++,i++)
*(New+i)=*(ch2+a2-1+j);
for(i=b1-a1+1+b2-a2+1,j=0;i<=b1-a1+1+b2-a2+1+b3-a3;j++,i++)
*(New+i)=*(ch3+a3-1+j);
for(i=0;i<=m-1;i++)
cout<<*(New+i);
cout<<endl;
delete []New;delete []ch1;delete []ch2;delete []ch3;
}
}
| true |
731a9e843c3566d69e83f239cfec3e2fd7599d55 | C++ | abique/mimosa | /mimosa/time.hh | UTF-8 | 2,900 | 3.0625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <cstdint>
#include <cstddef>
#include <ctime>
#include <stdexcept>
#include <unistd.h>
#include <sys/time.h>
#ifdef __MACH__
# include <mach/mach.h>
# include <mach/clock.h>
#endif
#ifndef CLOCK_MONOTONIC_COARSE
# define CLOCK_MONOTONIC_COARSE CLOCK_MONOTONIC
#endif
#ifndef CLOCK_REALTIME_COARSE
# define CLOCK_REALTIME_COARSE CLOCK_REALTIME
#endif
namespace mimosa
{
// signed to ease time substraction
using Time = std::int64_t;
const Time nanosecond = 1;
const Time microsecond = 1000 * nanosecond;
const Time millisecond = 1000 * microsecond;
const Time second = 1000 * millisecond;
const Time minute = 60 * second;
const Time hour = 60 * minute;
const Time day = 24 * hour;
#ifdef __MACH__
inline Time realTime() noexcept
{
::clock_serv_t cal_clock;
::mach_timespec tp;
::host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cal_clock);
::clock_get_time(cal_clock, &tp);
return tp.tv_nsec * nanosecond + tp.tv_sec * second;
}
inline Time monotonicTime() noexcept
{
::clock_serv_t sys_clock;
::mach_timespec tp;
::host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &sys_clock);
::clock_get_time(sys_clock, &tp);
return tp.tv_nsec * nanosecond + tp.tv_sec * second;
}
inline Time realTimeCoarse() noexcept
{
return realTime();
}
inline Time monotonicTimeCoarse() noexcept
{
return monotonicTime();
}
#else
inline Time realTime()
{
::timespec tp;
int ret = ::clock_gettime(CLOCK_REALTIME, &tp);
if (ret)
throw std::runtime_error("clock_gettime");
return tp.tv_nsec * nanosecond + tp.tv_sec * second;
}
inline Time monotonicTime()
{
::timespec tp;
int ret = ::clock_gettime(CLOCK_MONOTONIC, &tp);
if (ret)
throw std::runtime_error("clock_gettime");
return tp.tv_nsec * nanosecond + tp.tv_sec * second;
}
inline Time realTimeCoarse()
{
::timespec tp;
int ret = ::clock_gettime(CLOCK_REALTIME_COARSE, &tp);
if (ret)
throw std::runtime_error("clock_gettime");
return tp.tv_nsec * nanosecond + tp.tv_sec * second;
}
inline Time monotonicTimeCoarse()
{
::timespec tp;
int ret = ::clock_gettime(CLOCK_MONOTONIC_COARSE, &tp);
if (ret)
throw std::runtime_error("clock_gettime");
return tp.tv_nsec * nanosecond + tp.tv_sec * second;
}
#endif
inline Time time()
{
return monotonicTimeCoarse();
}
inline ::timespec toTimeSpec(Time time) noexcept
{
::timespec tp;
tp.tv_sec = time / second;
tp.tv_nsec = time % second;
return tp;
}
inline ::timeval toTimeVal(Time time) noexcept
{
::timeval tv;
tv.tv_sec = time / second;
tv.tv_usec = (time % second) / microsecond;
return tv;
}
inline void sleep(Time duration) noexcept
{
::usleep(duration / microsecond);
}
}
| true |
c21a18d57fb5003f8aea15594169ab5fcde319b1 | C++ | notoraptor/cigmar | /src/cpp/filesystem_windows.cpp | UTF-8 | 5,918 | 2.796875 | 3 | [] | no_license | /* Reference code for Windows: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365200(v=vs.85).aspx */
#ifdef WIN32
// #include <cstdio>
#include <cassert>
#include <string>
#include <direct.h>
#include <windows.h>
#include <cigmar/filesystem.hpp>
#include <cigmar/classes/String.hpp>
namespace cigmar {
namespace windows {
const String prefix = "\\\\?\\";
const String suffix = "\\*";
void formatPrefix(String& s, bool skipSpecialFolders = false) {
if (skipSpecialFolders && (s == "." || s == ".."))
return;
if (!s.startsWith(prefix))
s.insert(0, prefix);
}
void formatSuffix(String& s) {
if (!s.endsWith(suffix))
s << suffix;
}
void removePrefix(String& s) {
if (s.startsWith(prefix))
s.remove(0, prefix.length());
}
void removeSuffix(String& s) {
if (s.endsWith(suffix)) {
s.remove(s.length() - suffix.length(), suffix.length());
}
}
void formatIfNeeded(String& path) {
if (path != "." && path != "..") {
formatPrefix(path);
formatSuffix(path);
}
}
}
namespace sys {
class PlatformDir {
public:
String internal;
};
class PlatformDirent {
private:
HANDLE handle;
WIN32_FIND_DATA ffd;
friend class Dirent;
explicit PlatformDirent(const String& internalPath):
handle(INVALID_HANDLE_VALUE) {
handle = FindFirstFile(internalPath.cstring(), &ffd);
assert(handle != INVALID_HANDLE_VALUE);
};
public:
~PlatformDirent() {
FindClose(handle);
}
};
Dirent::Dirent() {
handler = nullptr;
}
Dirent::Dirent(Dir& dir) {
handler = new PlatformDirent(dir.handler->internal);
}
Dirent::~Dirent() {
delete handler;
}
Dirent& Dirent::operator++() {
if (handler) {
if (FindNextFile(handler->handle, &handler->ffd) == 0) {
delete handler;
handler = nullptr;
}
}
return *this;
}
bool Dirent::operator==(const Dirent& other) const {
return handler == other.handler;
}
bool Dirent::operator!=(const Dirent& other) const {
return handler != other.handler;
}
const char* Dirent::operator*() const {
return handler ? handler->ffd.cFileName : nullptr;
}
Dir::Dir(const char *pathname): handler(nullptr) {
String formatedFilename = sys::path::absolute(pathname);
windows::formatPrefix(formatedFilename);
windows::formatSuffix(formatedFilename);
WIN32_FIND_DATA ffd;
HANDLE handle = FindFirstFile(formatedFilename.cstring(), &ffd);
if (handle == INVALID_HANDLE_VALUE)
throw Exception("cigmar::sys::Dir: error opening directory: ", pathname);
FindClose(handle);
if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
throw Exception("cigmar::sys::Dir: not a directory: ", pathname);
}
handler = new PlatformDir();
handler->internal = formatedFilename;
}
Dir::~Dir() {
delete handler;
}
Dirent Dir::begin() {
return Dirent(*this);
}
Dirent Dir::end() {
return Dirent();
}
namespace path {
// const char* const separator;
const char* const separator = windowsSeparator;
String norm(const char* pathname) {
// Normalize separators.
String p(pathname);
String twoSeps = String::write(separator, separator);
size_t sepLength = strlen(separator);
p.replace(unixSeparator, separator);
windows::removePrefix(p);
windows::removeSuffix(p);
// Remove separators at start (only on Windows).
while (p.startsWith(separator))
p.remove(0, sepLength);
// Remove trailing separators.
while (p.endsWith(separator))
p.remove(p.length() - sepLength, sepLength);
// Remove consecutive separators.
while (p.contains(twoSeps))
p.replace(twoSeps, separator);
return p;
};
String absolute(const char* pathname) {
if (isAbsolute(pathname))
return String(pathname);
String normalized = sys::path::resolve(pathname);
if (isAbsolute(normalized.cstring()))
return normalized;
std::string& normalizedPath = normalized.cppstring();
size_t posFirstSeparator = normalizedPath.find(separator);
std::string parent;
size_t fullPathLength;
if(posFirstSeparator == std::string::npos) {
fullPathLength = GetFullPathName(normalizedPath.c_str(), 0, NULL, NULL);
} else {
parent = normalizedPath.substr(0, posFirstSeparator);
fullPathLength = GetFullPathName(parent.c_str(), 0, NULL, NULL);
}
if (fullPathLength > 0) {
char* buffer = new char[fullPathLength];
std::string* ptr = parent.empty() ? &normalizedPath : &parent;
size_t writtenLength = GetFullPathName(ptr->c_str(), fullPathLength, buffer, NULL);
if (writtenLength == fullPathLength - 1) {
std::string s = buffer;
if (!parent.empty()) {
s += normalizedPath.substr(posFirstSeparator);
}
delete[] buffer;
return String(s.c_str());
}
}
return "";
};
bool isRooted(const char* pathname) {
return isalpha(pathname[0]) && pathname[1] == ':' && pathname[2] == '\\';
}
bool isRoot(const char* pathname) {
return isRooted(pathname) && pathname[3] == '\0';
}
bool isDirectory(const char* pathname) {
try {
Dir d(pathname);
return true;
} catch (...) {
return false;
}
};
bool isFile(const char* pathname) {
String formatedFilename = sys::path::absolute(pathname);
windows::formatPrefix(formatedFilename);
DWORD attributes = GetFileAttributes(formatedFilename.cstring());
return attributes != INVALID_FILE_ATTRIBUTES && !(attributes & FILE_ATTRIBUTE_DIRECTORY);
}
}
int makeDirectory(const char* pathname) {
String formated = sys::path::absolute(pathname);
windows::formatPrefix(formated);
return _mkdir(formated.cstring());
};
int removeDirectory(const char* pathname) {
String formated = sys::path::absolute(pathname);
windows::formatPrefix(formated);
return _rmdir(formated.cstring());
};
}
}
#endif
| true |
15e0cb2a479ce56fed976770acd6ef4d162ff7dd | C++ | aniketshelke123/hello-world.io | /bst_using_linked_list.cpp | UTF-8 | 5,262 | 3.5 | 4 | [] | no_license |
# include <iostream>
using namespace std;
struct Node{
int data;
struct Node *left;
struct Node *right;
};
struct Node *root = nullptr, *t;
void insert(){
struct Node *temp, *parent;
temp = new Node();
cout << "Enter the data: ";
cin >> temp -> data;
temp -> right = nullptr;
temp -> left = nullptr;
if (root == nullptr){
root = temp;
t = root;
cout << "\n Data inserted..!!" << endl;
}
else{
struct Node *current;
current = root;
while(current){
parent = current;
if (temp -> data > current -> data){
current = current -> right;
}
else{
current = current -> left;
}
}
//here parent is pointing to last node
if (temp -> data > parent -> data){ // if data > parent
parent -> right = temp;
}
else{ // if data < parent
parent -> left = temp;
}
cout << "\nData inserted..!!" << endl;
}
}
void inorder(struct Node *t){
if (t -> left){
inorder(t -> left);
}
cout << t -> data << " ";
if (t -> right){
inorder(t -> right);
}
}
void Delete(){
int item, check;
cout << "Enter the item: ";
cin >> item;
struct Node *current = root, *parent;
while (current -> data != item){
parent = current;
if (item > current -> data){
current = current -> right;
}
else{
current = current -> left;
}
}
// logic for deleting leaf node
if (current -> right == nullptr && current -> left == nullptr){
if (current == parent -> right){
parent -> right = nullptr;
}
else{
parent -> left = nullptr;
}
delete current; // ends here.......
}
// logic for deleting child nodes on one side of current node.....
else if (current -> left != nullptr && current -> right == nullptr){
if (current == parent -> right){
parent -> right = current -> left;
}
else{
parent -> left = current -> left;
}
current -> left = nullptr;
delete current;
}
else if (current -> right != nullptr && current -> left == nullptr){
if (current == parent -> right){
parent -> right = current -> right;
}
else{
parent -> left = current -> right;
}
current -> right = nullptr;
delete current;
} // ends here......
// logic for deleting child nodes on both sides of current node.....
else if (current -> left != nullptr && current -> right != nullptr){
struct Node *temp1, *temp2;
temp1 = current -> right;
if (temp1 -> left == nullptr && temp1 -> right == nullptr){
current -> data = temp1 -> data;
current -> right = nullptr;
delete temp1;
}
else if (temp1 -> right != nullptr && temp1 -> left == nullptr){
current -> data = temp1 -> data;
current -> right = temp1 -> right;
temp1 -> right = nullptr;
delete temp1;
}
else if (temp1 -> left != nullptr){
while (temp1 -> left -> left != nullptr)
{
temp1 = temp1 -> left;
}
temp2 = temp1 -> left;
current -> data = temp2 -> data;
temp1 -> left = temp2 -> right;
delete temp2;
}
}
}
int search(){
struct Node *current = root, *temp;
temp = new Node();
cout << "Enter the item to be searched: ";
cin >> temp -> data;
temp -> left = nullptr;
temp -> right = nullptr;
while (current -> left != nullptr){
if (temp -> data > current -> data){
current = current -> right;
}
else if (temp -> data < current -> data){
current = current -> left;
}
if (temp -> data == current -> data){
return 1;
}
}
return 0;
}
int main()
{
int ch, item;
do {
cout << "\n1.INSERT" << endl;
cout << "2.DELETE" << endl;
cout << "3.DISPLAY" << endl;
cout << "4.SEARCH" << endl;
cout << "5. EXIT" << endl;
cout << "Enter your choice: ";
cin >> ch;
switch (ch)
{
case 1: insert();
break;
case 2: Delete();
break;
case 3: cout << endl;
inorder(t);
cout << endl;
break;
case 4: if (search()){
cout << "\nItem found..!!" << endl;
}
else{
cout << "\nNot found..!! " << endl;
}
break;
case 5: exit(0);
break;
}
}while(1);
return 0;
}
| true |
f231e177e24030710f230d698438fb28b82c61c4 | C++ | eyalya/Experis-CDR-Project | /include/cat.hpp | UTF-8 | 1,232 | 3.59375 | 4 | [] | no_license | #ifndef CAT_H
#define CAT_H
#include <cassert>
#include <iostream>
class Cat
{
public:
explicit Cat(int a_id=0, int a_age=0);
int ID() const;
int Age() const;
void ID(int const& a_ID);
void Age(int const& a_age);
std::ostream& Print(std::ostream& a_os) const;
private:
int m_id;
int m_age;
};
Cat::Cat(int a_id, int a_age)
: m_id(a_id)
, m_age(a_age)
{
}
inline int Cat::ID() const
{
return m_id;
}
inline int Cat::Age() const
{
return m_age;
}
inline void Cat::ID(int const& a_id)
{
m_id = a_id;
}
inline void Cat::Age(int const& a_age)
{
m_age = a_age;
}
std::ostream& Cat::Print(std::ostream& a_os) const
{
a_os << "ID:"<< ID() << ',' << Age() << ';' ;
return a_os;
}
//globals
inline bool operator == (Cat const& a_lhs, Cat const& a_rhs)
{
return (a_lhs.ID() == a_rhs.ID());
}
inline bool operator != (Cat const& a_lhs, Cat const& a_rhs)
{
return !(a_lhs.ID() == a_rhs.ID());
}
inline bool operator < (Cat const& a_lhs, Cat const& a_rhs)
{
return (a_lhs.ID() < a_rhs.ID());
}
inline bool operator > (Cat const& a_lhs, Cat const& a_rhs)
{
return (a_lhs.ID() > a_rhs.ID());
}
std::ostream& operator<<(std::ostream& a_os, Cat const& a_cat)
{
return a_cat.Print(a_os);
}
#endif //CAT_H
| true |
f644d2aa57ed7cbff7e60d4fe8202daf1ac1397a | C++ | SinncaStudios/SinncaEngine | /SinncaEngine/ListAlloc.h | UTF-8 | 1,227 | 2.640625 | 3 | [] | no_license | //
// ListAlloc.h
// SinncaEngine
//
// Created by Ryan Oldis on 12/13/13.
// Copyright (c) 2013 Ryan Oldis. All rights reserved.
//
#ifndef __SinncaEngine__ListAlloc__
#define __SinncaEngine__ListAlloc__
#include <iostream>
#include "Memory.h"
namespace sinnca
{
class list : public Memory
{
struct allocHeader
{
ui32 size;
ui32 adjust;
};
struct block
{
ui32 size;
block* next;
};
// ...and this block you cannot cha-a-ange...
block* freeBlock;
public:
list(ui32 size);
~list();
void* allocate(ui32 size, ui8 align);
void deallocate(void* p);
};
/*
class FreeListAllocator : public Allocator
{
public:
FreeListAllocator(ui32 size, void* pStart);
~FreeListAllocator();
void* allocate(ui32 size, ui8 alignment);
void deallocate(void* p);
private:
struct AllocationHeader
{
ui32 size;
ui32 adjustment;
};
struct FreeBlock
{
ui32 size;
FreeBlock* pNext;
};
//FreeListAllocator(const FreeListAllocator&) {}; //Prevent copies because it might cause errors
//FreeListAllocator& operator=(const FreeListAllocator&) {};
FreeBlock* _pFreeBlocks;
};
*/
}
#endif /* defined(__SinncaEngine__ListAlloc__) */
| true |
3ed6aff6d7e981f53bc831a05017564d04a4c219 | C++ | Nguyen-Duc-Cong/code-C | /Workshop1.cpp | UTF-8 | 596 | 2.515625 | 3 | [] | no_license | #include <stdio.h>
int n;
double x;
char cl;
int main()
{
int m;
short s;
long L;
float y;
printf("Code of main:%u\n", &main);
printf("Variable n, add:%u, memory size:%d\n", &n, sizeof(n));
printf("Variable x, add:%u, memory size:%d\n", &n, sizeof(x));
printf("Variable cl, add:%u, memory size:%d\n", &cl, sizeof(cl));
printf("Variable m, add:%u, memory size:%d\n", &m, sizeof(m));
printf("Variable s, add:%u, memory size:%d\n", &s, sizeof(s));
printf("Variable L, add:%u, memory size:%d\n", &L, sizeof(L));
printf("Variable y, add:%u, memory size:%d\n", &y, sizeof(y));
return 0;
}
| true |
3c284ed9900e07b6ea29d265c11c4ccc060cb9ea | C++ | leejaeseung/Algorithm | /BOJ/C++/4358_생태학.cpp | UHC | 2,256 | 3.046875 | 3 | [] | no_license | /*
п ϴ ߿ϴ. Ƿ ̱ ־ , ü % ϴ ϴ α Ѵ.
Է
α ٷ ̷ , ٿ ϳ ̸ ־. ̸ 30ڸ , Է¿ ִ 10,000 ־ ִ 1,000,000 ־.
־ ̸ ϰ, ϴ Ҽ 4°ڸ Բ Ѵ.
Ǯ:
Ʈ ˰ ⺻ Դϴ.
*/
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string>
#include<vector>
#include<stack>
#include<queue>
#include<map>
using namespace std;
#define FIO ios_base::sync_with_stdio(false); cin.tie(NULL)
#define pii pair<int, int>
#define pdd pair<double, double>
#define pic pair<int, char>
#define ll long long
#define vi vector<int>
#define vl vector<long long>
#define vc vector<char>
#define vii vector<pii>
#define IMAX 2000000001
#define LMAX 1000000000000000000
#define DMAX 0xFFFFFFFFFFFFF
int mv1[4] = { 0, 1, 0, -1 };
int mv2[4] = { 1, 0, -1, 0 };
class node {
public:
double cnt = 0;
string nowStr = "";
node* next[127];
};
node* root;
double allCnt = 0;
vector<pair<string, double>> ans;
void search(node* now) {
for (int i = 0; i < 127; i++)
{
if (now->next[i] == NULL) continue;
search(now->next[i]);
}
if (now->cnt != 0) {
ans.push_back({ now->nowStr, now->cnt / allCnt * 100 });
}
}
int main(void) {
FIO;
root = new node();
string str;
while (getline(cin, str)) {
allCnt++;
node* nowNode = root;
for (int i = 0; i < str.size(); i++)
{
int now = str[i];
if (nowNode->next[now] == NULL) {
nowNode->next[now] = new node();
nowNode->next[now]->nowStr = nowNode->nowStr + (char)now;
}
nowNode = nowNode->next[now];
}
nowNode->cnt++;
}
cout.precision(4);
cout << fixed;
search(root);
sort(ans.begin(), ans.end());
for (int i = 0; i < ans.size(); i++)
{
cout << ans[i].first << " " << ans[i].second << "\n";
}
} | true |
8d854b8ec1f124ec58e840518692220f0efb3212 | C++ | lyh458/InteractionModels_DemoCode | /src/iModOSG/MyInteractionTriangleMeshView.h | UTF-8 | 2,546 | 2.921875 | 3 | [] | no_license | //
// MyInteractionTriangleMeshView.h
// BoneAnimation
//
// Created by Christian on 30.11.13.
//
//
#ifndef __BoneAnimation__MyInteractionTriangleMeshView__
#define __BoneAnimation__MyInteractionTriangleMeshView__
#include "MyInteractionMeshView.h"
#include "MyInteractionTriangleMesh.h"
namespace MyInteractionMesh {
/**
* @brief View for a InteractionMesh made out of Triangle's
*/
class MyInteractionTriangleMeshView : MyInteractionMeshView {
public:
/**
* @brief Constructor
*
* @param model Pointer to a model from which the numbers for the view come from.
*/
MyInteractionTriangleMeshView(MyInteractionMeshModel* model);
/**
* @brief Deconstructor
*/
virtual ~MyInteractionTriangleMeshView();
private:
osg::Geode* createGeodeFacade(Shape* shape, osg::Vec4 color);
osg::Vec4f getColorFacade(Shape* currentShape, Shape* oldShape, osg::Vec4f oldColor = osg::Vec4f(1.0f, 0.0f, 0.0f, 1.0f));
osg::Geometry* createGeometryFacade(Shape* shape, osg::Vec4 color);
Shape* getShapeFromOSGGeometry(osg::Geometry* geometry, std::vector<Vertice>* verticeVec);
/**
* @brief Creates a Geode from a Triangle - Shape
* @param v1 a Vertice of the Triangle
* @param v2 a Vertice of the Triangle
* @param v3 a Vertice of the Triangle
* @param color Color for the Geode
* @return Pointer to the created Geode
*/
osg::Geode* createTriangleGeode(osg::Vec3 v1, osg::Vec3 v2, osg::Vec3 v3, osg::Vec4 color);
/**
* @brief Creates a Geometry from a Triangle - Shape
* @param v1 a Vertice of the Triangle
* @param v2 a Vertice of the Triangle
* @param v3 a Vertice of the Triangle
* @param color Color for the Geometry
* @return Pointer to the created Geometry
*/
osg::Geometry* createTriangleGeometry(osg::Vec3 v1, osg::Vec3 v2, osg::Vec3 v3, osg::Vec4 color);
/**
* @brief Calculates a color for a Triangle, based on the parameters
* @param current the coordinates of the current Triangle for which the color should be calculated
* @param old the old coordinates of the Triangle
* @param oldColor the old color of the Triangle (actually the color for the old coordinates)
* @return an osg 4 dimensional vector which describes the new color
*/
osg::Vec4f getColorForTriangle(TriangleCoordinates current, TriangleCoordinates old, osg::Vec4f oldColor = osg::Vec4f(1.0f, 0.0f, 0.0f, 1.0f));
};
}
#endif /* defined(__BoneAnimation__MyInteractionTriangleMeshView__) */
| true |
b969b8e422333411d826f7a48bca5901a041595c | C++ | LenyKholodov/wood | /new/misc/misc/list.inl | IBM866 | 2,576 | 2.890625 | 3 | [] | no_license | template <class T> List<T>::List (Pool* pool)
: MemObject (pool)
{ }
template <class T> List<T>::~List ()
{
int count = this->count (), i = 0;
for (iterator iter = *this;i<count;erase(iter),i++);
}
template <class T> bool List<T>::InsertFirst (const T& obj,bool exc) throw (ExcNoMemory&)
{
node_t* node = node_t::create (obj,GetPool());
if (!node)
{
if (exc) throw ExcNoMemory ("List::insert",sizeof (node_t),this);
return false;
}
BaseList::InsertFirst (*node);
return true;
}
template <class T> bool List<T>::InsertLast (const T& obj,bool exc) throw (ExcNoMemory&)
{
node_t* node = node_t::create (obj,GetPool());
if (!node)
{
if (exc) throw ExcNoMemory ("List::insert",sizeof (node_t),this);
return false;
}
BaseList::InsertLast (*node);
return true;
}
template <class T> bool List<T>::InsertAfter (iterator& i,iterator& ins)
{
return BaseList::InsertAfter (i.node (),ins.node ());
}
template <class T> bool List<T>::InsertBefore (iterator& i,iterator& ins)
{
return BaseList::InsertBefore (i.node (),ins.node ());
}
template <class T>
bool List<T>::InsertAfter (iterator& i,const T& obj,bool exc) throw (ExcNoMemory&)
{
if (!&i.node ()) return false;
node_t* node = node_t::create (obj,GetPool());
if (!node)
{
if (exc) throw ExcNoMemory ("List::InsertAfter",sizeof (node_t),this);
return false;
}
return InsertAfter (i,iterator (*node));
}
template <class T>
bool List<T>::InsertBefore (iterator& i,const T& obj,bool exc) throw (ExcNoMemory&)
{
if (!&i.node ()) return false;
node_t* node = node_t::create (obj,GetPool());
if (!node)
{
if (exc) throw ExcNoMemory ("List::InsertBefore",sizeof (node_t),this);
return false;
}
return InsertBefore (i,iterator (*node));
}
template <class T> List<T>::iterator List<T>::find (const T& obj) const
{
iterator iter = *this;
for (int i=0;i<count();i++,iter++)
// if (iter.data() == obj)
if (!memcmp (&iter.data(),&obj,sizeof (T))) // 室 . ७
return iter;
return iterator ();
}
template <class T> void List<T>::erase (List<T>::iterator& iter,bool autoDel)
{
node_t& node = iter.node ();
// if (!&node || &node == &mNull || &node == (listnode_t*)&mFirst || &node == (listnode_t*)&mLast)
if (!&node)
return;
BaseList::Erase (node);
if (autoDel)
{
iter++;
free (&node);
// iter = (node_t*)NULL;
}
}
| true |
13cb2a83ea7e03b2edf0a88db37a4850de3d583c | C++ | zgzhengSEU/Algorithm-Learning | /LeetCode/34.find-first-and-last-position-of-element-in-sorted-array.cpp | UTF-8 | 1,496 | 3.234375 | 3 | [] | no_license | /*
* @lc app=leetcode id=34 lang=cpp
*
* [34] Find First and Last Position of Element in Sorted Array
*
* https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/
*
* algorithms
* Medium (38.84%)
* Likes: 7670
* Dislikes: 244
* Total Accepted: 856.3K
* Total Submissions: 2.2M
* Testcase Example: '[5,7,7,8,8,10]\n8'
*
* Given an array of integers nums sorted in ascending order, find the starting
* and ending position of a given target value.
*
* If target is not found in the array, return [-1, -1].
*
* You must write an algorithm with O(log n) runtime complexity.
*
*
* Example 1:
* Input: nums = [5,7,7,8,8,10], target = 8
* Output: [3,4]
* Example 2:
* Input: nums = [5,7,7,8,8,10], target = 6
* Output: [-1,-1]
* Example 3:
* Input: nums = [], target = 0
* Output: [-1,-1]
*
*
* Constraints:
*
*
* 0 <= nums.length <= 10^5
* -10^9 <= nums[i] <= 10^9
* nums is a non-decreasing array.
* -10^9 <= target <= 10^9
*
*
*/
// @lc code=start
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int l = 0 , r = nums.size() - 1;
while (l < r) {
int mid = l + r >> 1;
if (nums[mid] >= target) r = mid;
else l = mid + 1;
}
if (l > r || nums[l] != target) return {-1, -1};
while (r + 1 < nums.size() && nums[r + 1] == nums[l]) ++r;
return {l, r};
}
};
// @lc code=end
| true |
5d2d30e4058ed877311a45518a959d60cd76de16 | C++ | weirdrag08/Data-Structures-Algorithms | /Graphs/Adjacency_list_implementation.cpp | UTF-8 | 813 | 3.453125 | 3 | [] | no_license | #include<iostream>
#include<list>
using namespace std;
class Graph{
int vertices;
list<int> *l;
public:
Graph(int vertices){
this-> vertices = vertices;
l = new list<int>[vertices];
}
void addEdge(int u, int v, bool bidir = true){
l[u].push_back(v);
if(bidir){
l[v].push_back(u);
}
}
void display(){
for(int i = 0; i < vertices; i++){
cout << i << "==> {";
for(int j : l[i]){
cout << j << ", ";
}
cout << " }" << '\n';
}
}
};
int main(){
int v;
cin >> v;
Graph g(v);
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.display();
} | true |
b98527369df7ab4f6f6a2ce8d9392725946c9738 | C++ | GreggGut/coen345 | /src/Grid.cpp | UTF-8 | 4,074 | 3.171875 | 3 | [] | no_license | /*
* Grid.cpp
*
* Created on: Jan 21, 2013
* Author: k_berson
*/
//Self
#include "Grid.h"
//C Library
#include <iostream>
//namespace
using namespace std;
//Constructor
// [I n|i n] Initialize the system: The values of the array floor are zeros and the robot is back to [0, 0], pen up and facing north. n size of the array, an integer greater than zero
Grid::Grid(int gridSize)
{
if (gridSize < 1)
gridSize = 1;
size = gridSize;
//robot init
robot.facing = robot.FACING_NORTH;
robot.penDown = false;
robot.x = 0;
robot.y = 0;
contents = new int*[gridSize];
for (int i = 0; i < gridSize; i++)
{
contents[i] = new int[gridSize];
//Initialize all values to 0
for (int j = 0; j < gridSize; j++)
{
contents[i][j] = 0;
}
}
}
//Destructor
Grid::~Grid()
{
for (int i = 0; i < size; i++)
{
delete[] contents[i];
}
delete[] contents;
}
/*----------------------------------------------------*/
/*- Private -*/
/*----------------------------------------------------*/
//Marks a space if within bounds
void Grid::markSpace(int x, int y)
{
if (x >= 0 && x < size && y >= 0 && y < size)
contents[x][y] = 1;
}
/*----------------------------------------------------*/
/*- Public -*/
/*----------------------------------------------------*/
//Raise pen
// [U|u] Pen up
void Grid::raisePen()
{
robot.penDown = false;
}
//Lower pen
// [D|d] Pen down
void Grid::lowerPen()
{
robot.penDown = true;
}
//Turn robot right
// [R|r] Turn right
void Grid::turnRight()
{
robot.facing = (
robot.facing == robot.FACING_NORTH ? robot.FACING_EAST :
robot.facing == robot.FACING_WEST ? robot.FACING_NORTH :
robot.facing == robot.FACING_SOUTH ? robot.FACING_WEST :
robot.facing == robot.FACING_EAST ?
robot.FACING_SOUTH : robot.facing);
}
//Turn robot left
// [L|l] Turn left
void Grid::turnLeft()
{
robot.facing = (
robot.facing == robot.FACING_NORTH ? robot.FACING_WEST :
robot.facing == robot.FACING_WEST ? robot.FACING_SOUTH :
robot.facing == robot.FACING_SOUTH ? robot.FACING_EAST :
robot.facing == robot.FACING_EAST ?
robot.FACING_NORTH : robot.facing);
}
//Move robot
// [M s|m s] Move forward s spaces (s is a non-negative integer)
int Grid::moveRobot(int distance)
{
int distMoved = 0;
int xDirn = (robot.facing == robot.FACING_WEST ? -1 :
robot.facing == robot.FACING_EAST ? 1 : 0);
int yDirn = (robot.facing == robot.FACING_SOUTH ? -1 :
robot.facing == robot.FACING_NORTH ? 1 : 0);
//mark starting space (even if not moving)
if (robot.penDown)
this->markSpace(robot.x, robot.y);
//move 1 space at a time
//check bounds before moving
while (distMoved < distance
&& ((robot.x + xDirn) >= 0 && (robot.x + xDirn) < size)
&& ((robot.y + yDirn) >= 0 && (robot.y + yDirn) < size))
{
//move into next space
robot.x += xDirn;
robot.y += yDirn;
distMoved++;
//mark new space
if (robot.penDown)
this->markSpace(robot.x, robot.y);
}
return distMoved;
}
//Print grid
// [P|p] Print the N by N array and display the indices
void Grid::print()
{
cout << endl;
cout << "\t";
for (int x = 0; x < size; x++)
{
cout << x << "\t";
}
cout << endl;
for (int y = size - 1; y >= 0; y--)
{
cout << y << "\t";
for (int x = 0; x < size; x++)
{
if (contents[x][y] == 1)
cout << '*';
cout << "\t";
}
cout << y << endl;
}
cout << "\t";
for (int x = 0; x < size; x++)
{
cout << x << "\t";
}
cout << endl;
cout << endl;
}
//Print robot position
// [C|c] Print current position of the pen and whether it is up or down and its facing direction
void Grid::printRobot()
{
cout << "Pos: (" << robot.x << ", " << robot.y << ")" << endl;
cout << "Facing: "
<< (robot.facing == robot.FACING_NORTH ? "north" :
robot.facing == robot.FACING_WEST ? "west" :
robot.facing == robot.FACING_SOUTH ? "south" :
robot.facing == robot.FACING_EAST ? "east" : "Unknown direction")
<< endl;
cout << "Pen: " << (robot.penDown ? "down" : "up") << endl;
}
| true |
0b2129c43d626fd22a150094d87383e0773557a0 | C++ | MattFiler/Planned-Obsolescence | /Source/ConfigParsers/MapData.h | UTF-8 | 2,407 | 2.984375 | 3 | [] | no_license | #ifndef PLANNEDOBSOLESCENCE_MAPDATA_H
#define PLANNEDOBSOLESCENCE_MAPDATA_H
#include "../Map/Room.h"
#include "../Sprites/ScaledSpriteArray.h"
#include <Engine/Renderer.h>
#include <vector>
struct MapData
{
// Load config data in
void load(json& passed_map_config)
{
// Select a map set
for (json::iterator maps = passed_map_config.begin(); maps != passed_map_config.end(); ++maps)
{
if (maps.key() != "DEFAULT")
{
available_roomsets.push_back(maps.key());
}
}
std::string map_name =
available_roomsets[static_cast<size_t>(rand() % static_cast<int>(available_roomsets.size()))];
// Debug log our map name
DebugText debug_text;
debug_text.print("LOADING MAP " + map_name);
// Load correct config
FileHandler file_handler;
json map_config = file_handler.loadConfigFromExisting(passed_map_config, map_name);
// Path to sprite
sprite_path = map_config["sprite"];
// Get room count and reserve space
room_count = static_cast<int>(map_config["rooms"].size());
rooms.reserve(static_cast<size_t>(room_count));
room_names.reserve(static_cast<size_t>(room_count));
// Map room dimensions
rooms_x = map_config["rooms_w"];
rooms_y = map_config["rooms_h"];
// Room names
for (int i = 0; i < room_count; i++)
{
room_names.push_back(map_config["rooms"][i]);
}
}
// Set map sprite
void loadMapSprite(ASGE::Renderer* renderer)
{
ASGE::Sprite* map_sprite = renderer->createRawSprite();
map_sprite->loadTexture(sprite_path);
sprite = std::make_shared<ScaledSpriteArray>(1);
sprite->addSprite(*map_sprite);
}
// Resize map sprite
void resizeMap(float width = 0, float height = 0)
{
if (width != 0 && height != 0)
{
map_width = width;
map_height = height;
}
sprite->setWidth(map_width);
sprite->setHeight(map_height);
}
// Map sprite
std::shared_ptr<ScaledSpriteArray> sprite = nullptr;
std::string sprite_path = "";
// Rooms in map
std::vector<Room> rooms;
std::vector<std::string> room_names;
// Map element counts
int room_count = 0;
int tile_count = 0;
// Map room dimensions
int rooms_x = 0;
int rooms_y = 0;
// Map size
float map_width = 0.0f;
float map_height = 0.0f;
private:
std::vector<std::string> available_roomsets;
};
#endif // PLANNEDOBSOLESCENCE_MAPDATA_H
| true |
f089cfc689f0bb3a270e3712ca499933bd482e7e | C++ | bryanibit/mosaic_multi_photos | /mosaic_multi_photos/mosaic.cpp | GB18030 | 6,646 | 2.78125 | 3 | [] | no_license | #include "mosaic.h"
#define SURFMETHOD 0
using namespace std;
using namespace cv;
mosaic::mosaic(){
}
mosaic::~mosaic(){
}
void mosaic::to_homogeneous(const std::vector< cv::Point2f >& non_homogeneous, std::vector< cv::Point3f >& homogeneous)
{
homogeneous.resize(non_homogeneous.size());
for (size_t i = 0; i < non_homogeneous.size(); i++) {
homogeneous[i].x = non_homogeneous[i].x;
homogeneous[i].y = non_homogeneous[i].y;
homogeneous[i].z = 1.0;
}
}
// Convert a vector of homogeneous 2D points to a vector of non-homogenehous 2D points.
void mosaic::from_homogeneous(const std::vector< cv::Point3f >& homogeneous, std::vector< cv::Point2f >& non_homogeneous)
{
non_homogeneous.resize(homogeneous.size());
for (size_t i = 0; i < non_homogeneous.size(); i++) {
non_homogeneous[i].x = homogeneous[i].x / homogeneous[i].z;
non_homogeneous[i].y = homogeneous[i].y / homogeneous[i].z;
}
}
// Transform a vector of 2D non-homogeneous points via an homography.
std::vector<cv::Point2f> mosaic::transform_via_homography(const std::vector<cv::Point2f>& points, const cv::Matx33f& homography)
{
std::vector<cv::Point3f> ph;
to_homogeneous(points, ph);
for (size_t i = 0; i < ph.size(); i++) {
ph[i] = homography*ph[i];
}
std::vector<cv::Point2f> r;
from_homogeneous(ph, r);
return r;
}
// Find the bounding box of a vector of 2D non-homogeneous points.
cv::Rect_<float> mosaic::bounding_box(const std::vector<cv::Point2f>& p)
{
cv::Rect_<float> r;
float x_min = std::min_element(p.begin(), p.end(), [](const cv::Point2f& lhs, const cv::Point2f& rhs) {return lhs.x < rhs.x; })->x;
float x_max = std::max_element(p.begin(), p.end(), [](const cv::Point2f& lhs, const cv::Point2f& rhs) {return lhs.x < rhs.x; })->x;
float y_min = std::min_element(p.begin(), p.end(), [](const cv::Point2f& lhs, const cv::Point2f& rhs) {return lhs.y < rhs.y; })->y;
float y_max = std::max_element(p.begin(), p.end(), [](const cv::Point2f& lhs, const cv::Point2f& rhs) {return lhs.y < rhs.y; })->y;
return cv::Rect_<float>(x_min, y_min, x_max - x_min, y_max - y_min);
}
// Warp the image src into the image dst through the homography H.
// The resulting dst image contains the entire warped image, this
// behaviour is the same of Octave's imperspectivewarp (in the 'image'
// package) behaviour when the argument bbox is equal to 'loose'.
// See http://octave.sourceforge.net/image/function/imperspectivewarp.html
void mosaic::homography_warp(const cv::Mat& src, const cv::Mat& H, cv::Mat& dst)
{
std::vector< cv::Point2f > corners;
corners.push_back(cv::Point2f(0, 0));
corners.push_back(cv::Point2f(src.cols, 0));
corners.push_back(cv::Point2f(0, src.rows));
corners.push_back(cv::Point2f(src.cols, src.rows));
std::vector< cv::Point2f > projected = transform_via_homography(corners, H);
cv::Rect_<float> bb = bounding_box(projected);
translation = (cv::Mat_<double>(3, 3) << 1, 0, -bb.tl().x, 0, 1, -bb.tl().y, 0, 0, 1);
vec_translation.push_back(translation);
cv::warpPerspective(src, dst, translation*H, bb.size());
}
void mosaic::findKeypoint(Mat image_main, Mat image_, Mat & H)
{
//image_mainΪͼ˺صHΪimageתΪijԺӶغ
Mat gray_image1, gray_image2;
if (!image_main.data || !image_.data)
{
std::cout << " --(!) Error reading images " << std::endl; return;
}
// Convert to Grayscale
cvtColor(image_main, gray_image1, CV_RGB2GRAY);
cvtColor(image_, gray_image2, CV_RGB2GRAY);
//-- Step 1: Detect the keypoints using SURF Detector
#if SURFMETHOD
int minHessian = 400;
SurfFeatureDetector detector(minHessian);
cout << "using SURF method" << endl;
#else
SiftFeatureDetector detector;
cout << "using SIFT method" << endl;
#endif
std::vector< KeyPoint > keypoints_object, keypoints_scene;
detector.detect(gray_image2, keypoints_object);
detector.detect(gray_image1, keypoints_scene);
//-- Step 2: Calculate descriptors (feature vectors)
#if SURFMETHOD
SurfDescriptorExtractor extractor;
#else
SiftDescriptorExtractor extractor;
#endif
Mat descriptors_object, descriptors_scene;
extractor.compute(gray_image2, keypoints_object, descriptors_object);
extractor.compute(gray_image1, keypoints_scene, descriptors_scene);
if ((descriptors_object.type() != CV_32F) || (descriptors_object.type() != CV_32F))
{
cout << "descriptors type are not right, I think" << endl;
return;
}
//-- Step 3: Matching descriptor vectors using FLANN matcher
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match(descriptors_object, descriptors_scene, matches);
double max_dist = 0; double min_dist = 100;
//-- Quick calculation of max and min distances between keypoints
for (int i = 0; i < descriptors_object.rows; i++)
{
double dist = matches[i].distance;
if (dist < min_dist) min_dist = dist;
if (dist > max_dist) max_dist = dist;
}
printf("-- Max dist : %f \n", max_dist);
printf("-- Min dist : %f \n", min_dist);
//-- Use only "good" matches (i.e. whose distance is less than 3*min_dist )
std::vector< DMatch > good_matches;
for (int i = 0; i < descriptors_object.rows; i++)
{
if (matches[i].distance < 3 * min_dist)
{
good_matches.push_back(matches[i]);
}
}
std::vector< Point2f > obj;
std::vector< Point2f > scene;
for (int i = 0; i < good_matches.size(); i++)
{
//-- Get the keypoints from the good matches
obj.push_back(keypoints_object[good_matches[i].queryIdx].pt);
scene.push_back(keypoints_scene[good_matches[i].trainIdx].pt);
}
// Find the Homography Matrix
H = findHomography(obj, scene, CV_RANSAC);
// Use the Homography Matrix to warp the images
//cout << H << endl;
}
void mosaic::addImage(Mat & image, Mat & container, int side_cols, int side_rows)
{
//imageΪӱ任ľӵcontainerϣcontainer
Mat container_roi = container(Rect(side_cols, side_rows, image.cols, image.rows));
Mat greyImage, greyContainer;
Mat thresholdImage, thresholdContainer, intersect, mask, maskImage;
cvtColor(image, greyImage, CV_RGB2GRAY);
cvtColor(container_roi, greyContainer, CV_RGB2GRAY);
threshold(greyImage, thresholdImage, 10, 255, THRESH_BINARY);
threshold(greyContainer, thresholdContainer, 10, 255, THRESH_BINARY);
bitwise_and(thresholdImage, thresholdContainer, intersect);
subtract(thresholdImage, intersect, mask);
Mat kernel(3, 3, CV_8UC1);
dilate(mask, mask, kernel);
bitwise_and(image, image, maskImage, mask);
add(container_roi, maskImage, container_roi);
}
| true |
d4aa141032894b254d76a2cf5c20defc5a3d0d28 | C++ | wonsangL/algorithm | /Problem/baekjoon/10987_vowelCount.cpp | UTF-8 | 265 | 3.0625 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
int main() {
int result = 0;
string input;
cin >> input;
for (char word : input)
if (word == 'a' || word == 'i' || word == 'e' || word == 'o' || word == 'u')
result++;
cout << result << endl;
} | true |
b57ba41370b7fcf9a0027685903c52bf80e572b2 | C++ | lucraraujo/CodesFromCollege | /POO/PraticalWork-III/03/graph.cpp | UTF-8 | 2,342 | 3.328125 | 3 | [
"Unlicense"
] | permissive | #include "graph.h"
GraphSingleton::GraphSingleton(int a) : Tamanho(a)
{
ListaDeAdjacencia.resize(a);
Arestas = 0;
}
bool GraphSingleton::insert(const Edge& aresta)
{
int no1 = aresta.GetNode1();
int no2 = aresta.GetNode2();
if (no1 > (Tamanho-1) || no2 > (Tamanho-1))
return false;
if (edge(aresta))
return false;
ListaDeAdjacencia [aresta.GetNode1()].push_back(aresta.GetNode2());
ListaDeAdjacencia [aresta.GetNode1()].sort();
ListaDeAdjacencia [aresta.GetNode2()].push_back(aresta.GetNode1());
ListaDeAdjacencia [aresta.GetNode2()].sort();
++Arestas;
return true;
}
void GraphSingleton::Imprime() const
{
std::list<int>::const_iterator i;
for (int j = 0; j < ListaDeAdjacencia.size(); ++j)
{
std::cout << j << " | ";
for (i = ListaDeAdjacencia[j].begin(); i != ListaDeAdjacencia[j].end(); ++i)
std::cout << *i << " -> ";
std::cout << std::endl;
}
}
bool GraphSingleton::remove(const Edge & aresta)
{
int no1 = aresta.GetNode1();
int no2 = aresta.GetNode2();
if (no1 > (Tamanho-1) || no2 > (Tamanho-1))
return false;
if (!edge(aresta))
return false;
ListaDeAdjacencia[no1].remove(no2);
ListaDeAdjacencia[no2].remove(no1);
--Arestas;
return true;
}
void GraphSingleton::NumArestasVertices() const
{
std::cout << "O grafo tem " << Arestas << " arestas e " << Tamanho << " vertices." << std::endl;
}
bool GraphSingleton::edge(const Edge & aresta)
{
if(std::find(ListaDeAdjacencia[aresta.GetNode1()].begin(),
ListaDeAdjacencia[aresta.GetNode1()].end(), aresta.GetNode2())
!= ListaDeAdjacencia[aresta.GetNode1()].end())
return true;
else
return false;
}
GraphSingleton *GraphSingleton::importar(std::string nomeArquivo)
{
std::ifstream arq;
arq.open(nomeArquivo.c_str());
if (!arq.is_open())
{
std::cerr << "Erro ao abrir o arquivo" << std::endl;
return false;
}
Edge aresta(0,0);
int tamanho, no1, no2;
arq >> tamanho;
GraphSingleton *grafo = GraphSingleton::instance(tamanho);
while (!arq.eof())
{
arq >> no1;
arq >> no2;
aresta.Set(no1, no2);
grafo->insert(aresta);
}
return grafo;
}
GraphSingleton* GraphSingleton::instance(int a)
{
static GraphSingleton *instancePtr = 0;
return instancePtr ? instancePtr : (instancePtr = new GraphSingleton(a));
} | true |
10b254c27ffe259a0ddbc9015b5e428fd51b7c6c | C++ | anand722000/DSA-cpp-Hacktoberfest2021 | /CPP Programs/Cpp/cpp-check-leap-year.cpp | UTF-8 | 194 | 2.5625 | 3 | [
"MIT"
] | permissive | #include<iostream.h>
#include<conio.h>
void main()
{
int y;
cout<<"Enter a year: ";
cin>>y;
if(y%4==0)
{
cout<<"Leap Year";
}
else
{
cout<<"Not a Leap Year";
}
getch();
} | true |
1e8c28f91f6e8d97986404da380434c90ef421a2 | C++ | yuanlinhu/AI_SDL | /Src/BTNode_Move.cpp | UTF-8 | 953 | 2.734375 | 3 | [] | no_license |
#include "BTNode_Move.hpp"
#include "GameObject.hpp"
BTNode_Move::BTNode_Move(GameObject* objParent)
: BTNode(BTNT_LEAF, objParent)
{
}
bool BTNode_Move::check()
{
GameObject* obj = getObjParent();
if (nullptr == obj)
{
return false;
}
if (obj->getCurPos() == obj->GetTargetPos())
{
return false;
}
return true;
}
bool BTNode_Move::run(int delta)
{
GameObject* obj = getObjParent();
if (nullptr == obj)
{
return false;
}
Vector2D& curPos = obj->getCurPos();
Vector2D& targetPos = obj->getTargetPos();
int x_mul = (targetPos.x > curPos.x) ? 1 : -1;
int y_mul = (targetPos.y > curPos.y) ? 1 : -1;
x_mul = (targetPos.x == curPos.x) ? 0 : x_mul;
y_mul = (targetPos.y == curPos.y) ? 0 : y_mul;
float speed = obj->getSpeed();
int xSept = (x_mul * speed * delta) / 1000;
int ySept = (y_mul * speed * delta) / 1000;
int newPosX = curPos.x += xSept;
int newPosY = curPos.y += ySept;
obj->setCurPos(newPosX, newPosY);
} | true |