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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
03971dcbd16f75c68c0c46c3ce820742b6dced7d | C++ | Alexis211/Melon | /Source/Library/Common/IStream.proto.h | UTF-8 | 571 | 2.890625 | 3 | [
"LicenseRef-scancode-public-domain"
] | permissive | #ifndef DEF_ISTREAM_PROTO_h
#define DEF_ISTREAM_PROTO_h
#include <String.class.h>
#include <SimpleList.class.h>
#include <Mutex.class.h>
class IStream : private Mutex {
private:
SimpleList<String> *m_buffer;
int m_ptr;
void operator =(IStream& other);
bool m_eof;
bool populate();
protected:
virtual String read() = 0;
public:
IStream();
IStream(const IStream& other);
virtual ~IStream();
bool eof() const { return m_eof && (m_buffer == NULL); }
WChar getChar();
String get(WChar delimiter = "\n");
String getWord() { return get(" "); }
};
#endif
| true |
3ccd5226c1eff83faddbeff320dfbcc187c1d769 | C++ | SOFTK2765/PS | /BOJ/15815.cpp | UTF-8 | 612 | 2.96875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
char s[101];
stack<int> stk;
int main()
{
int a, b;
char tmp;
scanf("%s", s);
int l = strlen(s);
for(int i=0;i<l;i++)
{
if('0'<=s[i] && s[i]<='9') stk.push(s[i]-'0');
else
{
b = stk.top();
stk.pop();
a = stk.top();
stk.pop();
if(s[i]=='+') stk.push(a+b);
else if(s[i]=='-') stk.push(a-b);
else if(s[i]=='*') stk.push(a*b);
else if(s[i]=='/') stk.push(a/b);
}
}
printf("%d", stk.top());
return 0;
} | true |
0c83c544625ac68db00e1510947932f01fcdbe02 | C++ | shreysingla11/ssl-project | /Backend/Parser/submissions/Assignment 6/53.cpp | UTF-8 | 1,515 | 2.546875 | 3 | [] | no_license | #include<string>
#include<iostream>
using namespace std;
int main(){
string main;
cin>>main;
int l,min_len,min_pos,length_w,i,j,m,a,n,b;
n=main.size();
//cout<<n;
l=1;
min_len=n;
min_pos=n;
a=0;b=0;
for(l=1;l<n;l=2*l){
for(m=0;m+l<n;){
//cout<<"2\n";
for(i=m,j=m+l-1;i<m+l&&j<m+4*l-1;){
//cout<<i;
if(main[i]==main[l+j]){i++;j++;}
else{i=m;j=l+j;}//if(j>3*l-1){break;}}
}
//cout<<i;
if(i==m+l){
//cout<<"abc";
length_w=j-i+1;
//cout<<length_w<<endl;
if(length_w>0){
for(i=m+l;a<length_w&&a<3*l-2;){//cout<<"4\n";
if(main[i]==main[l+j]){i++;j++;a++;}
else if(main[i-length_w]==main[l+j-length_w]){i++;j++;a++;}
else{break;}
}
if(a==length_w){
if(min_pos>(m)){min_pos=m;}//min_pos=i-length_w;}
if(min_len>length_w){min_len=length_w;}
//cout<<"found it!";
}
}
else if(n/2==length_w){
if(min_pos>0){min_pos=0;}
if(min_len>length_w){min_len=length_w;}
//cout<<"found it!";
}
}
//cout<<min_len<<" "<<min_pos<<endl;
a=0;
b=0;
m=l+m;
//cout<<m<<endl;
}
//cout<<l<<endl;
}
if(n==2&&main[0]==main[1]){min_len=1;min_pos=0;}
if(min_pos==n&&min_len==n){cout<<"0 0";}
else{cout<<min_len<<" "<<min_pos;}
return 0;
}
| true |
b20a98e491ce54ae63564734ef347ed771b525b5 | C++ | Atloas/ProjektGrafika3d | /ProjektGrafika3d/Effect.cpp | UTF-8 | 221 | 2.609375 | 3 | [] | no_license | #include "Effect.h"
Effect::Effect(sf::Vector2f position) : GameObject(position)
{
height = 70.0f;
}
Effect::~Effect()
{
}
bool Effect::operator<(Effect * effect)
{
return this->getHeight() < effect->getHeight();
}
| true |
65eae1fe19dc24875525aa4b240eb822b7467586 | C++ | ShadowArkitecht/sparky-game-engine | /include/sparky/rendering/directionalshader.hpp | UTF-8 | 4,233 | 2.609375 | 3 | [] | no_license | ///////////////////////////////////////////////////////////////////////////////////////////////////
//
// Sparky Engine
// 2016 - Benjamin Carter (benjamin.mark.carter@hotmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgement
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef __SPARKY_BASIC_SHADER_HPP__
#define __SPARKY_BASIC_SHADER_HPP__
/*
====================
Class Includes
====================
*/
#include <sparky\rendering\ishader.hpp> // Basic Shader is a type of shader.
namespace sparky
{
/*
====================
Sparky Forward Declarations
====================
*/
class DirectionalLight;
class DirectionalShader final : public IShaderComponent
{
private:
/*
====================
Member Variables
====================
*/
DirectionalLight* m_pLight; ///< The directional light of the shader.
public:
/*
====================
Ctor and Dtor
====================
*/
////////////////////////////////////////////////////////////
/// \brief Default construction of the Directional Shader object.
///
/// The Directional Shader inherits from the behaviour of the IShaderComponent
/// object, loads and compiles the basic vertex and fragment
/// shaders for use.
///
////////////////////////////////////////////////////////////
explicit DirectionalShader(void);
////////////////////////////////////////////////////////////
/// \brief Default destruction of the Directional Shader object.
////////////////////////////////////////////////////////////
~DirectionalShader(void) = default;
/*
====================
Methods
====================
*/
////////////////////////////////////////////////////////////
/// \brief Sets the directional light to render with the current
/// shader object.
///
/// \param pLight The directional light of the shader.
///
////////////////////////////////////////////////////////////
void setActiveLight(DirectionalLight* pLight);
////////////////////////////////////////////////////////////
/// \brief Updates the Uniform values of the Basic Shader.
///
/// The directional shader will bind the textures generated by
/// the deferred pipeline and apply a directional light effect to
/// the objects.
///
/// \param transform The transform of the current object being rendered.
///
////////////////////////////////////////////////////////////
void update(const Transform& transform) override;
};
}//namespace sparky
#endif//__SPARKY_BASIC_SHADER_HPP__
////////////////////////////////////////////////////////////
/// \class sparky::DirectionalShader
/// \ingroup rendering
///
/// sparky::DirectionalShader is one of the lighting specific shaders
/// used within the application. It is responsible for calculation the
/// effect that a directional light will have on the geometry within a
/// scene. It is used in conjunction with the PointShader for multi-pass
/// lighting.
///
/// Usage example:
/// \code
/// // Get a shader from the resource manager.
/// sparky::DirectionalShader pShader = sparky::ResourceManager::getInstance().getShader<sparky::DirectionalShader>("direction");
///
/// // Create a transform.
/// sparky::Transform t;
/// t.setPosition(0.0f, 0.0f, 5.0f);
///
/// // Pass the transform to the shader.
/// pShader->update(t);
/// \endcode
///
//////////////////////////////////////////////////////////// | true |
c14ca837c10da366e61db642db822a7500bbc965 | C++ | donghee11/Algorithm_Solve | /c++/15686.cpp | UTF-8 | 1,970 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int N, M;
int arr[51][51];
int visit[51][51];
vector <pair<int, int> > v; //치킨위치 넣어져있는 함수
int answer=100000; //최종답
//치킨거리 계산 함수
void calculate()
{
int finaldist = 0;
for(int i=1; i<=N; i++)
for (int j = 1; j <= N; j++)
{
int dist = 1000;
if (arr[i][j] == 1) //집이면
{
for (int k = 0; k < v.size(); k++)
{
int r = v[k].first;
int c = v[k].second;
cout << "r c 값은 : " << r << " " << c<<endl;
dist = min(abs(r - i) + abs(c - j),dist); //그 집에서 치킨 거리 구했음
}
cout << "dist finaldist " << dist << " " << finaldist << endl;
finaldist += dist;
}
}
answer = min(answer, finaldist);
}
void pickup(int x, int y, int n, int now) //now는 현재 뽑은갯수
{
//n개를 pick 한다
if (now == n) //뽑은 갯수가 n이랑 같으면
{
calculate();
return;
}
//뽑은갯수가 n 이하
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
if (arr[i][j] == 2 && visit[i][j]==0) //치킨집이면서 방문하지않은곳
{
v.push_back(make_pair(i, j)); //해당 치킨집 벡터에넣기
visit[i][j] = 1;
pickup(i, j, n, now + 1);
visit[i][j] = 0;
v.pop_back();
}
}
}
}
int main(void)
{
cin >> N >> M;
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
cin >> arr[i][j];
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
if (arr[i][j] == 2) //치킨집이면
{
for (int k = 1; k <= M; k++)
{
//여기서 (i,j)랑 가능한 조합 다 생성ㅎㅏ기 -> visit다시 0으로 바꿀필요 x
visit[i][j] = 1; //해당 치킨집 방문처리
v.push_back(make_pair(i, j));
pickup(i, j, k, 1); //1개, 2개, 3개,,,,,M개 까지 check
v.clear();
//visit[i][j] = 0;
}
}
}
}
cout << answer << endl;
return 0;
}
| true |
c20d980b199528e73451d866a95b42f838ab0fdb | C++ | ancues02/Redes_P2 | /P2.2/serializacion/ejercicio2.cc | UTF-8 | 2,468 | 3.25 | 3 | [] | no_license | #include "Serializable.h"
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
//el comando od representa en octal por defecto el archivo
//
class Jugador: public Serializable
{
public:
Jugador(const char * _n, int16_t _x, int16_t _y):x(_x),y(_y)
{
strncpy(name, _n, MAX_NAME);
};
virtual ~Jugador(){};
void to_bin()
{
int32_t data_size=MAX_NAME * sizeof(char) + 2 * sizeof(int16_t);
alloc_data(data_size);
char* tmp = _data;
memcpy(tmp, name, MAX_NAME*sizeof(char));
tmp+=MAX_NAME * sizeof(char);
memcpy(tmp, &x, sizeof(int16_t));
tmp+=sizeof(int16_t);
memcpy(tmp, &y, sizeof(int16_t));
}
int from_bin(char * data)
{
char* tmp = data;
memcpy(name, tmp, MAX_NAME*sizeof(char));
tmp+=MAX_NAME * sizeof(char);
memcpy(&x, tmp, sizeof(int16_t));
tmp+=sizeof(int16_t);
memcpy(&y, tmp, sizeof(int16_t));
return 0;
}
public:
static const size_t MAX_NAME = 20;
char name[MAX_NAME];
int16_t x;
int16_t y;
};
int main(int argc, char **argv)
{
Jugador one_r("", 0, 0);
Jugador one_w("Player_ONE", 123, 987);
int fd = open("./data_jugador", O_CREAT | O_TRUNC | O_RDWR, 0666);//se consigue el fichero
if(fd == -1 ){
std::cerr << "[open]: error en open del archivo ./data_jugador\n";
return -1;
}
one_w.to_bin();//se serializa
//write(fd, one_w.data(),one_w.size());
if( write(fd, one_w.data(),one_w.size()) == -1){//guardar en el archivo
std::cerr << "[write]: error en write\n";
return -1;
}
if(close(fd) == -1){
std::cerr << "[close]: error al cerrar el archivo \n";
return -1;
}
fd = open("./data_jugador", O_RDONLY, 0444);//se consigue el fichero
if(fd == -1 ){
std::cerr << "[open]: error en open del archivo ./data_jugador\n";
return -1;
}
char* data ;
if(read(fd,data,one_w.size()) == -1){
std::cerr << "[read]: error en read\n";
return -1;
}
one_r.from_bin(data);
std::cout << "Jugador des-serializado: name = " << one_r.name <<
" pos x: "<< one_r.x << " pos y: " << one_r.y <<"\n";
if(close(fd) == -1){
std::cerr << "[close]: error al cerrar el archivo \n";
return -1;
}
return 0;
}
| true |
a9aefdc159237d8539e99cec11f09e258a7b0599 | C++ | DragonJoker/ShaderWriter | /include/ShaderAST/Stmt/StmtInOutVariableDecl.hpp | UTF-8 | 1,907 | 2.765625 | 3 | [
"MIT"
] | permissive | /*
See LICENSE file in root folder
*/
#ifndef ___AST_StmtInOutVariableDecl_H___
#define ___AST_StmtInOutVariableDecl_H___
#pragma once
#include "Stmt.hpp"
namespace ast::stmt
{
class InOutVariableDecl
: public Stmt
{
public:
SDAST_API InOutVariableDecl( var::VariablePtr variable
, uint32_t location
, uint32_t streamIndex
, uint32_t blendIndex );
SDAST_API void accept( VisitorPtr vis )override;
inline var::VariablePtr getVariable()const
{
return m_variable;
}
inline uint32_t getLocation()const
{
return m_location;
}
inline uint32_t getStreamIndex()const
{
return m_streamIndex;
}
inline uint32_t getBlendIndex()const
{
return m_blendIndex;
}
private:
var::VariablePtr m_variable;
uint32_t m_location;
uint32_t m_streamIndex;
uint32_t m_blendIndex;
};
using InOutVariableDeclPtr = std::unique_ptr< InOutVariableDecl >;
inline InOutVariableDeclPtr makeInOutVariableDecl( var::VariablePtr variable
, uint32_t location )
{
return std::make_unique< InOutVariableDecl >( std::move( variable )
, location
, 0u
, 0u );
}
inline InOutVariableDeclPtr makeInOutVariableDecl( var::VariablePtr variable
, uint32_t location
, uint32_t streamIndex
, uint32_t blendIndex )
{
return std::make_unique< InOutVariableDecl >( std::move( variable )
, location
, streamIndex
, blendIndex );
}
inline InOutVariableDeclPtr makeInOutStreamVariableDecl( var::VariablePtr variable
, uint32_t location
, uint32_t streamIndex = 0u )
{
return std::make_unique< InOutVariableDecl >( std::move( variable )
, location
, streamIndex
, 0u );
}
inline InOutVariableDeclPtr makeInOutBlendVariableDecl( var::VariablePtr variable
, uint32_t location
, uint32_t blendIndex = 0u )
{
return std::make_unique< InOutVariableDecl >( std::move( variable )
, location
, 0u
, blendIndex );
}
}
#endif
| true |
52b2a77cf255a265b0d609c9298b2266f41ff327 | C++ | wilzegers/CounterMachine | /CounterMachine/Source/Transformation/TransformationRules.cpp | UTF-8 | 6,180 | 2.515625 | 3 | [] | no_license | #include <algorithm>
#include <vector>
#include "BoostIncludes.h"
#include "Transformation/TransformationRules.h"
#include "Descriptors/Computation.h"
namespace Transformation
{
void Skip(TransformedComputation& comp, std::unique_ptr<Descriptors::Instruction>&& instr)
{
comp.SkipInstruction(std::move(instr));
}
void Set1_Clear(TransformedComputation& comp, std::unique_ptr<Descriptors::Instruction>&& instr)
{
RuleGuard guard{ comp };
auto actual_instr = instr->As<Descriptors::Clear>();
const auto instruction_number = comp.GetInstructions().size();
const auto zero = comp.RequestZeroRegister();
comp.Add(new Descriptors::JumpIfZero{ actual_instr->reg_name, instruction_number + 3 }); // 0
comp.Add(new Descriptors::Decrease{ actual_instr->reg_name }); // 1
comp.Add(new Descriptors::JumpIfZero{ zero, instruction_number + 0 }); // 2
}
void Set1_Copy(TransformedComputation& comp, std::unique_ptr<Descriptors::Instruction>&& instr)
{
RuleGuard guard{ comp };
auto actual_instr = instr->As<Descriptors::Copy>();
const auto zero = comp.RequestZeroRegister();
const auto custom = comp.RequestHelperRegister();
comp.Add(new Descriptors::Clear{ actual_instr->to_register });
const auto algo_start = comp.GetInstructions().size();
comp.Add(new Descriptors::JumpIfZero{ actual_instr->from_register, algo_start + 5 }); // 0
comp.Add(new Descriptors::Decrease{ actual_instr->from_register }); // 1
comp.Add(new Descriptors::Increase{ custom }); // 2
comp.Add(new Descriptors::Increase{ actual_instr->to_register }); // 3
comp.Add(new Descriptors::JumpIfZero{ zero, algo_start }); // 4
comp.Add(new Descriptors::JumpIfZero{ custom, algo_start + 9 }); // 5
comp.Add(new Descriptors::Decrease{ custom }); // 6
comp.Add(new Descriptors::Increase{ actual_instr->from_register }); // 7
comp.Add(new Descriptors::JumpIfZero{ zero, algo_start + 5 }); // 8
}
void Set1_JumpIfEqual(TransformedComputation& comp, std::unique_ptr<Descriptors::Instruction>&& instr)
{
const RuleGuard guard{ comp };
auto actual_instr = instr->As<Descriptors::JumpIfEqual>();
const auto zero = comp.RequestZeroRegister();
const auto custom1 = comp.RequestHelperRegister();
const auto custom2 = comp.RequestHelperRegister();
comp.Add(new Descriptors::Copy{ actual_instr->register_a, custom1 });
comp.Add(new Descriptors::Copy{ actual_instr->register_b, custom2 });
const auto algo_start = comp.GetInstructions().size();
comp.Add(new Descriptors::JumpIfZero{ custom1, algo_start + 5 }); // 0
comp.Add(new Descriptors::JumpIfZero{ custom2, algo_start + 6 }); // 1
comp.Add(new Descriptors::Decrease{ custom1 }); // 2
comp.Add(new Descriptors::Decrease{ custom2 }); // 3
comp.Add(new Descriptors::JumpIfZero{ zero, algo_start }); // 4
comp.AddOuterJump(new Descriptors::JumpIfZero{ custom2, actual_instr->jump_destination }); // 5
comp.Add(new Descriptors::Clear{ custom1 }); // 6
comp.Add(new Descriptors::Clear{ custom2 }); // 7
}
void Set2_Decrease(TransformedComputation& comp, std::unique_ptr<Descriptors::Instruction>&& instr)
{
RuleGuard guard{ comp };
auto actual_instr = instr->As<Descriptors::Decrease>();
auto custom1 = comp.RequestHelperRegister();
auto custom2 = comp.RequestHelperRegister();
const auto algo_start = comp.GetInstructions().size();
comp.Add(new Descriptors::JumpIfEqual{ actual_instr->reg_name, custom1, algo_start + 3 }); // 0
comp.Add(new Descriptors::Increase{ custom1 }); // 1
comp.Add(new Descriptors::JumpIfEqual{ custom1, custom1, algo_start }); // 2
comp.Add(new Descriptors::Clear{ actual_instr->reg_name }); // 3
comp.Add(new Descriptors::Increase{ custom2 }); // 4
comp.Add(new Descriptors::JumpIfEqual{ custom1, custom2, algo_start + 9 }); // 5
comp.Add(new Descriptors::Increase{ custom2 }); // 6
comp.Add(new Descriptors::Increase{ actual_instr->reg_name }); // 7
comp.Add(new Descriptors::JumpIfEqual{ custom1, custom1, algo_start + 5 }); // 8
comp.Add(new Descriptors::Clear{ custom1 }); // 9
comp.Add(new Descriptors::Clear{ custom2 }); //10
}
void Set2_JumpIfZero(TransformedComputation& comp, std::unique_ptr<Descriptors::Instruction>&& instr)
{
RuleGuard guard{ comp };
auto actual_instr = instr->As<Descriptors::JumpIfZero>();
const auto zero = comp.RequestZeroRegister();
comp.AddOuterJump(new Descriptors::JumpIfEqual{ actual_instr->register_name, zero, actual_instr->jump_destination });
}
void Set3_Clear(TransformedComputation& comp, std::unique_ptr<Descriptors::Instruction>&& instr)
{
RuleGuard guard{ comp };
auto actual_instr = instr->As<Descriptors::Clear>();
const auto zero = comp.RequestZeroRegister();
comp.Add(new Descriptors::Copy{ zero, actual_instr->reg_name });
}
} | true |
5b0c8343da55350b6f63a3a53d65fd13706fa738 | C++ | vishalbelsare/XDATA | /textstructure/topic/src/chowtree/ChowLiuTree.h | UTF-8 | 3,297 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | #ifndef CHOWLIUTREE_H_
#define CHOWLIUTREE_H_
#include <map>
#include <limits>
#include <cfloat>
#include <iostream>
#include <fstream>
#include <ctime>
#include "math.h"
#include "InterfaceObservationLikelihood.h"
#include "InterfaceDetectorModel.h"
//#include "InterfacePlaceModel.h"
//const std::string CLTreeFilename = "ChowLiuTree.txt";
class ChowLiuTree : public InterfaceObservationLikelihood
{
public :
// constructor which trains the model using the training_data and saves the model into pCLTreeFilename
ChowLiuTree(std::vector<std::vector<int> >& training_data, std::string pCLTreeFilename);
void Train(std::vector<std::vector<int> >& training_data, std::string pCLTreeFilename);
// constructor which loads the model from pCLTreeFilename
ChowLiuTree(std::string pCLTreeFilename);
~ChowLiuTree();
// returns p(Z_k | L_i) as defined in equations (9)-(14) for the Chow Liu trees, i=location, Z_k=observations
/* double evaluate(std::vector<int>& observations, int location, InterfaceDetectorModel* detectorModel, InterfacePlaceModel* placeModel);
*/
// returns the marginal probability for observing a single attribute p(z_attr = val)
double getMarginalPriorProbability(int attr, int val);
// returns the whole marginal probabilities vector
std::vector<std::vector<double> >& getMarginalPriorProbabilities() { return mMarginalPriorProbability; };
// returns p(Z_k | L_u) for a randomly sampled place L_u with randomly sampled obervations Z_k as needed in equation (17)
// observation = Z_k
double sampleNewPlaceObservation(InterfaceDetectorModel* detectorModel, std::vector<int>& observation);
// returns p(Z_k | L_{avg}) for the average place L_{avg} as needed in equation (16)
double meanFieldNewPlaceObservation(InterfaceDetectorModel* detectorModel, const std::vector<int>& observation);
std::string getMututalInformationFile(void);
void setMututalInformationFile(std::string filename);
private:
std::vector< std::vector<double> > calculateMutualInformation();
void primMaximumSpanningTree(std::vector< std::vector<double> > mutualInf);
// after calculating the first order dependencies this function calculates the generative model from the training data
void generateChowLiuProbabilities();
// saves the Chow Liu Tree model
void saveModel(std::string pCLTreeFilename);
// loads the Chow Liu Tree model from file
void loadModel(std::string filename);
//the training data in the form [image[histogram of image]] = [sample][attribute]
std::vector<std::vector<int> > mTrainingData;
//discrete attribute sizes
std::vector<int> mAttributeSizes;
// mParentIndex[i] = the index of the parent attribute to atrribute i
std::vector<int> mParentIndex;
// stores the ChowLiu approximation probabilities mProbabilityModel[attr][a][b] stands for p( attr=a | parent(attr)=b )
std::vector<std::vector<std::vector<double> > > mProbabilityModel;
// stores the marginal probability for observing a single attribute p(z_attr = val) as mMarginalPriorProbability[attr][val]
std::vector<std::vector<double> > mMarginalPriorProbability;
// stores the order in which attributes can be sampled (i.e. when the parent is known)
std::vector<int> mSamplingOrder;
std::string mMutualInformationFile;
};
#endif /* CHOWLIUTREE_H_ */
| true |
981dc06f7af19eb1a08718c3e0219b84d2aaf711 | C++ | gcem/pathtracer | /src/AccelerationStructures/BoundingBox.hpp | UTF-8 | 2,730 | 3.265625 | 3 | [] | no_license | /**
* @file BoundingBox.hpp
* @author Cem Gundogdu
* @brief
* @version 1.0
* @date 2021-04-18
*
* @copyright Copyright (c) 2021
*
*/
#pragma once
#include "BruteForce.hpp"
namespace AccelerationStructures {
/**
* @brief Checks intersection with a bounding box before doing brute-force
* search
*
* Creates an axis-aligned bounding box. Triangles are tested one by one, only
* for rays that hit the bounding box.
*
*/
class BoundingBox : public BruteForce
{
public:
/**
* @brief Finds the closest intersection in front of the ray
*
* Finds the closest intersection with a triangle. If found, returns the t
* value at intersection and sets normalOut.
*
* @param ray Ray to test intersection with
* @param normalOut If return value is not -1, set to the surface normal at
* intersection point
* @return If there was no intersection in front of the ray, -1.
* Else, a positive t value such that origin + t * direction is on the
* closest triangle
*/
FloatT intersect(const Objects::Ray& ray,
LinearAlgebra::Vec3& normalOut) const override;
/**
* @brief Builds the acceleration structure from a vector of triangles
*
* @param triangles Triangles in this acceleration structure. The vector
* will be destroyed by this function. Use std::move to convert vector to
* an rvalue. Must be nonempty.
*/
void build(std::vector<Objects::Triangle>&& triangles) override;
protected:
/**
* @brief Checks for intersection with bounding box
*
* @param ray
* @return true Ray enters box in positive direction, or the origin of the
* ray is inside the bounding box
* @return false Ray doesn't hit the box
*/
bool hitsBoundingBox(const Objects::Ray& ray) const;
/**
* @brief Checks for intersection with bounding box
*
* This is for use by derived classes. This class doesn't need the t value.
* Maybe I will need to make this public later.
*
* @param ray
* @return If the ray doesn't hit the box or the box is behind the ray, -1.
* If ray's origin is inside the box, 0. Otherwise t at the entry point to
* the box.
*/
FloatT intersectBoundingBox(const Objects::Ray& ray) const;
/**
* @brief Set the limits of bounding box
*
* @param triangles Triangles that should be inside this bounding box. Must
* be nonempty.
*/
void createBoundingBox(const std::vector<Objects::Triangle>& triangles);
/**
* @name Limits
*
*/
///@{
/**
* @brief Coordinates of the bounding box
*
*/
float xMin, xMax, yMin, yMax, zMin, zMax;
///@}
};
} | true |
fbc73da56c5f1792ba84142142a9c147f8fc1852 | C++ | marco-c/gecko-dev-comments-removed | /third_party/libwebrtc/third_party/abseil-cpp/absl/container/internal/test_instance_tracker.h | UTF-8 | 6,019 | 2.734375 | 3 | [
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive |
#ifndef ABSL_CONTAINER_INTERNAL_TEST_INSTANCE_TRACKER_H_
#define ABSL_CONTAINER_INTERNAL_TEST_INSTANCE_TRACKER_H_
#include <cstdlib>
#include <ostream>
#include "absl/types/compare.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace test_internal {
class BaseCountedInstance {
public:
explicit BaseCountedInstance(int x) : value_(x) {
++num_instances_;
++num_live_instances_;
}
BaseCountedInstance(const BaseCountedInstance& x)
: value_(x.value_), is_live_(x.is_live_) {
++num_instances_;
if (is_live_) ++num_live_instances_;
++num_copies_;
}
BaseCountedInstance(BaseCountedInstance&& x)
: value_(x.value_), is_live_(x.is_live_) {
x.is_live_ = false;
++num_instances_;
++num_moves_;
}
~BaseCountedInstance() {
--num_instances_;
if (is_live_) --num_live_instances_;
}
BaseCountedInstance& operator=(const BaseCountedInstance& x) {
value_ = x.value_;
if (is_live_) --num_live_instances_;
is_live_ = x.is_live_;
if (is_live_) ++num_live_instances_;
++num_copies_;
return *this;
}
BaseCountedInstance& operator=(BaseCountedInstance&& x) {
value_ = x.value_;
if (is_live_) --num_live_instances_;
is_live_ = x.is_live_;
x.is_live_ = false;
++num_moves_;
return *this;
}
bool operator==(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ == x.value_;
}
bool operator!=(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ != x.value_;
}
bool operator<(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ < x.value_;
}
bool operator>(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ > x.value_;
}
bool operator<=(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ <= x.value_;
}
bool operator>=(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ >= x.value_;
}
absl::weak_ordering compare(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ < x.value_
? absl::weak_ordering::less
: value_ == x.value_ ? absl::weak_ordering::equivalent
: absl::weak_ordering::greater;
}
int value() const {
if (!is_live_) std::abort();
return value_;
}
friend std::ostream& operator<<(std::ostream& o,
const BaseCountedInstance& v) {
return o << "[value:" << v.value() << "]";
}
static void SwapImpl(
BaseCountedInstance& lhs,
BaseCountedInstance& rhs) {
using std::swap;
swap(lhs.value_, rhs.value_);
swap(lhs.is_live_, rhs.is_live_);
++BaseCountedInstance::num_swaps_;
}
private:
friend class InstanceTracker;
int value_;
bool is_live_ = true;
static int num_instances_;
static int num_live_instances_;
static int num_moves_;
static int num_copies_;
static int num_swaps_;
static int num_comparisons_;
};
class InstanceTracker {
public:
InstanceTracker()
: start_instances_(BaseCountedInstance::num_instances_),
start_live_instances_(BaseCountedInstance::num_live_instances_) {
ResetCopiesMovesSwaps();
}
~InstanceTracker() {
if (instances() != 0) std::abort();
if (live_instances() != 0) std::abort();
}
int instances() const {
return BaseCountedInstance::num_instances_ - start_instances_;
}
int live_instances() const {
return BaseCountedInstance::num_live_instances_ - start_live_instances_;
}
int moves() const { return BaseCountedInstance::num_moves_ - start_moves_; }
int copies() const {
return BaseCountedInstance::num_copies_ - start_copies_;
}
int swaps() const { return BaseCountedInstance::num_swaps_ - start_swaps_; }
int comparisons() const {
return BaseCountedInstance::num_comparisons_ - start_comparisons_;
}
void ResetCopiesMovesSwaps() {
start_moves_ = BaseCountedInstance::num_moves_;
start_copies_ = BaseCountedInstance::num_copies_;
start_swaps_ = BaseCountedInstance::num_swaps_;
start_comparisons_ = BaseCountedInstance::num_comparisons_;
}
private:
int start_instances_;
int start_live_instances_;
int start_moves_;
int start_copies_;
int start_swaps_;
int start_comparisons_;
};
class CopyableOnlyInstance : public BaseCountedInstance {
public:
explicit CopyableOnlyInstance(int x) : BaseCountedInstance(x) {}
CopyableOnlyInstance(const CopyableOnlyInstance& rhs) = default;
CopyableOnlyInstance& operator=(const CopyableOnlyInstance& rhs) = default;
friend void swap(CopyableOnlyInstance& lhs, CopyableOnlyInstance& rhs) {
BaseCountedInstance::SwapImpl(lhs, rhs);
}
static bool supports_move() { return false; }
};
class CopyableMovableInstance : public BaseCountedInstance {
public:
explicit CopyableMovableInstance(int x) : BaseCountedInstance(x) {}
CopyableMovableInstance(const CopyableMovableInstance& rhs) = default;
CopyableMovableInstance(CopyableMovableInstance&& rhs) = default;
CopyableMovableInstance& operator=(const CopyableMovableInstance& rhs) =
default;
CopyableMovableInstance& operator=(CopyableMovableInstance&& rhs) = default;
friend void swap(CopyableMovableInstance& lhs, CopyableMovableInstance& rhs) {
BaseCountedInstance::SwapImpl(lhs, rhs);
}
static bool supports_move() { return true; }
};
class MovableOnlyInstance : public BaseCountedInstance {
public:
explicit MovableOnlyInstance(int x) : BaseCountedInstance(x) {}
MovableOnlyInstance(MovableOnlyInstance&& other) = default;
MovableOnlyInstance& operator=(MovableOnlyInstance&& other) = default;
friend void swap(MovableOnlyInstance& lhs, MovableOnlyInstance& rhs) {
BaseCountedInstance::SwapImpl(lhs, rhs);
}
static bool supports_move() { return true; }
};
}
ABSL_NAMESPACE_END
}
#endif
| true |
177400bceda405c3e42566e4476efa7f5a367e05 | C++ | apacewi/BudgetApp | /User.cpp | UTF-8 | 561 | 2.875 | 3 | [] | no_license | #include "User.h"
string User::getName(){
return name;
}
string User::getSurname(){
return surname;
}
string User::getLogin(){
return login;
}
string User::getPassword(){
return password;
}
int User::getId(){
return id;
}
void User::setId(int newId){
id = newId;
}
void User::setName(string userName){
name = userName;
}
void User::setSurname(string userSurname){
surname = userSurname;
}
void User::setLogin(string userLogin){
login = userLogin;
}
void User::setPassword(string userPassword){
password = userPassword;
}
| true |
c29e6b20736b579774c44312370283497fdedf66 | C++ | rlodina99/Learn_cpp | /Diverse/42pe342.cpp | UTF-8 | 579 | 2.53125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream f("42pe342.in");
int n;
f >> n;
int arr[n];
for(int i=0;i<n;i++){
f >> arr[i];
}
int nrzerouri=0;
for(int i=0;i<n;i++){
if(arr[i]==0)
nrzerouri++;
}
while(nrzerouri){
for(int i=0;i<n-1;i++){
if(arr[i]==0){
arr[i]=arr[i+1];
arr[i+1]=0;
}
}
nrzerouri--;
}
for(int i=0;i<n;i++){
cout << arr[i] << ' ';
}
return 0;
}
| true |
b3934deaff99955644d3bafed2c50365d0cf12d1 | C++ | una1veritas/Workspace | /classes/otest.h | UTF-8 | 497 | 3.453125 | 3 | [] | no_license | class Object {
public:
long size;
Object() {
size = 4;
}
void test() {
cout << "Ok!\n";
}
virtual void print() {
cout << "Object\n";
}
};
class Integer : public Object {
public:
long value;
Integer(int & i) {
size = sizeof(value);
value = i;
}
Integer(Integer & i) {
size = sizeof(value);
value = i.value;
}
Integer * operator=(Integer * i) {
value = i->value;
return this;
}
void print() {
cout << value;
}
};
| true |
a150753e05f45e1fb974a092f6ab0356d12302b1 | C++ | RobertPeng/RobertTD1 | /Classes/MultiDirTower.cpp | UTF-8 | 2,146 | 2.546875 | 3 | [] | no_license | /*******************************
MultiDirTower.cpp
Robert 2014/09/23
*******************************/
#include "MultiDirTower.h"
#include "GameManager.h"
MultiDirTower::MultiDirTower()
{
}
MultiDirTower::~MultiDirTower()
{
}
bool MultiDirTower::init()
{
if (!TowerBase::init())
{
return false;
}
setScope(60);
setTowerValue(600);
setLethality(0.5);
setRate(3);
tower= Sprite::createWithSpriteFrameName("multiDirTower.png");
this->addChild(tower);
this->schedule(schedule_selector(MultiDirTower::createBullet6), 0.8f);
return true;
}
// Sprite* MultiDirTower::MultiDirTowerBullet()
// {
// Sprite* bullet = Sprite::createWithSpriteFrameName("bullet.png");
// bullet->setPosition(0, tower->getContentSize().height /4 );
// this->addChild(bullet);
//
// return bullet;
// }
Sprite* MultiDirTower::createBullet(std::string bulletTexName)
{
Sprite* bullet = Sprite::createWithSpriteFrameName(bulletTexName);
bullet->setPosition(0, tower->getContentSize().height /4 );
return bullet;
}
void MultiDirTower::createBullet6(float dt)
{
GameManager *instance = GameManager::getInstance();
auto bulletVector = instance->bulletVector;
int dirTotal = 10;
this->checkNearestEnemy();
if(nearestEnemy != NULL && nearestEnemy->getCurrHp() > 0 )
{
for(int i = 0; i < dirTotal; i++)
{
auto currBullet = createBullet("bullet.png");
instance->bulletVector.pushBack(currBullet);
auto moveDuration = getRate();
Point shootVector;
shootVector.x = 1;
shootVector.y = tan( i * 2 * M_PI / dirTotal );
shootVector.normalize();
Point normalizedShootVector;
if( i >= dirTotal / 2 )
{
normalizedShootVector = shootVector;
}else{
normalizedShootVector = -shootVector;
}
auto farthestDistance = Director::getInstance()->getWinSize().width;
Point overshotVector = normalizedShootVector * farthestDistance;
Point offscreenPoint = (currBullet->getPosition() - overshotVector);
currBullet->runAction(Sequence::create(MoveTo::create(moveDuration, offscreenPoint),
CallFuncN::create(CC_CALLBACK_1(MultiDirTower::removeBullet, this)),
NULL));
currBullet = NULL;
}
}
}
| true |
935d68d9e4318081bb247859f86447d4ff10482e | C++ | gaoxiangluke/algorithmsGroupProject | /point.h | UTF-8 | 3,114 | 3.75 | 4 | [] | no_license | #ifndef GROUPPROJECT_POINT_H
#define GROUPPROJECT_POINT_H
#include "SDL_Plotter.h"
class point {
public:
point();
point(int x_coordinate, int y_coordinate);
point(const point& p);
virtual ~point();
void setY(int y);
void setX(int x);
int getX();
int getY();
point& operator=(const point& rhs);
void display(ostream&);
void draw(SDL_Plotter& g);
private:
int x, y;
};
/*
* description: Point object destructor
* return: nothing
* precondition: point object exists
* postcondition: Point object memory is released
*
*/
point::~point(){
}
/*
* description: Point object constructor
* return: nothing
* precondition: nothing
* postcondition: Point object is created
*
*/
point::point()
{
this-> x = 0;
this-> y = 0;
}
/*
* description: Point object constructor w/ parameters
* return: point object
* precondition: nothing
* postcondition: point object is created w/ the given parameters
*
*/
point::point(int x_coordinate, int y_coordinate)
{
this-> x = x_coordinate;
this-> y = y_coordinate;
}
/*
* description: Point object copy constructor
* return: point object
* precondition: a point object exists
* postcondition: Point object is created and is identical to the first point
*
*/
point::point(const point& p)
{
this-> x = p.x;
this-> y = p.y;
}
/*
* description: Sets the y value
* return: nothing
* precondition: point object exists
* postcondition: Y value of the point is set
*
*/
void point::setY(int y_coordinate)
{
this-> y = y_coordinate;
}
/*
* description: Sets the x value
* return: nothing
* precondition: point object exists
* postcondition: X value of the point is set
*
*/
void point::setX(int x_coordinate)
{
this-> x = x_coordinate;
}
/*
* description: Gets the x value
* return: int
* precondition: point object exists
* postcondition: returns the x value of the point
*
*/
int point::getX()
{
return this-> x;
}
/*
* description: Gets the y value
* return: int
* precondition: point object exists
* postcondition: returns the y value of the point
*
*/
int point::getY()
{
return this-> y;
}
/*
* description: Overloaded assignment operator
* return: point&
* precondition: 2 point objects exist
* postcondition: first point object is the same as second point object
*
*/
point& point::operator=(const point& rhs)
{
if (this != &rhs)
{
this-> x = rhs.x;
this-> y = rhs.y;
}
return *this;
}
/*
* description: Displays information about the plot
* return: nothing
* precondition: point object exists
* postcondition: point information is outputted to ostream
*
*/
void point::display(ostream& out)
{
out << "(" << this-> x << ", " << this-> y << ")";
}
/*
* description: Draws the point on the plotter
* return: nothing
* precondition: plotter and point objects exist
* postcondition: Pixel is plotted on plotter
*
*/
void point::draw(SDL_Plotter& g)
{
int R = rand()%256;
int G = rand()%256;
int B = rand()%256;
g.plotPixel(x, y, R, G, B);
}
#endif //GROUPPROJECT_POINT_H
| true |
7a456ce35ced055c0ebfb193dc40e0b36ed10090 | C++ | rizemon/NUS-CS2040C | /Kattis/aaah.cpp | UTF-8 | 253 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(){
string first,second;
cin >> first;
cin >> second;
if(first.size()>=second.size()){
cout<<"go"<<endl;
}else{
cout<<"no"<<endl;
}
return 0;
} | true |
e895fd884e6a0e740db0db92cb8dc1382b4f71e9 | C++ | lrwlf/acmcpp | /first/7_11.cpp | UTF-8 | 1,571 | 2.90625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct Tree
{
int data;
Tree *lchild;
Tree *rchild;
};
int n;
int pre[31], mid[31];
string res = "";
Tree *creatTree(int pre[],int mid[],int n)
{
if(n==0)
return NULL;
Tree *t = (Tree *)malloc(sizeof(Tree));
t->data = pre[0];
int pos;
for(pos = 0; pos<n; pos++)
{
if(pre[0]==mid[pos])
break;
}
t->rchild = creatTree(pre+1,mid,pos);
t->lchild = creatTree(pre+pos+1,mid+pos+1,n-pos-1);
return t;
}
void Trans(Tree *t)
{
Tree *x;
x = t->lchild;
t->lchild = t->rchild;
t->rchild = x;
if (t->rchild)
{
Trans(t->rchild);
}
if (t->lchild)
{
Trans(t->lchild);
}
}
void preOut(Tree *t)
{
queue<Tree*> q;
q.push(t);
while(!q.empty())
{
Tree* temp = q.front();
if(temp->lchild)
q.push(temp->lchild);
if(temp->rchild)
q.push(temp->rchild);
int it = temp->data;
string st = "";
while(it)
{
st+=it%10+'0';
it/=10;
}
reverse(st.begin(), st.end());
res+=st;
res+=' ';
q.pop();
}
}
int main(int argc, char const *argv[])
{
// freopen("./in","r",stdin);
// freopen("./out","w",stdout);`
cin >> n;
for (int i = 0; i < n; ++i)
cin >> mid[i];
for (int i = 0; i < n; ++i)
cin >> pre[i];
Tree *t = creatTree(pre,mid,n);
// Trans(t);
preOut(t);
cout << res.substr(0,res.length()-1);
return 0;
}
| true |
f6b3d965abeec999a7b55734ad91fef1705a8203 | C++ | trymnilsen/Nithris | /Nithris/Nithris/Playboard.cpp | UTF-8 | 2,201 | 3.203125 | 3 | [] | no_license | //PG4400 - INNLEVERING 1 - TRYM NILSEN
#include "Playboard.h"
//initalizes the board and the array
Playboard::Playboard()
{
initalizeBoard();
}
//returns the color of the tile a position
const ETileColor Playboard::colorOfTileAt(int collum, int row )
{
const ETileColor returnColor = boardArray[collum][row];
return returnColor;
}
//sets the color at the pieces position in the playboard array
void Playboard::setPieceAt(int collum,int row, Piece& piece )
{
for(int y=0; y<4; y++)
{
for(int x=0; x<4; x++)
{
if(piece.tileAt(x,y))
boardArray[collum+x][row+y]=piece.PieceColor;
}
}
}
//checks the array for complete lines
short Playboard::checkBoard()
{
short linesRemoved=0;
//look through the lines
for(short y=0; y<PlayboardTilesHeight; ++y)
{
bool fullLine=false;
//for each new line reset the full line
for(short x=0; x<PlayboardTilesWidth; ++x)
{
if(boardArray[x][y]>0)
{
fullLine=true;
}
else
{
//a hole is found/the color is backgroundcolor
//break out of the loop so we dont bug it up by removing a whole line because there was one tile at the end
fullLine=false;
break;
}
}
if(fullLine)
{
//set the fact that a tile has been removed to true;
++linesRemoved;
moveBricksdown(y);
//move the bricks down
}
}
return linesRemoved;
}
//initilialize our board will all background
void Playboard::initalizeBoard()
{
for(int y=0; y<PlayboardTilesHeight; y++)
{
for (int x=0; x<PlayboardTilesWidth; x++)
{
boardArray[x][y]=TC_BACKGROUND;
}
}
}
//move the bricks about the line down one notch.. notice how we start at the bottom and work our way up!
void Playboard::moveBricksdown(short lineToRemove)
{
for(short y=lineToRemove; y>0; --y)
{
for(short x=0; x<PlayboardTilesWidth; ++x)
{
boardArray[x][y]=boardArray[x][y-1];
}
}
}
//check if the is a tile at the top
bool Playboard::checkGameOver()
{
bool gameover=false;
for(short x=0; x<PlayboardTilesWidth; x++)
{
if(boardArray[x][0]>0)
{
//if a tile is found we dont want to continue looking as we only need one to know its game over
gameover=true;
break;
}
else
{
gameover=false;
}
}
return gameover;
}
| true |
4522e7abc15bfb782ad4d2601e8e7aef9006caf6 | C++ | hellocomrade/happycoding | /matrix/rotateMatrix90.cpp | UTF-8 | 3,224 | 3.953125 | 4 | [] | no_license | #include <cassert>
#include <vector>
#include <iostream>
#include <iomanip>
using namespace std;
/*
Given an image represented by an NxN matrix, where each pixel in the image is
4 bytes, write a method to rotate the image by 90 degrees. Can you do this in
place?
1, 2, 3, 4 13, 9, 5, 1
5, 6, 7, 8 ==> 14,10, 6, 2
9,10,11,12 15,11, 7, 3
13,14,15,16 16,12, 8, 4
1, 2, 3, 4, 5 21,16,11, 6, 1
6, 7, 8, 9,10 22,17,12, 7, 2
11,12,13,14,15 ==> 23,18,13, 8, 3
16,17,18,19,20 24,19,14, 9, 4
21,22,23,24,25 25,20,15,10, 5
Obseration:
We are dealing with square here, if we access and swap the elements from outer square to inner square, given N as the length of the rim,
Only N-1 elemetns on each side (4 sides) need to be accessed since there are overlap. Put the A[i][i] on the temp variable, then swap value
from lower left, lower right to lower left, upper right to lower right, upper left to upper right. And then keep this loop from 0 to N-2.
When we are done, start from the inner square. Repeat...
Well, if you ask me this question next time, I probably give you a different index-loop schema. It's really messy...
*/
void rotateMatrixBy90(vector<vector<int> > &A)
{
int rowcount = A.size();
assert(rowcount > 0);
int colcount = A[0].size();
assert(colcount == rowcount);
int tmp = 0;
//remaining marks the number of elements we have to swap from otter to inner
//so, it's like 3, 2 for 4X4, 4, 3 for 5X5, [N-1,N/2]
for (int i = 0, remaining = rowcount - 1; i < remaining; ++i, --remaining)
{
//i is the baseline from upper left, j iterate from i to remaining
//For example 4X4 matrix, i=0 --> j=[0,2]; i=1 --> j=[1,1]
//Actually, is remaining really necessary to build the indexes?
for (int j = i; j < remaining; ++j)
{
tmp = A[i][j];
A[i][j] = A[i + remaining - j][i];
A[i + remaining - j][i] = A[remaining][i + remaining - j];
A[remaining][i + remaining - j] = A[j][remaining];
A[j][remaining] = tmp;
}
}
}
inline void printMatrix(const vector<vector<int> > &A)
{
for (vector<int> v : A)
{
for (int i : v)
cout << std::setw(2) << i << ',';
cout << endl;
}
}
void testRotateMatrixBy90()
{
vector<vector<int> > A1({ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } });
cout << "Given Matrix:" << endl;
printMatrix(A1);
cout << "Rotate 90 degree clockwise:" << endl;
rotateMatrixBy90(A1);
printMatrix(A1);
vector<vector<int> > A2({ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } });
cout << "Given Matrix:" << endl;
printMatrix(A2);
cout << "Rotate 90 degree clockwise:" << endl;
rotateMatrixBy90(A2);
printMatrix(A2);
vector<vector<int> > A3({ { 1, 2 }, { 3, 4 } });
cout << "Given Matrix:" << endl;
printMatrix(A3);
cout << "Rotate 90 degree clockwise:" << endl;
rotateMatrixBy90(A3);
printMatrix(A3);
vector<vector<int> > A4({ { 1 } });
cout << "Given Matrix:" << endl;
printMatrix(A4);
cout << "Rotate 90 degree clockwise:" << endl;
rotateMatrixBy90(A4);
printMatrix(A4);
}
| true |
8bc800cf4d9f858b85f4a65789b5e0e4e4335e44 | C++ | girl-6/C- | /小米 二面/小米 二面/s.cpp | UTF-8 | 400 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
int n;
vector <int> v;
cin >> n;
int flag=0;
if (n < 0)
{
flag = -1;
n *= flag;
}
v.push_back(n%10);
n /= 10;
while (n != 0)
{
v.push_back(n % 10);
n /= 10;
}
if (flag == -1)
cout << '-';
for (int i = 0; i < v.size(); i++)
cout << v[i];
cout << endl;
system("pause");
return 0;
} | true |
981597ee4a93e30fc2477752c83dafbbb2279175 | C++ | pd0220/1DStringSimulation | /main.cpp | UTF-8 | 11,348 | 3.265625 | 3 | [] | no_license | // 1D elastic string simulation (solving the wave equation numerically)
// including useful headers and/or libraries
#include <iostream>
#include <fstream>
#include <math.h>
#include <string>
#include <vector>
// Eigen library for matrices
#include <Eigen/Dense>
// -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
// number of time and space points on the lattice
const int numOfTimeSteps = 10000;
const int numOfSpaceSteps = 200;
// speed of wave [sqrt(tension / linear density)]
const double cWave = 10.;
// starting and ending (x = L) points in space
const double xStart = 0., xStop = 1.;
// starting and ending points in time
const double tStart = 0., tStop = 2.;
// step size for time and space
const double deltaT = (tStop - tStart) / numOfTimeSteps;
const double deltaX = (xStop - xStart) / numOfSpaceSteps;
// characteristic constant for stepping
const double StepperConst = cWave * cWave * deltaT * deltaT / deltaX / deltaX;
// initial conditions --> x0 and y0
const double X0 = xStop / 2;
const double Y0 = 0.01;
// file name
std::string fileName = "data_mixed_beat.txt";
// -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
// setting initial value for beat pattern interference
// hard coded: sum of two normal modes
auto SetInitialValueBeat = [&](Eigen::MatrixXd &mat, int mode1, int mode2)
{
// check matrix dimensions
if (mat.rows() != numOfTimeSteps || mat.cols() != numOfSpaceSteps)
{
std::cout << "ERROR\nGiven matrix dimensions are not appropriate." << std::endl;
std::exit(-1);
}
// set initial value
for (int xIndex{1}; xIndex < numOfSpaceSteps - 1; xIndex++)
{
double x = xIndex * deltaX;
mat(0, xIndex) = Y0 * (std::sin(mode1 * M_PI / (xStop - deltaX) * x) + std::sin(mode2 * M_PI / (xStop - deltaX) * x));
}
// y(x = 0, t) = y(x = L, t) = 0
for (int tIndex{0}; tIndex < numOfTimeSteps; tIndex++)
{
mat(tIndex, 0) = 0.;
mat(tIndex, numOfSpaceSteps - 1) = 0.;
}
};
// -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
// setting initial values for linearity testing
// left, right or both
auto SetInitialValueLinear = [&](Eigen::MatrixXd &mat, std::string detSwitch) {
// check matrix dimensions
if (mat.rows() != numOfTimeSteps || mat.cols() != numOfSpaceSteps)
{
std::cout << "ERROR\nGiven matrix dimensions are not appropriate." << std::endl;
std::exit(-1);
}
// left
if (detSwitch == "left")
{
double inRatio = Y0 / xStop * 3;
for (int xIndex{1}; xIndex < numOfSpaceSteps - 1; xIndex++)
{
double x = xIndex * deltaX;
if (x <= (double)xStop / 3)
{
mat(0, xIndex) = inRatio * x;
}
else
{
mat(0, xIndex) = -inRatio * (x - xStop + deltaX) / 2;
}
}
}
// right
else if (detSwitch == "right")
{
double inRatio = Y0 / xStop * 3 / 2;
for (int xIndex{1}; xIndex < numOfSpaceSteps - 1; xIndex++)
{
double x = xIndex * deltaX;
if (x <= (double)2 / 3 * xStop)
{
mat(0, xIndex) = -inRatio * x;
}
else
{
mat(0, xIndex) = inRatio * (x - xStop + deltaX) * 2;
}
}
}
// both
if (detSwitch == "both")
{
double inRatio = Y0 / xStop * 3 / 2;
// second mode
for (int xIndex{1}; xIndex < numOfSpaceSteps - 1; xIndex++)
{
double x = xIndex * deltaX;
if (x <= (double)xStop / 3)
{
mat(0, xIndex) = inRatio * x;
}
else if (x > (double)xStop / 3 && x <= (double)xStop * 2 / 3)
{
mat(0, xIndex) = -inRatio * (x - (xStop - deltaX) / 2) * 2;
}
else
{
mat(0, xIndex) = inRatio * (x - xStop + deltaX);
}
}
}
// y(x = 0, t) = y(x = L, t) = 0
for (int tIndex{0}; tIndex < numOfTimeSteps; tIndex++)
{
mat(tIndex, 0) = 0.;
mat(tIndex, numOfSpaceSteps - 1) = 0.;
}
};
// -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
// setting initial values (lambda) --> strumming
// X0 must be L / mode
auto SetInitialValueStrum = [&](Eigen::MatrixXd &mat, int mode) {
// check matrix dimensions
if (mat.rows() != numOfTimeSteps || mat.cols() != numOfSpaceSteps)
{
std::cout << "ERROR\nGiven matrix dimensions are not appropriate." << std::endl;
std::exit(-1);
}
// check space coordinate of initial value
if (X0 <= xStart || X0 >= xStop)
{
std::cout << "ERROR\nGive space coordinate is not appropriate." << std::endl;
std::exit(-1);
}
// check mode
if (mode != 1 && mode != 2 && mode != 3)
{
std::cout << "ERROR\nGiven order is not available." << std::endl;
std::exit(-1);
}
double inRatio = Y0 / X0;
// y(x, t = 0) = given value
if (mode == 1)
{
// first mode
for (int xIndex{1}; xIndex < numOfSpaceSteps - 1; xIndex++)
{
double x = xIndex * deltaX;
if (x <= X0)
{
mat(0, xIndex) = inRatio * x;
}
else
{
mat(0, xIndex) = -inRatio * (x - xStop);
}
}
}
else if (mode == 2)
{
// second mode
for (int xIndex{1}; xIndex < numOfSpaceSteps - 1; xIndex++)
{
double x = xIndex * deltaX;
if (x <= X0)
{
mat(0, xIndex) = inRatio * x;
}
else if (x > X0 && x <= 3 * X0)
{
mat(0, xIndex) = -inRatio * (x - xStop / 2);
}
else if (x > 3 * X0)
{
mat(0, xIndex) = inRatio * (x - xStop);
}
}
}
else if (mode == 3)
{
// third mode
for (int xIndex{1}; xIndex < numOfSpaceSteps - 1; xIndex++)
{
double x = xIndex * deltaX;
if (x <= X0)
{
mat(0, xIndex) = inRatio * x;
}
else if (x > X0 && x <= 3 * X0)
{
mat(0, xIndex) = -inRatio * (x - xStop / 3);
}
else if (x > 3 * X0 && x <= 5 * X0)
{
mat(0, xIndex) = inRatio * (x - 2 * xStop / 3);
}
else if (x > 5 * X0)
{
mat(0, xIndex) = -inRatio * (x - xStop);
}
}
}
// y(x = 0, t) = y(x = L, t) = 0
for (int tIndex{0}; tIndex < numOfTimeSteps; tIndex++)
{
mat(tIndex, 0) = 0.;
mat(tIndex, numOfSpaceSteps - 1) = 0.;
}
};
// setting initial values as normal modes
auto SetInitialValue = [&](Eigen::MatrixXd &mat, int mode) {
// check matrix dimensions
if (mat.rows() != numOfTimeSteps || mat.cols() != numOfSpaceSteps)
{
std::cout << "ERROR\nGiven matrix dimensions are not appropriate." << std::endl;
std::exit(-1);
}
// check mode
if (mode != 1 && mode != 2 && mode != 3)
{
std::cout << "ERROR\nGiven order is not available." << std::endl;
std::exit(-1);
}
// set normal mode
for (int xIndex{1}; xIndex < numOfSpaceSteps - 1; xIndex++)
{
double x = xIndex * deltaX;
mat(0, xIndex) = Y0 * std::sin(mode * M_PI / (xStop - deltaX) * x);
}
// y(x = 0, t) = y(x = L, t) = 0
for (int tIndex{0}; tIndex < numOfTimeSteps; tIndex++)
{
mat(tIndex, 0) = 0.;
mat(tIndex, numOfSpaceSteps - 1) = 0.;
}
};
// -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
// taking first step (lambda)
auto FirstStep = [](Eigen::MatrixXd &mat) {
// check matrix dimensions
if (mat.rows() != numOfTimeSteps || mat.cols() != numOfSpaceSteps)
{
std::cout << "ERROR\nGiven matrix dimensions are not appropriate." << std::endl;
std::exit(-1);
}
// initial velocity will be dy(x, t = 0) / dt = f(x) = 0 --> taking first step accordingly
for (int xIndex{1}; xIndex < numOfSpaceSteps - 1; xIndex++)
mat(1, xIndex) = mat(0, xIndex) * (1 - StepperConst) + StepperConst / 2 * (mat(0, xIndex + 1) + mat(0, xIndex - 1));
};
// -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
// taking a single step (from tIndex to tIndex + 1)
auto Step = [](Eigen::MatrixXd &mat, int tIndex) {
// check matrix dimensions
if (mat.rows() != numOfTimeSteps || mat.cols() != numOfSpaceSteps)
{
std::cout << "ERROR\nGiven matrix dimensions are not appropriate." << std::endl;
std::exit(-1);
}
// taking one timestep
for (int xIndex{1}; xIndex < numOfSpaceSteps - 1; xIndex++)
mat(tIndex + 1, xIndex) = 2 * mat(tIndex, xIndex) * (1 - StepperConst) - mat(tIndex - 1, xIndex) + StepperConst * (mat(tIndex, xIndex + 1) + mat(tIndex, xIndex - 1));
};
// -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
// main function
int main(int, char **)
{
// check for stability
if (StepperConst >= 1)
{
std::cout << "WARNING\nStability issues may occur." << std::endl;
std::cout << "StepperConst = " << StepperConst << std::endl;
}
// matrix for y(x, t) values
Eigen::MatrixXd matSolution(numOfTimeSteps, numOfSpaceSteps);
// setting initial values for y(x = 0, t) = y(x = L, t) = 0 and y(x, t = 0)
//SetInitialValue(matSolution, 1);
//SetInitialValueStrum(matSolution, 1);
//SetInitialValueLinear(matSolution, "both");
SetInitialValueBeat(matSolution, 20, 21);
// taking the first step seperately --> estimating y(x, t - dt) from initial condition: dy(x, t = 0) / dt = f(x)
FirstStep(matSolution);
// taking timesteps (rest of the simulation)
for (int tIndex{1}; tIndex < numOfTimeSteps - 1; tIndex++)
{
Step(matSolution, tIndex);
}
// simulation data
std::ofstream data;
data.open("animationData.txt");
for (int tIndex{0}; tIndex < numOfTimeSteps; tIndex++)
{
for (int xIndex{0}; xIndex < numOfSpaceSteps; xIndex++)
{
data << matSolution(tIndex, xIndex) << " ";
}
data << "\n";
}
data.close();
// analysis data
data.open(fileName);
for (int tIndex{0}; tIndex < numOfTimeSteps; tIndex++)
{
for (int xIndex{0}; xIndex < numOfSpaceSteps; xIndex++)
{
data << tIndex * deltaT << " " << xIndex * deltaX << " " << matSolution(tIndex, xIndex) << "\n";
}
}
data.close();
std::cout << deltaX / deltaT << std::endl;
}
| true |
0429c9618bbe29f46098ef55663758a632c9ce72 | C++ | h4hany/yeet-the-leet | /algorithms/Hard/1088.confusing-number-ii.cpp | UTF-8 | 1,355 | 3.390625 | 3 | [] | no_license | /*
* @lc app=leetcode id=1088 lang=cpp
*
* [1088] Confusing Number II
*
* https://leetcode.com/problems/confusing-number-ii/description/
*
* algorithms
* Hard (44.24%)
* Total Accepted: 15.2K
* Total Submissions: 34.4K
* Testcase Example: '20'
*
* We can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9
* are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. When 2, 3,
* 4, 5 and 7 are rotated 180 degrees, they become invalid.
*
* A confusing number is a number that when rotated 180 degrees becomes a
* different number with each digit valid.(Note that the rotated number can be
* greater than the original number.)
*
* Given a positive integer N, return the number of confusing numbers between 1
* and N inclusive.
*
*
*
* Example 1:
*
*
* Input: 20
* Output: 6
* Explanation:
* The confusing numbers are [6,9,10,16,18,19].
* 6 converts to 9.
* 9 converts to 6.
* 10 converts to 01 which is just 1.
* 16 converts to 91.
* 18 converts to 81.
* 19 converts to 61.
*
*
* Example 2:
*
*
* Input: 100
* Output: 19
* Explanation:
* The confusing numbers are
* [6,9,10,16,18,19,60,61,66,68,80,81,86,89,90,91,98,99,100].
*
*
*
*
* Note:
*
*
* 1 <= N <= 10^9
*
*
*/
class Solution {
public:
int confusingNumberII(int N) {
}
};
| true |
df6acd59f1402fb0864f6970cad28156f7027d11 | C++ | ginkgo/AMP-LockFreeSkipList | /pheet/primitives/PerformanceCounter/Time/TimePerformanceCounter.h | UTF-8 | 3,476 | 2.671875 | 3 | [] | no_license | /*
* TimePerformanceCounter.h
*
* Created on: 10.08.2011
* Author(s): Martin Wimmer
* License: Boost Software License 1.0 (BSL1.0)
*/
#ifndef TIMEPERFORMANCECOUNTER_H_
#define TIMEPERFORMANCECOUNTER_H_
#include <stdio.h>
#include <iostream>
#include <chrono>
#include "../../../settings.h"
#include "../../Reducer/Sum/SumReducer.h"
/*
*
*/
namespace pheet {
template <class Pheet, bool> class TimePerformanceCounter;
template <class Pheet>
class TimePerformanceCounter<Pheet, false> {
public:
TimePerformanceCounter();
TimePerformanceCounter(TimePerformanceCounter<Pheet, false> const& other);
~TimePerformanceCounter();
void start_timer();
void stop_timer();
void print(char const* const formatting_string);
static void print_header(char const* const string);
};
template <class Pheet>
inline
TimePerformanceCounter<Pheet, false>::TimePerformanceCounter() {
}
template <class Pheet>
inline
TimePerformanceCounter<Pheet, false>::TimePerformanceCounter(TimePerformanceCounter<Pheet, false> const&) {
}
template <class Pheet>
inline
TimePerformanceCounter<Pheet, false>::~TimePerformanceCounter() {
}
template <class Pheet>
inline
void TimePerformanceCounter<Pheet, false>::start_timer() {
}
template <class Pheet>
inline
void TimePerformanceCounter<Pheet, false>::stop_timer() {
}
template <class Pheet>
inline
void TimePerformanceCounter<Pheet, false>::print(char const* const) {
}
template <class Pheet>
inline
void TimePerformanceCounter<Pheet, false>::print_header(char const* const) {
}
template <class Pheet>
class TimePerformanceCounter<Pheet, true> {
public:
TimePerformanceCounter();
TimePerformanceCounter(TimePerformanceCounter<Pheet, true>& other);
~TimePerformanceCounter();
void start_timer();
void stop_timer();
void print(char const* formatting_string);
static void print_header(char const* const string);
private:
SumReducer<Pheet, double> reducer;
std::chrono::high_resolution_clock::time_point start_time;
#ifdef PHEET_DEBUG_MODE
bool is_active;
#endif
};
template <class Pheet>
inline
TimePerformanceCounter<Pheet, true>::TimePerformanceCounter()
#ifdef PHEET_DEBUG_MODE
: is_active(false)
#endif
{
}
template <class Pheet>
inline
TimePerformanceCounter<Pheet, true>::TimePerformanceCounter(TimePerformanceCounter<Pheet, true>& other)
: reducer(other.reducer)
#ifdef PHEET_DEBUG_MODE
, is_active(false)
#endif
{
}
template <class Pheet>
inline
TimePerformanceCounter<Pheet, true>::~TimePerformanceCounter() {
}
template <class Pheet>
inline
void TimePerformanceCounter<Pheet, true>::start_timer() {
#ifdef PHEET_DEBUG_MODE
pheet_assert(!is_active);
is_active = true;
#endif
start_time = std::chrono::high_resolution_clock::now();
}
template <class Pheet>
inline
void TimePerformanceCounter<Pheet, true>::stop_timer() {
auto stop_time = std::chrono::high_resolution_clock::now();
double time = 1.0e-6 * std::chrono::duration_cast<std::chrono::microseconds>(stop_time - start_time).count();
reducer.add(time);
#ifdef PHEET_DEBUG_MODE
pheet_assert(is_active);
is_active = false;
#endif
}
template <class Pheet>
inline
void TimePerformanceCounter<Pheet, true>::print(char const* const formatting_string) {
#ifdef PHEET_DEBUG_MODE
pheet_assert(!is_active);
#endif
printf(formatting_string, reducer.get_sum());
}
template <class Pheet>
inline
void TimePerformanceCounter<Pheet, true>::print_header(char const* const string) {
std::cout << string;
}
}
#endif /* TIMEPERFORMANCECOUNTER_H_ */
| true |
b4aea894f3db17552e360663126a074d3eece41e | C++ | Tonyyytran/Polynomial1.0 | /polynomial.cpp | UTF-8 | 8,088 | 3.703125 | 4 | [] | no_license | //
// Created by Tony Tran on 11/20/19.
//
#include "polynomial.h"
Polynomial::Polynomial(){
head = new Term;// 0th node is a dummy.
head->next = head;
head->prev = head;
size = 0;
}
Polynomial::Polynomial( const Polynomial &rhs ) {
head = new Term; // create a dummy
head->next = head;
head->prev = head;// then assign rhs to this. *this = rhs;
size = 0;
if ( rhs.isEmpty() )
return;
Term *Current = rhs.head->next;
while( Current != rhs.head) { //stops when reaching header because circularly linked
insert(Current->coeff, Current->power);
Current = Current -> next;
}
}
Polynomial::~Polynomial( ) {
clear( ); // delete items starting 1st
delete head; // delete a dummy (at 0th).
}
bool Polynomial::isEmpty( ) const {
return head->next == head;
}
void Polynomial::clear( ) {
while ( !isEmpty( ) ) {
Term *node = head->next; // find the 1st object
remove( node );
}
}
bool Polynomial::remove( Term* pos ) {
Term *deleteNode = pos;
if ( isEmpty()) // list is empty
return false;
deleteNode->prev->next = deleteNode->next;
deleteNode->next->prev = deleteNode->prev;
delete deleteNode; // deallocate
size--;
return true;
}
void Polynomial::removeEmptyCoeff(){
Term *current = head->next;
while ( current->next != head){
if (current->coeff == 0)
remove(current);
current = current->next;
}
}
bool Polynomial::insert(const double newCoefficient, const int power ) {
Term *current = head;// find an indexed object
Term *newPtr = new Term; // allocate space
newPtr->power = power; // fix pointers
newPtr->coeff = newCoefficient;
while(current->next->power > newPtr->power)
current = current->next; // move down the power list
if (newPtr->power == current->next->power) {
remove(current->next);
insert(newCoefficient, power);
}
else {
newPtr->next = current->next;
current->next = newPtr;
newPtr->next->prev = newPtr;
newPtr->prev = current;
}
size++;
return true;
}
bool Polynomial::insertAdd(const double newCoefficient, const int power ) {
Term *current = head;// find an indexed object
Term *newPtr = new Term; // allocate space
newPtr->power = power; // fix pointers
newPtr->coeff = newCoefficient;
while(current->next->power > newPtr->power)
current = current->next; // move down the power list
if (current->next->power == newPtr->power) {
current->next->coeff = current->next->coeff + newPtr->coeff;
}
else {
newPtr->next = current->next;
current->next = newPtr;
newPtr->next->prev = newPtr;
newPtr->prev = current;
size++;
}
return true;
}
bool Polynomial::insertSubtract(const double newCoefficient, const int power) {
Term *current = head;// find an indexed object
Term *newPtr = new Term; // allocate space
newPtr->power = power; // fix pointers
newPtr->coeff = newCoefficient;
while(current->next->power > newPtr->power)
current = current->next; // move down the power list
if (current->next->power == newPtr->power) {
current->next->coeff = current->next->coeff - newPtr->coeff;
}
else {
newPtr->next = current->next;
current->next = newPtr;
newPtr->next->prev = newPtr;
newPtr->prev = current;
size++; // increase size, although subtract it will add extra term
}
return true;
}
void Polynomial::print() const { // print the list
string out;
Term *Current = head->next;
while(Current != head) {
cout << Current->coeff << "x^" << Current->power<<endl;
Current = Current->next;
}
}
int Polynomial::degree() const{ // return the highest degree polynomial
if ( isEmpty()){
return 0;
}
return head->next->power;
}
int Polynomial::degreeLow( ) const{ // return the lowest degree polynomial
Term * Current = head->next;
while(Current->next != head)
Current = Current->next;
return Current->power;
}
double Polynomial::coefficient( const int power ) const{
if ( isEmpty()){
return 0.0;
}
Term *Current = head->next;
while(Current != head) {
if ( Current->power == power)
return Current->coeff;
Current = Current->next;
}
return 0.0;
}
int Polynomial::getSize() const {
return size;
}
bool Polynomial::changeCoefficient( const double newCoefficient, const int power ){
return insert(newCoefficient, power);
}
ostream& operator<<( ostream &output, const Polynomial& p ) {
for(int i = p.degree(); i >= p.degreeLow(); i-- ){
if (p.coefficient(i) != 0){
if ( i != p.degree()) {
if (i == 1)
output << " + " << p.coefficient(i) << "x";
else
output << " + " << p.coefficient(i) << "x^" << i;
}
else{
if (i == 1)
output << p.coefficient(i) << "x";
else
output << p.coefficient(i) << "x^" << i ;
}
}
}
return output;
}
Polynomial Polynomial::operator+( const Polynomial& p )const{
Polynomial temp = *this;
Term *Current = p.head->next;
while( Current != p.head) { //stops when reaching header because circularly linked
temp.insertAdd(Current->coeff, Current->power);
Current = Current -> next;
}
return temp;
}
Polynomial Polynomial::operator-( const Polynomial& p ) const{
Polynomial temp = *this;
Term *Current = p.head->next;
while( Current != p.head) { //stops when reaching header because circularly linked
temp.insertSubtract(Current->coeff, Current->power);
Current = Current -> next;
}
return temp;
}
Polynomial& Polynomial::operator=( const Polynomial& p ){
if ( head == p.head )
return *this;
this->clear();
Term *Current = p.head->next;
while( Current != p.head) { //stops when reaching header because circularly linked
this->insert(Current->coeff, Current->power);
Current = Current -> next;
}
return *this;
}
bool Polynomial::operator==( const Polynomial& p ) const{ // Boolean comparison operators
if (degree() == p.degree() && getSize() == p.getSize()){
Term *current = head->next;
Term *currentP = p.head->next;
while(current != head){
if ( current->coeff != currentP->coeff || current->power != currentP->power)
return false;
current = current->next;
currentP = currentP->next;
}
return true;
}
return false;
}
bool Polynomial::operator!=( const Polynomial& p ) const{ // Boolean comparison operators
if (degree() == p.degree() && getSize() == p.getSize()){
Term *current = head->next;
Term *currentP = p.head->next;
while(current != head){
if ( current->coeff != currentP->coeff || current->power != currentP->power)
return true;
current = current->next;
currentP = currentP->next;
}
return false;
}
return true;
}
Polynomial& Polynomial::operator+=( const Polynomial& p ){
Term *Current = p.head->next;
while( Current != p.head) { //stops when reaching header because circularly linked
insertAdd(Current->coeff, Current->power);
Current = Current -> next;
}
return *this;
}
Polynomial& Polynomial::operator-=( const Polynomial& p ){
Term *Current = p.head->next;
while( Current != p.head) { //stops when reaching header because circularly linked
insertSubtract(Current->coeff, Current->power);
Current = Current -> next;
}
return *this;
} | true |
a8c6671c6b30535274c26f92fc7f2525b7f3cbfd | C++ | tangjz/c0-compiler | /scanner.cpp | UTF-8 | 7,964 | 2.515625 | 3 | [] | no_license | #include "scanner.h"
const char *reserver[] = {"int", "char", "const", "void", "main", "scanf", "printf", "return", "if", "else", "for", "switch", "case", "default", NULL};
const char *pattern = "+-*/=,;:()[]{}";
char buffer[BUF_SIZE];
char ch = ' ', token[TOKEN_MAX] = {}, *tokenTail = token;
unsigned number = 0;
enum SYMBOL symbol = NOTSY;
int lineIndex = 0, columnIndex = 0, columnLimit = 0;
int currentFrontLineIndex = 0, currentFrontColumnIndex = 0;
int lastEndLineIndex = 0, lastEndColumnIndex = 0;
bool tokenOverlong = false;
void getChar() {
if(columnIndex == columnLimit) { // get a new line
if(feof(fin)) {
ch = EOF;
return;
}
++lineIndex;
columnIndex = columnLimit = 0;
for(char tp; !feof(fin) && (tp = fgetc(fin)) != '\n'; buffer[columnLimit++] = tp);
buffer[columnLimit++] = '\n';
if(columnLimit > BUF_SIZE)
addError(1);
#if (defined SCANNER_DEBUG) || (defined SYNTAX_DEBUG) || (defined SEMANTIC_DEBUG)
fprintf(ferr, "Scanner: read a new line %d with %d characters.\n", lineIndex, columnLimit);
#endif
}
// ch = fgetc(fin);
ch = buffer[columnIndex++];
}
void revokeChar(char preChar) {
ungetc(ch, fin);
ch = preChar;
}
void clearToken() {
tokenOverlong = false;
tokenTail = token;
*tokenTail = '\0';
}
void catToken() {
if(tokenTail - token == TOKEN_MAX) {
if(!tokenOverlong) {
tokenOverlong = true;
addWarning(1);
}
} else {
*(tokenTail++) = ch;
*tokenTail = '\0';
}
}
bool isEof() {
return ch == EOF;
}
bool isBlank() {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
}
bool isLetter() {
return ch == '_' || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
bool isDigit() {
return ch >= '0' && ch <= '9';
}
bool isSingleChar() {
return ch == '+' || ch == '-' || ch == '*' || ch == '/' || isLetter() || isDigit();
}
bool isVisible() {
return ch != 34 && ch >= 32 && ch <= 126;
}
int getReserver() {
for(int i = 0; reserver[i] != NULL; ++i)
if(strcmp(token, reserver[i]) == 0)
return INTSY + i;
return 0;
}
unsigned getNumber() {
unsigned val = 0, pre = 0;
for(char *ptr = token; ptr != tokenTail; ++ptr) {
pre = val;
val = (val << 3) + (val << 1) + *ptr - '0';
if(val < pre) { // overflow
addWarning(5);
return UINT_MAX;
}
}
if(val > (unsigned)INT_MAX + 1)
addWarning(5);
return val;
}
void getSymbol() {
lastEndLineIndex = lineIndex;
lastEndColumnIndex = columnIndex;
for(clearToken(); isBlank(); getChar());
currentFrontLineIndex = lineIndex;
currentFrontColumnIndex = columnIndex;
if(isEof()) {
symbol = NOTSY;
} else if(isLetter()) {
while(isLetter() || isDigit()) {
catToken();
getChar();
} // else token is collected
int retVal = getReserver();
symbol = retVal != 0 ? (SYMBOL)retVal : IDSY;
} else if(isDigit()) {
bool hasLetter = false; // support to recognize wrong identifier
while(isDigit() || isLetter()) {
hasLetter |= isLetter();
catToken();
getChar();
} // else number (or wrong identifier) is collected
if(hasLetter) {
addError(27);
symbol = IDSY;
} else {
number = getNumber();
if(token[0] == '0' && token[1] != '\0') {
addWarning(3);
}
symbol = NUMSY;
}
} else if(ch == '\'') {
getChar();
if(isSingleChar()) {
catToken();
getChar();
if(ch != '\'') {
for( ; !isEof() && ch != '\'' && ch != '\n'; getChar());
if(ch == '\'') {
addWarning(2);
} else {
addError(6);
}
}
} else if(ch != '\'') {
catToken();
for( ; !isEof() && ch != '\'' && ch != '\n'; getChar());
if(ch == '\'') {
addError(28);
} else {
addError(6);
}
} else { // ch == '\'' // no character
addError(29);
}
if(ch == '\'' || ch == '\n')
getChar();
symbol = CHSY;
} else if(ch == '\"') {
getChar();
while(isVisible()) {
catToken();
getChar();
}
if(ch != '\"') {
for( ; !isEof() && ch != '\"' && ch != '\n'; getChar())
catToken();
if(ch == '\"') {
addError(30);
} else {
addError(7);
}
}
if(ch == '\"' || ch == '\n')
getChar();
symbol = STRSY;
} else if(ch == '=') {
getChar();
if(ch == '=') {
symbol = EQSY;
getChar();
} else {
symbol = ASSIGNSY;
}
} else if(ch == '!') {
getChar();
if(ch == '=') {
getChar();
} else {
addError(8);
}
symbol = NEQSY;
} else if(ch == '<') {
getChar();
if(ch == '=') {
symbol = LEQSY;
getChar();
} else {
symbol = LESSY;
}
} else if(ch == '>') {
getChar();
if(ch == '=') {
symbol = GEQSY;
getChar();
} else {
symbol = GRESY;
}
} else {
symbol = (SYMBOL)0;
for(int i = 0; pattern[i]; ++i)
if(ch == pattern[i]) {
symbol = (SYMBOL)(PLUSSY + i);
break;
}
if(!symbol && !isEof()) {
symbol = NOTSY;
} else {
getChar();
}
}
}
#ifdef SCANNER_DEBUG
void printSymbol() {
#define OUTPUT_SYMBOL(x) case x: fputs(#x " ", fout); break;
switch(symbol) {
OUTPUT_SYMBOL(EQSY);
OUTPUT_SYMBOL(NEQSY);
OUTPUT_SYMBOL(LESSY);
OUTPUT_SYMBOL(LEQSY);
OUTPUT_SYMBOL(GRESY);
OUTPUT_SYMBOL(GEQSY);
OUTPUT_SYMBOL(PLUSSY);
OUTPUT_SYMBOL(MINUSSY);
OUTPUT_SYMBOL(MULTISY);
OUTPUT_SYMBOL(DIVISY);
OUTPUT_SYMBOL(ASSIGNSY);
OUTPUT_SYMBOL(COMMASY);
OUTPUT_SYMBOL(SEMISY);
OUTPUT_SYMBOL(COLONSY);
OUTPUT_SYMBOL(LPARSY);
OUTPUT_SYMBOL(RPARSY);
OUTPUT_SYMBOL(LBRASY);
OUTPUT_SYMBOL(RBRASY);
OUTPUT_SYMBOL(BEGINSY);
OUTPUT_SYMBOL(ENDSY);
OUTPUT_SYMBOL(IDSY);
OUTPUT_SYMBOL(NUMSY);
OUTPUT_SYMBOL(CHSY);
OUTPUT_SYMBOL(STRSY);
OUTPUT_SYMBOL(INTSY);
OUTPUT_SYMBOL(CHARSY);
OUTPUT_SYMBOL(CONSTSY);
OUTPUT_SYMBOL(VOIDSY);
OUTPUT_SYMBOL(MAINSY);
OUTPUT_SYMBOL(IFSY);
OUTPUT_SYMBOL(ELSESY);
OUTPUT_SYMBOL(SWITCHSY);
OUTPUT_SYMBOL(CASESY);
OUTPUT_SYMBOL(FORSY);
OUTPUT_SYMBOL(DEFAULTSY);
OUTPUT_SYMBOL(READSY);
OUTPUT_SYMBOL(WRITESY);
OUTPUT_SYMBOL(RETURNSY);
default: puts("Unknown symbol detected."); error();
}
if(symbol >= EQSY && symbol <= GEQSY) {
switch(symbol) {
case EQSY: fputc('=', fout); break;
case NEQSY: fputc('!', fout); break;
case LESSY: case LEQSY: fputc('<', fout); break;
case GRESY: case GEQSY: fputc('>', fout); break;
default: ;
}
switch(symbol) {
case EQSY: case NEQSY: case LEQSY: case GEQSY: fputs("=\n", fout); break;
default: fputs("\n", fout);
}
} else if(symbol >= PLUSSY && symbol <= ENDSY) {
fprintf(fout, "%c\n", pattern[symbol - PLUSSY]);
} else if(symbol == IDSY) {
fprintf(fout, "%s\n", token);
} else if(symbol == NUMSY) {
fprintf(fout, "%u\n", number);
} else if(symbol == CHSY) {
fprintf(fout, "\'%c\'\n", token[0]);
} else if(symbol == STRSY) {
fprintf(fout, "\"%s\"\n", token);
} else if(symbol >= INTSY && symbol <= DEFAULTSY) {
fprintf(fout, "%s\n", reserver[symbol - INTSY]);
} else { // not a symbol
fputs("\n", fout);
}
}
#endif
| true |
672ee5e70c6539dd36a35e9ebb3da315e9010846 | C++ | njzhangyifei/oj | /leetcode/PowerOfTwo_cpp/solution.cpp | UTF-8 | 614 | 2.515625 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <queue>
#include <iterator>
#include <numeric>
#include <memory>
#include <set>
#include <map>
#include <bitset>
#include <unordered_map>
#include <cstring>
#include <climits>
#include <iostream>
#include <algorithm>
using namespace std;
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n < 0) {
return false;
}
std::bitset<sizeof(int) * 8> bs(n);
return (bs.count() == 1);
}
};
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
| true |
0d634aa61b4e4e34fc9207cd8a7db9bc4874c550 | C++ | stratoseus1998/axastoi | /askisi2.cpp | UTF-8 | 624 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
main(){
int num;
printf("Give your AFM \n");
num=scanf("%d",&num);
int array[8];
int i=0;
array[i] = num % 10;
array[i+1] = ( num / 10 ) % 10;
array[i+2] = ( num / 100 ) % 10;
array[i+3] = ( num / 1000 ) % 10;
array[i+4] = ( num / 10000 ) % 10;
array[i+5] = ( num / 100000 ) % 10;
array[i+6] = ( num / 1000000 ) % 10;
array[i+7] = ( num / 10000000 ) % 10;
array[i+8] = ( num / 100000000 ) % 10;
int j;
//for(j=0;j<=8;j++){
// printf("%d",array[j-1]);
//}
printf("%d",array[8]);
}
| true |
93ad0987216bf7ebaac16549931e88b391c3f68f | C++ | jcoughlan/new_layout_eyelevel2 | /MZFormSheetController-master/Example/Xcode5 iOS 7 Example/Xcode5Example/Xcode5Example/EyeLevelSource/include/VertexBuffer.h | UTF-8 | 1,113 | 2.71875 | 3 | [
"MIT"
] | permissive | //\=====================================================================================
///
/// @file VertexBuffer.h
/// @author Jamie Stewart
/// @date 9 Oct 2010
///
//\=====================================================================================
#ifndef __VERTEX_BUFFER_H__
#define __VERTEX_BUFFER_H__
#ifdef __cplusplus
#include "Maths.h"
#include <OpenGLES//ES2//gl.h>
#include <OpenGLES//ES2//glext.h>
#include "VertexSource.h"
enum VertexType
{
V_3F_4UC,
V_3F_3F,
V_3F_2F,
V_3F_3F_2F,
V_3F_3F_4F,
V_3F_3F_4F_2F
};
class VertexBuffer
{
public:
VertexBuffer(unsigned int vertexDataSize, unsigned int vertexCount, VertexType vertexType);
~VertexBuffer();
void Fill( void* bufferData );
void* Lock();
void Unlock();
void Bind();
void UnBind();
unsigned int GetVertexDataSize(){ return m_VertexSize;};
unsigned int GetNumVertices() { return m_numVerticies;};
VertexType GetVertexDataType() { return m_VertexType; };
private:
// Vertex and index buffer objects
GLuint m_VBO;
unsigned int m_numVerticies;
unsigned int m_VertexSize;
VertexType m_VertexType;
};
#endif
#endif | true |
72472aff38425f7a21b67653be36499d25751b2f | C++ | Du0ngkylan/C-Cpp | /TKDGTT/Bai Tap/Bai Tap Giua Ky/TL.Nhom05.LamThiHang.TranThiThuHang.VuMinhHang.TranManhHung/Tiểu luận giữa kì/bubbleSort.cpp | UTF-8 | 489 | 2.734375 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
void bubbleSort( int a[], int n){
int i,j,temp;
for(i=2;i<n;i++)
for(j=n;j>=i;j--)
if(a[j-1]>a[j]){
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
for(i=1;i<=n;i++)
printf("%4d",a[i]);
}
int main(){
int a[100],n,i;
printf("Nhap do dai day so: ");
scanf("%d",&n);
for(i=1;i<=n;i++){
printf("Nhap a[%d] = ",i);
scanf("%d",&a[i]);
}
printf("Day sap xep tang dan : \n");
bubbleSort(a,n);
getch();
return 0;
}
| true |
64b5d31468e9965adaf28dd129f5c5147a38bc9e | C++ | vmihaylenko/omim | /generator/filter_interface.hpp | UTF-8 | 462 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
struct OsmElement;
namespace feature
{
class FeatureBuilder;
} // namespace feature
namespace generator
{
// Implementing this interface allows an object to filter OsmElement and FeatureBuilder1 elements.
class FilterInterface
{
public:
virtual ~FilterInterface() = default;
virtual bool IsAccepted(OsmElement const &) { return true; }
virtual bool IsAccepted(feature::FeatureBuilder const &) { return true; }
};
} // namespace generator
| true |
b9e7e77922ce7bf5c10697daba6937752b2f0e1a | C++ | nslo/path-planning-2d | /src/geometry/triangle.cpp | UTF-8 | 3,718 | 3.203125 | 3 | [] | no_license | #include "triangle.hpp"
namespace nslo
{
Triangle::Triangle(std::vector<Vector2> _pts)
{
assert(_pts.size() == 3);
// init default triangle
num_points = _pts.size();
pts = _pts;
drag_point = -1;
radius = get_radius();
centroid = get_centroid();
}
Triangle::~Triangle() {}
void Triangle::draw()
{
// draw the triangle
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_TRIANGLES);
for (size_t i = 0; i < num_points; ++i)
{
glVertex2f(pts[i].x, pts[i].y);
}
glEnd();
// draw the outline
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINE_LOOP);
for (size_t i = 0; i < num_points; ++i)
{
glVertex2f(pts[i].x, pts[i].y);
}
glEnd();
}
bool Triangle::on_down(Vector2 p)
{
last_mouse = p;
// check to see if mouse is on a corner; set drag_point if so
for (size_t i = 0; i < num_points; ++i)
{
if (close_enough(p, pts[i]))
{
drag_point = i;
return true;
}
}
// check to see if mouse is inside triangle
if (point_in_polygon(p))
{
drag_point = -2;
return true;
}
return false;
}
// move the drag_point corner along with the mouse
void Triangle::on_drag(Vector2 p)
{
if (drag_point > -1)
{
pts[drag_point] = p;
}
if (drag_point == -2)
{
for (size_t i = 0; i < num_points; ++i)
{
pts[i].x += (p.x - last_mouse.x);
pts[i].y += (p.y - last_mouse.y);
}
}
last_mouse = p;
radius = get_radius();
centroid = get_centroid();
}
void Triangle::move(double dx, double dy)
{
for (size_t i = 0; i < num_points; ++i)
{
pts[i].x += dx;
pts[i].y += dy;
}
centroid = get_centroid();
}
// TODO: is this the radius or the circumference?
double Triangle::get_radius()
{
double a = distance(pts[0], pts[1]);
double b = distance(pts[1], pts[2]);
double c = distance(pts[2], pts[0]);
double radius = 2 * a * b * c /
std::sqrt((a + b + c) * (-a + b + c) * (a - b + c) * (a + b - c));
return radius;
}
Vector2 Triangle::get_centroid()
{
Vector2 s = pts[0];
Vector2 t = pts[1];
Vector2 u = pts[2];
double cx = (s.x + t.x + u.x) / 3.0;
double cy = (s.y + t.y + u.y) / 3.0;
Vector2 centroid = Vector2(cx, cy);
return centroid;
}
// true if this point is inside triangle described by a, b, and c
bool Triangle::point_in_polygon(Vector2 p)
{
// Compute barycentric coordinates (u, v, w) for
// point p with respect to triangle (a, b, c)
double u, v, w;
Vector2 a = pts[0];
Vector2 b = pts[1];
Vector2 c = pts[2];
Vector2 v0 = Vector2(b.x - a.x, b.y - a.y);
Vector2 v1 = Vector2(c.x - a.x, c.y - a.y);
Vector2 v2 = Vector2(p.x - a.x, p.y - a.y);
double d00 = dot(v0, v0);
double d01 = dot(v0, v1);
double d11 = dot(v1, v1);
double d20 = dot(v2, v0);
double d21 = dot(v2, v1);
double denom = d00 * d11 - d01 * d01;
v = (d11 * d20 - d01 * d21) / denom;
w = (d00 * d21 - d01 * d20) / denom;
u = 1.0f - v - w;
bool u_ok = u >= 0.0 && u <= 1.0;
bool v_ok = v >= 0.0 && v <= 1.0;
bool w_ok = w >= 0.0 && w <= 1.0;
if (u_ok && v_ok && w_ok)
{
return true;
}
else
{
return false;
}
}
// TODO: pass vectors
bool Triangle::edge_polygon_intersect(Vector2 e1, Vector2 e2)
{
for (size_t i = 0; i < num_points; i++)
{
Vector2 p = pts[i];
Vector2 q = pts[(i + 1) % num_points];
if (edge_edge_intersect(e1.x, e1.y, e2.x, e2.y, p.x, p.y, q.x, p.y))
{
return true;
}
}
return false;
}
}
| true |
1f08ce6b064d6e262a5685d6e89c2543af34892c | C++ | cRyanPMcN/batch_launcher | /batch_lancher/batch_lancher/batch_launcher_main.cpp | UTF-8 | 1,367 | 3.28125 | 3 | [] | no_license | /*
File: LaunchTimes_main.cpp
Author: Ryan McNamee
Date Created: Tuesday, 19, September, 2017
Date Updated: Monday, 9, October, 2017
Purpose: Start the program
*/
#include "rm_Launcher.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
using namespace std;
int main(int argc, char* argv[]) {
// Print program info
cout << endl << "launchtimes.exe, by Ryan McNamee, 2017" << endl << endl;
// Only allow 2 arguments
if (argc != 2) {
// Complain
cerr << "Error: Invalid parameter list" << endl
<< "Usage: launchtime.exe [text file]" << endl;
// Abandon
return EXIT_FAILURE;
}
// Create File
wifstream file(argv[1]);
// Check if file could be opened
if (!file) {
// Complain
cerr << "Error: File could not be opened" << endl;
// Abandon
return EXIT_FAILURE;
}
cout << "Parsing File: " << endl;
// Create launcher and parse file
rm::Launcher launcher;
try {
file >> launcher;
}
catch (exception e) { // No exception should be thrown but code may change later
cerr << e.what() << endl;
return EXIT_FAILURE;
}
// File no longer needed
file.close();
// Run processes and output data
cout << endl << "Running Applications: " << endl;
launcher.RunAll();
cout << endl << "Printing Data: " << endl;
wcout << launcher;
cout << endl << "Progrma End." << endl;
// Everything worked
return EXIT_SUCCESS;
} | true |
4c65fe733db14e2746f37681cbe033a87911b17c | C++ | FSWL98/OOP | /Factorizer-lab4-5/headers/exceptions.h | UTF-8 | 316 | 3.109375 | 3 | [] | no_license | #pragma once
#include <exception>
#include <string>
class IOException : public std::exception
{
public:
IOException() = default;
explicit IOException(const std::string& filename)
{
this->filename = filename;
}
const char* what() const throw() override;
private:
std::string filename;
}; | true |
50d03e6fc17874b80b432455f26671c7c3b7d0b2 | C++ | Growb0y/IncomeAndChargeList | /table.cpp | UTF-8 | 383 | 2.828125 | 3 | [] | no_license | #include "table.h"
Table::Table(){}
Table::Table(QList <TableEntry> en_)
: entries(en_){}
Table::~Table(){}
void Table::addItem(TableEntry en_){
entries.push_back(en_);
}
void Table::deleteItem(int i){
entries.removeAt(i);
}
TableEntry Table::getItem(int i){
return entries[i];
}
int Table::amountItem(){
return entries.length();
}
| true |
75e0acab7b0b2d77bb085a333f234113db687b0e | C++ | XutongLi/Leetcode-Solution | /386. Lexicographical Numbers/solution_1.cpp | UTF-8 | 508 | 2.75 | 3 | [] | no_license | class Solution {
private:
void dfs(int num, int n, vector<int> &res) {
for (int k = 0; k <= 9; ++ k) {
if (k > n)
return;
int cur = num * 10 + k;
if (cur > n)
continue;
if (cur != 0) {
res.push_back(cur);
dfs(cur, n, res);
}
}
}
public:
vector<int> lexicalOrder(int n) {
vector<int> res;
dfs(0, n, res);
return res;
}
};
//dfs | true |
ab139929b5be2110429db1c711b21d7bed2c7365 | C++ | DerNerger/CppProjects | /cppLearn/IO/Read.cpp | UTF-8 | 362 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
int main(void){
//lesen aus datei
ifstream ifs;
ifs.open("output.txt");
if(ifs){
string line;
while(!ifs.eof()){
ifs >> line;
cout << line << endl;
}
}
else {
cout << "Datei konnte nicht gelesen werden" << endl;
}
}
| true |
6f0b4d6903307b0a07e39ca4cc6d36480da52236 | C++ | llwwlql/Dictionary | /代码库/Dev c++/2059龟兔赛跑(1).cpp | UTF-8 | 647 | 2.5625 | 3 | [] | no_license | #include <stdio.h>
double dp[105];
int main()
{
int n,c,t,l;
int vr,v1,v2;
int i,j;
int a[105];
while(~scanf("%d",&l))
{
scanf("%d %d %d",&n,&c,&t);
scanf("%d %d %d",&vr,&v1,&v2);
for(i=1;i<=n;i++)
scanf("%d",a+i);
a[0]=0;
a[n+1]=l;
dp[0]=.0;
for(i=1;i<=n+1;i++)
{
dp[i]=1000000.0;
for(j=0;j<i;j++)
{
int len=a[i]-a[j];
double temp= len>=c? c*1.0/v1+(len-c)*1.0/v2 : len*1.0/v1;
if(j)
temp+=t;
if(dp[i]>dp[j]+temp)
dp[i]=dp[j]+temp;
}
}
double rabbit=l*1.0/vr;
if(rabbit<dp[n+1])
printf("Good job,rabbit!\n");
else
printf("What a pity rabbit!\n");
}
return 0;
}
| true |
58218896e88a21dc5cf53bd7ea9a5d7214ddabaa | C++ | void-productions/arrows | /cpp/src/entity/bullets/SimpleArrow.hpp | UTF-8 | 591 | 2.53125 | 3 | [] | no_license | #ifndef __SIMPLEARROW_CLASS__
#define __SIMPLEARROW_CLASS__
class Mob;
class GameRect;
#include <entity/Bullet.hpp>
class SimpleArrow : public Bullet
{
public:
SimpleArrow(const GameVector& pos, const GameVector& speed, Mob* owner);
SimpleArrow(CompressBuffer*);
CompressID getCompressID() const override;
virtual void tick() override;
virtual float getCollisionPriority(Entity*) const;
virtual std::string toString() const;
virtual float getMass() const;
virtual sf::Texture* getTexture() const;
virtual CollisionType getCollisionType() const override;
};
#endif
| true |
aa7cbb2775ef298e0e4d02e17ef7754a6379f463 | C++ | hjcho7311/sticky-notes | /KeyActionCreator.cpp | UTF-8 | 5,389 | 2.65625 | 3 | [] | no_license | //KeyActionCreator.cpp
#include "KeyActionCreator.h"
#include "LeftArrowKey.h"
#include "UpArrowKey.h"
#include "DownArrowKey.h"
#include "RightArrowKey.h"
#include "CtrlLeftArrowKey.h"
#include "CtrlRightArrowKey.h"
#include "CtrlCKey.h"
#include "CtrlVKey.h"
#include "CtrlXKey.h"
#include "ShiftLeftArrowKey.h"
#include "ShiftRightArrowKey.h"
#include "ShiftUpArrowKey.h"
#include "ShiftDownArrowKey.h"
#include "ShiftHomeKey.h"
#include "ShiftEndKey.h"
#include "ShiftCtrlHomeKey.h"
#include "ShiftCtrlEndKey.h"
//#include "CtrlShiftLeftArrowKey.h"
//#include "CtrlShiftRightArrowKey.h"
#include "TabKey.h"
#include "ReturnKey.h"
#include "BackspaceKey.h"
#include "DeleteKey.h"
#include "HomeKey.h"
#include "EndKey.h"
#include "CtrlHomeKey.h"
#include "CtrlEndKey.h"
KeyActionCreator::KeyActionCreator() {
}
KeyActionCreator::KeyActionCreator(const KeyActionCreator& source) {
}
KeyActionCreator::~KeyActionCreator() {
}
KeyActionCreator& KeyActionCreator::operator=(const KeyActionCreator& source) {
return *this;
}
KeyAction* KeyActionCreator::Create(Form *form, UINT nChar, UINT nRepCnt, UINT nFlags) {
if (nChar == VK_LEFT && GetKeyState(VK_CONTROL) < 0) {
return new CtrlLeftArrowKey(form);
}
else if (nChar == VK_RIGHT && GetKeyState(VK_CONTROL) < 0) {
return new CtrlRightArrowKey(form);
}
else if ((nChar == 'C'|| nChar == 'c') && GetKeyState(VK_CONTROL) < 0) {
return new CtrlCKey(form);
}
else if ((nChar == 'V' || nChar == 'v') && GetKeyState(VK_CONTROL) < 0) {
return new CtrlVKey(form);
}
else if ((nChar == 'X' || nChar == 'x') && GetKeyState(VK_CONTROL) < 0) {
return new CtrlXKey(form);
}
else if (nChar == VK_HOME && GetKeyState(VK_SHIFT) < 0 && GetKeyState(VK_CONTROL) < 0) {
return new ShiftCtrlHomeKey(form);
}
else if (nChar == VK_END && GetKeyState(VK_SHIFT) < 0 && GetKeyState(VK_CONTROL) < 0) {//todo
return new ShiftCtrlEndKey(form);
}
else if (nChar == VK_HOME && GetKeyState(VK_CONTROL) < 0) {
return new CtrlHomeKey(form);
}
else if (nChar == VK_END && GetKeyState(VK_CONTROL) < 0) {
return new CtrlEndKey(form);
}
else if (nChar == VK_LEFT && GetKeyState(VK_SHIFT) < 0) {
return new ShiftLeftArrowKey(form);
}
else if (nChar == VK_RIGHT && GetKeyState(VK_SHIFT) < 0) {
return new ShiftRightArrowKey(form);
}
else if (nChar == VK_UP && GetKeyState(VK_SHIFT) < 0) {
return new ShiftUpArrowKey(form);
}
else if (nChar == VK_DOWN && GetKeyState(VK_SHIFT) < 0) {
return new ShiftDownArrowKey(form);
}
else if (nChar == VK_HOME && GetKeyState(VK_SHIFT) < 0) {
return new ShiftHomeKey(form);
}
else if (nChar == VK_END && GetKeyState(VK_SHIFT) < 0) {
return new ShiftEndKey(form);
}
else if (nChar == VK_END && GetKeyState(VK_SHIFT) < 0) {
return new ShiftEndKey(form);
}
else if (nChar == VK_LEFT) {
return new LeftArrowKey(form);
}
else if (nChar == VK_UP) {
return new UpArrowKey(form);
}
else if (nChar == VK_DOWN) {
return new DownArrowKey(form);
}
else if (nChar == VK_RIGHT) {
return new RightArrowKey(form);
}
else if (nChar == VK_TAB) {
return new TabKey(form);
}
else if (nChar == VK_RETURN) {
return new ReturnKey(form);
}
else if (nChar == VK_BACK) {
return new BackspaceKey(form);
}
else if (nChar == VK_DELETE) {
return new DeleteKey(form);
}
else if (nChar == VK_HOME) {
return new HomeKey(form);
}
else if (nChar == VK_END) {
return new EndKey(form);
}
return 0;
}
//KeyAction* KeyActionCreator::Create(OtherNoteForm *otherNoteForm, UINT nChar, UINT nRepCnt, UINT nFlags) {
//
// if (nChar == VK_LEFT && GetKeyState(VK_CONTROL) < 0) {
// return new CtrlLeftArrowKey(otherNoteForm);
// }
// else if (nChar == VK_RIGHT && GetKeyState(VK_CONTROL) < 0) {
// return new CtrlRightArrowKey(otherNoteForm);
// }
//
// else if (nChar == VK_LEFT && GetKeyState(VK_SHIFT) < 0) {
// return new ShiftLeftArrowKey(otherNoteForm);
// }
// else if (nChar == VK_UP && GetKeyState(VK_SHIFT) < 0) {
// return new ShiftUpArrowKey(otherNoteForm);
// }
// else if (nChar == VK_DOWN && GetKeyState(VK_SHIFT) < 0) {
// return new ShiftDownArrowKey(otherNoteForm);
// }
// else if (nChar == VK_RIGHT && GetKeyState(VK_SHIFT) < 0) {
// return new ShiftRightArrowKey(otherNoteForm);
// }
//
// else if (nChar == VK_HOME && GetKeyState(VK_CONTROL) < 0) {
// return new CtrlHomeKey(otherNoteForm);
// }
// else if (nChar == VK_END && GetKeyState(VK_CONTROL) < 0) {
// return new CtrlEndKey(otherNoteForm);
// }
// else if ((nChar == 'C' || nChar=='c') && GetKeyState(VK_CONTROL) < 0) {
// return new CtrlCKey(otherNoteForm);
// }
// else if ((nChar == 'V' || nChar == 'v') && GetKeyState(VK_CONTROL) < 0) {
// return new CtrlVKey(otherNoteForm);
// }
//
// else if (nChar == VK_LEFT) {
// return new LeftArrowKey(otherNoteForm);
// }
// else if (nChar == VK_UP) {
// return new UpArrowKey(otherNoteForm);
// }
// else if (nChar == VK_DOWN) {
// return new DownArrowKey(otherNoteForm);
// }
// else if (nChar == VK_RIGHT) {
// return new RightArrowKey(otherNoteForm);
// }
//
//
// else if (nChar == VK_TAB) {
// return new TabKey(otherNoteForm);
// }
// else if (nChar == VK_RETURN) {
// return new ReturnKey(otherNoteForm);
// }
// else if (nChar == VK_BACK) {
// if (nChar == VK_BACK) {
// return new BackspaceKey(otherNoteForm);
// }
// else if (nChar == VK_DELETE) {
// return new DeleteKey(otherNoteForm);
// }
//
// return 0;
//} | true |
b08b067602b78eaba3c95d19071126136774bf5a | C++ | ntosta/genetic-tsp | /src/tsp.cpp | UTF-8 | 3,596 | 3.546875 | 4 | [] | no_license | // Nick Tosta
// August 2015
// tsp.cpp
// contains the implementation for functions related to the traveling salesman problem
#include <cmath>
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
#include "tsp.h"
using namespace std;
// Constructor that automatically reads the points from the file
// And automatically populates the distances array
TSP::TSP(string filename) : filename_(filename) {
read_points(filename_);
calculate_distances();
}
// Read the points from a file, store them in the x and y vectors
void TSP::read_points(string filename) {
ifstream file(filename);
string line, xVal, yVal;
cout << "Reading points from: " << filename << endl;
while (getline(file, line)) {
xVal = line.substr(0, line.find_first_of(" "));
yVal = line.substr(line.find_first_of(" "), line.length());
x_.push_back(stof(xVal));
y_.push_back(stof(yVal));
}
num_points_ = x_.size();
if (num_points_ > 0) {
cout << num_points_ << " points read successfully" << endl;
}
else {
cout << "Error - no points were read. Ensure the points file exists in the specified path" << endl
<< "Press any key to exit" << endl;
cin.get();
exit(EXIT_FAILURE);
}
file.close();
}
// Calculate the distance from every point to every other point
// Store the distances in the distances matrix
void TSP::calculate_distances() {
// Fill the distances matrix with "0"s
for (int i = 0; i < num_points_; i++) {
vector<float> row;
for (int j = 0; j < num_points_; j++) {
row.push_back(0);
}
distances_.push_back(row);
}
// For every set of points, calculate the distance
// This just uses the standard distance formula sqrt((x1-x2)^2 + (y1-y2)^2)
for (int i = 0; i < num_points_; i++) {
for (int j = i + 1; j < num_points_; j++) {
float distance = sqrt(pow(x_[i]-x_[j], 2) + pow(y_[i]-y_[j], 2));
distances_[i][j] = distance;
distances_[j][i] = distance;
}
}
}
// Return the length of a tour
float TSP::get_tour_length(const vector<int> &tour) {
float distance = 0;
for (int i = 0; i < num_points_-1; i++) {
distance += distances_[tour[i]][tour[i + 1]];
}
distance += distances_[tour.back()][tour[0]];
return distance;
}
// Generic getter for the number of points in the problem
int TSP::get_num_points() {
return num_points_;
}
// Checks for an intersection between two line segments pA-pB and pC-pD
// This function works by computing the cross product and checking to see if
// each pair of points is on opposite sides of the other segment. This works
// because the segments intersect if and only if:
// ((A and B are on different sides of [CD]) and (C and D are on different sides of [AB])),
// which is checked using the XORs in the return statement.
bool TSP::check_intersection(int pA, int pB, int pC, int pD) {
int cpC = (x_[pB] - x_[pA]) * (y_[pC] - y_[pB]) - (y_[pB] - y_[pA]) * (x_[pC] - x_[pB]);
int cpD = (x_[pB] - x_[pA]) * (y_[pD] - y_[pB]) - (y_[pB] - y_[pA]) * (x_[pD] - x_[pB]);
int cpA = (x_[pD] - x_[pC]) * (y_[pA] - y_[pD]) - (y_[pD] - y_[pC]) * (x_[pA] - x_[pD]);
int cpB = (x_[pD] - x_[pC]) * (y_[pB] - y_[pD]) - (y_[pD] - y_[pC]) * (x_[pB] - x_[pD]);
return ((cpA ^ cpB) < 0) && ((cpC ^ cpD) < 0);
}
// Returns the points in the TSP as a pre-formatted string so that it can be written directly
// to an output file
string TSP::get_points_as_string() {
string pointString;
for (int i = 0; i < num_points_; i++) {
pointString += to_string((int)x_[i]);
pointString += " ";
pointString += to_string((int)y_[i]);
pointString += "\n";
}
return pointString;
} | true |
4e994df4967ff9bd09e66740b989dd0324f6d17f | C++ | kiyoony/donga-university | /p10205.cpp | UTF-8 | 1,339 | 2.96875 | 3 | [] | no_license | #include <stdio.h>
char suit[4][10] = { "Clubs", "Diamonds","Hearts","Spades" };
char value[13][10] = { "2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace" };
int get(char *x)
{
int sum = 0;
for (int i = 0; i<3; i++)
{
if (x[i] >= '0' && x[i] <= '9') {
if (sum)
sum = sum * 10;
sum += x[i] - '0';
}
}
return sum;
}
int main()
{
FILE *inp = fopen("p10205.inp", "r");
FILE *out = fopen("p10205.out", "w");
int testcase;
int iCount = 0;
fscanf(inp, "%d", &testcase);
for (iCount = 0; iCount < testcase; iCount++)
{
int n;
int pos[101][53];
int cur[2][53];
char Text[5];
int type;
if (iCount)fprintf(out, "\n");
fscanf(inp, "%d", &n);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= 52; j++)
{
fscanf(inp, "%d", &pos[i][j]);
}
}
for (int i = 1; i <= 52; i++)
{
cur[0][i] = cur[1][i] = i;
}
fgets(Text, 4, inp);
char temp;
int i = 0;
while (fgets(Text, 5, inp) && Text[0])
{
type = get(Text);
if (!type)break;
for (int j = 1; j <= 52; j++)
{
cur[i % 2][j] = cur[(i + 1) % 2][pos[type][j]];
}
i++;
}
n = i;
for (int i = 1; i <= 52; i++)
{
int suitN = (cur[(n + 1) % 2][i] - 1) / 13;
int valueN = (cur[(n + 1) % 2][i] - 1) % 13;
fprintf(out, "%s of %s\n", value[valueN], suit[suitN]);
}
}
return 0;
} | true |
389af83743086d00cdff526fec8b39b1114da64f | C++ | Pangolin-hmt/DNU-CNTT08-02 | /vuongcanrong.cpp | UTF-8 | 295 | 2.6875 | 3 | [] | no_license | #include<iostream>
using namespace std;
void main()
{
int d, i, j;
cout << "nhap vao d, r : ";
cin >> d; cin.ignore();
for (j = 1; j <=d; j++)
{
for (i = d; i >=1; i--)
{
if (j == d || j == d - i + 1 || i == d) cout << "* ";
else cout << " ";
}
cout << "\n";
}
cin.get();
} | true |
452fbafd3587f3e6fa865857b99d8bad343d4020 | C++ | nikki93/thesis-2015 | /ds-ovr/scene.cpp | UTF-8 | 1,162 | 2.671875 | 3 | [] | no_license | #include "scene.h"
#include <GL/glew.h>
#include <SDL.h>
void Scene::add_cloud(std::shared_ptr<Cloud> cloud)
{
main_cloud.merge(cloud);
}
void Scene::update(void)
{
// pitch/yaw using mouse
int x, y;
auto state = SDL_GetMouseState(&x, &y);
if (state & SDL_BUTTON_LMASK)
{
m_yaw += 0.3f * (x - m_prev_mouse.x);
m_pitch += 0.3f * (y - m_prev_mouse.y);
}
if (state & SDL_BUTTON_MMASK)
m_dist += 0.05f * (y - m_prev_mouse.y);
m_prev_mouse = vec2(x, y);
}
void Scene::draw(std::shared_ptr<Cloud> cloud)
{
glMatrixMode(GL_MODELVIEW);
// rotate around the scene
glTranslatef(0, 0, -m_dist);
glRotatef(m_pitch, 1, 0, 0);
glRotatef(m_yaw, 0, 1, 0);
glTranslatef(0, 0, 2);
// clouds
main_cloud.draw();
if (cloud)
{
cloud->draw();
if (cloud->has_finger)
{
glLineWidth(2.5);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex3fv(value_ptr(cloud->finger));
auto end = cloud->finger + vec3(0, 0.2, 0);
glVertex3fv(value_ptr(end));
glEnd();
}
}
}
| true |
4c76afca25eb69e64f62bff4bb53a3b38a61ffd0 | C++ | tinchop/tp-taller-1-2018 | /src/client/view/sprite-text.h | UTF-8 | 1,036 | 2.546875 | 3 | [] | no_license | #ifndef SPRITETEXT_H
#define SPRITETEXT_H
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include "sprite-sheet.h"
#include "../../shared/logger.h"
class SpriteText : public SpriteSheet
{
public:
SpriteText(SDL_Renderer* renderer, TTF_Font* fontStyle, std::string text, SDL_Color color) : SpriteSheet (renderer, "")
{
Logger::getInstance()->debug("CREANDO SPRITETEXT para '" + text + "'");
this->renderer = renderer;
// TODO: deberia levantarse desde config.
this->path = "src/client/sprites/" + text;
this->texture = NULL;
this->width = 0;
this->height = 0;
this->LoadFromRenderedText(fontStyle, text, color, false);
};
~SpriteText();
bool LoadFromRenderedText( TTF_Font * font, std::string textureText, SDL_Color textColor, bool wrapped );
protected:
int wrappedLength = 800;
};
#endif // SPRITETEXT_H
| true |
98f39a8a8abf02496b79b16481fa54e52e288d3a | C++ | ZJUCADGeoSim/Hausdorff | /src/mesh/definition.hpp | UTF-8 | 1,189 | 2.671875 | 3 | [
"MIT"
] | permissive | /*
State Key Lab of CAD&CG Zhejiang Unv.
Author:
Yicun Zheng (3130104113@zju.edu.cn)
Haoran Sun (hrsun@zju.edu.cn)
Jin Huang (hj@cad.zju.edu.cn)
Copyright (c) 2004-2021 <Jin Huang>
All rights reserved.
Licensed under the MIT License.
*/
#ifndef _DEFINITION_HPP
#define _DEFINITION_HPP
#include <unordered_map>
#include <utility>
#include "core/common/conf.h"
struct primitive_pair {
std::pair<size_t, size_t> pair_;
primitive_pair(size_t t1, size_t t2) {
if (t1 < t2)
pair_ = std::make_pair(t1, t2);
else
pair_ = std::make_pair(t2, t1);
}
bool operator==(const primitive_pair &other) const {
return (this->pair_.first == other.pair_.first) && (this->pair_.second == other.pair_.second);
}
};
struct primitive_hasher {
std::size_t operator()(const primitive_pair &primitive) const {
return (std::hash<size_t>()(primitive.pair_.first) ^
(std::hash<size_t>()(primitive.pair_.second) << 1));
}
};
struct edge_hasher {
std::size_t operator()(const edge_t &edge) const {
return (std::hash<size_t>()(edge.first)) ^
(std::hash<size_t>()(edge.second) << 1);
}
};
#endif | true |
62d48d587b03f41ed05b5d50e993fa681dd03c6e | C++ | dkdlel/DongA-University | /ProblemSolve/28번(crt)/crt.cpp | UTF-8 | 2,153 | 3 | 3 | [] | no_license | //
// crt.cpp
// ProblemSolve
//
// Created by JeJn on 2020/05/20.
// Copyright © 2020 JeJn. All rights reserved.
//
#include<fstream>
#include<vector>
using namespace std;
ifstream fcin("/Users/jejn/Desktop/ProblemSolve/ProblemSolve/crt.inp");
ofstream fcout("/Users/jejn/Desktop/ProblemSolve/ProblemSolve/crt.out");
typedef long long ll;
struct info{ ll r, m; };// r : 나머지, m : 몫
struct qs{ ll q,s; }; // q : 몫, s : 역원
vector<info> input; // crt의 input
void Init(){
input.clear();
int k; // 식의 정수
fcin >> k;
input.resize(k);
for(int i = 0 ; i < k ; i++){
ll r, m;
fcin >> r >> m;
input[i].r = r; input[i].m = m;
}
}
ll GCD(ll a, ll b) { return b ? GCD(b , a%b) : a;}
qs Extended_Euclid(ll a, ll b){
ll q, r1 = a, r2 = b, r, s1 = 1, s2 = 0, s, t1 = 0, t2 = 1, t;
while(1){
q = r1/r2;
r = r1 - q * r2;
s = s1 - q * s2;
t = t1 - q * t2;
if(r == 0) break;
r1 = r2;
r2 = r;
s1 = s2;
s2 = s;
t1 = t2;
t2 = t;
}
return {r2,s2};
}
void Crt(){
ll ans_r = input[0].r, ans_m = input[0].m;
for(int i = 1 ; i < input.size() ; i++){
ll cur_r = input[i].r, cur_m = input[i].m;
cur_r -= ans_r;
while(cur_r < 0) cur_r += cur_m; // 나머지가 음수가 나올경우 양수로 바꿈
ll gcd = GCD(GCD(ans_m,cur_r),cur_m); // 현재 식에서 최대공약수가 있는지 확인
cur_m /= gcd; cur_r /= gcd;
qs inv = Extended_Euclid(ans_m / gcd, cur_m); // inv : inverse, ans_m이 변하면 안되기 때문에 매개변수로 넘겨줌
if(inv.q != 1){ fcout << "-1\n"; return; }; // 곲의 역원은 1
if(cur_r){ // 현재의 나머지가 자연수 일때 ex) 0(mod n)
cur_r *= inv.s;
cur_r %= cur_m;
while(cur_r < 0) cur_r += cur_m;
}
ans_r += ans_m * cur_r;
ans_m *= cur_m;
}
fcout << ans_r << '\n';
}
int main(){
int testcase;
fcin >> testcase;
while(testcase--){
Init();
Crt();
}
return 0;
}
| true |
774cfba7a87b3d0afcef7c63ce9bdcbbd5891b6e | C++ | elados93/ex05 | /src/server/ThreadPool.h | UTF-8 | 1,192 | 3.125 | 3 | [] | no_license |
// Created by Elad Aharon on 14/01/18.
// ID: 311200786
//
#ifndef EX04_THREADPOOL_H
#define EX04_THREADPOOL_H
#include "Task.h"
#include <queue>
#include <pthread.h>
using namespace std;
class ThreadPool {
public:
/**
* constructor
* @param threadsNum is the number of threads that in the pool
*/
ThreadPool(int threadsNum);
/**
* this function adds tasks to the queue that the pool should excute
* by their turn.
* @param task is the task to add.
*/
void addTask(Task *task);
/**
* this function close all the threads in the pool and delete the mutex.
*/
void terminate();
/**
* distructor
*/
virtual ~ThreadPool();
private:
queue<Task *> tasksQueue;
pthread_t* threads;
/**
* loop all the threads in the pool and checks if there is any task to excute.
*/
void executeTasks();
/**
* signify if there pool should stop executing.
*/
bool stopped;
pthread_mutex_t lock;
/**
* execute a specific task.
* @param arg is the parameters needed to execute the task.
*/
static void *execute(void *arg);
};
#endif //EX04_THREADPOOL_H
| true |
4393c1660f53b20305ffc7a86336a5952918d9d3 | C++ | sachin-bisht/Data-Structures-And-Algorithms-1 | /advanced/segment_tree.cpp | UTF-8 | 1,565 | 2.8125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int tree[3*100000];
void build(int arr[], int node, int st, int en)
{
if(st == en)
{
tree[node] = arr[st];
}
else
{
int mid = (st + en) / 2;
build(arr, 2*node, st, mid);
build(arr, 2*node + 1, mid+1, en);
tree[node] = min(tree[node * 2], tree[node * 2 + 1]);
}
}
int query(int node, int st, int en, int l, int r)
{
if(r < st || l > en)
return INT_MAX;
if(r >= en && l <= st)
return tree[node];
int mid = st + en;
mid /= 2;
return (min(query(2*node, st, mid, l, r), query(2*node + 1, mid + 1, en, l, r)));
}
void update(int node, int st, int en, int ind, int val)
{
if(st == en)
{
tree[node] = val;
}
else
{
int mid = st + en;
mid /= 2;
if(ind >= st && ind <= mid) update(2*node, st, mid, ind, val);
else update(2*node + 1, mid + 1, en, ind, val);
tree[node] = min(tree[2*node], tree[2*node + 1]);
}
}
int main()
{
int n, q;
cin >> n >> q;
int arr[n+2];
for(int i = 1; i <= n; i++) cin >> arr[i];
int x = ceil((double)log2(n));
int last = 2 * pow(2, x) - 1;
for(int i = 0; i <= last; i++) tree[i] = INT_MAX;
build(arr, 1, 1, n);
while(q--)
{
char ch;
int a, b;
cin >> ch >> a >> b;
if(ch == 'q')
{
cout << query(1, 1, n, a, b) << endl;
}
else
{
update(1, 1, n, a, b);
arr[a] = b;
}
}
}
| true |
1cd9bc7e755e2cae679086c781089e6ed0e669dd | C++ | WitoldKaczor/cpp_repo | /ScientificComputing/Chapter02_FlowControl/Chapter02_FlowControl/exercise02.cpp | UTF-8 | 803 | 3.765625 | 4 | [] | no_license | #include <iostream>
//1.Set the variable x to the value 5 if either p is greater than or equal to q, or the
//variable j is not equal to 10.
//2. Set the variable x to the value 5 if both y is greater than or equal to q, and the
//variable j is equal to 20. If this compound condition is not met, set x to take the
//same value as p.
//3. Set the variable x according to the following rule.
//x =
//0, p > q,
//1, p <= q, and j = 10,
//2, otherwise.
int main(int argc, char* argv[])
{
double p = 3.6, q = 5.1, x, y = 18;
int j = 1;
//1.
if (p >= q || j != 10)
x = 5;
//2.
if (y >= q && j == 20)
x = 5;
else
x = p;
//equivalent to 2. with ternary operator
x = (y >= q && j == 20) ? x : p;
//3.
if (p > q)
x = 0;
else if (p <= q && j == 10)
x = 1;
else
x = 2;
return 0;
} | true |
0ac354e82343f212a615b9a04c96a1c8c7dd3a6e | C++ | avakar/cpp2sir | /test/enum.cpp | UTF-8 | 203 | 2.734375 | 3 | [
"MIT"
] | permissive | enum s1 { s1_1, s1_2, s1_3 };
void e1();
void e2(s1);
s1 f1()
{
return s1_2;
}
void f2(s1 a)
{
switch (a)
{
case s1_1:
e1();
break;
default:
e2(a);
}
}
| true |
4517b59503611b5b1c8b34c9aaba9800bdbf8f2f | C++ | Susree/Lab-1 | /problem 4.cpp | UTF-8 | 225 | 3.203125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main ()
{
int l,b,p;
cout << "enter a length"<< endl;
cin >> l;
cout << "enter a breadth"<< endl;
cin >> b;
p=2*(l+b);
cout << "perimeter ="<< p;
return 0;
}
| true |
3b0ae2015dba2720e0e3eb6e32c51540be7e9ab8 | C++ | 1904477/CMP105_W6 | /Week6/CMP105App/Bullet.cpp | UTF-8 | 1,345 | 2.703125 | 3 | [] | no_license | #include "Bullet.h"
Bullet::Bullet()
{
mouseStartPos = sf::Vector2f(0.f, 0.f);
mouseEndPos = sf::Vector2f(0.f, 0.f);
mousedown = false;
activation = false;
bulletScale = 100.f;
gravity = sf::Vector2f(0,9.8)*bulletScale;
fired = false;
}
void Bullet::setTextureBullet()
{
bulletText.loadFromFile("gfx/Beach_Ball.png");
setSize(sf::Vector2f(100, 100));
setPosition(sf::Vector2f(100, 500));
setTexture(&bulletText);
}
void Bullet::Handleinput(Input* input)
{
if (input->isMouseLDown() && !mousedown)
{
mouseStartPos = sf::Vector2f(input->getMouseX(), input->getMouseY());
std::cout << "Dragging mouse\n";
mousedown = true;
}
if (!input->isMouseLDown()&&mousedown)
{
mouseEndPos = sf::Vector2f(input->getMouseX(), input->getMouseY());
std::cout << "Projectile fired\n";
mousedown = false;
activation = true;
}
}
void Bullet::update(float dt, Input* input)
{
if (activation == true)
{
sf::Vector2f trajectory = (mouseStartPos-mouseEndPos);
float force = (Vector::magnitude(trajectory) * 10);
trajectory = Vector::normalise(trajectory);
sf::Vector2f velocity = (trajectory * force);
setPosition(getPosition() + (velocity * dt));
fired = true;
}
if (fired == true)
{
sf::Vector2f pos = velocity * dt + 0.5f * gravity * dt * dt;
velocity += gravity * dt;
setPosition(getPosition() + pos);
}
} | true |
d80d3736a727d542f247aeaeb0221ccd1b1accdf | C++ | tjniemi/GisToSWMM5 | /src/Grid.cpp | UTF-8 | 98,576 | 2.90625 | 3 | [
"MIT"
] | permissive | #include "Grid.h"
Grid::Grid()
{
clear();
}
Grid::~Grid()
{
clear();
}
void Grid::clear()
{
cells = 0;
nCols = 0;
nRows = 0;
cellSize = 0.0;
xllCorner = 0.0;
yllCorner = 0.0;
urcorner[0] = urcorner[1] = 0.0;
llcorner[0] = llcorner[1] = 0.0;
gridType = -1;
delete [] cells;
cells = 0;
}
// Create normal grid by treating each grid cell as a subcatchment
int Grid::create(int gridTypeNew, Raster &landuseRaster, Raster &demRaster)
{
if (gridTypeNew == 0)
{
clear();
gridType = gridTypeNew; // gridType is set to -1 in clear() method
nCols = landuseRaster.nCols;
nRows = landuseRaster.nRows;
cells = new Cell[ nCols * nRows ];
return 0;
}
else
{
return 1;
}
}
// (Legacy mode of creating N*(2^a) x N*(2^a) grid where a is the number of subdivisions)
// Create adaptive grid by subdividing cells with the same landuse
int Grid::create(int gridTypeNew, double cellSizeMax, int maxSubdivisions, Raster &landuseRaster, Raster &demRaster)
{
if (gridTypeNew == 1 && cellSizeMax > 0.0 && maxSubdivisions >= 0)
{
clear(); // gridType is set to -1 in clear() method
gridType = gridTypeNew;
// Create cells.
int numberOfCellsX;
int numberOfCellsY;
//double cellSizeMax = 16.0;
numberOfCellsX = (int)((double)landuseRaster.nCols * landuseRaster.cellSize / cellSizeMax + 0.5);
numberOfCellsY = (int)((double)landuseRaster.nRows * landuseRaster.cellSize / cellSizeMax + 0.5);
double lowerLeftCornerX = landuseRaster.xllCorner;
double lowerLeftCornerY = landuseRaster.yllCorner;
int subdivisions = 0;
//int maxSubdivisions = 3; // 16 -> 8 -> 4 -> 2
std::vector<Cell> cellsAdaptive;
for (int i = 0; i < numberOfCellsX * numberOfCellsY; i++)
{
subdivideCell(cellSizeMax, lowerLeftCornerX, lowerLeftCornerY, i, numberOfCellsX,
landuseRaster, subdivisions, maxSubdivisions, cellsAdaptive);
}
// Transfer adaptive cell data to the pointer array.
nCols = (int)cellsAdaptive.size();
nRows = 1;
cells = new Cell[nRows * nCols];
for (int i = 0; i < nRows * nCols; i++ )
{
cells[i].cellSize = cellsAdaptive[i].cellSize;
cells[i].area = cells[i].cellSize * cells[i].cellSize; // Temp. place
cells[i].centerCoordX = cellsAdaptive[i].centerCoordX;
cells[i].centerCoordY = cellsAdaptive[i].centerCoordY;
cells[i].landuse = cellsAdaptive[i].landuse;
}
return 0;
}
else
{
std::cout << "\n-> Error, when using the adaptive discretization algorithm ";
std::cout << "check that the maximum cell width is above zero and maximum number of subdivisions ";
std::cout << "is equal to or above zero.";
return 1;
}
}
void Grid::subdivideCell(double cellSize, double llcornerx, double llcornery, int index, int numberOfCells,
Raster &landuseRaster, int subdivisions, int maxSubdivisions, std::vector<Cell> &cellsAdaptive)
{
int cellIndexX = index % numberOfCells;
int cellIndexY = index / numberOfCells;
llcornerx = llcornerx + cellIndexX * cellSize;
llcornery = llcornery + cellIndexY * cellSize;
if (isSingleLanduse(llcornerx, llcornery, cellSize, landuseRaster) || subdivisions >= maxSubdivisions)
{
Cell cell;
cell.cellSize = cellSize;
cell.centerCoordX = llcornerx + cell.cellSize * 0.5;
cell.centerCoordY = llcornery + cell.cellSize * 0.5;
std::string landuse = landuseRaster.getPixelValue(cell.centerCoordX, cell.centerCoordY);
cell.landuse = atoi(landuse.c_str());
cellsAdaptive.push_back(cell);
}
else
{
subdivisions++;
for (int i = 0; i < 4; i++)
{
subdivideCell(0.5 * cellSize, llcornerx, llcornery, i, 2,
landuseRaster, subdivisions, maxSubdivisions, cellsAdaptive);
}
}
}
void Grid::computeHistogram(std::vector<std::string> &catLabels, std::vector<int> &catCount,
double lowerLeftCornerX, double lowerLeftCornerY, double cellSizeLoc, Raster &landuseRaster)
{
catLabels.clear();
catCount.clear();
int indexMinX = (int)((lowerLeftCornerX - landuseRaster.xllCorner) / landuseRaster.cellSize + 0.5);
int indexMaxX = (int)((lowerLeftCornerX + cellSizeLoc - landuseRaster.xllCorner) / landuseRaster.cellSize + 0.5);
int indexMinY = (int)((lowerLeftCornerY - landuseRaster.yllCorner) / landuseRaster.cellSize + 0.5);
int indexMaxY = (int)((lowerLeftCornerY + cellSizeLoc - landuseRaster.yllCorner) / landuseRaster.cellSize + 0.5);
if (indexMinX < 0)
{
indexMinX = 0;
}
if (indexMinY < 0)
{
indexMinY = 0;
}
if (indexMaxX > landuseRaster.nCols)
{
indexMaxX = landuseRaster.nCols;
}
if (indexMaxY > landuseRaster.nRows)
{
indexMaxY = landuseRaster.nRows;
}
for (int j = indexMinY; j < indexMaxY; j++)
{
for (int i = indexMinX; i < indexMaxX; i++)
{
double coordinateX = landuseRaster.xllCorner + i * landuseRaster.cellSize + landuseRaster.cellSize * 0.5;
double coordinateY = landuseRaster.yllCorner + j * landuseRaster.cellSize + landuseRaster.cellSize * 0.5;
std::string landuse = landuseRaster.getPixelValue(coordinateX, coordinateY);
bool landuseCatFound = false;
for (int k = 0; k < (int)catLabels.size(); k++)
{
if (catLabels[k] == landuse)
{
catCount[k]++;
landuseCatFound = true;
}
}
if (landuseCatFound == false)
{
catLabels.push_back(landuse);
catCount.push_back(1);
}
}
}
}
bool Grid::isSingleLanduse(double lowerLeftCornerX, double lowerLeftCornerY, double cellSizeLoc, Raster &landuseRaster)
{
std::vector<std::string> catLabels;
std::vector<int> catCount;
computeHistogram(catLabels, catCount, lowerLeftCornerX, lowerLeftCornerY, cellSizeLoc, landuseRaster);
int numberOfCategories = 0;
for (int i = 0; i < (int)catCount.size(); i++)
{
if (catCount[i] > 0)
{
numberOfCategories++;
}
}
if (numberOfCategories == 1)
{
return true;
}
else
{
return false;
}
}
void Grid::setCellNames()
{
for (int i = 0; i < nCols * nRows; i++)
{
std::stringstream sstream("");
sstream << "s" << i;
cells[i].name = sstream.str();
}
}
void Grid::computeCellDimensions(double cellSizeNew)
{
cellSize = cellSizeNew;
for (int i = 0; i < nCols * nRows; i++)
{
cells[i].area = cellSize * cellSize;
cells[i].cellSize = cellSize;
}
}
void Grid::computeCellCenterpoints(double xllCornerNew, double yllCornerNew)
{
xllCorner = xllCornerNew; // is this needed anymore here?
yllCorner = yllCornerNew; // is this needed anymore here?
for (int j = 0; j < nRows; j++)
{
for (int i = 0; i < nCols; i++)
{
double centerCoordX = (double)i * cellSize + 0.5 * cellSize + xllCorner;
double centerCoordY = (double)j * cellSize + 0.5 * cellSize + yllCorner;
cells[ i + j * nCols ].centerCoordX = centerCoordX;
cells[ i + j * nCols ].centerCoordY = centerCoordY;
}
}
}
void Grid::setCellElevations(Raster &demRaster)
{
// Regular grid.
if (gridType == 0)
{
for (int i = 0; i < nCols * nRows; i++)
{
std::string elevation = demRaster.getPixelValue( cells[i].centerCoordX, cells[i].centerCoordY );
cells[i].elevation = atof(elevation.c_str());
cells[i].elevNoData = std::stod(demRaster.noDataValue);
}
}
// (Legacy mode of creating N*(2^a) x N*(2^a) grid where a is the number of subdivisions)
// Adaptive grid.
else if (gridType == 1)
{
for (int i = 0; i < nRows * nCols; i++ )
{
std::vector<std::string> catLabels;
std::vector<int> catCount;
computeHistogram(catLabels, catCount, cells[i].centerCoordX - 0.5 * cells[i].cellSize,
cells[i].centerCoordY - 0.5 * cells[i].cellSize, cells[i].cellSize, demRaster);
double elevation = 0;
int count = 0;
for (int j = 0; j < (int)catLabels.size(); j++)
{
elevation += atof( catLabels[j].c_str() ) * (double)catCount[j];
count += catCount[j];
}
if (count > 0)
{
elevation /= (double)count;
cells[i].elevation = elevation;
}
else
{
std::cout << "\n-> Error, no elevation data was found for the cell " << i;
}
}
}
}
void Grid::setCellFlowdirs(Raster &flowdirRaster)
{
for (int i = 0; i < nCols * nRows; i++)
{
std::string flowdir = flowdirRaster.getPixelValue( cells[i].centerCoordX, cells[i].centerCoordY );
cells[i].flowdir = atoi(flowdir.c_str());
}
}
void Grid::setCellLanduse(Raster &landuseRaster)
{
for (int j = 0; j < nRows; j++)
{
for (int i = 0; i < nCols; i++)
{
std::string landuseType = landuseRaster.getPixelValue( i, nRows - 1 - j );
cells[ i + j * nCols ].landuse = atoi(landuseType.c_str());
}
}
}
void Grid::computeGridExtents()
{
if (nCols * nRows > 0)
{
urcorner[0] = llcorner[0] = cells[0].centerCoordX;
urcorner[1] = llcorner[1] = cells[0].centerCoordY;
}
for (int i = 0; i < nCols * nRows; i++)
{
if (cells[i].landuse != LANDUSE_NONE)
{
if (cells[i].centerCoordX < llcorner[0])
{
llcorner[0] = cells[i].centerCoordX;
}
if (cells[i].centerCoordX > urcorner[0])
{
urcorner[0] = cells[i].centerCoordX;
}
if (cells[i].centerCoordY < llcorner[1])
{
llcorner[1] = cells[i].centerCoordY;
}
if (cells[i].centerCoordY > urcorner[1])
{
urcorner[1] = cells[i].centerCoordY;
}
}
}
}
void Grid::setSubcatchmentProperties(Table &catchPropTable)
{
for (int i = 0; i < nCols * nRows; i++)
{
for (int j = 1; j < catchPropTable.nRows; j++)
{
if (cells[i].landuse == atoi(catchPropTable.data[j * catchPropTable.nCols].c_str()))
{
cells[i].raingage = catchPropTable.data[j * catchPropTable.nCols + 7];
cells[i].imperv = catchPropTable.data[j * catchPropTable.nCols + 1].c_str();
cells[i].N_Imperv = catchPropTable.data[j * catchPropTable.nCols + 3].c_str();
cells[i].N_Perv = catchPropTable.data[j * catchPropTable.nCols + 5].c_str();
cells[i].S_Imperv = catchPropTable.data[j * catchPropTable.nCols + 2].c_str();
cells[i].S_Perv = catchPropTable.data[j * catchPropTable.nCols + 4].c_str();
cells[i].PctZero = catchPropTable.data[j * catchPropTable.nCols + 6].c_str();
cells[i].Suction = catchPropTable.data[j * catchPropTable.nCols + 10].c_str();
cells[i].HydCon = catchPropTable.data[j * catchPropTable.nCols + 8].c_str();
cells[i].IMDmax = catchPropTable.data[j * catchPropTable.nCols + 9].c_str();
cells[i].snowPack = catchPropTable.data[j * catchPropTable.nCols + 11];
if (catchPropTable.nCols > 12)
cells[i].tag = catchPropTable.data[j * catchPropTable.nCols + 12].c_str();
break;
}
}
}
}
void Grid::findCellNeighbours()
{
// Regular grid.
if (gridType == 0)
{
for (int j = 0; j < nRows; j++)
{
for (int i = 0; i < nCols; i++)
{
int currentCell = i + j * nCols;
cells[currentCell].neighCellIndices.assign(8, -1);
cells[currentCell].distanceToNeighbours.assign(8, 0.0 );
// Change routing of cells so that flow directions go from 0-7
// with 0 pointing Northeast and numbers increasing
// in counterclockwise direction
if (j < nRows - 1)
{
cells[currentCell].neighCellIndices[1] = currentCell + nCols;
}
if (j < nRows - 1 && i > 0)
{
cells[currentCell].neighCellIndices[2] = currentCell + nCols - 1;
}
if (i > 0)
{
cells[currentCell].neighCellIndices[3] = currentCell - 1;
}
if (j > 0 && i > 0)
{
cells[currentCell].neighCellIndices[4] = currentCell - nCols - 1;
}
if (j > 0)
{
cells[currentCell].neighCellIndices[5] = currentCell - nCols;
}
if (i < nCols - 1 && j > 0)
{
cells[currentCell].neighCellIndices[6] = currentCell + 1 - nCols;
}
if (i < nCols - 1)
{
cells[currentCell].neighCellIndices[7] = currentCell + 1;
}
if (i < nCols - 1 && j < nRows - 1)
{
cells[currentCell].neighCellIndices[0] = currentCell + nCols + 1;
}
}
}
}
// (Legacy mode of creating N*(2^a) x N*(2^a) grid where a is the number of subdivisions)
// Adaptive grid. This section could be optimized.
else if (gridType == 1)
{
double thresholdDistance = 0.5; // magic number !
for (int i = 0; i < nRows * nCols; i++ )
{
std::vector<int> neighbours;
for (int j = 0; j < nRows * nCols; j++ )
{
if
(
// Corner points.
(
(
fabs((cells[i].centerCoordX + 0.5 * cells[i].cellSize) - (cells[j].centerCoordX - 0.5 * cells[j].cellSize)) < thresholdDistance
||
fabs((cells[i].centerCoordX - 0.5 * cells[i].cellSize) - (cells[j].centerCoordX + 0.5 * cells[j].cellSize)) < thresholdDistance
)
&&
(
fabs((cells[i].centerCoordY + 0.5 * cells[i].cellSize) - (cells[j].centerCoordY - 0.5 * cells[j].cellSize)) < thresholdDistance
||
fabs((cells[i].centerCoordY - 0.5 * cells[i].cellSize) - (cells[j].centerCoordY + 0.5 * cells[j].cellSize)) < thresholdDistance
)
)
||
// Side points.
(
(
(
fabs((cells[i].centerCoordX + 0.5 * cells[i].cellSize) - (cells[j].centerCoordX - 0.5 * cells[j].cellSize)) < thresholdDistance
||
fabs((cells[i].centerCoordX - 0.5 * cells[i].cellSize) - (cells[j].centerCoordX + 0.5 * cells[j].cellSize)) < thresholdDistance
)
&&
(
(cells[i].centerCoordY + 0.5 * cells[i].cellSize >= cells[j].centerCoordY && cells[i].centerCoordY - 0.5 * cells[i].cellSize <= cells[j].centerCoordY)
||
(cells[j].centerCoordY + 0.5 * cells[j].cellSize >= cells[i].centerCoordY && cells[j].centerCoordY - 0.5 * cells[j].cellSize <= cells[i].centerCoordY)
)
)
||
(
(
fabs((cells[i].centerCoordY + 0.5 * cells[i].cellSize) - (cells[j].centerCoordY - 0.5 * cells[j].cellSize)) < thresholdDistance
||
fabs((cells[i].centerCoordY - 0.5 * cells[i].cellSize) - (cells[j].centerCoordY + 0.5 * cells[j].cellSize)) < thresholdDistance
)
&&
(
(cells[i].centerCoordX + 0.5 * cells[i].cellSize >= cells[j].centerCoordX && cells[i].centerCoordX - 0.5 * cells[i].cellSize <= cells[j].centerCoordX)
||
(cells[j].centerCoordX + 0.5 * cells[j].cellSize >= cells[i].centerCoordX && cells[j].centerCoordX - 0.5 * cells[j].cellSize <= cells[i].centerCoordX)
)
)
)
)
{
if (i != j && cells[j].landuse != LANDUSE_NONE)
{
neighbours.push_back(j);
}
}
}
cells[i].neighCellIndices = neighbours;
cells[i].distanceToNeighbours.assign( (int)neighbours.size(), 0.0 );
}
}
}
// (Legacy mode of creating N*(2^a) x N*(2^a) grid where a is the number of subdivisions)
// Route cells in old adaptive grid
void Grid::routeCells()
{
for (int i = 0; i < nCols * nRows; i++)
{
double slope = 0.0;
double maxSlope = -1.0;
double elevation = cells[i].elevation;
int neighCellIndex = -1;
cells[i].flowWidth = cells[i].cellSize;
int flowDirection = -1;
// Compute distances between neighbour cells.
for (int j = 0; j < (int)cells[i].neighCellIndices.size(); j++)
{
if (cells[i].neighCellIndices[j] != -1)
{
double distance = sqrt( (cells[i].centerCoordX - cells[ cells[i].neighCellIndices[j] ].centerCoordX)
* (cells[i].centerCoordX - cells[ cells[i].neighCellIndices[j] ].centerCoordX)
+ (cells[i].centerCoordY - cells[ cells[i].neighCellIndices[j] ].centerCoordY)
* (cells[i].centerCoordY - cells[ cells[i].neighCellIndices[j] ].centerCoordY) );
if (distance > 0.0)
{
cells[i].distanceToNeighbours[j] = distance;
}
else
{
std::cout << "\n-> Error, distance between cell " << i << " and cell " << j << " is zero or below zero";
}
}
}
// Find outlet.
for (int k = 0; k < (int)cells[i].neighCellIndices.size(); k++)
{
if (cells[i].neighCellIndices[k] != -1 && cells[ cells[i].neighCellIndices[k] ].landuse >= BUILT_AREA)
{
double distance = cells[i].distanceToNeighbours[k];
if (distance > 0.0)
slope = fabs((cells[i].elevation - cells[ cells[i].neighCellIndices[k] ].elevation) / distance);
if (cells[ cells[i].neighCellIndices[k] ].elevation < elevation && slope > maxSlope)
{
neighCellIndex = cells[i].neighCellIndices[k];
flowDirection = k;
maxSlope = slope;
}
}
}
// Save the outlet name and compute flow width.
if (neighCellIndex != -1)
{
cells[i].outlet = cells[neighCellIndex].name;
cells[i].outletCoordX = cells[neighCellIndex].centerCoordX;
cells[i].outletCoordY = cells[neighCellIndex].centerCoordY;
if (cells[i].distanceToNeighbours[flowDirection] > 0.0)
{
cells[i].flowWidth = cells[i].area / cells[i].distanceToNeighbours[flowDirection];
}
}
}
}
// Use flow direction raster to route cells when using NxN or adap grid
void Grid::routeCellsReg()
{
for (int i = 0; i < nCols * nRows; i++)
{
int neighCellIndex = -1;
cells[i].flowWidth = cells[i].cellSize;
int flowDirection = -1;
// Compute distances between neighbour cells.
for (int j = 0; j < (int)cells[i].neighCellIndices.size(); j++)
{
if (cells[i].neighCellIndices[j] != -1)
{
double distance = sqrt( (cells[i].centerCoordX - cells[ cells[i].neighCellIndices[j] ].centerCoordX)
* (cells[i].centerCoordX - cells[ cells[i].neighCellIndices[j] ].centerCoordX)
+ (cells[i].centerCoordY - cells[ cells[i].neighCellIndices[j] ].centerCoordY)
* (cells[i].centerCoordY - cells[ cells[i].neighCellIndices[j] ].centerCoordY) );
if (distance > 0.0)
{
cells[i].distanceToNeighbours[j] = distance;
}
else
{
std::cout << "\n-> Error, distance between cell " << i << " and cell " << j << " is zero or below zero";
}
}
}
// Find outlet.
flowDirection = cells[i].flowdir - 1;
if (flowDirection != -1 &&
cells[i].neighCellIndices[flowDirection] != -1 &&
cells[ cells[i].neighCellIndices[flowDirection] ].landuse >= BUILT_AREA)
{
neighCellIndex = cells[i].neighCellIndices[flowDirection];
}
// Save the outlet name and compute flow width.
if (neighCellIndex != -1)
{
cells[i].outletID = neighCellIndex;
cells[i].outlet = cells[neighCellIndex].name;
cells[i].outletCoordX = cells[neighCellIndex].centerCoordX;
cells[i].outletCoordY = cells[neighCellIndex].centerCoordY;
if (cells[i].distanceToNeighbours[flowDirection] > 0.0)
{
cells[i].flowWidth = cells[i].area / cells[i].distanceToNeighbours[flowDirection] ;
}
}
}
}
void Grid::computeCellSlopes()
{
for (int i = 0; i < nCols * nRows; i++)
{
double slope = 0.0;
int slopeCount = 0;
for (int k = 0; k < (int)cells[i].neighCellIndices.size(); k++)
{
if (cells[i].neighCellIndices[k] != -1 && cells[ cells[i].neighCellIndices[k] ].landuse >= BUILT_AREA)
{
double distance = cells[i].distanceToNeighbours[k];
if (distance > 0.0 && cells[i].elevation > cells[i].elevNoData && cells[ cells[i].neighCellIndices[k] ].elevation > cells[i].elevNoData)
{
slope += fabs((cells[i].elevation - cells[ cells[i].neighCellIndices[k] ].elevation) / distance);
slopeCount++;
}
else
{
std::cout << "\n-> Error, no data to calculate slope between cells " << i << " and " << cells[i].neighCellIndices[k] << ".";
}
}
}
// Save the average slope.
if (slopeCount > 0)
{
cells[i].slope = slope / (double)slopeCount;
}
// Fix slope for the rooftops.
if (cells[i].landuse >=ROOF_CONNECTED && cells[i].landuse < BUILT_AREA)
{
cells[i].slope = 0.05;
}
// Set minimum slope
if (cells[i].slope < 0.001)
{
cells[i].slope = 0.001;
}
}
}
// This relies (implicitly) on the cell connected to junction being a local
// pit in the DEM, if it is not (and e.g. the next cell is) most of the water flows past
// the junction...
// 23 Oct 2017 UPDATE: Using 3x3 area surrounding junctions as the collecting area for water
void Grid::connectCellsToJunctions(Table &juncTable)
{
for (int k = 1; k < juncTable.nRows; k++) // pass the header line
{
double juncPosX = atof( juncTable.data[k * juncTable.nCols].c_str() );
double juncPosY = atof( juncTable.data[k * juncTable.nCols + 1].c_str() );
int isOpen = atoi( juncTable.data[k * juncTable.nCols + 6].c_str() );
// NxN or adap grid
if (gridType == 0)
{
if (juncPosX >= xllCorner && juncPosX < xllCorner + nCols * cellSize
&& juncPosY >= yllCorner && juncPosY < yllCorner + nRows * cellSize && isOpen == 1) // pass closed junctions
{
if (nCols > 0 && nRows > 0 && cellSize > 0.0)
{
int col = (int)((juncPosX - xllCorner) / cellSize);
int row = (int)((juncPosY - yllCorner) / cellSize);
if (col + row * nCols >= 0 && col + row * nCols < nCols * nRows)
{
cells[ col + row * nCols ].outletID = col + row * nCols; // Set outletID to the outletID of junction cell
cells[ col + row * nCols ].outlet = juncTable.data[k * juncTable.nCols + 2];
cells[ col + row * nCols ].flowWidth = cells[ col + row * nCols ].cellSize;
cells[ col + row * nCols ].outletCoordX = stod(juncTable.data[k * juncTable.nCols + 0]);
cells[ col + row * nCols ].outletCoordY = stod(juncTable.data[k * juncTable.nCols + 1]);
// Use the 3x3 cell area surrounding each stormwater inlet as the collecting area for the inlet.
// This should help with misplacement of stormwater inlets when not just the cell with the inlet is used
// to collect water
for (int i = 0; i < (int)cells[ col + row * nCols ].neighCellIndices.size(); i++)
{
if (cells[ col + row * nCols ].neighCellIndices[i] != -1
&& cells[ cells[ col + row * nCols ].neighCellIndices[i] ].landuse >= BUILT_AREA)
{
cells[ cells[ col + row * nCols ].neighCellIndices[i] ].outletID = col + row * nCols; // Set outletID to the outletID of junction cell
cells[ cells[ col + row * nCols ].neighCellIndices[i] ].outlet = juncTable.data[k * juncTable.nCols + 2];
cells[ cells[ col + row * nCols ].neighCellIndices[i] ].flowWidth = cells[ cells[ col + row * nCols ].neighCellIndices[i] ].cellSize; // This is unnecessary?
cells[ cells[ col + row * nCols ].neighCellIndices[i] ].outletCoordX = stod(juncTable.data[k * juncTable.nCols + 0]);
cells[ cells[ col + row * nCols ].neighCellIndices[i] ].outletCoordY = stod(juncTable.data[k * juncTable.nCols + 1]);
}
}
}
}
}
}
// (Legacy mode)
// N*(2^a) x N*(2^a) grid where a is the number of subdivisions
else if (gridType == 1)
{
for (int i = 0; i < nCols * nRows; i++)
{
if (cells[i].centerCoordX - 0.5 * cells[i].cellSize <= juncPosX
&& cells[i].centerCoordX + 0.5 * cells[i].cellSize > juncPosX
&& cells[i].centerCoordY - 0.5 * cells[i].cellSize <= juncPosY
&& cells[i].centerCoordY + 0.5 * cells[i].cellSize > juncPosY
&& isOpen == 1 // pass closed junctions
)
{
cells[i].outlet = juncTable.data[k * juncTable.nCols + 2];
cells[i].flowWidth = cells[i].cellSize;
cells[i].outletCoordX = stod(juncTable.data[k * juncTable.nCols + 0]);
cells[i].outletCoordY = stod(juncTable.data[k * juncTable.nCols + 1]);
}
}
}
}
}
void Grid::routePavedPitAndRooftopCells(Table &juncTable)
{
// Route paved pit cells and connected rooftop cells to junctions.
double distanceMaxSquared = (urcorner[0] - llcorner[0]) * (urcorner[0] - llcorner[0]) +
(urcorner[1] - llcorner[1]) * (urcorner[1] - llcorner[1]);
for (int i = 0; i < nCols * nRows; i++)
{
// Route connected roofs to nearest junction
if (cells[i].landuse >= ROOF_CONNECTED && cells[i].landuse < ROOF_UNCONNECTED) // should this be here?
{
double distanceSquared = distanceMaxSquared;
for (int j = 1; j < juncTable.nRows; j++) // pass the header line
{
double juncPosX = atof( juncTable.data[j * juncTable.nCols].c_str() );
double juncPosY = atof( juncTable.data[j * juncTable.nCols + 1].c_str() );
double dx = juncPosX - cells[i].centerCoordX;
double dy = juncPosY - cells[i].centerCoordY;
int isroutable = atoi( juncTable.data[j * juncTable.nCols + 10].c_str() );
int col = (int)((juncPosX - xllCorner) / cellSize);
int row = (int)((juncPosY - yllCorner) / cellSize);
if (dx * dx + dy * dy < distanceSquared && isroutable == 1)
{
distanceSquared = dx * dx + dy * dy;
cells[i].outletID = col + row * nCols; // Set outletID to the outletID of junction cell
cells[i].outlet = juncTable.data[j * juncTable.nCols + 2];
cells[i].flowWidth = cells[i].cellSize; //Modified 20160909, compute by area / sqrt (distanceSquared) ?
cells[i].outletCoordX = stod(juncTable.data[j * juncTable.nCols + 0]);
cells[i].outletCoordY = stod(juncTable.data[j * juncTable.nCols + 1]);
}
}
// Mark local pits where water is routed forcefully
cells[i].isSink = 2;
}
// Route unconnected rooftop cells to the nearest non-roof cell
else if (cells[i].landuse >= ROOF_UNCONNECTED && cells[i].landuse < BUILT_AREA)
{
double distanceSquared = distanceMaxSquared;
for (int j = 0; j < nCols * nRows; j++)
{
if (cells[j].landuse >= BUILT_AREA)
{
double dx = cells[i].centerCoordX - cells[j].centerCoordX;
double dy = cells[i].centerCoordY - cells[j].centerCoordY;
if (dx * dx + dy * dy < distanceSquared)
{
distanceSquared = dx * dx + dy * dy;
cells[i].outletID = j;
cells[i].outlet = cells[j].name;
cells[i].flowWidth = cells[i].cellSize; //Modified 20160909, compute by area / sqrt (distanceSquared) ?
cells[i].outletCoordX = cells[j].centerCoordX;
cells[i].outletCoordY = cells[j].centerCoordY;
}
}
}
}
// Route pits in built areas to themselves, i.e. water is not routed downstream
else if (cells[i].landuse >= BUILT_AREA && cells[i].landuse < NATURAL_AREA && cells[i].outlet == "*")
{
cells[i].outletID = i;
cells[i].outlet = cells[i].name;
cells[i].outletCoordX = cells[i].centerCoordX;
cells[i].outletCoordY = cells[i].centerCoordY;
// Mark local pits where water is not routed
cells[i].isSink = 1;
}
}
}
// Route pits in natural areas to themselves, i.e. water is not routed downstream
void Grid::routePitCells()
{
for (int i = 0; i < nCols * nRows; i++)
{
if (cells[i].outlet == "*" && cells[i].landuse >= NATURAL_AREA)
{
cells[i].outletID = i;
cells[i].outlet = cells[i].name;
// Set depression storage of pit cells in permeable areas to a very high value ...
// ... to prevent loss of water from the system.
cells[i].S_Imperv = "50000";
cells[i].S_Perv = "50000";
cells[i].outletCoordX = cells[i].centerCoordX;
cells[i].outletCoordY = cells[i].centerCoordY;
// Mark local pits where water is not routed
cells[i].isSink = 1;
}
}
}
// Find cells routed to outlet and save routing and pipe information
std::vector<int> Grid::findRouted(Table &juncTable, std::string &path)
{
// Set inletIDs contributing to each cell
for (int i = 0; i < nCols*nRows; i++)
{
if ( cells[i].landuse >= ROOF_UNCONNECTED && i != cells[i].outletID ) // Connected roofs are treated separately
{
cells[cells[i].outletID].inletIDs.push_back(i);
}
}
// Empty vector for final list of routed subcatchments ID's
std::vector<int> final_IDs;
// Go through junctions
for (int i = 1; i < juncTable.nRows; i++)
{
double juncPosX = atof( juncTable.getData(i, 0).c_str() );
double juncPosY = atof( juncTable.getData(i, 1).c_str() );
int isOpen = atoi( juncTable.getData(i, 6).c_str() );
// Add open cells with junctions to final list of subcatchments
if (juncPosX >= xllCorner
&&
juncPosX < xllCorner + nCols * cellSize
&&
juncPosY >= yllCorner
&&
juncPosY < yllCorner + nRows * cellSize
&&
isOpen == 1) // pass closed junctions
{
if (nCols > 0 && nRows > 0 && cellSize > 0.0)
{
int col = (int)((juncPosX - xllCorner) / cellSize);
int row = (int)((juncPosY - yllCorner) / cellSize);
if (col + row * nCols >= 0 && col + row * nCols < nCols * nRows)
{
std::vector<int> selection_IDs;
selection_IDs.reserve(nCols*nRows); // Is this necessary?
final_IDs.push_back(col + row * nCols);
selection_IDs.push_back(col + row * nCols);
// Iterate through cells with open jucntions and add cells as they flow towrads the opening
int counter = 0;
while (!selection_IDs.empty() && counter < nCols*nRows)
{
// Get all subcatchments routed into the current cell
std::vector<int> inSubs = cells[selection_IDs.front()].inletIDs;
// Go through the subcatchments routed into the current cell
for (auto it=inSubs.begin(); it != inSubs.end(); ++it)
{
final_IDs.push_back(*it);
if (!(std::find(selection_IDs.begin(), selection_IDs.end(), *it) != selection_IDs.end()))
{
// Add subcatchment to selected subactchments if it's not there yet
selection_IDs.push_back(*it);
}
}
// Remove the subcatchment from the list of selected ID's
selection_IDs.erase(selection_IDs.begin());
counter++;
}
}
}
}
}
for (int i = 0; i < nCols*nRows; i++)
{
// Add connected roofs to final subcatchments
if ( (cells[i].landuse >= ROOF_CONNECTED && cells[i].landuse < ROOF_UNCONNECTED) && (i != cells[i].outletID) )
{
final_IDs.push_back(i);
}
}
// Create and save a WKT vector file of routed subcatchments
saveSubcatchmentRouting(path, final_IDs);
return final_IDs;
}
// Simplify computation grid based on common flow direction and landuse
void Grid::simplify(Table &juncTable, std::string &path)
{
/*** NON-ROOF CELLS ***/
// Ensure there are no inletIDs
for (int i = 0; i < nCols*nRows; i++)
cells[i].inletIDs.clear();
// Set inletIDs contributing to each cell
for (int i = 0; i < nCols*nRows; i++)
{
if ( cells[i].landuse >= BUILT_AREA && i != cells[i].outletID )
{
cells[cells[i].outletID].inletIDs.push_back(i);
}
}
// Set the 3x3 cell area surrounding each stormwater inlet as the collecting area for the inlet.
// This should help with misplacement of stormwater inlets when not just the cell with the inlet is used
// to collect water
for (int i = 1; i < juncTable.nRows; i++) // pass the header line
{
double juncPosX = atof( juncTable.data[i * juncTable.nCols].c_str() );
double juncPosY = atof( juncTable.data[i * juncTable.nCols + 1].c_str() );
int isOpen = atoi( juncTable.data[i * juncTable.nCols + 6].c_str() );
if (juncPosX >= xllCorner && juncPosX < xllCorner + nCols * cellSize
&& juncPosY >= yllCorner && juncPosY < yllCorner + nRows * cellSize && isOpen == 1) // pass closed junctions
{
if (nCols > 0 && nRows > 0 && cellSize > 0.0)
{
int col = (int)((juncPosX - xllCorner) / cellSize);
int row = (int)((juncPosY - yllCorner) / cellSize);
if (col + row * nCols >= 0 && col + row * nCols < nCols * nRows)
{
for (int j = 0; j < (int)cells[ col + row * nCols ].neighCellIndices.size(); j++)
{
if (cells[ col + row * nCols ].neighCellIndices[j] != -1
&& cells[ cells[ col + row * nCols ].neighCellIndices[j] ].landuse >= BUILT_AREA)
{
cells[cells[ cells[ col + row * nCols ].neighCellIndices[j] ].outletID].inletIDs.push_back(cells[ col + row * nCols ].neighCellIndices[j]);
}
}
}
}
}
}
// Empty vector for final list of routed cell ID's
std::vector<int> final_IDs;
std::vector<Cell> cellsAdaptive;
std::unordered_map<int, std::vector<Cell>::size_type> adapID; // A lookup table of subcatchmentID's in cellsAdaptive
int subcatchmentID = -1;
// Go through junctions
for (int i = 1; i < juncTable.nRows; i++)
{
double juncPosX = atof( juncTable.getData(i, 0).c_str() );
double juncPosY = atof( juncTable.getData(i, 1).c_str() );
int isOpen = atoi( juncTable.getData(i, 6).c_str() );
// Add cells with open junctions to final list of cells
if (juncPosX >= xllCorner
&&
juncPosX < xllCorner + nCols * cellSize
&&
juncPosY >= yllCorner
&&
juncPosY < yllCorner + nRows * cellSize
&&
isOpen == 1) // pass closed junctions
{
if (nCols > 0 && nRows > 0 && cellSize > 0.0)
{
int col = (int)((juncPosX - xllCorner) / cellSize);
int row = (int)((juncPosY - yllCorner) / cellSize);
if (col + row * nCols >= 0 && col + row * nCols < nCols * nRows)
{
std::vector<int> selection_IDs;
selection_IDs.reserve(nCols*nRows); // Is this necessary???
final_IDs.push_back(col + row * nCols);
selection_IDs.push_back(col + row * nCols);
// Update the subcatchmentID of current cell...
subcatchmentID++;
cells[col + row * nCols].subcatchmentID = subcatchmentID;
// ... create a new adaptive subcatchment...
Cell newCell;
newCell.cellSize = cellSize;
newCell.area += cells[col + row * nCols].area;
newCell.centerCoordX += cells[col + row * nCols].centerCoordX;
newCell.centerCoordY += cells[col + row * nCols].centerCoordY;
newCell.elevation += cells[col + row * nCols].elevation;
newCell.slope += cells[col + row * nCols].slope;
newCell.landuse = cells[col + row * nCols].landuse;
newCell.imperv = cells[col + row * nCols].imperv;
newCell.outlet = juncTable.getData(i, 2).c_str();
newCell.outletID = subcatchmentID;
newCell.outletCoordX = juncPosX;
newCell.outletCoordY = juncPosY;
newCell.subcatchmentID = subcatchmentID;
newCell.raingage = cells[col + row * nCols].raingage;
newCell.snowPack = cells[col + row * nCols].snowPack;
newCell.N_Imperv = cells[col + row * nCols].N_Imperv;
newCell.N_Perv = cells[col + row * nCols].N_Perv;
newCell.S_Imperv = cells[col + row * nCols].S_Imperv;
newCell.S_Perv = cells[col + row * nCols].S_Perv;
newCell.PctZero = cells[col + row * nCols].PctZero;
newCell.RouteTo = cells[col + row * nCols].RouteTo;
newCell.PctRouted = cells[col + row * nCols].PctRouted;
newCell.Suction = cells[col + row * nCols].Suction;
newCell.HydCon = cells[col + row * nCols].HydCon;
newCell.IMDmax = cells[col + row * nCols].IMDmax;
newCell.isSink = cells[col + row * nCols].isSink;
newCell.tag = cells[col + row * nCols].tag;
newCell.hasInlet = 1;
newCell.numElements++;
std::stringstream subcatchmentName("");
subcatchmentName << "s" << subcatchmentID + 1;
newCell.name = subcatchmentName.str();
cellsAdaptive.push_back(newCell);
// ... and update the lookup table of subcatchments and their indexes.
adapID[subcatchmentID] = cellsAdaptive.size()-1;
// Use the 3x3 cell area surrounding each stormwater inlet as the collecting area for the inlet.
// This should help with misplacement of stormwater inlets when not just the cell with the inlet is used
// to collect water
for (int j = 0; j < (int)cells[ col + row * nCols ].neighCellIndices.size(); j++)
{
if (cells[ col + row * nCols ].neighCellIndices[j] != -1
&& cells[ cells[ col + row * nCols ].neighCellIndices[j] ].landuse >= BUILT_AREA
&& cells[ cells[ col + row * nCols ].neighCellIndices[j] ].landuse != cells[ col + row * nCols ].landuse) // Don't create new subcatchments if the landuse is the same as in inlet cell
{
final_IDs.push_back(cells[ col + row * nCols ].neighCellIndices[j]);
selection_IDs.push_back(cells[ col + row * nCols ].neighCellIndices[j]);
// Update the subcatchmentID of current cell...
subcatchmentID++;
cells[ cells[ col + row * nCols ].neighCellIndices[j]].subcatchmentID = subcatchmentID;
// ... create a new adaptive subcatchment...
Cell newCell;
newCell.cellSize = cellSize;
newCell.area += cells[ cells[ col + row * nCols ].neighCellIndices[j] ].area;
newCell.centerCoordX += cells[ cells[ col + row * nCols ].neighCellIndices[j] ].centerCoordX;
newCell.centerCoordY += cells[ cells[ col + row * nCols ].neighCellIndices[j] ].centerCoordY;
newCell.elevation += cells[ cells[ col + row * nCols ].neighCellIndices[j] ].elevation;
newCell.slope += cells[ cells[ col + row * nCols ].neighCellIndices[j] ].slope;
newCell.landuse = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].landuse;
newCell.imperv = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].imperv;
newCell.outlet = juncTable.getData(i, 2).c_str();
newCell.outletID = subcatchmentID;
newCell.outletCoordX = juncPosX;
newCell.outletCoordY = juncPosY;
newCell.subcatchmentID = subcatchmentID;
newCell.raingage = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].raingage;
newCell.snowPack = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].snowPack;
newCell.N_Imperv = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].N_Imperv;
newCell.N_Perv = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].N_Perv;
newCell.S_Imperv = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].S_Imperv;
newCell.S_Perv = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].S_Perv;
newCell.PctZero = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].PctZero;
newCell.RouteTo = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].RouteTo;
newCell.PctRouted = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].PctRouted;
newCell.Suction = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].Suction;
newCell.HydCon = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].HydCon;
newCell.IMDmax = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].IMDmax;
newCell.isSink = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].isSink;
newCell.tag = cells[ cells[ col + row * nCols ].neighCellIndices[j] ].tag;
newCell.hasInlet = 1;
newCell.numElements++;
std::stringstream subcatchmentName("");
subcatchmentName << "s" << subcatchmentID + 1;
newCell.name = subcatchmentName.str();
cellsAdaptive.push_back(newCell);
// ... and update the lookup table of subcatchments and their indexes.
adapID[subcatchmentID] = cellsAdaptive.size()-1;
}
}
// Iterate through cells and add cells as they flow towards the inlet
int counter = 0; // Failsafe to prevent infinite while loop
while (!selection_IDs.empty() && counter < nCols*nRows)
{
// Get all subcatchments routed into the current cell
std::vector<int> inSubs = cells[selection_IDs.front()].inletIDs;
// Go through the cells routed into the current cell
for (auto it=inSubs.begin(); it != inSubs.end(); ++it)
{
// Add cell to selected cells if it is not there or in final cells yet
if (!(std::find(selection_IDs.begin(), selection_IDs.end(), *it) != selection_IDs.end())
&&
!(std::find(final_IDs.begin(), final_IDs.end(), *it) != final_IDs.end()))
{
selection_IDs.push_back(*it);
}
// Add cell to final cells if it is not there yet
if (!(std::find(final_IDs.begin(), final_IDs.end(), *it) != final_IDs.end()))
{
final_IDs.push_back(*it);
// Add current cell to existing adaptive subctahment or create a new one if old doesn't exist
if (
cells[cells[*it].outletID].subcatchmentID > -1 // adaptive subcatchment exists
&&
cells[*it].landuse == cells[cells[*it].outletID].landuse // cell has same landuse as the downstream subcatchment
)
{
// Update subcatchmentID of current cell ...
cells[*it].subcatchmentID = cells[cells[*it].outletID].subcatchmentID;
// ... and add current cell to existing subcatchment
int i = adapID[cells[cells[*it].outletID].subcatchmentID];
cellsAdaptive[i].area += cells[*it].area;
cellsAdaptive[i].centerCoordX += cells[*it].centerCoordX;
cellsAdaptive[i].centerCoordY += cells[*it].centerCoordY;
cellsAdaptive[i].elevation += cells[*it].elevation;
cellsAdaptive[i].slope += cells[*it].slope;
cellsAdaptive[i].numElements++;
}
else
{
// Update the subcatchmentID of current cell...
subcatchmentID++;
cells[*it].subcatchmentID = subcatchmentID;
// Get index of downstream subcatchment
int i = adapID[cells[cells[*it].outletID].subcatchmentID];
// ... and create a new adaptive subcatchment...
Cell newCell;
newCell.cellSize = cellSize;
newCell.area += cells[*it].area;
newCell.centerCoordX += cells[*it].centerCoordX;
newCell.centerCoordY += cells[*it].centerCoordY;
newCell.elevation += cells[*it].elevation;
newCell.slope += cells[*it].slope;
newCell.landuse = cells[*it].landuse;
newCell.imperv = cells[*it].imperv;
newCell.outlet = cellsAdaptive[i].name;
newCell.outletID = cells[cells[*it].outletID].subcatchmentID;
newCell.subcatchmentID = subcatchmentID;
newCell.raingage = cells[*it].raingage;
newCell.snowPack = cells[*it].snowPack;
newCell.N_Imperv = cells[*it].N_Imperv;
newCell.N_Perv = cells[*it].N_Perv;
newCell.S_Imperv = cells[*it].S_Imperv;
newCell.S_Perv = cells[*it].S_Perv;
newCell.PctZero = cells[*it].PctZero;
newCell.RouteTo = cells[*it].RouteTo;
newCell.PctRouted = cells[*it].PctRouted;
newCell.Suction = cells[*it].Suction;
newCell.HydCon = cells[*it].HydCon;
newCell.IMDmax = cells[*it].IMDmax;
newCell.isSink = cells[*it].isSink;
newCell.tag = cells[*it].tag;
newCell.numElements++;
std::stringstream subcatchmentName("");
subcatchmentName << "s" << subcatchmentID + 1;
newCell.name = subcatchmentName.str();
cellsAdaptive.push_back(newCell);
// ... and update the lookup table of subcatchments and their indexes.
adapID[subcatchmentID] = cellsAdaptive.size()-1;
}
}
}
// Remove the cell ID from the list of selected ID's
selection_IDs.erase(selection_IDs.begin());
counter++;
}
}
}
}
}
/*** UNCONNECTED ROOFS ***/
// Ensure the are no earlier inletIDs
for (int i = 0; i < (int)cellsAdaptive.size(); ++i)
cellsAdaptive[i].inletIDs.clear();
// Find outlets of unconnected roof cells
for (int i = 0; i < nCols*nRows; i++)
{
if ( (cells[i].landuse >= ROOF_UNCONNECTED && cells[i].landuse < BUILT_AREA)
&&
(cells[cells[i].outletID].subcatchmentID > -1) // Check that the roof is connected to routed cell
&&
(i != cells[i].outletID) )
{
// Get index of downstream subcatchment
int j = adapID[cells[cells[i].outletID].subcatchmentID];
cellsAdaptive[j].inletIDs.push_back(i);
}
}
std::vector<int> roofOutlets; // Temp vector of subcatchments where unconnnectd roofs are connected
for (int i = 0; i < (int)cellsAdaptive.size(); ++i)
{
if (!cellsAdaptive[i].inletIDs.empty())
roofOutlets.push_back(i);
}
// Combine unconnected roof cells with the same outlet into one subcatchment
for (auto it=roofOutlets.begin(); it != roofOutlets.end(); ++it)
{
if (!cellsAdaptive[*it].inletIDs.empty())
{
// Get all roof cells routed into the current cell
std::vector<int> roofCells = cellsAdaptive[*it].inletIDs;
// Update the subcatchmentID of current cell...
subcatchmentID++;
cells[roofCells.front()].subcatchmentID = subcatchmentID;
// ... and create a new adaptive subcatchment.
Cell newCell;
newCell.cellSize = cellSize;
newCell.area += cells[roofCells.front()].area;
newCell.centerCoordX += cells[roofCells.front()].centerCoordX;
newCell.centerCoordY += cells[roofCells.front()].centerCoordY;
newCell.elevation += cells[roofCells.front()].elevation;
newCell.slope += cells[roofCells.front()].slope;
newCell.landuse = cells[roofCells.front()].landuse;
newCell.imperv = cells[roofCells.front()].imperv;
newCell.outlet = cellsAdaptive[*it].name;
newCell.outletID = *it;
newCell.subcatchmentID = subcatchmentID;
newCell.raingage = cells[roofCells.front()].raingage;
newCell.snowPack = cells[roofCells.front()].snowPack;
newCell.N_Imperv = cells[roofCells.front()].N_Imperv;
newCell.N_Perv = cells[roofCells.front()].N_Perv;
newCell.S_Imperv = cells[roofCells.front()].S_Imperv;
newCell.S_Perv = cells[roofCells.front()].S_Perv;
newCell.PctZero = cells[roofCells.front()].PctZero;
newCell.RouteTo = cells[roofCells.front()].RouteTo;
newCell.PctRouted = cells[roofCells.front()].PctRouted;
newCell.Suction = cells[roofCells.front()].Suction;
newCell.HydCon = cells[roofCells.front()].HydCon;
newCell.IMDmax = cells[roofCells.front()].IMDmax;
newCell.isSink = cells[roofCells.front()].isSink;
newCell.tag = cells[roofCells.front()].tag;
newCell.numElements++;
std::stringstream subcatchmentName("");
subcatchmentName << "s" << subcatchmentID + 1;
newCell.name = subcatchmentName.str();
// Remove the current cell ID from the list of rooCell ID's
roofCells.erase(roofCells.begin());
// Go through rest of the roof cells and add to the current subcatchment
for (auto it=roofCells.begin(); it != roofCells.end(); ++it)
{
// Update subcatchmentID of current cell ...
cells[*it].subcatchmentID = subcatchmentID;
// ... and add current cell to existing subcatchment
newCell.area += cells[*it].area;
newCell.centerCoordX += cells[*it].centerCoordX;
newCell.centerCoordY += cells[*it].centerCoordY;
newCell.elevation += cells[*it].elevation;
newCell.slope += cells[*it].slope;
newCell.numElements++;
}
// Save current subcatchment
cellsAdaptive.push_back(newCell);
// ... and update the lookup table of subcatchments and their indexes.
adapID[subcatchmentID] = cellsAdaptive.size()-1;
}
}
/*** CONNECTED ROOFS ***/
// Ensure the are no earlier inletIDs
for (int i = 0; i < nCols*nRows; ++i)
cells[i].inletIDs.clear();
// Find outlet cells of connected roof cells
for (int i = 0; i < nCols*nRows; i++)
{
if ( (cells[i].landuse >= ROOF_CONNECTED && cells[i].landuse < ROOF_UNCONNECTED)
&&
(i != cells[i].outletID) )
{
cells[cells[i].outletID].inletIDs.push_back(i);
}
}
// Go through junctions
for (int i = 1; i < juncTable.nRows; i++)
{
double juncPosX = atof( juncTable.getData(i, 0).c_str() );
double juncPosY = atof( juncTable.getData(i, 1).c_str() );
int isRoutable = atoi( juncTable.getData(i, 10).c_str() );
// Check that cell is routable and within catchment
if (juncPosX >= xllCorner
&&
juncPosX < xllCorner + nCols * cellSize
&&
juncPosY >= yllCorner
&&
juncPosY < yllCorner + nRows * cellSize
&&
isRoutable == 1) // pass closed junctions
{
if (nCols > 0 && nRows > 0 && cellSize > 0.0)
{
int col = (int)((juncPosX - xllCorner) / cellSize);
int row = (int)((juncPosY - yllCorner) / cellSize);
int j = col + row * nCols; // Cell index of junction i
if (j >= 0 && j < nCols * nRows)
{
std::vector<int> selection_IDs;
selection_IDs.reserve(nCols*nRows); // Is this necessary???
for (auto it = cells[j].inletIDs.begin(); it != cells[j].inletIDs.end(); ++it) // Inlet roof cell to junction i in cell j
{
// Add cell to final cells if it is not there yet
if (!(std::find(final_IDs.begin(), final_IDs.end(), *it) != final_IDs.end()))
{
final_IDs.push_back(*it);
selection_IDs.push_back(*it);
// Update the subcatchmentID of current cell...
subcatchmentID++;
cells[*it].subcatchmentID = subcatchmentID;
// ... create a new adaptive subcatchment...
Cell newCell;
newCell.cellSize = cellSize;
newCell.area += cells[*it].area;
newCell.centerCoordX += cells[*it].centerCoordX;
newCell.centerCoordY += cells[*it].centerCoordY;
newCell.elevation += cells[*it].elevation;
newCell.slope += cells[*it].slope;
newCell.landuse = cells[*it].landuse;
newCell.imperv = cells[*it].imperv;
newCell.outlet = juncTable.getData(i, 2).c_str();
newCell.outletID = j;
newCell.outletCoordX = juncPosX;
newCell.outletCoordY = juncPosY;
newCell.subcatchmentID = subcatchmentID;
newCell.raingage = cells[*it].raingage;
newCell.snowPack = cells[*it].snowPack;
newCell.N_Imperv = cells[*it].N_Imperv;
newCell.N_Perv = cells[*it].N_Perv;
newCell.S_Imperv = cells[*it].S_Imperv;
newCell.S_Perv = cells[*it].S_Perv;
newCell.PctZero = cells[*it].PctZero;
newCell.RouteTo = cells[*it].RouteTo;
newCell.PctRouted = cells[*it].PctRouted;
newCell.Suction = cells[*it].Suction;
newCell.HydCon = cells[*it].HydCon;
newCell.IMDmax = cells[*it].IMDmax;
newCell.isSink = cells[*it].isSink;
newCell.tag = cells[*it].tag;
newCell.hasInlet = 1;
newCell.numElements++;
std::stringstream subcatchmentName("");
subcatchmentName << "s" << subcatchmentID + 1;
newCell.name = subcatchmentName.str();
cellsAdaptive.push_back(newCell);
// ... and update the lookup table of subcatchments and their indexes.
adapID[subcatchmentID] = cellsAdaptive.size()-1;
// Iterate through neighbouring roof cells and add cells connected to same junction
int counter = 0; // Failsafe to prevent infinite while loop
while (!selection_IDs.empty() && counter < nCols*nRows)
{
std::vector<int> neighCells = cells[selection_IDs.front()].neighCellIndices;
// Go through the neighbour cells routed into the same junction
for (int k = 0; k < (int) neighCells.size(); k++)
{
if (neighCells[k] != -1
&&
cells[neighCells[k]].landuse >= ROOF_CONNECTED && cells[neighCells[k]].landuse < ROOF_UNCONNECTED // Neighbouring cell is connected roof
&&
cells[neighCells[k]].outletID == cells[selection_IDs.front()].outletID // Neighbouring cell is connected to same junction
)
{
// Add cell to selected cells if it is not there or in final cells yet
if (!(std::find(selection_IDs.begin(), selection_IDs.end(), neighCells[k]) != selection_IDs.end())
&&
!(std::find(final_IDs.begin(), final_IDs.end(), neighCells[k]) != final_IDs.end()))
{
selection_IDs.push_back(neighCells[k]);
}
// Add cell to final cells if it is not there yet
if (!(std::find(final_IDs.begin(), final_IDs.end(), neighCells[k]) != final_IDs.end()))
{
final_IDs.push_back(neighCells[k]);
// Update subcatchmentID of current cell ...
cells[neighCells[k]].subcatchmentID = cells[selection_IDs.front()].subcatchmentID;
// ... and add current cell to existing subcatchment
int i = adapID[cells[selection_IDs.front()].subcatchmentID];
cellsAdaptive[i].area += cells[neighCells[k]].area;
cellsAdaptive[i].centerCoordX += cells[neighCells[k]].centerCoordX;
cellsAdaptive[i].centerCoordY += cells[neighCells[k]].centerCoordY;
cellsAdaptive[i].elevation += cells[neighCells[k]].elevation;
cellsAdaptive[i].slope += cells[neighCells[k]].slope;
cellsAdaptive[i].numElements++;
}
}
}
// Remove the cell ID from the list of selected ID's
selection_IDs.erase(selection_IDs.begin());
counter++;
}
}
}
}
}
}
}
// Create and save a raster of adaptive grid for inspection before destroying the cells
std::cout << "\n-> Creating an output raster of adaptive grid for inspection";
saveRaster(path);
// Save grid extent before destroying the cells
double urcornerOld[2];
double llcornerOld[2];
urcornerOld[0] = urcorner[0];
urcornerOld[1] = urcorner[1];
llcornerOld[0] = llcorner[0];
llcornerOld[1] = llcorner[1];
clear();
nCols = (int)cellsAdaptive.size();
nRows = 1;
cells = new Cell[nRows * nCols];
// Copy grid extent after destroying the cells
urcorner[0] = urcornerOld[0];
urcorner[1] = urcornerOld[1];
llcorner[0] = llcornerOld[0];
llcorner[1] = llcornerOld[1];
// Compute adaptive subcatchment averages
for (int i = 0; i < nRows * nCols; i++ )
{
if (cellsAdaptive[i].numElements > 0)
{
cellsAdaptive[i].centerCoordX /= (double) cellsAdaptive[i].numElements;
cellsAdaptive[i].centerCoordY /= (double) cellsAdaptive[i].numElements;
cellsAdaptive[i].elevation /= (double) cellsAdaptive[i].numElements;
cellsAdaptive[i].slope /= (double) cellsAdaptive[i].numElements;
}
else
std::cout << "\nError: No cells in adaptive subcatchment " << i << "!";
}
// Transfer adaptive cell data to the pointer array.
for (int i = 0; i < nRows * nCols; i++ )
{
cells[i].name = cellsAdaptive[i].name;
cells[i].centerCoordX = cellsAdaptive[i].centerCoordX;
cells[i].centerCoordY = cellsAdaptive[i].centerCoordY;
cells[i].elevation = cellsAdaptive[i].elevation;
cells[i].cellSize = cellsAdaptive[i].cellSize;
cells[i].slope = cellsAdaptive[i].slope;
cells[i].area = cellsAdaptive[i].area;
cells[i].flowWidth = 0.7 * std::sqrt(cellsAdaptive[i].area); // Krebs et al. (2014). Journal of Hydrology.
cells[i].landuse = cellsAdaptive[i].landuse;
if (cellsAdaptive[i].hasInlet == 1) // Outlet is junction
{
cells[i].outletCoordX = cellsAdaptive[i].outletCoordX;
cells[i].outletCoordY = cellsAdaptive[i].outletCoordY;
}
else // outlet is another subcatchment
{
cells[i].outletCoordX = cellsAdaptive[cellsAdaptive[i].outletID].centerCoordX;
cells[i].outletCoordY = cellsAdaptive[cellsAdaptive[i].outletID].centerCoordY;
}
cells[i].outletID = cellsAdaptive[i].outletID;
cells[i].outlet = cellsAdaptive[i].outlet;
cells[i].raingage = cellsAdaptive[i].raingage;
cells[i].imperv = cellsAdaptive[i].imperv;
cells[i].snowPack = cellsAdaptive[i].snowPack;
cells[i].N_Imperv = cellsAdaptive[i].N_Imperv;
cells[i].N_Perv = cellsAdaptive[i].N_Perv;
cells[i].S_Imperv = cellsAdaptive[i].S_Imperv;
cells[i].S_Perv = cellsAdaptive[i].S_Perv;
cells[i].PctZero = cellsAdaptive[i].PctZero;
cells[i].RouteTo = cellsAdaptive[i].RouteTo;
cells[i].PctRouted = cellsAdaptive[i].PctRouted;
cells[i].Suction = cellsAdaptive[i].Suction;
cells[i].HydCon = cellsAdaptive[i].HydCon;
cells[i].IMDmax = cellsAdaptive[i].IMDmax;
cells[i].isSink = cellsAdaptive[i].isSink;
cells[i].tag = cellsAdaptive[i].tag;
}
}
void Grid::saveRaster(std::string path)
{
path += ".asc";
Raster outputRaster;
outputRaster.pathName = path;
outputRaster.nCols = nCols;
outputRaster.nRows = nRows;
outputRaster.xllCorner = xllCorner;
outputRaster.yllCorner = yllCorner;
outputRaster.cellSize = cellSize;
std::string noValue = "-1";
outputRaster.noDataValue = noValue;
outputRaster.data = new std::string[outputRaster.nCols * outputRaster.nRows];
for (int j = 0; j < outputRaster.nRows; j++)
{
for (int i = 0; i < outputRaster.nCols; i++)
{
std::stringstream sstream;
// sstream << std::fixed;
// sstream.precision(8);
if (cells[ i + j * nCols ].landuse != LANDUSE_NONE)
{
sstream << cells[ i + j * nCols ].subcatchmentID + 1;
}
else
{
sstream << noValue.c_str();
}
int flippedIndex = outputRaster.nRows - 1 - j;
outputRaster.data[ i + flippedIndex * outputRaster.nCols ] = sstream.str();
}
}
outputRaster.save( outputRaster.pathName );
}
int Grid::saveSubcatchmentPolygon(std::string path)
{
std::stringstream sstream;
std::stringstream sstream_csvt;
sstream << std::fixed;
sstream << "id;";
sstream << "wkt;"; // Polygon defining the shape of the subcatchment
sstream << "name;"; // Name of the subcatchment
sstream << "outlet;"; // Name of node or another subcatchment that receives runoff
sstream << "area_m2;"; // Area of subcatchment (m2)
sstream << "slope_pct;"; // Average surface slope (%)
sstream << "elevation;"; // Elevation of the subcatchment
sstream << "landuse;"; // Code for landuse type
sstream << "imp_pct;"; // Percent of impervious area (%)
sstream << "n_imp;"; // Mannings N for impervious area (-)
sstream << "n_per;"; // Mannings N for pervious area (-)
sstream << "S_imp_mm;"; // Depth of depression storage on impervious area (mm)
sstream << "S_per_mm;"; // Depth of depression storage on pervious area (mm)
sstream << "suct_mm;"; // Soil capillary suction head (mm)
sstream << "Ksat_mmhr;"; // Soil saturated hydraulic conductivity (mm/hr)
sstream << "IMDmax;"; // Difference between soil porosity and initial moisture content (a fraction)
sstream << "isSink;"; // Cell is a local sink
sstream << "Tag"; // Optional tag sepcifying e.g. cell landuse in string format
// Create a .csvt file defining the field types of the .wkt file for ogr2ogr conversion to shapefile
sstream_csvt << "Integer,";
sstream_csvt << "WKT,";
sstream_csvt << "String,";
sstream_csvt << "String,";
sstream_csvt << "Real,";
sstream_csvt << "Real,";
sstream_csvt << "Real,";
sstream_csvt << "Real,";
sstream_csvt << "Real,";
sstream_csvt << "Real,";
sstream_csvt << "Real,";
sstream_csvt << "Real,";
sstream_csvt << "Real,";
sstream_csvt << "Real,";
sstream_csvt << "Real,";
sstream_csvt << "Real,";
sstream_csvt << "Integer,";
sstream_csvt << "String";
// Write polygon vertex coordinates.
int polyId = 1;
for (int i = 0; i < nRows * nCols; i++)
{
if (cells[i].landuse != LANDUSE_NONE)
{
sstream << "\n" << polyId << ";POLYGON((";
sstream.precision(2);
sstream << std::fixed << cells[i].centerCoordX - 0.5 * cells[i].cellSize << " ";
sstream << std::fixed << cells[i].centerCoordY + 0.5 * cells[i].cellSize;
sstream << ",";
sstream << std::fixed << cells[i].centerCoordX - 0.5 * cells[i].cellSize << " ";
sstream << std::fixed << cells[i].centerCoordY - 0.5 * cells[i].cellSize;
sstream << ",";
sstream << std::fixed << cells[i].centerCoordX + 0.5 * cells[i].cellSize << " ";
sstream << std::fixed << cells[i].centerCoordY - 0.5 * cells[i].cellSize;
sstream << ",";
sstream << std::fixed << cells[i].centerCoordX + 0.5 * cells[i].cellSize << " ";
sstream << std::fixed << cells[i].centerCoordY + 0.5 * cells[i].cellSize;
sstream << ",";
sstream << std::fixed << cells[i].centerCoordX - 0.5 * cells[i].cellSize << " ";
sstream << std::fixed << cells[i].centerCoordY + 0.5 * cells[i].cellSize;
sstream << "));" << cells[i].name;
sstream << ";" << cells[i].outlet;
sstream.precision(5);
sstream << ";" << cells[i].area;
sstream << ";" << cells[i].slope * 100.0; // convert fraction to percentage * 100.0
sstream << ";" << cells[i].elevation;
sstream << ";" << cells[i].landuse;
sstream << ";" << cells[i].imperv;
sstream.precision(3);
sstream << ";" << cells[i].N_Imperv;
sstream << ";" << cells[i].N_Perv;
sstream.precision(2);
sstream << ";" << cells[i].S_Imperv;
sstream << ";" << cells[i].S_Perv;
sstream << ";" << cells[i].Suction;
sstream << ";" << cells[i].HydCon;
sstream << ";" << cells[i].IMDmax;
sstream << ";" << cells[i].isSink;
sstream << ";" << cells[i].tag;
polyId++;
}
}
// Write files to disk.
FileIO fileio;
std::string path_csvt = path + ".csvt";
path += ".wkt";
int res = fileio.saveAsciiFile( path, sstream.str() );
res = std::min(res, fileio.saveAsciiFile( path_csvt, sstream_csvt.str() ));
return res;
}
void Grid::saveSubcatchmentRouting(std::string path, std::vector<int> cellIDs)
{
std::stringstream sstream;
std::stringstream sstream_csvt;
sstream << std::fixed;
sstream << "id;";
sstream << "wkt;"; // Line object defining the route between "from" and "to" subcatchments
sstream << "from;"; // Name of the origin subcatchment
sstream << "to"; // Name of the target subcatchment
// Create a .csvt file defining the field types of the .wkt file for ogr2ogr conversion to shapefile
sstream_csvt << "Integer,";
sstream_csvt << "WKT,";
sstream_csvt << "String,";
sstream_csvt << "String,";
// Write polygon vertex coordinates.
int lineId = 1;
for (auto i : cellIDs)
{
if (cells[i].landuse != LANDUSE_NONE)
{
sstream << "\n" << lineId << ";LINESTRING(";
sstream.precision(2);
sstream << std::fixed << cells[i].centerCoordX << " ";
sstream << std::fixed << cells[i].centerCoordY;
sstream << ",";
sstream << std::fixed << cells[i].outletCoordX << " ";
sstream << std::fixed << cells[i].outletCoordY;
sstream << ");" << cells[i].name;
sstream << ";" << cells[i].outlet;
lineId++;
}
}
// Write files to disk.
FileIO fileio;
std::string path_csvt = path + ".csvt";
path += ".wkt";
int res = fileio.saveAsciiFile( path, sstream.str() );
res = fileio.saveAsciiFile( path_csvt, sstream_csvt.str() );
}
void Grid::saveSubcatchmentRouting(std::string path)
{
std::vector<int> ind(nCols*nRows);
std::iota (std::begin(ind), std::end(ind), 0); // Fill with 0, 1, ..., (nCols*nROws-1)
saveSubcatchmentRouting(path, ind);
}
void Grid::saveNetworkRouting(std::string path, Table &condTable)
{
std::stringstream sstream;
std::stringstream sstream_csvt;
sstream << std::fixed;
sstream << "id;";
sstream << "wkt;"; // Line object defining the route between "from" and "to" junctions
sstream << "name;"; // Name of the conduit
sstream << "from;"; // Name of the origin junction
sstream << "to"; // Name of the target junction
// Create a .csvt file defining the field types of the .wkt file for ogr2ogr conversion to shapefile
sstream_csvt << "Integer,";
sstream_csvt << "WKT,";
sstream_csvt << "String,";
sstream_csvt << "String,";
sstream_csvt << "String,";
// Write polyline vertex coordinates.
int lineId = 0;
for (int i = 1; i < condTable.nRows; i++)
{
sstream << "\n" << lineId << ";LINESTRING(";
sstream.precision(2);
sstream << std::fixed << condTable.getData(i, 0) << " ";
sstream << std::fixed << condTable.getData(i, 1);
sstream << ",";
sstream << std::fixed << condTable.getData(i, 2) << " ";
sstream << std::fixed << condTable.getData(i, 3);
sstream << ");" << condTable.getData(i, 4);
sstream << ";" << condTable.getData(i, 8);
sstream << ";" << condTable.getData(i, 9);
lineId++;
}
// Write files to disk.
FileIO fileio;
std::string path_csvt = path + "_network_routing.csvt";
path += "_network_routing.wkt";
int res = fileio.saveAsciiFile( path, sstream.str() );
res = fileio.saveAsciiFile( path_csvt, sstream_csvt.str() );
}
void Grid::saveSWMM5File(Table &headerTable, Table &catchPropTable, Table &evaporationTable, Table &temperatureTable,
Table &inflowsTable, Table ×eriesTable, Table &reportTable, Table &snowpacksTable,
Table &raingagesTable, Table &symbolsTable, Table &juncTable, Table &outfallsTable,
Table &condTable, Table &pumpsTable, Table &pumpCurvesTable, Table &dwfTable, Table &patternsTable,
Table &lossesTable, Table &storageTable, Table &xsectionTable, std::string path)
{
std::stringstream sstream;
sstream << std::fixed;
// If the output file is a PEST template file, write an identifier (ptf #) into the begining of the file
if (path.substr ((int)path.length() - 3, 3) == "TPL")
{
std::cout << "\n-> test print: " << path.substr ((int)path.length() - 3, 3);
sstream << "ptf #\n";
}
// Write the header table.
std::cout << "\n-> Writing header table";
sstream << "[TITLE]";
sstream << "\n;;Project Title/Notes";
sstream << "\n;;Generated with the GisToSWMM5 program";
sstream << "\n";
sstream << "\n[OPTIONS]";
sstream << "\n;Option Value";
headerTable.writeToStringStream(sstream);
sstream << "\n";
// Write the evaporation table.
std::cout << "\n-> Writing evaporation table";
sstream << "\n[EVAPORATION]";
sstream << "\n;;Evap Data Parameters";
sstream << "\n;;-------------- ----------------";
evaporationTable.writeToStringStream(sstream);
sstream << "\n";
// Write the temperature table.
std::cout << "\n-> Writing temperature table";
sstream << "\n[TEMPERATURE]";
sstream << "\n;;Temp/Wind/Snow Source/Data";
temperatureTable.writeToStringStream(sstream);
sstream << "\n";
// Write raingage properties.
std::cout << "\n-> Writing raingages";
sstream << "\n[RAINGAGES]";
sstream << "\n;;Gage Format Interval SCF Source";
sstream << "\n;;-------------- --------- ------ ------ ----------";
raingagesTable.writeToStringStream(sstream);
sstream << "\n";
// Write subcatchment properties.
std::cout << "\n-> Writing subcatchment properties";
sstream << "\n[SUBCATCHMENTS]";
sstream << "\n;;Subcatchment Rain Gage Outlet Area %Imperv Width %Slope CurbLen Snow Pack ";
sstream << "\n;;-------------- ---------------- ---------------- -------- -------- -------- -------- -------- ----------------";
for (int i = 0; i < nRows * nCols; i++)
{
if (cells[i].landuse != LANDUSE_NONE)
{
sstream << "\n;" << cells[i].landuse;
sstream << "\n" << cells[i].name << " ";
sstream << cells[i].raingage << " ";
sstream << cells[i].outlet << " ";
sstream.precision(5);
sstream << cells[i].area / 10000.0 << " "; // convert m2 to ha
sstream.precision(2);
sstream << cells[i].imperv << " ";
sstream << cells[i].flowWidth << " ";
sstream.precision(4);
sstream << cells[i].slope * 100.0 << " "; // convert fraction to percentage * 100.0
sstream.precision(2);
sstream << cells[i].cellSize << " ";
sstream << cells[i].snowPack << " ";
}
}
sstream << "\n";
// Write subarea properties.
std::cout << "\n-> Writing subarea properties";
sstream << "\n[SUBAREAS]";
sstream << "\n;;Subcatchment N-Imperv N-Perv S-Imperv S-Perv PctZero RouteTo PctRouted ";
sstream << "\n;;-------------- ---------- ---------- ---------- ---------- ---------- ---------- ----------";
for (int i = 0; i < nRows * nCols; i++)
{
if (cells[i].landuse != LANDUSE_NONE)
{
sstream << "\n" << cells[i].name << " ";
//sstream.precision(3);
sstream << cells[i].N_Imperv << " ";
sstream << cells[i].N_Perv << " ";
//sstream.precision(2);
sstream << cells[i].S_Imperv << " ";
sstream << cells[i].S_Perv << " ";
sstream << cells[i].PctZero << " ";
sstream << cells[i].RouteTo << " ";
sstream << cells[i].PctRouted << " ";
}
}
sstream << "\n";
// Write infiltration properties.
std::cout << "\n-> Writing infiltration properties";
sstream << "\n[INFILTRATION]";
sstream << "\n;;Subcatchment Suction HydCon IMDmax ";
sstream << "\n;;-------------- ---------- ---------- ----------";
for (int i = 0; i < nRows * nCols; i++)
{
if (cells[i].landuse != LANDUSE_NONE)
{
sstream << "\n" << cells[i].name << " ";
//sstream.precision(2);
sstream << cells[i].Suction << " ";
//sstream.precision(4);
sstream << cells[i].HydCon << " ";
//sstream.precision(2);
sstream << cells[i].IMDmax << " ";
}
}
sstream << "\n";
// Write the snowpacks table.
std::cout << "\n-> Writing snowpacks table";
sstream << "\n[SNOWPACKS]";
sstream << "\n;;Name Surface Parameters";
sstream << "\n;;-------------- ---------- ----------";
snowpacksTable.writeToStringStream(sstream);
sstream << "\n";
// Write junction properties.
std::cout << "\n-> Writing junction properties";
sstream << "\n[JUNCTIONS]";
sstream << "\n;;Junction Invert MaxDepth InitDepth SurDepth Aponded ";
sstream << "\n;;-------------- ---------- ---------- ---------- ---------- ----------";
for (int i = 1; i < juncTable.nRows; i++)
{
sstream << "\n" << juncTable.getData(i, 2) << " "; // Junction name
sstream << juncTable.getData(i, 4) << " "; // Invert elevation
sstream << juncTable.getData(i, 5) << " "; // Max depth
sstream << juncTable.getData(i, 7) << " "; // Initial depth
sstream << juncTable.getData(i, 8) << " "; // Surcharge dept
sstream << juncTable.getData(i, 9) << " "; // Ponded area
}
sstream << "\n";
// Write outfall properties.
std::cout << "\n-> Writing outfalls properties";
sstream << "\n[OUTFALLS]";
sstream << "\n;;Outfall Invert Type Stage Data Gated ";
sstream << "\n;;-------------- ---------- ---------- ---------------- --------";
for (int i = 1; i < outfallsTable.nRows; i++)
{
sstream << "\n" << outfallsTable.data[i * outfallsTable.nCols + 2] << " "; // Outfall name
sstream << outfallsTable.data[i * outfallsTable.nCols + 3] << " "; // Invert height
sstream << outfallsTable.data[i * outfallsTable.nCols + 4] << " "; // Type
sstream << outfallsTable.data[i * outfallsTable.nCols + 5] << " "; // Stage data
sstream << outfallsTable.data[i * outfallsTable.nCols + 6] << " "; // Gated
}
sstream << "\n";
// Write storage properties.
// TODO: This is outdated formatting and needs to be updated
std::cout << "\n-> Writing storage properties";
sstream << "\n[STORAGE]";
sstream << "\n;;Name Elev. MaxDepth InitDepth Shape Curve Name/Params Fevap Psi Ksat IMD ";
sstream << "\n;;-------------- -------- ---------- ----------- ---------- ---------------------------- -------- -------- -------- --------";
for (int i = 1; i < storageTable.nRows; i++)
{
sstream << "\n" << storageTable.getData(i, 2) << " ";
sstream << storageTable.getData(i, 3) << " ";
sstream << storageTable.getData(i, 4) << " ";
sstream << storageTable.getData(i, 5) << " ";
sstream << storageTable.getData(i, 6) << " ";
sstream << storageTable.getData(i, 7) << " ";
sstream << storageTable.getData(i, 8) << " ";
}
sstream << "\n";
// Write conduits properties.
std::cout << "\n-> Writing conduits properties";
sstream << "\n[CONDUITS]";
sstream << "\n;;Conduit From Node To Node Length Roughness InOffset OutOffset InitFlow MaxFlow ";
sstream << "\n;;-------------- ---------------- ---------------- ---------- ---------- ---------- ---------- ---------- ----------";
for (int i = 1; i < condTable.nRows; i++)
{
sstream << "\n" << condTable.data[i * condTable.nCols + 4] << " "; // Conduit name
sstream << condTable.data[i * condTable.nCols + 8] << " "; // From node
sstream << condTable.data[i * condTable.nCols + 9] << " "; // To node
sstream << condTable.data[i * condTable.nCols + 7] << " "; // Length
sstream << condTable.data[i * condTable.nCols + 10] << " "; // roughness
sstream << condTable.data[i * condTable.nCols + 11] << " "; // InOffset
sstream << condTable.data[i * condTable.nCols + 12] << " "; // OutOffset
sstream << 0.0 << " "; // InitFlow
sstream << 0.0 << " "; // MaxFlow
}
sstream << "\n";
// Write pump properties.
std::cout << "\n-> Writing pumps";
sstream << "\n[PUMPS]";
sstream << "\n;;Name From node To node Pump curve Status Startup Shutoff";
sstream << "\n;;------ ------ ------ ------ ------ ------ ------";
pumpsTable.writeToStringStream(sstream);
sstream << "\n";
// Write conduit cross section properties.
std::cout << "\n-> Writing conduit cross section properties";
sstream << "\n[XSECTIONS]";
sstream << "\n;;Link Shape Geom1 Geom2 Geom3 Geom4 Barrels Culvert ";
sstream << "\n;;-------------- ------------ ---------------- ---------- ---------- ---------- ---------- ----------";
xsectionTable.writeToStringStream(sstream);
sstream << "\n";
// Write losses table.
std::cout << "\n-> Writing losses table";
sstream << "\n[LOSSES]";
sstream << "\n;;Link Kentry Kexit Kavg Flap Gate Seepage ";
sstream << "\n;;-------------- ---------- ---------- ---------- ---------- ----------";
lossesTable.writeToStringStream(sstream);
sstream << "\n";
// Write pump curve properties.
std::cout << "\n-> Writing pump curves";
sstream << "\n[CURVES]";
sstream << "\n;;Name Type X-value Y-value";
sstream << "\n;;------ ------ ------ ------";
pumpCurvesTable.writeToStringStream(sstream);
sstream << "\n";
// Write inflows table.
std::cout << "\n-> Writing inflows table";
sstream << "\n[INFLOWS]";
sstream << "\n;;Node Constituent Time Series Type Mfactor Sfactor Baseline Pattern";
sstream << "\n;;-------------- ---------------- ---------------- -------- -------- -------- -------- --------";
inflowsTable.writeToStringStream(sstream);
sstream << "\n";
// Write time series table.
std::cout << "\n-> Writing time series table";
sstream << "\n[TIMESERIES]";
sstream << "\n;;Name Date Time Value";
sstream << "\n;;-------------- ---------- ---------- ----------";
timeseriesTable.writeToStringStream(sstream);
sstream << "\n";
// Write dry weather flow table.
std::cout << "\n-> Writing dry weather flow table";
sstream << "\n[DWF]";
sstream << "\n;;Node Constituent Baseline Patterns ";
sstream << "\n;;-------------- ---------------- ---------- ----------";
dwfTable.writeToStringStream(sstream);
sstream << "\n";
// Write patterns table.
std::cout << "\n-> Writing patterns table";
sstream << "\n[PATTERNS]";
sstream << "\n;;Name Type Multipliers";
sstream << "\n;;-------------- ---------- -----------";
patternsTable.writeToStringStream(sstream);
sstream << "\n";
// Write reporting settings.
std::cout << "\n-> Writing reporting settings";
sstream << "\n[REPORT]";
sstream << "\n;;Reporting Options";
reportTable.writeToStringStream(sstream);
sstream << "\n";
// Write tags.
sstream << "\n[TAGS]";
if (catchPropTable.nCols > 12)
{
for (int i = 0; i < nRows * nCols; i++)
{
if (cells[i].landuse != LANDUSE_NONE)
{
sstream << "\nSubcatch " << cells[i].name ;
sstream << " " << cells[i].tag;
}
}
}
sstream << "\n";
// Write map settings.
std::cout << "\n-> Writing map settings";
sstream << "\n[MAP]";
sstream << "\nDIMENSIONS ";
sstream.precision(2);
sstream << llcorner[0] * 0.99999 << " ";
sstream << llcorner[1] * 0.99999 << " ";
sstream << urcorner[0] * 1.00001 << " ";
sstream << urcorner[1] * 1.00001;
sstream << "\nUnits Meters";
sstream << "\n";
// Write node coordinates.
std::cout << "\n-> Writing node coordinates";
sstream << "\n[COORDINATES]";
sstream << "\n;;Node X-Coord Y-Coord ";
sstream << "\n;;-------------- ------------------ ------------------";
for (int i = 1; i < juncTable.nRows; i++)
{
sstream << "\n" << juncTable.data[i * juncTable.nCols + 2] << " ";
sstream << juncTable.data[i * juncTable.nCols + 0] << " ";
sstream << juncTable.data[i * juncTable.nCols + 1] << " ";
}
for (int i = 1; i < outfallsTable.nRows; i++)
{
sstream << "\n" << outfallsTable.data[i * outfallsTable.nCols + 2] << " ";
sstream << outfallsTable.data[i * outfallsTable.nCols] << " ";
sstream << outfallsTable.data[i * outfallsTable.nCols + 1] << " ";
}
for (int i = 1; i < storageTable.nRows; i++)
{
sstream << "\n" << storageTable.getData(i, 2) << " ";
sstream << storageTable.getData(i, 0) << " ";
sstream << storageTable.getData(i, 1) << " ";
}
sstream << "\n";
sstream << "\n[VERTICES]";
sstream << "\n;;Link X-Coord Y-Coord ";
sstream << "\n;;-------------- ------------------ ------------------";
sstream << "\n";
// Write polygon vertex coordinates.
std::cout << "\n-> Writing polygon vertex coordinates";
sstream << "\n[Polygons]";
sstream << "\n;;Subcatchment X-Coord Y-Coord ";
sstream << "\n;;-------------- ------------------ ------------------";
for (int i = 0; i < nRows * nCols; i++)
{
if (cells[i].landuse != LANDUSE_NONE)
{
sstream.precision(2);
sstream << "\n" << cells[i].name << " ";
sstream << std::fixed << cells[i].centerCoordX - 0.5 * cells[i].cellSize << " ";
sstream << std::fixed << cells[i].centerCoordY + 0.5 * cells[i].cellSize;
sstream << "\n" << cells[i].name << " ";
sstream << std::fixed << cells[i].centerCoordX - 0.5 * cells[i].cellSize << " ";
sstream << std::fixed << cells[i].centerCoordY - 0.5 * cells[i].cellSize;
sstream << "\n" << cells[i].name << " ";
sstream << std::fixed << cells[i].centerCoordX + 0.5 * cells[i].cellSize << " ";
sstream << std::fixed << cells[i].centerCoordY - 0.5 * cells[i].cellSize;
sstream << "\n" << cells[i].name << " ";
sstream << std::fixed << cells[i].centerCoordX + 0.5 * cells[i].cellSize << " ";
sstream << std::fixed << cells[i].centerCoordY + 0.5 * cells[i].cellSize;
sstream << "\n" << cells[i].name << " ";
sstream << std::fixed << cells[i].centerCoordX - 0.5 * cells[i].cellSize << " ";
sstream << std::fixed << cells[i].centerCoordY + 0.5 * cells[i].cellSize;
}
}
sstream << "\n";
// Write symbols.
std::cout << "\n-> Writing symbols";
sstream << "\n[SYMBOLS]";
sstream << "\n;;Gage X-Coord Y-Coord";
sstream << "\n;;-------------- ------------------ ------------------";
symbolsTable.writeToStringStream(sstream);
sstream << "\n";
sstream << "\n";
// Write the file to disk.
std::cout << "\n-> Writing the file to disk";
FileIO fileio;
path += ".inp";
int res = fileio.saveAsciiFile( path, sstream.str() );
}
void Grid::printReport(Table &catchPropTable, std::vector<int> routedIDs)
{
double elevationAverage = 0.0;
double slopeAverage = 0.0;
int numOfLandUseClasses = catchPropTable.nRows - 1;
if (numOfLandUseClasses < 0)
{
numOfLandUseClasses = 0;
}
std::vector<int> cellsInlandUseClass;
cellsInlandUseClass.assign(numOfLandUseClasses, 0);
std::vector<int> landUseClassIds;
landUseClassIds.assign(numOfLandUseClasses, 0);
std::vector<double> areasInlandUseClass;
areasInlandUseClass.assign(numOfLandUseClasses, 0.0);
for (int i = 0; i < (int)landUseClassIds.size(); i++)
{
landUseClassIds[i] = atoi(catchPropTable.data[(i + 1) * catchPropTable.nCols].c_str());
}
int numOfActiveCells = 0;
double areaOfActiveCellsNoRoofs = 0.0;
for (auto i : routedIDs)
{
if (cells[i].landuse != LANDUSE_NONE)
{
numOfActiveCells += 1;
// Don't use roofs and noData areas for catchment mean slope and elevation calculations
if ((cells[i].landuse >= BUILT_AREA) && cells[i].elevation > cells[i].elevNoData)
{
elevationAverage += cells[i].elevation * cells[i].area;
slopeAverage += cells[i].slope * cells[i].area;
areaOfActiveCellsNoRoofs += cells[i].area;
}
for (int j = 0; j < (int)landUseClassIds.size(); j++)
{
if (landUseClassIds[j] == cells[i].landuse)
{
cellsInlandUseClass[j] += 1;
areasInlandUseClass[j] += cells[i].area;
break;
}
}
}
}
double area = 0.0;
for (int i = 0; i < numOfLandUseClasses; i++)
{
area += areasInlandUseClass[i];
}
if (areaOfActiveCellsNoRoofs > 0.0)
{
elevationAverage /= areaOfActiveCellsNoRoofs;
slopeAverage /= areaOfActiveCellsNoRoofs;
}
std::cout << "\n-> Total number of cells: " << nCols * nRows;
std::cout << "\n-> Number of active cells: " << numOfActiveCells;
std::cout << "\n-> Catchment area: " << area / 10000.0 << " ha";
std::cout << "\n-> Catchment average elevation: " << elevationAverage << " m";
std::cout << "\n-> Catchment average slope: " << slopeAverage;
std::cout << "\n-> Landuse information (code, number of cells, area in ha, % of catchment):";
for (int i = 0; i < (int)cellsInlandUseClass.size(); i++)
{
std::cout << "\n"
<< "\t" << landUseClassIds[i]
<< "\t" << cellsInlandUseClass[i]
<< "\t" << areasInlandUseClass[i] / 10000.0
<< "\t" << areasInlandUseClass[i] / area * 100.0;
}
}
void Grid::printReport(Table &catchPropTable)
{
std::vector<int> ind(nCols*nRows);
std::iota (std::begin(ind), std::end(ind), 0); // Fill with 0, 1, ..., (nCols*nROws-1)
printReport(catchPropTable, ind);
}
| true |
50ad3289fc163c128ac4ca681527bd1d5ce00e4f | C++ | SammyEnigma/tp_utils | /inc/tp_utils/Progress.h | UTF-8 | 5,588 | 2.796875 | 3 | [
"MIT"
] | permissive | #ifndef tp_utils_Progress_h
#define tp_utils_Progress_h
#include "tp_utils/CallbackCollection.h"
namespace tp_utils
{
class AbstractCrossThreadCallbackFactory;
//##################################################################################################
struct ProgressMessage
{
std::string message;
bool error{false};
size_t indentation{0};
ProgressMessage() = default;
ProgressMessage(const std::string& message_, bool error_, size_t indentation_):
message(message_),
error(error_),
indentation(indentation_)
{
}
};
//##################################################################################################
//! A class for recording the progress of an operation.
/*!
*/
class TP_UTILS_SHARED_EXPORT Progress
{
public:
//################################################################################################
//! Thread safe constructor.
Progress(AbstractCrossThreadCallbackFactory* crossThreadCallbackFactory);
//################################################################################################
//! Blocking operation constructor.
Progress(const std::function<bool()>& poll);
//################################################################################################
//! Child step constructor.
Progress(Progress* parent);
//################################################################################################
virtual ~Progress();
//################################################################################################
void setPrintToConsole(bool printToConsole);
//################################################################################################
//! Set the progress
/*!
\param fraction of the way through this task (0 to 1)
*/
void setProgress(float fraction);
//################################################################################################
//! Set the progress and the description of what is being processes
/*!
\param fraction of the way through this task (0 to 1)
*/
void setProgress(float fraction, const std::string& description);
//################################################################################################
//! Returns the current progress as a fraction
float progress() const;
//################################################################################################
//! Sets the description of the task that is being performed
/*!
This should be updated to describe what is happening at each stage of a process, this should be a
short string that will be hisplayed to the user.
\param description - The new description
*/
void setDescription(const std::string& description);
//################################################################################################
//! Returns the descripton of the current stage of the task.
std::string description() const;
//################################################################################################
/*!
\param description of the child step.
\param completeFraction the progress of this once the child step is complete.
\return A pointer to new Progress object, owned by this.
*/
Progress* addChildStep(const std::string& message, float completeFraction);
//################################################################################################
//! Log a message that will be kept in the tree of messages.
void addMessage(const std::string& message);
//################################################################################################
//! Log a message that will be kept in the tree of messages.
void addError(const std::string& error);
//################################################################################################
//! Return the tree of messages.
std::vector<ProgressMessage> allMessages() const;
//################################################################################################
//! Return the tree of error messages.
std::vector<ProgressMessage> errorMessages() const;
//################################################################################################
std::string compileErrors() const;
//################################################################################################
std::vector<Progress*> childSteps() const;
//################################################################################################
//! Returs true if this task should stop
bool shouldStop() const;
//################################################################################################
//! Use this to stop the task
void stop(bool shouldStop);
//################################################################################################
bool poll();
//################################################################################################
CallbackCollection<void()> changed;
protected:
//################################################################################################
void callChanged();
//################################################################################################
void getAllMessages(size_t indentation, std::vector<ProgressMessage>& messages) const;
//################################################################################################
bool getErrors(size_t indentation, std::vector<ProgressMessage>& messages) const;
private:
struct Private;
Private* d;
friend struct Private;
};
}
#endif
| true |
0ddacaea8a2afe7f5568d755a130384cf3cbb457 | C++ | aockie/03_Puzzle | /03_MyDobot/dobot_ws/src/dobot/src/DobotServer3.cpp | UTF-8 | 2,580 | 2.734375 | 3 | [] | no_license | //
#include "ros/ros.h"
#include "stdio.h"
#include "std_msgs/String.h"
#include "std_msgs/Float32MultiArray.h"
#include "DobotDll.h"
#include "time.h"
/****** まとめ ******/
//main関数が呼ばれる
//main関数は、InitPTPService関数を呼ぶ
//InitPTPService関数は、
//サーバノード作成
//サーバのインスタンス生成。同時に、コールバック関数として、SetPTPCmdService関数を登録する。
//SetPTPCmdService関数は、実際の処理内容を記載。APIの、SetPTP関数を呼ぶ。
/*--- test用xミリ秒経過するのを待つ ---*/
int sleepa(unsigned long x)
{
clock_t s = clock();
clock_t c;
do {
if ((c = clock()) == (clock_t)-1) /* エラー */
return (0);
} while (1000UL * (c - s) / CLOCKS_PER_SEC <= x);
return (1);
}
/****** サーバから呼ばれるコールバック関数:実際の処理 ******/
#include "dobot/SetPTPCmd.h"
//Requestと、Responseが引数
bool SetPTPCmdService(dobot::SetPTPCmd::Request &req, dobot::SetPTPCmd::Response &res)
{
int code;
PTPCmd cmd;
uint64_t queuedCmdIndex;
cmd.ptpMode = req.ptpMode;
cmd.x = req.x; //Request型から、PTPCmd型に値を移し替える?
cmd.y = req.y;
cmd.z = req.z;
cmd.r = req.r;
//APIのSetPTPCmdを呼ぶ。結果は
//res.result = SetPTPCmd(&cmd, true, &queuedCmdIndex);
//test用
code = sleepa(1000);
ROS_INFO_STREAM("Hello World!");
res.result = 0;
//SetPTPCmd
/*
uint8 ptpMode
float32 x
float32 y
float32 z
float32 r
---
int32 result
uint64 queuedCmdIndex
*/
return true;
}
/****** サーバ関数 ******/
void InitPTPServices(ros::NodeHandle &n, std::vector<ros::ServiceServer> &serverVec)
{
//サーバの(戻り値の?)型
ros::ServiceServer server;
//サーバインスタンス作成。名前:"/DobotServer/SetPTPCmd"。 コールバックする関数:SetPTPCmdSerVice
server = n.advertiseService("/DobotServer/SetPTPCmd", SetPTPCmdService);
//?
serverVec.push_back(server);
}
/****** main関数 ******/
int main(int argc, char **argv)
{
//ノード作成。名前は、"DobotServer"
ros::init(argc, argv, "DobotServer");
//ノードハンドラ。なにこれ?
ros::NodeHandle n;
//サーバー番号?
std::vector<ros::ServiceServer> serverVec;
//サーバープログラム実行
InitPTPServices(n, serverVec);
//終了するまでループ
ros::spin();
// Disconnect Dobot
DisconnectDobot();
return 0;
}
| true |
284d24184f98b1e90dbfcf689d18b4d8417e5a56 | C++ | danielgrigg/sandbox | /testing/bandit/example.cpp | UTF-8 | 1,530 | 3 | 3 | [
"WTFPL"
] | permissive | #include <bandit/bandit.h>
#include <memory>
#include <iostream>
using namespace bandit;
using namespace std;
struct fuzzbox {
void flip() { _flipped = true;}
bool _flipped = false;
};
enum class sounds {
clean,
distorted
};
struct guitar {
void add_effect(fuzzbox& f) { _effect = &f; }
sounds sound() { return _effect != nullptr && _effect->_flipped ? sounds::distorted : sounds::clean; }
fuzzbox* _effect;
};
typedef std::unique_ptr<guitar> guitar_ptr;
typedef std::unique_ptr<fuzzbox> fuzzbox_ptr;
// Tell bandit there are tests here.
go_bandit([](){
// We're describing how a fuzzbox works.
describe("fuzzbox:", [](){
guitar_ptr guitar;
fuzzbox_ptr fuzzbox;
// Make sure each test has a fresh setup with
// a guitar with a fuzzbox connected to it.
before_each([&](){
guitar = guitar_ptr(new struct guitar());
fuzzbox = fuzzbox_ptr(new struct fuzzbox());
guitar->add_effect(*fuzzbox);
});
it("starts in clean mode", [&](){
AssertThat(guitar->sound(), Equals(sounds::clean));
});
// Describe what happens when we turn on the fuzzbox.
describe("in distorted mode", [&](){
// Turn on the fuzzbox.
before_each([&](){
fuzzbox->flip();
});
it("sounds distorted", [&](){
AssertThat(guitar->sound(), Equals(sounds::distorted));
});
});
});
});
int main(int argc, char* argv[])
{
// Run the tests.
return bandit::run(argc, argv);
}
| true |
f4592953ca2de2275fb9b6451388b7786b9cb80c | C++ | PeekLeon/Somfy-Library | /Arduino/exemple-MySomfy/exemple-MySomfy.ino | UTF-8 | 1,420 | 2.609375 | 3 | [] | no_license | #include <MySomfy.h>
MySomfy MySomfy(A5); //Instanciation de MySomfy avec le port TX utilisé
int rcTelecommande[3] = {97, 42, 856};
int telecommande;
void setup() {
Serial.begin(9600);
MySomfy.telecommande(0xBC, 0xDB, 0xCD);
pinMode(4, OUTPUT);
}
void loop() {
}
//*
void serialEvent() {
if(Serial.available()){
String entreeSerie = Serial.readString();
String commande = entreeSerie.substring(0,3);
String valeur = entreeSerie.substring(3);
if(commande == "tel"){
cfgTel(valeur.toInt());
}
if(commande == "act"){
digitalWrite(4, HIGH);
char retvaleur = valeur[0];
rcTelecommande[telecommande]++;
MySomfy.action(retvaleur, rcTelecommande[telecommande]);
digitalWrite(4, LOW);
}
if(commande == "lst"){
menu();
}
}
}
void menu(){
Serial.println("1 - Couloir");
Serial.println("2 - Chambre 1");
Serial.println("3 - Chambre 2");
}
void cfgTel(int valeur){
switch (valeur) {
case 1:
MySomfy.telecommande(0xBC, 0xDB, 0x01);
telecommande = valeur;
break;
case 2:
MySomfy.telecommande(0xBC, 0xDB, 0x02);
telecommande = valeur;
break;
case 3:
MySomfy.telecommande(0xBC, 0xDB, 0x03);
telecommande = valeur;
break;
default :
Serial.println("Telecommande inexistante reportez vous aux menu ci-dessous : ");
menu();
break;
}
}
//*//
| true |
ad9988a36473eacb36f32c2be73ac7b9d9670478 | C++ | m80126colin/Judge | /since2020/CodeForces/1321A.cpp | UTF-8 | 586 | 2.921875 | 3 | [] | no_license | /**
* @judge CodeForces
* @id 1321A
* @name Contest for Robots
* @contest CodeForces Round #625 div.2
*
* @tag Ad-hoc, Math
*/
#include <iostream>
using namespace std;
#define MAX 110
int a[MAX], b[MAX];
int solve(int n) {
int A, B, C;
A = B = C = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 1)
A++;
if (b[i] == 1)
B++;
if (a[i] > b[i])
C++;
}
if (C == 0)
return -1;
return (B - A + C + C) / C;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < n; i++)
cin >> b[i];
cout << solve(n) << endl;
} | true |
6ed76832628f7fa627cf79a1988b9464ffb40cd6 | C++ | yurifariasg/yuris-adventure | /YurisAdventure/YurisAdventure/Player.h | UTF-8 | 3,210 | 2.65625 | 3 | [] | no_license | #pragma once
// PREPROCESSOR INCLUDE STATEMENTS
#include "stdafx.h"
#include "SSSF_SourceCode\gsm\physics\Physics.h"
#include "SSSF_SourceCode\game\Game.h"
#include "SSSF_SourceCode\gsm\sprite\AnimatedSprite.h"
#include "PlayerComboState.h"
#include "Creature.h"
#include "YAGame.h"
#include "ImageShower.h"
const int TIME_FOR_DEATH_ANIMATION = 300;
const int TIME_FOR_ATTACK_ANIMATION = 20;
const int TIME_FOR_COMBO_ANIMATION = 200;
const int BUFF_TIME = 1000;
const int INCREASE_DEFENSE_PERCENTAGE = 50;
const int ATTACK_COMBO_MANA = 40;
const int MAGIC_COMBO_MANA = 25;
const int DEFENSE_COMBO_MANA = 30;
const int MAGIC_ATTACK_MANA = 10;
/*
Class will hold properties for our Player
*/
class Player : public Creature, public AnimatedSprite
{
private:
PlayerComboState comboState;
AnimatedSprite* aura;
int actionTime;
int attackingTime;
bool isCharging;
bool isCasting;
bool isCrouched;
bool isPenetrationActive;
bool isTakingDamage;
int buffTimer;
int comboAnimationTimer;
ImageShower* comboImageShower;
// Update Player's Buff (Decrements time or Deactivate, if timed out)
void updateBuffs();
public:
// Creates a Player
Player(int hp, int mana, int attack);
// Process Player's Combo using the given pressed key
void processCombo(unsigned int pressedKey);
// Updates Player's Sprite
void updateSprite();
// Get Current ActionTime
int getActionTime() { return actionTime; }
// Sets players Animated Aura
void setAura(AnimatedSprite* as) { aura = as; }
// Verifies if the death animation is finished
bool getDeathAnimationFinished() { return attackingTime == 1 && isDead(); }
// Activate or Deactivate Taking Damage State
void setTakingDamage(bool isTaking) {
if (isTaking) actionTime = 100;
isTakingDamage = isTaking; }
// Verifies if the player is on the 'Taking Damage' state
bool getIsTakingDamage() { return isTakingDamage; }
// Activates Player's Crouch State
void crouch();
// Gets Player's current combo state
PlayerComboState getCurrentComboState() { return comboState; }
// Activates Charging State
void charges() { isCharging = true; }
// Stops Charging State
void stopCharging() { isCharging = false; }
// Verifies if the Player is doing some action
bool canDoSomething() { return !isDead() && !isCharging && !isAttacking() && !isCasting; }
// Verifies if the player is not charging
bool notCharging() { return !isCharging; }
// Verifies if magic penetration is active
bool getPenetrationIsActive() { return isPenetrationActive; }
// Verifies if has buff active
bool hasBuffActives() { return buffTimer != 0; }
// Sets a ImageShower, which will show Player's Combo Image
void setImageShower(ImageShower* i) { comboImageShower = i; }
// Activate a Casting Animation
void casts() {
attackingTime = 10;
isCasting = true;
}
// Reload all player data (resets)
void reloadData() {
actionTime = 0;
attackingTime = 0;
buffTimer = 0;
comboState = COMBO_NONE;
isCharging = false;
isCasting = false;
isPenetrationActive = false;
isTakingDamage = false;
Creature::resetData();
}
}; | true |
af9c3a70b80591503530308d6a0dfdea2105a5a4 | C++ | Muszek1996/METODY-NUMERYCZNE | /METODY NUMERYCZNE/Source.cpp | UTF-8 | 652 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include "Punkt.h"
#include "vector"
#include "LagrangeInterpolation.h"
#include "GetFromFile.h"
#include "NewtonianInterpolation.h"
int main()
{
std::vector<Punkt> points;
GetFromFile dane("dane.txt");
dane.fillPoints(points);
if (points.size() < 1)std::cout << "ERROR";
LagrangeInterpolation InterpolacjaLagrangea(points);
double val = InterpolacjaLagrangea.interpolationFunction(7);
NewtonianInterpolation InterpolacjaNewtona(points);
std::cout << InterpolacjaNewtona.valueOfX(1) << std::endl;
std::cout << InterpolacjaLagrangea.interpolationFunction(2) << std::endl;
getchar();
return 0;
}
| true |
98c2d669733c468654537dbbad8bd0ddc558b259 | C++ | WhiZTiM/coliru | /Archive2/ab/5b6c3066a42851/main.cpp | UTF-8 | 1,066 | 3.78125 | 4 | [] | no_license | #include <cstring>
#include <cstdlib>
#include <iostream>
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cout << "Usage: << " << argv[0] << " command\n";
exit(0);
}
size_t cmd_size = 0;
for (int i = 1; i != argc; ++i) {
// + 1 for separating spaces
cmd_size += strlen(argv[i]) + 1;
}
// create C string to hold the command to be executed
char* cmd = new char[cmd_size];
// index in the cmd C string to write to
size_t cmd_ndx = 0;
// copy argv[1] and all subsequent args to the cmd
for (int i = 1; i != argc; ++i) {
strcpy(&cmd[cmd_ndx], argv[i]);
const size_t len = strlen(argv[i]);
cmd_ndx += len;
// separate with spaces
cmd[cmd_ndx] = ' ';
++cmd_ndx;
}
// replace last space with null character
cmd[cmd_ndx - 1] = '\0';
std::cout << "The command is \"" << cmd << "\"\n";
int return_value = system(cmd);
delete[] cmd;
std::cout << "The returned value was " << return_value << "\n";
return 0;
} | true |
74d0750d579598b5240f4fee9d4b05d4d371b240 | C++ | FreeButter/Team-Project-GP | /Project 1/BasicGameTemplate/Parser.h | UTF-8 | 680 | 2.578125 | 3 | [] | no_license | /**
Simple Json Parser
Parser.h
Purpose: Manages Json Document objects
@author Miguel Saavedra
@version 1.1 3/10/16
*/
#ifndef __PARSER_H__
#define __PARSER_H__
#include <string>
#include "document.h"
#include "filereadstream.h"
#pragma warning (disable : 4996)
using namespace std;
using namespace rapidjson;
class Parser
{
//Member Methods:
public:
static Parser& GetInstance();
~Parser();
void loadInFile(string file);
protected:
private:
Parser();
Parser(const Parser& parser);
Parser& operator=(const Parser& parser);
//Member Data:
public:
Document document;
protected:
static Parser* sm_pInstance;
private:
};
#endif //__PARSER_H__
string readFile(string file); | true |
070d099e2c7f294113660e43ca40329aee9c50d0 | C++ | jpaterso/fire-engine | /src/WindowManagerWin32.h | UTF-8 | 4,386 | 2.734375 | 3 | [] | no_license | /**
* $Id: WindowManagerWin32.h 114 2007-10-04 04:57:03Z jpaterso $
* Author: Joseph Paterson
*
* The Win32 window manager.
**/
#ifndef __WINDOW_MANAGER_WIN32_H
#define __WINDOW_MANAGER_WIN32_H
#include <windows.h>
#include "CompileConfig.h"
#include "Types.h"
#include "dimension2.h"
#include "IWindowManager.h"
#include "HashTable.h"
#include "MouseEvent.h"
#include "Device.h"
#include "Object.h"
#include "KeyEvent.h"
namespace fire_engine
{
class String;
class IRenderer;
class _FIRE_ENGINE_API_ WindowManagerWin32 : public IWindowManager, public virtual Object
{
private:
/** Cursor control class for Win32 systems. */
class CursorWin32 : public ICursor
{
public:
/** Constructor. */
CursorWin32(WindowManagerWin32 * owner);
virtual ~CursorWin32();
virtual void setRelativePosition(const vector2f& newpos);
virtual vector2f getRelativePosition() const;
virtual void setCursorVisible(bool vis);
private:
WindowManagerWin32 * mOwner;
};
public:
/** Destructor. */
virtual ~WindowManagerWin32(void);
virtual void setTitle(const String& newTitle);
virtual void onResize(const dimension2i& newSize);
virtual bool run(void);
virtual void swapBuffers(void);
virtual void close(void);
virtual void toggleFullScreen();
virtual ICursor * getCursor();
//! Set whether the window is still running or not
void setRunning(bool r);
/**
* Create a singleton instance of the WindowManager
* This acts as a sort of Constructor.
* @param dType The driver to use. FE_OPENGL is
* currently supported
* @param rd The renderer currently being used
* @param wSize The size of the window to create
* @param title The default title of the window
* Note that all parameters are ignored when the m_instance field
* of the WindowManagerWin32 is already set.
**/
static IWindowManager * Create(EDRIVER_TYPE dType,
const dimension2i& wSize,
const String& title);
private:
HINSTANCE mHinstance; //! The instance of our program
WNDCLASSEX mHWndClass; //! Our window class
HWND mHwnd; //! The main window
PIXELFORMATDESCRIPTOR mPFD; //! The pixel format to use
HDC mHDC; //! The rendering context
#if defined(_FIRE_ENGINE_COMPILE_WITH_OPENGL_)
HGLRC mHGLRC; //! The OpenGL rendering context
#endif
MSG mMsg; //! Messages we read and transmit
static HashTable<s32, KeyEvent::EKEY_CODE> * mKeyCodeHT;
ICursor * mCursor;
DWORD mSavedExStyle, mSavedStyle;
RECT mOldSize;
//! Hash tables used to generate MouseEvents faster
static HashTable<UINT, MouseEvent::MouseButton> * m_msg_to_mbutton;
static HashTable<UINT, MouseEvent::MouseEventType> * m_msg_to_mevent_type;
static HashTable<UINT, s32> * m_msg_to_click_count;
/**
* Creates a window capable of rendering using a specified driver
* This function must be private to ensure only a single copy of the
* WindowManager.
* @param dType The driver to use. Only FE_OPENGL is
* currently supported.
* @param rd The renderer currently being used.
* @param wSize The size of the window to create.
* @param title The default title of the window.
**/
WindowManagerWin32(u32 dType,
const dimension2i& wSize,
const String& title);
/**
* Set the pixel format for the newly created window
**/
void setPixelFormat(void);
#if defined(_FIRE_ENGINE_COMPILE_WITH_OPENGL_)
//! Initialize the OpenGL context
void createOpenGLContext(void);
//! Release the OpenGL context
void releaseOpenGLContext(void);
#endif
/**
* Our callback function, it will be called automatically by Windows
**/
static LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);
//! Create a KeyEvent from a user keystroke
static KeyEvent fromKeyStroke(WPARAM wParam);
//! Create a mouse event
static MouseEvent fromMouse(UINT msg, WPARAM wParam, LPARAM lParam);
//! Initialize the hash table of virtual key codes
static void initKeyCodeHashTable(void);
static void initMouseHashTables(void);
/** Goes into full screen size, in native mode (no control over the resolution). */
void setFullScreen();
};
} // namespace fire_engine
#endif
| true |
e5b6feff0392aed22d2df1f49bef69a8c9950c6e | C++ | HolyHooly/Biseul-ReadingRoom-Reservation | /Biseul ReadingRoom Reservation/DBInterface.h | UTF-8 | 2,616 | 2.65625 | 3 | [] | no_license | #pragma once
#include "DBsystem.h"
namespace biseul_rroom {
class Exception {
public:
Exception() {};
~Exception() {};
void scenario(int code) {
switch (code) {
case (int)signal::DBREMOVEERR:
std::cout << "From DBsystem: From DBsystem: Despite of data existence remove error.try again" << std::endl;
return;
case (int)signal::DBCLOSEFAIL:
std::cout << "From DBsystem: close DBsystem::filename fail. May be memory leap occur" << std::endl;
return;
case (int)signal::DBOVERLAP:
std::cout << "From DBsystem: student data already exists" << std::endl;
return;
case (int)signal::DBPARAMETERERR:
std::cout << "From DBsystem: Recognize disallowed input. Acceptable input : name length <99, student id, rfid != 0 ,student id with 9 digit number , rfid id with 10 digit number." << std::endl;
return;
case (int)signal::DBMODIFYERR:
std::cout << "From DBsystem: Modify error. try again" << std::endl;
return;
case (int)signal::DBUPDATEERR:
std::cout << "From DBsystem: Update error. try again" << std::endl;
return;
case (int)signal::DBSORTERR:
std::cout << "From DBsystem: date sorting error. fatal!" << std::endl;
return;
}
}
void scenario(bool expn) {
switch (expn) {
case (bool)signal::DBNOTEXIST:
std::cout << std::endl << "From DBsystem: no data found corresponding to input " << std::endl;
}
}
void scenario(char* error) {
std::cout << "From DBsystem: Sqlite query FAIL. error message: " << error;
}
};
class DBinterface {
private:
DBsystem dbsys;
class Exception exception;
public:
DBinterface()noexcept;
DBinterface(std::string filename)noexcept;
DBinterface(std::string filename, int max_name_length)noexcept { DBsystem(&filename, max_name_length) = dbsys; }
virtual~DBinterface() {}
virtual bool closeDB();
virtual bool openDB(std::string* filename);
virtual bool insert(std::string* name, int stud_id, _int64 rfid_id);
virtual bool modify_byrfid(const std::string name, const int stud_id, const _int64 rfid_id, const int warning);
virtual bool remove(_int64 rfid_id);
virtual bool remove_by_studid(int stud_id);
virtual bool existence_check(int stud_id);
virtual bool existence_check_byrfid(_int64 rfid_id);
virtual bool get_studinf(std::string*& name, const int& stud_id, _int64& rfid, int& warning);
virtual bool get_studinf_byrfid(std::string*& name, int& stud_id, const _int64& rfid, int& warning);
virtual bool give_penalty(int stud_id);
virtual bool give_penalty_byrfid(_int64 rfid);
virtual bool get_all_student(std::vector<studinf>& x);
};
} | true |
553eac6c5b78b36a6dbeedd9264ef9729235ceb7 | C++ | andreasatle/DesignPatternsCpp | /SOLID/main.cpp | UTF-8 | 4,725 | 3.234375 | 3 | [] | no_license | #include "single_responsibility.h"
#include "open_closed.h"
#include "open_closed.hpp"
#include "liskov_substitution.h"
#include "interface_segregation.h"
#include "dependency_inversion.h"
using namespace std;
void single_responsibility() {
cout << endl << "== Single Responsibility Principle ==" << endl;
Journal journal{"Dear Diary"};
journal.add_entry("I ate a bug.");
journal.add_entry("I cried today.");
journal.add_entry("It's a beautiful day.");
// Write journal to stout.
cout << journal.str() << endl;
// Bad way of storing the journal.
journal.bad_save("journal.txt");
// Good way of storing the journal.
PersistenceManager pm;
pm.good_save(journal, "pm-journal.txt");
cout << endl;
}
void open_closed() {
cout << endl << "== Open Closed Principle ==" << endl;
// Create the data
Product apple{"Apple", Color::green, Size::small};
Product tree{"Tree", Color::green, Size::large};
Product house{"House", Color::blue, Size::large};
Product watermelon{"Watermelon", Color::green, Size::large};
vector<Product*> items{&apple, &tree, &house, &watermelon};
for (auto& item : items) {
cout << item->name << endl;
}
// Bad filter, that violate the Open Closed Principle.
ProductFilter pf;
auto bad_green_things = pf.by_color(items, Color::green);
for (auto& item : bad_green_things) {
cout << item->name << " is green" << endl;
}
auto bad_large_things = pf.by_size(items, Size::large);
for (auto& item : bad_large_things) {
cout << item->name << " is large" << endl;
}
auto bad_large_green_things = pf.by_size_and_color(items, Size::large, Color::green);
for (auto& item : bad_large_green_things) {
cout << item->name << " is large and green" << endl;
}
// Good filter, that builds the filter using a Specification.
Filter<Product> filter;
ColorSpecification green(Color::green);
auto good_green_things = filter.find(items, green);
for (auto& item : good_green_things) {
cout << item->name << " is green" << endl;
}
SizeSpecification large(Size::large);
auto good_large_things = filter.find(items, large);
for (auto& item : good_large_things) {
cout << item->name << " is large" << endl;
}
// Half-good way of creating a conjunction of two specifications.
AndSpecification large_and_green(large, green);
auto good_large_green_things = filter.find(items, large_and_green);
for (auto& item : good_large_green_things) {
cout << item->name << " is large and green" << endl;
}
// Better way of creating a conjunction, where the type can be hidden.
// We still need to instantiate the conjunction, with an overloaded &&-operator.
auto large_and_green2 = large && green;
auto good_large_green_things2 = filter.find(items, large_and_green2);
for (auto& item : good_large_green_things2) {
cout << item->name << " is large and green 2" << endl;
}
cout << endl;
}
void liskov_substitution() {
cout << endl << "== Liskov Substitution Principle ==" << endl;
// Use constructor and the stringer.
Rectangle rectangle(10, 5);
cout << rectangle.str() << endl;
// Modify with setter routines.
rectangle.setWidth(8);
rectangle.setHeight(7);
cout << rectangle.str() << endl;
// Process rectangle with rectangle logic.
process(rectangle);
// Use square constructor and rectangle stringer.
Square square(12);
cout << square.str() << endl;
// Process square with rectangle logic.
process(square);
cout << endl;
}
void interface_segregation() {
cout << endl << "== Interface Segregation Principle ==" << endl;
Document doc;
MultiFunctionPrinter mfp;
ScannerBad scannerBad;
Printer printer;
Scanner scanner;
Machine machine(printer, scanner);
mfp.print(doc);
mfp.scan(doc);
mfp.fax(doc);
scannerBad.print(doc);
scannerBad.scan(doc);
scannerBad.fax(doc);
machine.print(doc);
machine.scan(doc);
cout << endl;
}
void dependency_inversion() {
cout << endl << "== Dependency Inversion Principle ==" << endl;
Person parent{"Andreas"};
Person son{"Anton"};
Person daughter{"Annelie"};
Relationships rel;
rel.add_parent_and_child(parent, son);
rel.add_parent_and_child(parent, daughter);
rel.add_siblings(son, daughter);
cout << rel.str() << endl;
ResearchBad _1(rel);
ResearchGood _2(rel);
cout << endl;
}
int main() {
single_responsibility();
open_closed();
liskov_substitution();
interface_segregation();
dependency_inversion();
return 0;
} | true |
9e03413644e23acaa509da58eb49d64699a7d800 | C++ | rafal-tarnow/TEMPLATES | /GLUT/TexturesBMPGlut/main.cpp | UTF-8 | 7,225 | 3.09375 | 3 | [] | no_license | #include <GL/freeglut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <bmp_load.h>
/* ascii code for the escape key */
#define ESCAPE 27
/* The number of our GLUT window */
int window;
/* floats for x rotation, y rotation, z rotation */
float xrot, yrot, zrot;
/* storage for one texture */
GLuint texture[1];
// Load Bitmaps And Convert To Textures
void LoadGLTextures() {
// Load Texture
Image *image1;
// allocate space for texture
image1 = (Image *) malloc(sizeof(Image));
if (image1 == NULL) {
printf("Error allocating space for image");
exit(0);
}
if (!ImageLoadBMP("Data/lesson6/NeHe.bmp", image1)) {
exit(1);
}
// Create Texture
glGenTextures(1, &texture[0]);
glBindTexture(GL_TEXTURE_2D, texture[0]); // 2d texture (x and y size)
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // scale linearly when image bigger than texture
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // scale linearly when image smalled than texture
// 2d texture, level of detail 0 (normal), 3 components (red, green, blue), x size from image, y size from image,
// border 0 (normal), rgb color data, unsigned byte data, and finally the data itself.
glTexImage2D(GL_TEXTURE_2D, 0, 3, image1->sizeX, image1->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, image1->data);
};
/* A general OpenGL initialization function. Sets all of the initial parameters. */
void InitGL(int Width, int Height) // We call this right after our OpenGL window is created.
{
LoadGLTextures(); // Load The Texture(s)
glEnable(GL_TEXTURE_2D); // Enable Texture Mapping
glClearColor(0.0f, 0.0f, 1.0f, 0.0f); // Clear The Background Color To Blue
glClearDepth(1.0); // Enables Clearing Of The Depth Buffer
glDepthFunc(GL_LESS); // The Type Of Depth Test To Do
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glShadeModel(GL_SMOOTH); // Enables Smooth Color Shading
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); // Reset The Projection Matrix
gluPerspective(45.0f,(GLfloat)Width/(GLfloat)Height,0.1f,100.0f); // Calculate The Aspect Ratio Of The Window
glMatrixMode(GL_MODELVIEW);
}
/* The function called when our window is resized (which shouldn't happen, because we're fullscreen) */
void ReSizeGLScene(int Width, int Height)
{
if (Height==0) // Prevent A Divide By Zero If The Window Is Too Small
Height=1;
glViewport(0, 0, Width, Height); // Reset The Current Viewport And Perspective Transformation
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(GLfloat)Width/(GLfloat)Height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);
}
/* The main drawing function. */
void DrawGLScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glLoadIdentity(); // Reset The View
glTranslatef(0.0f,0.0f,-5.0f); // move 5 units into the screen.
glRotatef(xrot,1.0f,0.0f,0.0f); // Rotate On The X Axis
glRotatef(yrot,0.0f,1.0f,0.0f); // Rotate On The Y Axis
glRotatef(zrot,0.0f,0.0f,1.0f); // Rotate On The Z Axis
glBindTexture(GL_TEXTURE_2D, texture[0]); // choose the texture to use.
glBegin(GL_QUADS);
{
// Front Face (note that the texture's corners have to match the quad's corners)
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Left Of The Texture and Quad
glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Bottom Right Of The Texture and Quad
glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // Top Right Of The Texture and Quad
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Top Left Of The Texture and Quad
// Back Face
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Right Of The Texture and Quad
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); // Top Right Of The Texture and Quad
glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Top Left Of The Texture and Quad
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Bottom Left Of The Texture and Quad
// Top Face
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); // Top Left Of The Texture and Quad
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Texture and Quad
glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // Bottom Right Of The Texture and Quad
glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Top Right Of The Texture and Quad
// Bottom Face
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f); // Top Right Of The Texture and Quad
glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Top Left Of The Texture and Quad
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Bottom Left Of The Texture and Quad
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Right Of The Texture and Quad
// Right face
glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Bottom Right Of The Texture and Quad
glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Top Right Of The Texture and Quad
glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // Top Left Of The Texture and Quad
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Bottom Left Of The Texture and Quad
// Left Face
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Left Of The Texture and Quad
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Right Of The Texture and Quad
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Top Right Of The Texture and Quad
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); // Top Left Of The Texture and Quad
}
glEnd(); // done with the polygon.
glutSwapBuffers();
}
void timer(int value){
glutTimerFunc(30,timer,0);
xrot+=1.0f; // X Axis Rotation
yrot+=1.0f; // Y Axis Rotation
zrot+=1.0f; // Z Axis Rotation
glutPostRedisplay();
}
void keyPressed(unsigned char key, int x, int y)
{
/* avoid thrashing this procedure */
usleep(100);
if (key == ESCAPE)
{
glutDestroyWindow(window);
exit(0);
}
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH);
glutInitWindowSize(480, 320);
glutInitWindowPosition(0, 0);
window = glutCreateWindow("Jeff Molofee's GL Code Tutorial ... NeHe '99");
glutDisplayFunc(&DrawGLScene);
glutIdleFunc(&DrawGLScene);
glutTimerFunc(30,timer,0);
/* Register the function called when our window is resized. */
glutReshapeFunc(&ReSizeGLScene);
/* Register the function called when the keyboard is pressed. */
glutKeyboardFunc(&keyPressed);
/* Initialize our window. */
InitGL(480, 320);
/* Start Event Processing Engine */
glutMainLoop();
return 1;
}
| true |
b92b4d2208412b7539a9c7d4012ac9c390f94807 | C++ | aeremin/Codeforces | /alexey/Solvers/6xx/611/Solver611A.cpp | UTF-8 | 909 | 3 | 3 | [] | no_license | #include <Solvers/pch.h>
using namespace std;
// Solution for Codeforces problem http://codeforces.com/contest/611/problem/A
class Solver611A
{
public:
void run();
};
void Solver611A::run()
{
vector<int> monthLengths = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int64_t n;
cin >> n;
string s;
cin >> s;
cin >> s;
if (s == "week")
{
if (n == 5 || n == 6)
cout << 53;
else
cout << 52;
}
else
{
int ans = 0;
for (auto& m : monthLengths)
if (m >= n) ++ans;
cout << ans;
}
}
class Solver611ATest : public ProblemTest
{
};
TEST_F( Solver611ATest, Example1 )
{
setInput("4 of week");
Solver611A().run();
EXPECT_EQ("52", getOutput());
}
TEST_F( Solver611ATest, Example2 )
{
setInput("30 of month");
Solver611A().run();
EXPECT_EQ("11", getOutput());
} | true |
12e724e7138e74f92f949fd4976c575230591ceb | C++ | JosiasWerly/dllStudies | /ModularDLL/GeneralProgram/dynamicLoad/jDynamicLoad.cpp | UTF-8 | 790 | 2.8125 | 3 | [] | no_license | #include "jDynamicLoad.h"
#include <windows.h>
#include <iostream>
#include <tchar.h>
using namespace std;
list<jDll*> dynamicLoad::DynamicLibraries = list<jDll*>();
void dynamicLoad::load(wstring path, wstring name) {
wstring strg;
strg = path;
strg += name;
HINSTANCE instance = LoadLibrary((LPCWSTR)strg.c_str());
if (!instance)
throw 1;
auto converter = [=](wstring &from)->string{
string stgName;
for (size_t i = 0; i < from.length(); i++){
stgName += from.at(i);
}
return stgName;
};
dynamicLoad::DynamicLibraries.emplace_back(new jDll(converter(name), instance));
}
jDll* dynamicLoad::at(string name) {
for (list<jDll*>::iterator i = DynamicLibraries.begin(); i != DynamicLibraries.end(); i++){
if (name == (*i)->name)
return (*i);
}
return nullptr;
} | true |
e8276761ec259b62962d1297ca1ce75424985583 | C++ | blighli/graphics2017 | /21651026王晓瑶/project01/homework1.cpp | GB18030 | 1,965 | 2.953125 | 3 | [] | no_license | // ConsoleApplication1.cpp : ̨Ӧóڵ㡣
//
#include <GL/glut.h>
static int day = 0;
void Display()
{
//Ȳ
glEnable(GL_DEPTH_TEST);
//ɫ
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//ʹͶӰ
glMatrixMode(GL_PROJECTION);
//ǰûϵԭƵĻ
glLoadIdentity();
//һ
gluPerspective(85, 1, 1, 500000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//һΪԴλãڶΪ۾λãͷķ
gluLookAt(0, -200000, 200000, 0, 0, 0, 0, 0, 1);
//̫
glColor3f(1, 0, 0);
glutSolidSphere(69600, 20, 20);
//Ƶ
glColor3f(0, 0, 1);
glRotatef(day, 0, 0, -1);
glTranslatef(150000, 0, 0);
glutSolidSphere(15945, 20, 20);
//
glColor3f(1, 1, 0);
glRotatef(day / 30.0 * 360 - day, 0, 0, -1);
glTranslatef(38000, 0, 0);
glutSolidSphere(4345, 20, 20);
//ִ˫彻
glutSwapBuffers();
}
//valueĸʱںıλйصıglutPostRedisplay()ػ
//ٴεglutTimerFuncΪglutĶʱǵһβŲһζʱ
void Timer(int value)
{
day++;
if (day > 365)
{
day = 0;
}
//ǵǰҪ»
glutPostRedisplay();
glutTimerFunc(50, Timer, 0);
}
int main(int argc, char **argv)
{
//GLUTгʼв
glutInit(&argc, argv);
//ָʹRGBAģʽ˫崰
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
//ôڴʱĿ
glutInitWindowSize(800, 800);
//һ
glutCreateWindow("test");
//صҪʾʱעĻصᱻִ
glutDisplayFunc(Display);
//ʱ
glutTimerFunc(50, Timer, 0);
glutMainLoop();
return 0;
} | true |
5018af982fdcad2e25fc937c7264c8324a3c2948 | C++ | klemens-morgenstern/mw.test.gen | /include/mw/test/ast/code.hpp | UTF-8 | 1,366 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | /**
* @file code.hpp
* @date 26.11.2015
* @author Klemens
*
* Published under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0.html)
*/
#ifndef MW_TEST_AST_CODE_HPP_
#define MW_TEST_AST_CODE_HPP_
#include <string>
#include <iterator>
#include <boost/spirit/include/support_line_pos_iterator.hpp>
namespace mw
{
namespace test
{
namespace ast
{
struct code
{
typedef
boost::spirit::line_pos_iterator<
BOOST_DEDUCED_TYPENAME
std::string::const_iterator>
iterator;
iterator _begin;
iterator _end;
iterator begin() const {return _begin;};
iterator end() const {return _end;}
std::string to_string() const
{
return std::string(_begin, _end);
}
void clear()
{
_begin = iterator();
_end = iterator();
}
std::size_t size()
{
return std::distance(_begin, _end);
}
};
struct code_list
{
typedef
boost::spirit::line_pos_iterator<
BOOST_DEDUCED_TYPENAME
std::string::const_iterator>
iterator;
iterator _begin;
iterator _end;
iterator begin() const {return _begin;};
iterator end() const {return _end;}
std::vector<std::string> data;
std::string to_string() const
{
return std::string(_begin, _end);
}
void clear()
{
_begin = iterator();
_end = iterator();
data.clear();
}
std::size_t size()
{
return data.size();
}
};
}
}
}
#endif /* MW_TEST_AST_CODE_HPP_ */
| true |
a701ef6c99d3d511d31fc1e053e7f78805db1a9d | C++ | AndrewShkrob/KerberosDesCpp | /des/src/des_string.cpp | UTF-8 | 2,113 | 2.703125 | 3 | [
"MIT"
] | permissive | #include <sstream>
#include <boost/algorithm/string/trim.hpp>
#include "../des_string.hpp"
#include "../des_data.hpp"
DesString::DesString(const std::string &key)
: des(0) {
assert(key.size() <= 7);
ui64 buffer = 0;
std::istringstream input(key);
input.read(reinterpret_cast<char *>(&buffer), 8);
des = Des(buffer);
}
std::string DesString::encrypt(const std::string &text) {
return cipher(text, DesMode::ENCRYPT);
}
std::string DesString::decrypt(const std::string &text) {
return cipher(text, DesMode::DECRYPT);
}
std::string DesString::cipher(const std::string &text, DesMode mode) {
ui64 buffer;
ui64 size = text.size();
ui64 block = size / 8;
if (mode == DesMode::DECRYPT)
--block;
std::istringstream input(text);
std::ostringstream output;
for (ui64 i = 0; i < block; ++i) {
buffer = 0;
input.read(reinterpret_cast<char *>(&buffer), 8);
if (mode == DesMode::ENCRYPT)
buffer = des.encrypt(buffer);
else
buffer = des.decrypt(buffer);
output << std::string(reinterpret_cast<char *>(&buffer), 8);
}
if (mode == DesMode::ENCRYPT) {
ui8 padding = 8 - (size % 8);
if (padding == 0)
padding = 8;
buffer = 0;
if (padding != 8) {
input.read(reinterpret_cast<char *>(&buffer), 8 - padding);
ui8 shift = padding * 8;
buffer <<= shift;
buffer |= LB64_MASK << (shift - 1u);
buffer = des.encrypt(buffer);
std::string res = std::string(reinterpret_cast<char *>(&buffer), 8);
output << res;
}
} else {
buffer = 0;
input.read(reinterpret_cast<char *>(&buffer), 8);
buffer = des.decrypt(buffer);
ui8 padding = 0;
while (!(buffer & 0x00000000000000ffu)) {
buffer >>= 8u;
++padding;
}
buffer >>= 8u;
++padding;
if (padding != 8)
output << std::string(reinterpret_cast<char *>(&buffer), 8 - padding);
}
return output.str();
} | true |
395e7b88a13b5e24347a0be69921b33b52d41594 | C++ | lixpam/awesome-leetcode | /src/852.cc | UTF-8 | 900 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
static const int _ = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
/* O(N)
class Solution {
public:
int peakIndexInMountainArray(vector<int>& A) {
int len = A.size();
for (int i = 0; i < len-1; ++i) {
if (A[i] > A[i+1]) {
return i;
}
}
return len-1;
}
};
*/
class Solution {
public:
int peakIndexInMountainArray(vector<int>& A) {
int lo = 0, hi = A.size()-1;
while (lo < hi) {
int mid = lo + (hi-lo)/2;
if (A[mid] < A[mid+1]) {
lo = mid+1;
} else {
hi = mid;
}
}
return lo;
}
};
int main()
{
Solution s;
vector<int> args{0,1,2,3,1,0};
cout << s.peakIndexInMountainArray(args) << endl;
}
| true |
82d203ca5671638d3b6242e5619231101b111439 | C++ | OctupusTea/Online-Judge | /Zero Judge/a216.cpp | UTF-8 | 554 | 3.34375 | 3 | [] | no_license | #include<iostream>
#include<string.h>
using namespace std;
unsigned long long int f(int);
unsigned long long int g(int);
int main(void)
{
int n = 0;
while( cin >> n)
{
cout << f(n) << " " << g(n) <<endl;
}
return 0;
}
unsigned long long int f(int i)
{
unsigned long long int tmp = i;
tmp = ( tmp + 1 ) * tmp / 2;
return tmp;
}
unsigned long long int g(int i)
{
unsigned long long int tmp = i;
if( i == 1)
{
tmp = 1;
}
else
{
tmp = f(i) + g(i-1);
}
return tmp;
}
| true |
43ac6f23ddf1367a5736cd529ec103ab979ad741 | C++ | JohnVithor/EDB1-2 | /Vector_EDB/include/vector.hpp | UTF-8 | 16,315 | 3.78125 | 4 | [] | no_license | /**
* @file vector.hpp
* @brief Definição das classes sc::MyIterator e sc::vector, seus atributos e métodos
* @details
*
* @author João Vítor Venceslau Coelho
* @since 18/10/2017
* @date 21/10/2017
*/
#ifndef VECTOR_H
#define VECTOR_H
#include <memory>
#include <initializer_list>
#include <iostream> //std::cout
#include <string> //std::string
#include <iterator>
#include <stdexcept> // out_of_range
#include <cassert> //assert
#include <algorithm> //std::copy
namespace sc
{
/**
* @brief Um tipo simplificado de iterador
* @tparam T Tipo do valor que será utilizado para o template do iterador
*/
template < typename T >
class MyIterator
{
public:
typedef T value_type;
typedef std::size_t size_type;
typedef MyIterator self_type;
typedef std::ptrdiff_t difference_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::random_access_iterator_tag iterator_category;
private:
pointer m_ptr;
public:
/**
* @brief Construtor da classe MyIterator. Inicia o ponteiro interno
* @param[in] ptr Ponteiro interno
*/
MyIterator( pointer ptr = nullptr );
/**
* @brief Destrutor da classe MyIterator.
*/
~MyIterator() = default;
/**
* @brief Sobrecarga do operador ++ de pré-incremento
* @return Iterador incrementado
*/
self_type operator++(void);
/**
* @brief Sobrecarga do operador ++ de pós-incremento
* @return Iterador incrementado
*/
self_type operator++(int);
/**
* @brief Sobrecarga do operador -- de pré-incremento
* @return Iterador decrementado
*/
self_type operator--(void);
/**
* @brief Sobrecarga do operador -- de pós-incremento
* @return Iterador decrementado
*/
self_type operator--(int);
/**
* @brief Sobrecarga do operador +
* @param[in] num valor a ser somado
* @return Novo iterador
*/
self_type operator+( size_type num );
/**
* @brief Sobrecarga do operador - de pós-incremento
* @param[in] num valor a ser subtraido
* @return Novo iterador
*/
self_type operator-( size_type num );
/**
* @brief Sobrecarga do operador * para derreferenciar o ponteiro interno
* @return Referencia para o conteudo do ponteiro interno
*/
reference operator*(void);
/**
* @brief Sobrecarga do operador * para derreferenciar o ponteiro interno, mas não é possivel alterar seu valor
* @return Referencia constante para o conteudo do ponteiro interno
*/
const_reference operator*(void) const;
/**
* @brief Sobrecarga do operador - para calcular a distancia dos dois iteradores envolvidos
* @param[in] other Iterador a ser subtraido
* @return Valor numerico da distancia dos dois iteradores
*/
difference_type operator-( const MyIterator< value_type >& other );
/**
* @brief Sobrecarga do operador != para comparar dois iteradores
* @param[in] other Iterador a ser comparado
* @return true se os iteradores são diferentes, false caso contrário
*/
bool operator!=(const self_type& other) const;
/**
* @brief Sobrecarga do operador == para comparar dois iteradores
* @param[in] other Iterador a ser comparado
* @return true se os iteradores são iguais, false caso contrário
*/
bool operator==(const self_type& other) const;
/**
* @brief Sobrecarga do operador == para comparar um iteradores com um ponteiro
* @param[in] other Ponteiro a ser comparado
* @return true se o iterador e o ponteiro são diferentes, false caso contrário
*/
bool operator!=(const_pointer other) const;
/**
* @brief Sobrecarga do operador == para comparar um iteradores com um ponteiro
* @param[in] other Ponteiro a ser comparado
* @return true se o iterador e o ponteiro são iguais, false caso contrário
*/
bool operator==(const_pointer other) const;
};
template < typename value_type >
class vector; // Declaração antecipada da classe vector
template < typename value_type > // Definição antecipada do template para o operador de inserção
std::ostream& operator<< ( std::ostream&, vector<value_type> & );
template < typename value_type > // Definição antecipada do template para o metodo swap
void swap ( vector< value_type >&, vector<value_type> & );
/**
* @brief Um tipo simplificado de vector
* @tparam T Tipo do valor que será utilizado para o template do vector
*/
template < typename T >
class vector
{
public:
typedef T value_type;
typedef std::size_t size_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef std::unique_ptr< value_type > u_pointer;
typedef std::unique_ptr< const value_type > const_u_pointer;
typedef std::ptrdiff_t difference_type;
using iterator = MyIterator< value_type >;
using const_iterator = MyIterator< const value_type >;
private:
pointer m_storage;
size_t m_end;
size_t m_capacity;
public:
// ===============================
// ===== [I] SPECIAL MEMBERS =====
/**
* @brief Construtor vazio do vector.
*/
vector();
/**
* @brief Construtor do vector, com um valor inicial de capacidade
* @param[in] cap capacidade inicial de armazenamento do vector
*/
explicit vector( size_type cap );
/**
* @brief Construtor do vector, com base em um intervalo
* @param[in] first Inicio do intervalor
* @param[in] last Fim do intervalo
*/
template < typename InputItr >
vector( InputItr first, InputItr last);
/**
* @brief Construtor cópia do vector
* @param[in] other Vector a ser copiado
*/
vector( const vector & other);
/**
* @brief Construtor do vector a partir de uma lista inicializadora
* @param[in] ilist Lista a ser utilizada
*/
vector( std::initializer_list< value_type > ilist );
/**
* @brief Destrutor do vector
*/
~vector()
{
delete[] m_storage;
}
/**
* @brief Sobrecarga do operador = a partir de outro vector
* @param[in] other vector a ser atribuido
* @return O vector já modificado
*/
vector& operator=( const vector& other );
/**
* @brief Sobrecarga do operador = a partir de uma lista inicializadora
* @param[in] ilist lista a ser atribuida
* @return O vector já modificado
*/
vector& operator=( std::initializer_list< value_type > ilist );
// ==========================
// ===== [II] Iterators =====
/**
* @brief Cria e retorna um iterador a partir do endereço do primeiro elemento do vector
* @return Iterador para o primeiro elemento do vector
*/
iterator begin( void );
/**
* @brief Cria e retorna um iterador a partir do endereço do ultimo elemento do vector
* @return Iterador para o ultimo elemento do vector
*/
iterator end( void );
/**
* @brief Cria e retorna um iterador constante a partir do endereço do primeiro elemento do vector
* @return Iterador para o primeiro elemento do vector
*/
const_iterator cbegin( void ) const;
/**
* @brief Cria e retorna um iterador constante a partir do endereço do ultimo elemento do vector
* @return Iterador para o ultimo elemento do vector
*/
const_iterator cend( void ) const;
// ==========================
// ===== [III] Capacity =====
/**
* @brief Acessa e retorna o tamanho lógico do vector
* @return tamanho lógico do vector
*/
size_type size( void );
/**
* @brief Acessa e retorna o tamanho fisico do vector
* @return tamanho fisico do vector
*/
size_type capacity( void );
/**
* @brief Verifica se o vector possui algum elemento, isto é o tamanho lógico é 0
* @return true se ele não está vazio, false caso esteja
*/
bool empty( void );
// ===========================
// ===== [IV] Modifiers =====
/**
* @brief Zera o tamanho lógico do vector
*/
void clear( void );
/**
* @brief Adiciona o elemento indicado ao inicio do vector
* @param[in] valor a ser adicionado
*/
void push_front( const_reference value );
/**
* @brief Adiciona o elemento indicado ao fim do vector
* @param[in] valor a ser adicionado
*/
void push_back (const_reference value );
/**
* @brief Elimina o ultimo elemento do vector
*/
void pop_back( void );
/**
* @brief Elimina o primeiro elemento do vector
*/
void pop_front( void );
/**
* @brief Insere o elemento indicado na posição indicada pelo iterador
* @param[in] itrt Iterador que indica a posição
* @param[in] value Elemento a ser inserido
* @return Iterador que indica a posição do elemento inserido ( a mesma que foi passada )
*/
iterator insert( iterator itrt, const_reference value );
/**
* @brief Insere todos os elementos indicados do intervalo indicado no vector
* a partir posição indicada pelo iterador
* @param[in] itrt Iterador que indica a posição inicial
* @param[in] first Inicio do intevalo indicado
* @param[in] last Fim do intevalo indicado
* @return Iterador que indica a posição do ultimo elemento inserido
*/
template < typename InputItr >
iterator insert( iterator itrt, InputItr first, InputItr last);
/**
* @brief Insere todos da lista inicializadora indicada no vector
* a partir posição indicada pelo iterador
* @param[in] itrt Iterador que indica a posição inicial
* @param[in] ilist Lista inicializadora
* @return Iterador que indica a posição do ultimo elemento inserido
*/
iterator insert( iterator itrt, std::initializer_list< value_type > ilist );
/**
* @brief Aumenta a capacidade do vector para o valor indicado
* @param[in] new_cap Nova capacidade do vector
*/
void reserve (size_type new_cap);
/**
* @brief Reduz a capacidade do vector para exatamente o numero de elementos
*/
void shrink_to_fit( void );
/**
* @brief Aumenta a capacidade do vector para o valor indicado
* @param[in] new_cap Nova capacidade do vector
*/
void assign( const_reference value);
/**
* @brief Aumenta a capacidade do vector para o valor indicado
* @param[in] new_cap Nova capacidade do vector
*/
void assign( std::initializer_list< value_type > ilist );
/**
* @brief Substitui todos os elementos do vector pelos do intervalo indicado
* @details Se o fim do intervalo for alcançado, os proximos elementos do vector
* serão substituidos pela lista novamente, de maneira repetitiva até o vector ficar completo
* @param[in] first Inicio do intervalo
* @param[in] last Fim do intervalo
*/
template < typename InputItr >
void assign( InputItr first, InputItr last);
/**
* @brief Retira do vector os elementos no intervalo indicado
* @param[in] first Inicio do intervalo
* @param[in] last Fim do intervalo
* @return Retorna um iterador para a ultima posição válida do vector
*/
iterator erase( iterator first, iterator last );
/**
* @brief Retira do vector o elemento da itrtição indicada
* @param[in] pos Iterador para a posição do elemento a ser retirado
* @return Retorna um iterador para a ultima posição válida do vector
*/
iterator erase( iterator itrt );
// ==============================
// ===== [V] Element access =====
/**
* @brief Acessa o ultimo elemento do vector
* @return Retorna uma referencia para o ultimo elemento do vector
*/
reference back( void );
/**
* @brief Acessa o primeiro elemento do vector
* @return Retorna uma referencia para o primeiro elemento do vector
*/
reference front(void);
/**
* @brief Acessa o primeiro elemento do vector, mas não é possivel alterar o seu valor
* @return Retorna uma referencia constante para o primeiro elemento do vector
*/
const_reference back( void ) const;
/**
* @brief Acessa o primeiro elemento do vector, mas não é possivel alterar o seu valor
* @return Retorna uma referencia constante para o primeiro elemento do vector
*/
const_reference front( void ) const;
/**
* @brief Acessa o elemento do vector indicado pelo indice passado
* @param[in] id Indice para a posição do elemento a ser acessado
* @return Retorna uma referencia constante para o elemento acessado
*/
reference operator[]( size_type id );
/**
* @brief Acessa o elemento do vector indicado pelo indice passado, mas não é possivel alterar o seu valor
* @param[in] id Indice para a posição do elemento a ser acessado
* @return Retorna uma referencia constante para o elemento acessado
*/
const_reference operator[]( size_type id ) const;
/**
* @brief Acessa o elemento do vector indicado pelo indice passado
* @details Realiza uma verificação para saber se o indice passado é válido.
* Caso não seja, lança a excessão out_of_range
* @param[in] id Indice para a posição do elemento a ser acessado
* @return Retorna uma referencia constante para o elemento acessado
*/
reference at( size_type id );
/**
* @brief Acessa o elemento do vector indicado pelo indice passado, mas não é possivel alterar o seu valor
* @details Realiza uma verificação para saber se o indice passado é válido.
* Caso não seja, lança a excessão out_of_range
* @param[in] id Indice para a posição do elemento a ser acessado
* @return Retorna uma referencia constante para o elemento acessado
*/
const_reference at( size_type id ) const;
/**
* @brief Acessa o vetor interno do vector
* @return Retorna um pointeiro para o vetor interno
*/
pointer data( void );
/**
* @brief Acessa o vetor interno do vector, mas não é possivel alterar seu valor
* @return Retorna um pointeiro constante para o vetor interno
*/
const_pointer data( void ) const;
// ==========================
// ===== [VI] Operators =====
/**
* @brief sobrecarga do operador de ==
* @return true se forem iguais, false caso contrário
*/
bool operator==( const vector & other) const;
/**
* @brief sobrecarga do operador de !=
* @return true se forem diferentes, false caso contrário
*/
bool operator!=( const vector & other) const;
// ==================================
// ===== [VII] Friend Functions =====
//friend std::ostream& operator<< <value_type>(std::ostream &os_, vector<value_type> const &v_);
/**
* @brief Sobrecarga falha do operador de << para mostrar o conteudo do vector
* @param[in] os_ Stream de saída do conteudo do vector
* @param[in] v_ Vector alvo
* @return Retorna um stream de saída com o conteudo do vector já formatado
*/
friend std::ostream& operator<< (std::ostream &os_, vector<value_type> &v_)
{
os_ << "[ ";
for( size_type i = 0 ; i < v_.size() ; ++i )
os_ << v_.m_storage[i] << " ";
os_ << "| ";
for( size_type i = v_.size() ; i < v_.capacity() ; ++i )
os_ << v_.m_storage[i] << " ";
os_ << "]";
os_ << " Tamanho Lógico: " << v_.size() << ", Tamanho Físico: " << v_.capacity() << std::endl;
return os_;
}
friend void swap < value_type >( vector< value_type > & first_, vector< value_type > & second_ );
/**
* @brief Sobrecarga do método swap da std
* @param[in] first_ Primeiro vector a ser trocado
* @param[in] second_ Segundo vector a ser trocado
*/
friend void swap ( vector< value_type > & first_, vector< value_type > & second_ )
{
sc::vector< value_type > temp(first_);
first_ = second_;
second_ = temp;
}
/**
* @brief Método swap da própria classe
* @param[in] other Primeiro vector a ser trocado
*/
void swap ( vector< value_type > & other );
/**
* @brief Método que mostra o conteudo do vector na saida (stream) padrão
*/
void print () const;
};
}
#include "MyIterator.inl"
#include "vector_Special_Members.inl"
#include "vector_Iterators_Capacity.inl"
#include "vector_Modifiers.inl"
#include "vector_Element_Access.inl"
#include "vector_Operators_Friend_Functions.inl"
#endif | true |
9c9e9819f013674b5563113b10625755802e1c53 | C++ | PICdew/Turnado-Hardware-MIDI-Controller | /Code/TurnadoController/RotaryEncoder.cpp | UTF-8 | 3,750 | 2.90625 | 3 | [] | no_license | #include "RotaryEncoder.h"
RotaryEncoder::RotaryEncoder (uint8_t encPin1, uint8_t encPin2, int8_t switchPin)
{
encoder = new Encoder (encPin1, encPin2);
if (switchPin >= 0)
{
switchDebouncer = new Bounce (switchPin, DEBOUNCE_TIME);
pinMode (switchPin, INPUT_PULLUP);
}
else
{
switchEnabled = false;
}
}
RotaryEncoder::~RotaryEncoder()
{
delete encoder;
if (switchEnabled)
delete switchDebouncer;
}
void RotaryEncoder::update()
{
//Check for encoder turn
int env_val = encoder->read();
//If there is an encoder value change
if (env_val >= 4 || env_val <= - 4)
{
if (accelerationEnabled)
{
//get time interval between this change and previous change
currentTime = millis();
revolutionTime = currentTime - prevTime;
prevTime = currentTime;
// trigger acceleration only when encoder speed is sufficiently high (small time value)
if (revolutionTime < revTimeThreshold)
{
rev = revTimeThreshold - revolutionTime;
b = (int)a * rev + c; //slope of a line equation
env_val = env_val * b; //apply acceleration
}
} //if (accelerationEnabled)
env_val /= 4;
//constrain value to expected range to get rid of occasional incorrect large encoder readings
env_val = constrain (env_val, -4, 4);
if (shouldSendEncoderValue (env_val))
{
this->handle_encoder_change (*this, env_val);
}
encoder->write(0);
} //if (env_val >= 4 || env_val <= - 4)
if (switchEnabled)
{
//Check for switch state change
switchDebouncer->update();
if (switchDebouncer->risingEdge())
{
switchState = 0;
this->handle_switch_change (*this);
}
else if (switchDebouncer->fallingEdge())
{
switchState = 1;
this->handle_switch_change (*this);
}
}//if (switchEnabled)
}
uint8_t RotaryEncoder::getSwitchState()
{
return switchState;
}
void RotaryEncoder::onEncoderChange( void (*function)(RotaryEncoder&, int) )
{
this->handle_encoder_change = function;
}
void RotaryEncoder::onSwitchChange( void (*function)(RotaryEncoder&) )
{
this->handle_switch_change = function;
}
bool RotaryEncoder::operator==(RotaryEncoder& b)
{
return (this == &b);
}
void RotaryEncoder::enableAcceleration (bool shouldEnable)
{
accelerationEnabled = shouldEnable;
}
bool RotaryEncoder::shouldSendEncoderValue (int incVal)
{
//Only send the encoder value if it's the first turn after a certain time period or if
//the direction is the same as with the previous x amount of turns.
//This is done to prevent stray sets of positive values within fast negative turns from being processed.
bool shouldSend = false;
//if the first encoder turn after a certain time period
if (millis() - prevIncTime >= 50)
{
shouldSend = true;
//set all prevIncDirs to match incVal to reset process of checking previous values
for (uint8_t i = 0; i < NUM_OF_PREV_VALS; i++)
incVal > 0 ? prevIncDirs[i] = 1 : prevIncDirs[i] = -1;
}
//else if the value direction matches that of the previous set of values
else if (doesValDirMatchPrevVals (incVal))
{
shouldSend = true;
//move all values in prevIncDirs backward (removing end/oldest value)
//and add new value based on incVal at the beginning
for (uint8_t i = NUM_OF_PREV_VALS - 1; i > 0; i--)
prevIncDirs[i] = prevIncDirs[i - 1];
incVal > 0 ? prevIncDirs[0] = 1 : prevIncDirs[0] = -1;
}
prevIncTime = millis();
return shouldSend;
}
bool RotaryEncoder::doesValDirMatchPrevVals (int incVal)
{
int8_t valDir = incVal > 0 ? 1 : -1;
for (uint8_t i = 0; i < NUM_OF_PREV_VALS; i++)
{
if (valDir != prevIncDirs[i])
return false;
}
return true;
}
| true |
1292af5c1db3aec8504102222cf3cd1e4876be1b | C++ | Spetsnaz-Dev/CPP | /Codechef/HXOR.cpp | UTF-8 | 1,220 | 2.703125 | 3 | [] | no_license | #include "bits/stdc++.h"
#define ll long long int
#define ull unsigned long long int
#define pb push_back
using namespace std;
// print ans
void printAns(vector<ll> arr){
for(ll i=0; i<arr.size(); i++)
cout<<arr[i]<<" ";
cout<<"\n";
}
// Krantiveer
int main()
{
ll t, n, x, z;
cin>>t;
while (t--)
{
cin>>n>>x;
// array input
vector<ll> arr(n);
for(ll i=0; i<n; i++)
cin>>arr[i];
ll i=0;
for(ll k=x; k>0 and i<n-1; k--)
{
bool flag = 0;
ll p = log2(arr[i]);
ll r = pow(2, p);
arr[i] = arr[i] ^ r;
for (ll j = i+1; j<n; j++){
if((arr[j]^r) < arr[j]){
arr[j] = arr[j] ^ r;
flag = 1;
break;
}
}
if(flag == 0){
arr[n-1] = arr[n-1] ^ r;
}
while (arr[i] <= 0)
i++;
z = k+1;
if(n<3 and z%2 == 0 and z > 0){
arr[n-1] = arr[n-1] ^ 1;
arr[n-2] = arr[n-2] ^ 1;
}
}
printAns(arr);
}
} | true |
c7138c105178a50d1abba79d26a7ae3f4b3989da | C++ | liangjisheng/C-Cpp | /books/C++_Standard_Template_Library/Chapter6/stl_set1.cpp | GB18030 | 1,744 | 3.9375 | 4 | [
"MIT"
] | permissive |
#include <iostream>
#include <set>
#include <iterator>
using namespace std;
int main()
{
/* type of the collection : sets:
* no duplicates
* elements are integral values
* descending order
*/
typedef set<int , greater<int> > IntSet;
IntSet coll1; // empty set container
// insert elements in random order
coll1.insert(4);
coll1.insert(3);
coll1.insert(5);
coll1.insert(1);
coll1.insert(6);
coll1.insert(2);
coll1.insert(5);
// iterate over all elements and print them
IntSet::iterator pos;
for (pos = coll1.begin(); pos != coll1.end(); ++pos)
cout << *pos << ' ';
cout << endl;
// insert 4 again and process return value
// ɹpairеiterator²ԪصλãboolΪtrue
// ԭȲԪؾʹڣpairеiteratorزԪصλãboolΪfalse
pair<IntSet::iterator, bool> status = coll1.insert(4);
if(status.second)
cout << "4 inserted as element "
<< distance(coll1.begin(), status.first) + 1 << endl;
else
cout << "4 already exists" << endl;
// assign elements to another set with ascending order
set<int> coll2(coll1.begin(), coll1.end());
// print all element of the copy
copy(coll2.begin(), coll2.end(), ostream_iterator<int>(cout, " "));
cout << endl;
// remove all elements up to element with value 3
coll2.erase(coll2.begin(), coll2.find(3));
// print all element
copy(coll2.begin(), coll2.end(), ostream_iterator<int>(cout, " "));
cout << endl;
// remove all elements with value 5
int num;
num = coll2.erase(5);
cout << num << " element(s) removed" << endl;
// print all element
copy(coll2.begin(), coll2.end(), ostream_iterator<int>(cout, " "));
cout << endl;
system("pause");
return 0;
} | true |
eda2037276a54c1128dc30a353cd385d4ff9232a | C++ | gaoxiang007/chapter_nine | /chapter_6/N_Queens_I.cpp | UTF-8 | 1,894 | 3.8125 | 4 | [] | no_license | // https://oj.leetcode.com/problems/n-queens/
class Solution {
public:
vector<string> drawChessBoard(const vector<int>& C) {
vector<string> res;
int N = C.size(); // square matrix
for(int i = 0; i < N; ++i) {
res.push_back(""); // init the ith row
for(int j = 0; j < N; ++j) {
if(C[i] == j) {
res[i].push_back('Q');
} else {
res[i].push_back('.');
}
}
}
return res;
}
// isValid的作用是验证 (C.size(), col) 这个点是否可行
bool isValid(const vector<int>& C, int col) {
int row = C.size();
for(int i =0; i < row; ++i) {
// check column
if(C[i] == col) {
return false;
}
if(row + col == i + C[i]) { // 次对角线上两点的性质,举例验证
return false;
}
if(row - col == i - C[i]) { // 主对角线上两点的性质,举例验证
return false;
}
}
return true;
}
void dfs(vector<vector<string> >& sol, int n, vector<int>& C) {
if(C.size() == n) {
// draw the chessboard
sol.push_back(drawChessBoard(C));
return;
}
for(int col = 0; col < n; ++col) {
if(!isValid(C, col)) {
continue;
}
C.push_back(col); // go to next row
dfs(sol, n, C);
C.pop_back(); // revoke current row
}
}
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > sol;
if(n <= 0) {
return sol;
}
vector<int> C; // c[i] = j -> the Queen on row i is on column j
dfs(sol, n, C);
}
};
| true |
393746dbda4edbd34d93b1d78591b8850688cde9 | C++ | GandhiGames/speedrunner | /speedrunner_win/speedrunner/AnimationGroup.cpp | UTF-8 | 1,384 | 3.0625 | 3 | [] | no_license | #include "AnimationGroup.h"
AnimationGroup::AnimationGroup() : m_goToState(ANIMATION_STATE::COUNT) {}
void AnimationGroup::AddAnimation(std::shared_ptr<Animation> animation)
{
m_animations.emplace_back(animation);
}
void AnimationGroup::SetFacingDirection(MOVEMENT_DIRECTION dir)
{
for (auto& a : m_animations)
{
a->SetFacingDirection(dir);
}
}
//TODO: convert this to facing direction
MOVEMENT_DIRECTION AnimationGroup::GetFacingFirection()
{
return (m_animations.size() > 0) ? m_animations.at(0)->GetFacingFirection() : MOVEMENT_DIRECTION::COUNT;
}
void AnimationGroup::Draw(sf::RenderWindow &window, float timeDelta)
{
for (auto& a : m_animations)
{
a->Draw(window, timeDelta);
}
}
void AnimationGroup::SetPosition(const sf::Vector2f pos)
{
for (auto& a : m_animations)
{
a->SetPosition(pos);
}
}
void AnimationGroup::Reset()
{
for (auto& a : m_animations)
{
a->Reset();
}
}
std::vector<std::shared_ptr<Animation>>& AnimationGroup::GetAnimations()
{
return m_animations;
}
bool AnimationGroup::IsFinished()
{
for (auto& a : m_animations)
{
if (!a->IsFinished()) { return false; }
}
return true;
}
bool AnimationGroup::HasNextState()
{
return m_goToState != ANIMATION_STATE::COUNT;
}
ANIMATION_STATE AnimationGroup::GetNextState()
{
return m_goToState;
}
void AnimationGroup::SetNextState(ANIMATION_STATE state)
{
m_goToState = state;
} | true |
6b01967d3f143c2293ca667c67bc4334f84f75ac | C++ | Rohit-Jalari/Cpp | /Assignments/NOV 29 LAB-2/5.cpp | UTF-8 | 655 | 3.65625 | 4 | [] | no_license | #include<iostream>
using namespace std;
class Laptop{
string brand_name;
string model;
int price;
public :
void getData()
{
cout<<"\nEnter the Name of the Brand : ";
getline(cin,brand_name);
cout<<"\nEnter the Model Name : ";
getline(cin,model);
cout<<"\nEnter the Price : ";
cin>>price;
}
void displayData()
{
cout<<"\n\tBrand Name : "<<brand_name;
cout<<"\n\tModel Name : "<<model;
cout<<"\n\tPrice : "<<price;
}
};
int main()
{
Laptop laptop1;
laptop1.getData();
laptop1.displayData();
}
| true |
a11f593b7e2305da481f4aefe62df4e9cf9d92d6 | C++ | iYaphetS/CPP | /字符串类封装/MyString.h | UTF-8 | 974 | 3.34375 | 3 | [] | no_license | #pragma once
#include <iostream>
using namespace std;
class MyString
{
//字符串输出 cout << str
friend ostream& operator<<(ostream &os, const MyString &str);
//字符串输入 cout >> str
friend istream& operator>>(istream &in, MyString &str);
public:
//无参构造函数
MyString();
//有参构造函数 MyString str = "hello"
MyString(const char *str);
//有参构造函数 MyString str(2, 'c')
MyString(int n, char c);
//拷贝构造函数 MyString str1 = str2
MyString(const MyString &str);
//赋值=重载 str1 = str3
MyString& operator=(const MyString &str);
//析构函数
~MyString();
//字符串拼接 ret = str1 + str2
MyString operator+(const MyString &str);
//ret = str1 + "hello"
MyString operator+(const char *str);
//字符串追加 str1 += str2
MyString& operator+=(const MyString &str);
//str1 += "hello"
MyString& operator+=(const char *str);
//字符串有效长度
int mysize();
private:
char *pString;
int size;
}; | true |
b30e4141ba77fc17ebd8a87d92c3605b50c31cc8 | C++ | apurv-sawant1506/Algorithms | /week4_divide_and_conquer/3_improving_quicksort/my_quick_sorting.cpp | UTF-8 | 1,286 | 3.4375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef struct pivot_index
{
int lower, higher;
} index;
// typedef struct pivot_index index;
index partition2(vector<int> &a, int l, int r)
{
int pivot = a[r];
index p_i;
p_i.lower = l;
p_i.higher = l;
int temp;
for (int i = l; i < r; i++)
{
if (a[i] < pivot)
{
//remove arr[i] from the vector
//insert it at position vector.begin() + p_i.lower
//dont't increment p_i.lower
temp = a[i];
a.erase(a.begin() + i);
a.insert(a.begin() + p_i.lower, temp);
p_i.higher += 1;
p_i.lower += 1;
}
else if (a[i] == pivot)
{
swap(a[i], a[p_i.higher]);
p_i.higher++;
}
}
swap(a[p_i.higher], a[r]);
return p_i;
}
void randomized_quick_sort(vector<int> &a, int l, int r)
{
if (l >= r)
{
return;
}
int k = l + rand() % (r - l + 1);
swap(a[l], a[k]);
index x = partition2(a, l, r);
randomized_quick_sort(a, l, x.lower - 1);
randomized_quick_sort(a, x.higher + 1, r);
}
int main()
{
int n;
cin >> n;
vector<int> a(n);
for (size_t i = 0; i < a.size(); ++i)
{
cin >> a[i];
}
randomized_quick_sort(a, 0, a.size() - 1);
for (size_t i = 0; i < a.size(); ++i)
{
cout << a[i] << ' ';
}
return 0;
}
| true |
1bb3bef8d6d76f01d05e171a84c709a299c75702 | C++ | fruitbox12/Qt | /network.cpp | UTF-8 | 3,721 | 2.953125 | 3 | [] | no_license | #include "network.h"
Network::Network(QObject *parent) : QObject(parent) {
// 1. Create a TCP socket: set up the server and make it listen for new connections on server ip address and TCP port
server = new QTcpServer(this);
// 2. Bind: associate the socket with your adapter's IP address and a TCP port number
// Pick a port number from 29152 through 65535. IANA publishes a list of currently assigned ports
// For localhost can use QHostAddress:LocalHost(127.0.0.1)
// QHostAddress ipAddress("127.0.0.1");
QHostAddress ipAddress("192.168.1.59");
if (!(server->listen(ipAddress, 56789))) {
// qFatal() never returns - it crashes the program immediantely
qFatal("ERROR: Failed to bind TCP server to port 56789 on 192.168.1.59");
}
// Most OS's are event driven, they wait for certain events to occur and auto run special functions/methods.
// Programmers "schedule" event handlers. In Qt, event are called SIGNALS, even handler functions are called SLOTS.
// Connect the socket object's client connection request event to the sendData() even handler.
// When the client sends a connect() request (called newConnection() it Qt), auto. run the event handler sendData().
connect(server, SIGNAL(newConnection()), this, SLOT(sendData()));
data.append(QByteArray("You've been leading a dog's life. Stay off the furniture. \n"));
data.append(QByteArray("You have to think about tomorrow. \n"));
data.append(QByteArray("You will be surprised by a loud noise. \n"));
data.append(QByteArray("You will feel hungry again in another hour. \n"));
data.append(QByteArray("My ears my ears. \n"));
data.append(QByteArray("You ugly. \n"));
data.append(QByteArray("Water is not wet. \n"));
}
Network::~Network() {
// Shut down the server first
server->close();
// Disconnect all signals and slots connected to this server
server->disconnect();
// Queue this object for deletion at the first opportune moment.
// Dont delete any QObject-derived object the standard C++ way because there might be pending signals
// that must be processed by the object. If we delete the object and Qt tries to deliver a signal to it,
// the program will segfault and crash. We call the deleteLater() method (which is actually defined as a slot,
// and we will use that property in the next function we define),
// and this makes sure there are no pending tasks for the object before pulling the plug on it.
server->deleteLater();
}
void Network::sendData() {
// Take a client socket off of the server
QTcpSocket * clientSocket = server->nextPendingConnection();
// Wait until the client socket is connected
if (!(clientSocket->waitForConnected())) {
// qDebug() works just like std::cout, except that it automatically inserts a new line at the end
// of every statement
// qDebug is not a stream, but a stream factory.
qDebug() << clientSocket->errorString();
return;
}
// Choose a random fortune and send it to the receiver
clientSocket->write(data.at(qrand() % data.size()));
// Tear down the host connection. Call disconnectFromHost(), not disconnect(), because disconnect()
// on any QObject derived class (which is almost all the classes in Qt) discconects all signals and slots
// connected to the object. Finally, we connect the disconnected() signal (which is emitted when the socket
// has finally disconnected) to the deleteLater() slot on the same socket. So now, when the socket disconects,
// it will be queued for deletion. This is the standard way of tearing down a socket.
clientSocket->disconnectFromHost();
connect(clientSocket, SIGNAL(disconnected()), clientSocket, SLOT(deleteLater()));
}
| true |
a1f0335322b7755331baf6edf869640d989a2774 | C++ | vikasdongare/DSA-SEM3 | /assignment9.cpp | UTF-8 | 997 | 3.703125 | 4 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
class stack
{
int top;
public:
char a[25];
stack()
{
top=-1;
}
bool push(char x);
char pop();
bool isempty();
};
bool stack::push(char x)
{
if(top>=24)
{
cout<<"Stack overflow";
return false;
}
else
{
a[++top]=x;
return true;
}
}
char stack::pop()
{
if(top<0)
{
cout<<"Stack Underflow";
}
else
{
char x=a[top--];
return x;
}
}
bool stack::isempty()
{
return (top<0);
}
int main()
{
stack s;
int i;
char str[25],rev[25];
cout<<"\nEnter string:";
cin>>str;
for(i=0;str[i]!='\0';i++)
{
s.push(str[i]);
}
for(i=0;s.isempty()==false;i++)
{
rev[i]=s.pop();
}
int x=strcmp(str,rev);
cout<<str<<endl;
cout<<rev<<endl;
cout<<x<<endl;
if(x==0)
{
cout<<"String is palindrome";
}
else
{
cout<<"String is not palindrome";
}
}
| true |
83f97df3e4604cee544208a45afbea7fbc073c73 | C++ | adityanjr/code-DS-ALGO | /CodeForces/Complete/400-499/448B-SuffixStructures.cpp | UTF-8 | 875 | 3.0625 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <iostream>
#include <vector>
int main(){
std::string first; getline(std::cin, first);
std::string second; getline(std::cin, second);
int index = 0;
for(int p = 0; p < first.size(); p++){
if(first[p] == second[index]){++index;}
}
if(index >= second.size()){puts("automaton");}
else{
const int N = 26;
std::vector<int> countVec(N,0);
for(int p = 0; p < first.size(); p++){++countVec[first[p] - 'a'];}
for(int p = 0; p < second.size(); p++){--countVec[second[p] - 'a'];}
bool array(1), tree(0);
for(int p = 0; p < N; p++){
if(countVec[p] != 0){array = 0;};
if(countVec[p] < 0){tree = 1; break;}
}
if(array){puts("array");}
else if(!tree){puts("both");}
else{puts("need tree");}
}
return 0;
}
| true |
360292330ffb471a829e6c93f1cb3e71af1f221b | C++ | yahoo/tunitas-basics | /src/tunitas/time/ratio.xcpp | UTF-8 | 2,052 | 2.59375 | 3 | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | permissive | // This is -*- c++ -*- nearly C++23 with Modules TS but in the S.C.O.L.D. stylings that are so popular these days.
// Copyright Yahoo Inc. 2021.
// Licensed under the terms of the Apache-2.0 license.
// For terms, see the LICENSE file at https://github.com/yahoo/tunitas-basics/blob/master/LICENSE
// For terms, see the LICENSE file at https://git.tunitas.technology/all/components/basics/tree/LICENSE
#divert <fpp>
#import std.ratio
#import std.ratio_multiply
namespace tunitas::time::ratio {
//
// There are many ratios that we care about.
// All of these ar daypart and calendar-level quantities.
// Of course there is an error term in the multi-year durations which span leap year.
// And the unforseen and unannounced leap seconds, or the arrival of aliens who tell us of new time lines altogether.
//
// Many of these already exist in C++23
//
using Microsecond = std::micro;
using Millisecond = std::milli;
using Second = std::ratio<1, 1>;
using Minute = std::ratio_multiply<std::ratio<60>, Second>::type;
using Hour = std::ratio_multiply<std::ratio<60>, Minute>::type;
using Day = std::ratio_multiply<std::ratio<24>, Hour>::type;
using Week = std::ratio_multiply<std::ratio<7>, Day>::type;
using Fortnight = std::ratio_multiply<std::ratio<2>, Week>::type;
// It becomes controversial and cultural after here ... with some embedded error terms.
using Month = std::ratio_multiply<std::ratio<30>, Day>::type;
using Year = std::ratio_multiply<std::ratio<365>, Day>::type;
//
// pesky plurality ... just sounds wrong when conjugated badly
using Microseconds = Microsecond;
using Milliseconds = Millisecond;
using Seconds = Second;
using Minutes = Minute;
using Hours = Hour;
using Days = Day;
using Weeks = Week;
using Fortnights = Fortnight;
using Months = Month;
using Years = Year;
}
namespace tunitas::time {
namespace [[deprecated("tunitas::time::ratios (plural) never was a namespace name; use tunitas::time::ratio (singular)")]] ratios {
using namespace ratio;
}
}
#endiv
| true |
9f22af077c41395a0f22ddf93628693ca72f28f1 | C++ | PabloSzx/Estructura-de-Datos-INFO053 | /Clase 5/pila.h | UTF-8 | 1,171 | 3.203125 | 3 | [] | no_license | #ifndef LISTA_H
#define LISTA_H
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
typedef struct nodo {
int edad;
char nombre[100];
struct nodo *siguiente;
}nodo;
typedef struct lista {
nodo *inicio;
int largo;
} lista;
void insertar(lista **lista, int edad, char *nombre) {
nodo *n = (nodo *)malloc(sizeof(nodo));
n->edad = edad;
strcpy(n->nombre, nombre);
if ((*lista)->inicio == NULL) {
n->siguiente = NULL;
(*lista)->inicio = n;
(*lista)->largo++;
} else {
n->siguiente = (*lista)->inicio;
(*lista)->inicio = n;
(*lista)->largo++;
}
}
void imprimir(lista **lista) {
system("clear");
cout << "\n El largo de la lista es: " << (*lista)->largo;
nodo *ptr = (*lista)->inicio;
cout << "\n [\n";
while (ptr != NULL) {
cout << "\n" << ptr->edad << " " << ptr->nombre;
ptr = ptr->siguiente;
}
cout << "\n] \n";
}
void eliminar(lista **lista) {
nodo *ptr = (*lista)->inicio;
nodo *sig = ptr->siguiente;
if (ptr->siguiente == NULL) {
(*lista)->inicio = NULL;
} else {
(*lista)->inicio = (sig);
}
(*lista)->largo--;
}
#endif
| true |
dd59e8eb32302c8b502dc7b49156a6ca21cc858a | C++ | synchronized/gtd | /lang/c-cpp/practice/src/std-algo-find.cpp | UTF-8 | 1,052 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <list>
#include <deque>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
template<typename iterator>
void ergodic(iterator first, iterator last, string contName);
int main() {
int i;
const int n=10;
list<int> ilist;
list<int>::iterator elem1, elem2;
//deque<int> ideq;
//vector<int> ivec;
for( i=0; i<n; i++) {
ilist.push_back(i);
}
cout << "================== init ===================" << endl;
ergodic( ilist.begin(), ilist.end(), "ilist");
elem1 = find( ilist.begin(), ilist.end(), 31);
elem2 = find( elem1, ilist.end(), 31);
ilist.erase( elem1, elem2);
cout << "================== earse ==================" << endl;
ergodic( ilist.begin(), ilist.end(), "ilist");
return 0;
}
template<typename iterator>
void ergodic(iterator first, iterator last, string contName) {
iterator iter = first;
int i=0;
for( ; iter!=last; iter++) {
cout << contName << "[" << i << "]=" << *iter << endl;
i++;
}
cout << "-------------------------------------------" << endl;
}
| true |
b541c03af75ceb0328ff3de8c435838808716f61 | C++ | Bhitt/Hitt_Branden_CSC17A_48983 | /Hmwk/Assignment 5/Gaddis_Chap13_Prob4/PersonalInfo.cpp | UTF-8 | 476 | 2.71875 | 3 | [] | no_license | /*
* File: card.cpp
* Author: Branden Hitt
* Created on November 8th, 2015, 4:00 PM
* Purpose: Implementation for the Personal Info Class
*/
using namespace std;
//User Library for the Specification
#include "PersonalInfo.h"
void PrsInfo::setName(string n){
name=n;
}
void PrsInfo::setAdd(string a){
address=a;
}
void PrsInfo::setAge(unsigned short a){
age=a;
}
unsigned short PrsInfo::getAge(){
return age;
}
void PrsInfo::setPhn(string p){
phone=p;
} | true |
591bc0bf0efd3b903aec6b6c0265b7a930af8f28 | C++ | tatiandu/MARP | /Semana 4 - FULL/10.Arbol Libre/Source.cpp | ISO-8859-1 | 1,707 | 3.125 | 3 | [] | no_license |
// Tatiana Duarte Balvs
// Comentario general sobre la solucin,
// explicando cmo se resuelve el problema
#include <iostream>
#include <fstream>
#include "Grafo.h"
void dfs(const Grafo& g, int v, std::vector<bool>& visit, std::vector<int>& ant, int& visitados) {
visit[v] = true;
for (int w : g.ady(v)) {
if (!visit[w]) {
ant[w] = v;
dfs(g, w, visit, ant, visitados);
visitados++;
}
}
}
// funcin que resuelve el problema
// comentario sobre el coste, O(f(N)), donde N es ...
void resolver(const Grafo& g) {
std::vector<bool> visit(g.V(), false);
std::vector<int> ant(g.V());
int origen = 0, visitados = 0;
dfs(g, origen, visit, ant, visitados);
if (visitados >= g.V() - 1 && g.A() == g.V() - 1) { //-1 porque el primero no cuenta
std::cout << "SI" << '\n';
}
else {
std::cout << "NO" << '\n';
}
}
// resuelve un caso de prueba, leyendo de la entrada la
// configuracin, y escribiendo la respuesta
bool resuelveCaso() {
// leer los datos de la entrada
int V, A;
std::cin >> V >> A;
if (!std::cin) // fin de la entrada
return false;
Grafo g(V); //construye grafo
int v, w;
for (int i = 0; i < A; ++i) {
std::cin >> v >> w;
g.ponArista(v, w);
}
resolver(g);
return true;
}
int main() {
// ajustes para que cin extraiga directamente de un fichero
#ifndef DOMJUDGE
std::ifstream in("casos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf());
#endif
while (resuelveCaso());
// para dejar todo como estaba al principio
#ifndef DOMJUDGE
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif
return 0;
}
| true |
bddb59e5b3325198074c7ee4896696a35e884941 | C++ | Fen99/Dipole | /Src/Common.cpp | UTF-8 | 929 | 3.109375 | 3 | [] | no_license | #include "Common.h"
//========================================================================
//========================================================================
double operator*(const Vector3D& first, const Vector3D& second)
{
return first[0]*second[0] + first[1]*second[1] + first[2]*second[2];
}
ComplexSpaceFunction operator*(ComplexSpaceFunction first, ComplexSpaceFunction second)
{
return [first, second](const Vector3D& point) { return first(point)*second(point); };
}
ComplexSpaceFunction GetConjugate(ComplexSpaceFunction func)
{
return [func](const Vector3D& point) { return std::conj(func(point)); };
}
DoubleMatrix Make3DMatrixFromRows(std::vector<Vector3D> rows)
{
assert(rows.size() == 3);
DoubleMatrix result_matrix(3, 3);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
result_matrix(i, j) = rows[i][j];
}
}
return result_matrix;
} | true |
2cc8ac08e4d79d64f1e9753a864c2c60bd682b87 | C++ | eric-zhao/leetcode | /BT_levelTraverse_Rec.cpp | UTF-8 | 1,870 | 3.9375 | 4 | [] | no_license | /*Binary Tree Level Order Traversal: Given a binary tree, return the bottom-up level order traversal of its nodes' values.
This is done by recursion. The problem can be divided as: (1) once level n-1 is traversed by level, then level n is just needed to
be appended at last.*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
vector<vector<int>> myVector;
if (root == NULL) return myVector;
else{
vector<vector<int>> leftVector = levelOrderBottom(root->left);
vector<vector<int>> rightVector = levelOrderBottom(root->right);
int leftSize = leftVector.size();
int rightSize = rightVector.size();
vector<int> inner;
inner.push_back(root->val);
if(leftSize >= rightSize){
while(rightSize){
rightSize--;
leftSize--;
leftVector[leftSize].insert(leftVector[leftSize].end(), rightVector[rightSize].begin(), rightVector[rightSize].end());
}
myVector.insert(myVector.begin(), leftVector.begin(), leftVector.end());
myVector.push_back(inner);
}
else{
while(leftSize){
leftSize--;
rightSize--;
rightVector[rightSize].insert(rightVector[rightSize].begin(), leftVector[leftSize].begin(), leftVector[leftSize].end());
}
myVector.insert(myVector.begin(), rightVector.begin(), rightVector.end());
myVector.push_back(inner);
}
}
return myVector;
}
}; | true |
62395c5536161ee261f19900d204f841b758671f | C++ | zhenghongpeng/usacoepcpp | /usacoepcpp/convention/main.cpp | UTF-8 | 747 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int N,M,C;
int t[100000];
bool pos(int wait)
{
int buses = 1;
int fA = t[0];
int fI = 0;
for(int i=1;i<N;i++)
{
if(t[i] - fA > wait || i + 1 - fI > C)
{
buses += 1;
fA = t[i];
fI = i;
}
}
return (buses <= M);
}
int binSearch(int L,int H)
{
if(L == H) return L;
if(L + 1 == H)
{
if(pos(L)) return L;
return H;
}
int mid = (L+H)/2;
if(pos(mid)) return binSearch(L,mid);
else return binSearch(mid+1,H);
}
int main()
{
cin >> N >> M >> C;
for(int i=0;i<N;i++)
cin >> t[i];
sort(t,t+N);
cout << binSearch(0, 1000000000) << '\n';
} | true |
962be1fe8ced507fb2328440707bccb26b288228 | C++ | hexu1985/cpp_book_code | /boost.intro/signals2/parking_lot_guard.h | UTF-8 | 1,618 | 3.40625 | 3 | [] | no_license | #ifndef PARKING_LOT_GUARD_INC
#define PARKING_LOT_GUARD_INC
#include <string>
#include <vector>
#include <iostream>
#include "boost/shared_ptr.hpp"
#include "boost/signals2.hpp"
class parking_lot_guard {
typedef
boost::signals2::signal<void (const std::string&)> alarm_type;
typedef alarm_type::slot_type slot_type;
boost::shared_ptr<alarm_type> alarm_;
typedef std::vector<std::string> cars;
typedef cars::iterator iterator;
boost::shared_ptr<cars> cars_;
public:
parking_lot_guard()
: alarm_(new alarm_type), cars_(new cars) {}
boost::signals2::connection
connect_to_alarm(const slot_type& a) {
return alarm_->connect(a);
}
void operator()
(bool is_entering,const std::string& car_id) {
if (is_entering)
enter(car_id);
else
leave(car_id);
}
private:
void enter(const std::string& car_id) {
std::cout <<
"parking_lot_guard::enter(" << car_id << ")\n";
// 如果车辆已经在这,就触发警报
if (std::binary_search(cars_->begin(),cars_->end(),car_id))
(*alarm_)(car_id);
else // Insert the car_id
cars_->insert(
std::lower_bound(
cars_->begin(),
cars_->end(),car_id),car_id);
}
void leave(const std::string& car_id) {
std::cout <<
"parking_lot_guard::leave(" << car_id << ")\n";
// 如果是未登记的车辆,就触发警报
std::pair<iterator,iterator> p=
std::equal_range(cars_->begin(),cars_->end(),car_id);
if (p.first==cars_->end() || *(p.first)!=car_id)
(*alarm_)(car_id);
else
cars_->erase(p.first);
}
};
#endif
| true |
18bdf1989a81047f9946317eea558505ed88b02d | C++ | FroxCode/Portfolio-MOSH | /Tesla.h | UTF-8 | 1,971 | 2.578125 | 3 | [
"MIT"
] | permissive | ////////////////////////////////////////////////////////////
//
// Created by Connor
// Worked on by Dale
//
////////////////////////////////////////////////////////////
#ifndef _TESLA_H_
#define _TESLA_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "Turret.h"
#include "ShockBlast.h"
#include "SoundManager.h"
class Tesla : public Turret
{
public:
////////////////////////////////////////////////////////////
//
// Default constructor
//
////////////////////////////////////////////////////////////
Tesla();
////////////////////////////////////////////////////////////
//
// Default destructor
//
////////////////////////////////////////////////////////////
~Tesla();
////////////////////////////////////////////////////////////
//
// Overloaded constructor
//
////////////////////////////////////////////////////////////
Tesla(sf::Vector2f position, string const &texture, int radius);
////////////////////////////////////////////////////////////
//
// Sets the tesla position
//
////////////////////////////////////////////////////////////
void setPosition(Vector2f pos);
////////////////////////////////////////////////////////////
//
// Updates the object
//
////////////////////////////////////////////////////////////
void update();
////////////////////////////////////////////////////////////
//
// Changes the level of the tesla
//
////////////////////////////////////////////////////////////
void upgrade(int num);
////////////////////////////////////////////////////////////
//
// targets the nearest enemy based that isnt slowed
//
////////////////////////////////////////////////////////////
void targetEnemy(shared_ptr<Enemy> enemy);
int slow = 1;
void fire(Vector2f & target);
vector<shared_ptr<Bullet>> getBullets();
private:
SoundManager fired;
vector<shared_ptr<ShockBlast>> ammunition;
};
#endif | true |
4435c5d142e734dfd54dd4fe4e9fe5f9aa52378f | C++ | liuguoyou/retarget-toolkit | /shift_map/Common/traceback.cpp | UTF-8 | 1,289 | 3.203125 | 3 | [] | no_license |
/*
* Implementation for the Traceback class
*
* Author: Edward Alston Anthony
*
*/
#include <iostream>
#include <stdlib.h>
#include "traceback.h"
#ifdef USE_TRACEBACK
/* constructor */
Traceback::Traceback(int Levels)
{
Trace = new tracebackNodeType[Levels];
MaxTracebackLevels = Levels;
}
/* destructor */
Traceback::~Traceback()
{
delete Trace;
}
/* private function that returns n-number
* of blank space in a character array
*/
char *Traceback::Space(const int n)
{
char *space = new char[n+1] = {'\0'};
for (int i = 0; i < n; i++)
space[i] = ' ';
space[n] = '\0';
return space;
}
/* add an entry to the traceback history */
void Traceback::Add(const char *file, int line)
{
for (int i = 0; i < MaxTracebackLevels - 1; i++) {
strcpy(Trace[i].Filename, Trace[i+1].Filename);
Trace[i].Line = Trace[i+1].Line;
}
strcpy(Trace[MaxTracebackLevels - 1].Filename, file);
Trace[MaxTracebackLevels - 1].Line = line;
}
/* print the last n traceback recorded */
void Traceback::Print()
{
cerr << "Last " << MaxTracebackLevels << " location traced" << endl;
for (int i = 0; i < MaxTracebackLevels; i++) {
cerr << Space(MaxTracebackLevels - (i + 1)) << "FILE: " << Trace[i].Filename;
cerr << ", LINE : " << Trace[i].Line << endl;
}
}
#endif
| true |
1ad9aa5ea55f8179fdf6fea56bb1395341bf9514 | C++ | magicmoremagic/bengine-core | /test/test_a3_vmm_alloc.cpp | UTF-8 | 1,967 | 2.78125 | 3 | [
"MIT"
] | permissive | #ifdef BE_TEST
#include "a3_vmm_alloc.hpp"
#include <catch/catch.hpp>
#define BE_CATCH_TAGS "[core][core:a3][core:a3:VmmAlloc]"
using namespace be::a3;
TEST_CASE("be::a3::VmmAlloc", BE_CATCH_TAGS) {
REQUIRE(VmmAlloc::granularity >= VmmAlloc::alignment);
REQUIRE(VmmAlloc::granularity % VmmAlloc::alignment == 0);
VmmAlloc alloc;
std::size_t sizes[] = { 1, 2, 3, 8, 11, 1337, 4096 };
for (std::size_t size : sizes) {
REQUIRE(alloc.preferred_size(size) == VmmAlloc::alignment);
void* ptr = alloc.allocate(size);
REQUIRE(ptr != nullptr);
REQUIRE(reinterpret_cast<uintptr_t>(ptr) % VmmAlloc::granularity == 0);
memset(ptr, 0xF0, size);
SECTION("expand") {
REQUIRE_FALSE(alloc.expand(nullptr, 0, size));
REQUIRE_FALSE(alloc.expand(nullptr, size, size));
REQUIRE_FALSE(alloc.expand(nullptr, size, size + 1));
REQUIRE_FALSE(alloc.expand(nullptr, size, size * 2));
REQUIRE(alloc.expand(ptr, size, 0));
REQUIRE(alloc.expand(ptr, size, 1));
memset(ptr, 0xF0, size + 1);
REQUIRE(alloc.expand(ptr, size + 1, size));
memset(ptr, 0xF0, size * 2 + 1);
REQUIRE_FALSE(alloc.expand(ptr, size * 2 + 1, VmmAlloc::granularity));
REQUIRE(alloc.deallocate(ptr, size * 2 + 1));
}
SECTION("reallocate") {
REQUIRE(alloc.reallocate(ptr, size, size) == ptr);
REQUIRE(alloc.reallocate(ptr, size, size + 1) == ptr);
memset(ptr, 0xF0, size + 1);
REQUIRE(alloc.reallocate(ptr, size + 1, size * 2) == ptr);
memset(ptr, 0xF0, size * 2);
void* ptr2 = alloc.reallocate(ptr, size * 2, size + VmmAlloc::granularity);
CHECK(ptr != ptr2);
REQUIRE(ptr2 != nullptr);
REQUIRE(alloc.deallocate(ptr2, size + VmmAlloc::granularity));
}
REQUIRE(alloc.deallocate(nullptr, 0));
REQUIRE(alloc.deallocate(nullptr, size));
}
}
#endif
| true |
0a9ccfa66a94fbe1c0d9dfca0e52d4e1a3576295 | C++ | ejaandersson/EDA031 | /src/test/myclient.cc | UTF-8 | 6,698 | 3.3125 | 3 | [] | no_license | #include "clientmessagehandler.h"
#include <algorithm>
#include <iostream>
#include <cstdlib>
using namespace std;
int commandToInt(string &cmd) {
if (cmd.compare("help") == 0) {
return 0;
} else if (cmd.compare("listng") == 0){
return Protocol::COM_LIST_NG;
} else if (cmd.compare("createng") == 0) {
return Protocol::COM_CREATE_NG;
} else if (cmd.compare("deleteng") == 0) {
return Protocol::COM_DELETE_NG;
} else if (cmd.compare("listart") == 0) {
return Protocol::COM_LIST_ART;
} else if (cmd.compare("readart") == 0) {
return Protocol::COM_GET_ART;
} else if(cmd.compare("createart") == 0) {
return Protocol::COM_CREATE_ART;
} else if (cmd.compare("deleteart") == 0) {
return Protocol::COM_DELETE_ART;
}
return -1;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
cerr << "Required parameters: hostname portnumber" << endl;
exit(1);
}
int port = -1;
try {
port = stoi(argv[2]);
} catch (exception& e) {
cerr << "Port must be an integer." << endl;
exit(1);
}
if (port < 1025) {
cerr << "Port must be > 1024" << endl;
exit(1);
}
Connection* ptr = new Connection(argv[1], stoi(argv[2]));
shared_ptr<Connection> con = shared_ptr<Connection>(ptr);
if (!con->isConnected()) {
cerr << "Connection failed!" << endl;
exit(1);
}
cout << "Connected to server." << endl;
cout << "For a list of commands, input 'help'." << endl;
shared_ptr<MessageHandler> msgptr = make_shared<MessageHandler>(MessageHandler(con));
ClientMessageHandler cmh(msgptr);
string command;
while (cin >> command) {
int c = commandToInt(command);
try {
switch (c) {
case -1 : {
cout << "Invalid command. Use 'help' to see commands." << endl;
break;
}
case 0 : {
cout << "Valid commands:" << endl;
cout << "listng - Lists all newsgroups with id numbers." << endl;
cout << "createng - Creates a new newsgroup." << endl;
cout << "deleteng - Deletes a newsgroup." << endl;
cout << "listart - Lists all articles in a newsgroup." << endl;
cout << "readart - Reads an article in a newsgroup." << endl;
cout << "createart - Creates a new article in a newsgroup." << endl;
cout << "deleteart - Delets an article in a newsgroup." << endl;
break;
}
case Protocol::COM_LIST_NG : {
vector<string> names = cmh.listGroups();
if (names.empty()) {
cout << "There are no newsgroups." << endl;
} else {
cout << "The current newsgroups are: " << endl;
for (string &s : names) {
cout << s << endl;
}
}
break;
}
case Protocol::COM_CREATE_NG : {
string title;
cout << "Choose newsgroup name: ";
cin >> ws;
getline(cin, title);
cmh.createGroup(title);
cout << "Newsgroup created." << endl;
break;
}
case Protocol::COM_DELETE_NG : {
string group_id;
cout << "Newsgroup id number: ";
cin >> group_id;
int gId = -1;
try {
gId = stoi(group_id);
} catch (exception& e) {
cout << "Group id must be a number." << endl;
break;
}
if (cmh.deleteGroup(gId) == 0) {
cout << "Newsgroup deleted." << endl;
} else {
cout << "Invalid newsgroup id." << endl;
}
break;
}
case Protocol::COM_LIST_ART : {
string group_id;
cout << "Newsgroup id number: ";
cin >> group_id;
int gId = -1;
try {
gId = stoi(group_id);
} catch (exception& e) {
cout << "Group id must be a number." << endl;
break;
}
vector<string> arts = cmh.listArticles(gId);
if (arts.empty()) {
cout << "There are no articles in this newsgroup." << endl;
} else {
for (string &s : arts) {
cout << s << endl;
}
}
break;
}
case Protocol::COM_GET_ART :{
string group_id, art_id;
cout << "Newsgroup id number: ";
cin >> group_id;
int gId = -1;
try {
gId = stoi(group_id);
} catch (exception& e) {
cout << "Group id must be a number." << endl;
break;
}
cout << "Article id number: ";
cin >> art_id;
cout << endl;
int aId = -1;
try {
aId = stoi(art_id);
} catch (exception& e) {
cout << "Article id must be a number." << endl;
break;
}
vector<string> artInfo = cmh.getArticle(gId, aId);
if (artInfo.empty()) {
cout << "Article does not exist." << endl;
break;
}
cout << artInfo[0] << " " << artInfo[1] << endl;
cout << artInfo[2] << endl;
break;
}
case Protocol::COM_CREATE_ART : {
string group_id, title, author, text;
cout << "Choose newsgroup id number: ";
cin >> group_id;
int gId = -1;
try {
gId = stoi(group_id);
} catch (exception& e) {
cout << "Group id must be a number." << endl;
break;
}
cout << "Choose a title: ";
cin >> ws;
getline(cin, title);
cout << "Choose author name: ";
cin >> ws;
getline(cin, author);
cout << "Write article: ";
cin >> ws;
getline(cin, text);
if (cmh.createArticle(gId, title, author, text) == 0) {
cout << "Article created." << endl;
} else {
cout << "That newsgroup does not exist." << endl;
}
break;
}
case (Protocol::COM_DELETE_ART) : {
string group_id, art_id;
cout << "Newsgroup id number: ";
cin >> group_id;
int gId = -1;
try {
gId = stoi(group_id);
} catch (exception& e) {
cout << "Newsgroup id must be a number." << endl;
break;
}
cout << "Article id number: ";
cin >> art_id;
int aId = -1;
try {
aId = stoi(art_id);
} catch (exception& e) {
cout << "Article id must be a number." << endl;
break;
}
cout << endl;
if (cmh.deleteArticle(gId, aId) == 0) {
cout << "Article removed." << endl;
} else {
cout << "That article does not exist." << endl;
}
break;
}
}
}
catch (...) {
cerr << "Something went wrong!" << endl;
exit(1);
}
}
}
| true |