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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4111b619bfd0b4daa4c78c12ca788755f5698ac3 | C++ | orlinhristov/cportlib | /tests/event_ut.cpp | UTF-8 | 3,076 | 3.21875 | 3 | [] | no_license | #include <catch.hpp>
#include <cport/util/event.hpp>
#include <cport/util/thread_group.hpp>
#include <algorithm>
#include <atomic>
using namespace cport::util;
TEST_CASE("Block current thread on wait_for(), until timed out", "[event]")
{
event e;
REQUIRE_FALSE(e.signaled());
const auto result = e.wait_for(std::chrono::nanoseconds(1));
REQUIRE(std::cv_status::timeout == result);
REQUIRE_FALSE(e.signaled());
}
TEST_CASE("Block current thread on wait_until(), until timed out", "[event]")
{
event e;
REQUIRE_FALSE(e.signaled());
const auto result = e.wait_until(std::chrono::system_clock::now());
REQUIRE(std::cv_status::timeout == result);
REQUIRE_FALSE(e.signaled());
}
TEST_CASE("Block current thread on wait(), until signaled", "[event]")
{
event e;
REQUIRE_FALSE(e.signaled());
std::thread t([&](){ e.notify_all(); });
e.wait();
t.join();
REQUIRE(e.signaled());
e.reset();
REQUIRE_FALSE(e.signaled());
}
TEST_CASE("Block current thread on wait_for(), until signaled", "[event]")
{
event e;
REQUIRE_FALSE(e.signaled());
std::thread t([&](){ e.notify_all(); });
const auto result = e.wait_for(std::chrono::hours(1));
t.join();
REQUIRE(e.signaled());
e.reset();
REQUIRE_FALSE(e.signaled());
REQUIRE(std::cv_status::no_timeout == result);
}
TEST_CASE("Block current thread on wait_until(), until signaled", "[event]")
{
event e;
REQUIRE_FALSE(e.signaled());
std::thread t([&](){ e.notify_all(); });
const auto result = e.wait_until(std::chrono::time_point<std::chrono::system_clock>::max());
t.join();
REQUIRE(e.signaled());
REQUIRE(std::cv_status::no_timeout == result);
e.reset();
REQUIRE_FALSE(e.signaled());
}
TEST_CASE("Block multiple threads on event until all signaled", "[event]")
{
event e;
REQUIRE_FALSE(e.signaled());
const auto concurrency = std::max(2u, std::thread::hardware_concurrency());
std::atomic<unsigned> count{ 0 };
thread_group tg([&](){
const auto result = e.wait_for(std::chrono::seconds(5));
if (std::cv_status::timeout != result)
++count;
}, concurrency);
std::this_thread::sleep_for(std::chrono::seconds(1));
e.notify_all();
tg.join();
REQUIRE(e.signaled());
e.reset();
REQUIRE_FALSE(e.signaled());
REQUIRE(concurrency == count);
}
TEST_CASE("Block multiple threads on event until one is signaled", "[event]")
{
event e;
REQUIRE_FALSE(e.signaled());
const auto concurrency = std::max(2u, std::thread::hardware_concurrency());
std::atomic<unsigned> count{ 0 };
thread_group tg([&](){
const auto result = e.wait_for(std::chrono::seconds(2));
if (std::cv_status::timeout != result)
++count;
}, concurrency);
std::this_thread::sleep_for(std::chrono::seconds(1));
e.notify_one();
tg.join();
REQUIRE(e.signaled());
e.reset();
REQUIRE_FALSE(e.signaled());
REQUIRE(1 == count);
}
| true |
af9d42f96f342be3d6a58d73b9a3e6f0caf66377 | C++ | rohitganda/ScheduleFinder | /ScheduleFinder/ScheduleFinder/ScheduleEntry.h | UTF-8 | 453 | 2.65625 | 3 | [] | no_license | #ifndef __SCHEDULE_ENTRY__
#define __SCHEDULE_ENTRY__
#include <string>
#include "Constants.h"
using std::string;
struct ScheduleEntry{
string title;
size_t duration;
bool isVisited;
bool isIncluded;
ScheduleEntry(string name, size_t dur) :title(name), duration(dur)
{isVisited = false; isIncluded = false;}
ScheduleEntry(){
title = ""; duration = INVALID_DURATION;
isVisited = false; isIncluded = false;
}
};
#endif | true |
752a54b56f039be3a39e0fc736d573c788cc9eab | C++ | You-Yeon/Algorithm | /algorithm/algorithm/stack1.cpp | UTF-8 | 937 | 3.703125 | 4 | [] | no_license | #include <iostream>
#define MAXSIZE 100
using namespace std;
template<typename T>
class Stack
{
public:
int top;
int size;
T* values;
Stack()
{
size = MAXSIZE;
values = new T[size];
top = -1;
}
~Stack()
{
delete[] values;
}
void push(T value)
{
if (!isFull())
values[++top] = value;
else
cout << "Stack is Full" << endl;
}
void pop()
{
if (!empty())
top--;
else
cout << "Stack is Empty" << endl;
}
T Top()
{
if (!empty())
return values[top];
else
return NULL;
}
bool empty()
{
if (top < 0)
return true;
else
return false;
}
bool isFull()
{
if (top + 1 == size)
return true;
else
return false;
}
}; | true |
91d1ecf52700dd408a861ac80a071208ad6f99d6 | C++ | Gaurav047/CPP_STL_Competitive | /Samsung/DP/LIS.cpp | UTF-8 | 1,458 | 3.859375 | 4 | [] | no_license | // Optimal Substructure of a LIS problem:
/**
* Let arr[0...n-1] be the input array and L(i) be
* the length of the LIS ending at index i such that
* arr[i] is the last element of LIS.
* Then we can write L(i) as:
* L(i) = 1+max(L(j)) where 0<j<i and arr[j] < arr[i] ;
* L(i) = 1, if no such j exists.
* To find the LIS for a given array, we need to return max(L(i)) where 0<i<n.
* Thus, the LIS problem satisfies the optimal substructure property.
* **/
// A recursive and memoryless solution will look like:
#include <bits/stdc++.h>
using namespace std;
int _lis(int arr[], int n, int *max_ref){
//Base case
if ( n==1 )
return 1;
// 'max_ending_here' is length of LIS ending with arr[n-1]
int res, max_ending_here = 1;
//Recursively get the value of LIS
for ( int i=1 ; i<n ; i++ ){
res = _lis(arr, i, max_ref);
if ( arr[i-1] < arr[n-1] && res+1 > max_ending_here)
max_ending_here = res+1;
}
//compare max_ending_here with the overall max
if ( *max_ref < max_ending_here ){
*max_ref = max_ending_here;
}
return max_ending_here;
}
int lis(int arr[], int n){
int max = 1;
_lis(arr, n , &max);
return max;
}
int main(){
int arr[] = {10, 22, 9, 33, 21, 50, 41, 60};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Length of LIS is : " << lis(arr, n) << endl;
return 0;
} | true |
6929caf73c8a71a0da10aa228b74724a0a88ead7 | C++ | rocking-around/PoL1.62.002 | /src/shared/mll_fs/src/zip_eocd.h | UTF-8 | 2,120 | 2.515625 | 3 | [] | no_license | #if !defined(__ZIP_EOCD_H_INCLUDED_7552370787048739__)
#define __ZIP_EOCD_H_INCLUDED_7552370787048739__
namespace mll
{
namespace ml_encrypted_zip
{
#pragma pack(push,1)
//=====================================================================================//
// struct zip_EOCD_header //
//=====================================================================================//
struct zip_EOCD_header
{
// long integer - 4 bytes, short integer - 2 bytes
unsigned long m_signature;
unsigned short m_curr_disk_num;
unsigned short m_CDir_disk_num;
unsigned short m_entries_on_curr_disk;
unsigned short m_entries_total;
unsigned long m_CDir_size;
unsigned long m_CDir_start_offset;
unsigned short m_comment_length;
};
#pragma pack(pop)
//=====================================================================================//
// class zip_endOfCentralDir //
//=====================================================================================//
class EndOfCentralDirEntry
{
private:
zip_EOCD_header m_header;
std::string m_zip_comment;
public:
EndOfCentralDirEntry(std::istream &file);
EndOfCentralDirEntry(const EndOfCentralDirEntry &a);
~EndOfCentralDirEntry() {}
public:
unsigned count() { return m_header.m_entries_total; }
unsigned CDir_offset() { return m_header.m_CDir_start_offset; }
const std::string &zipfile_comment() { return m_zip_comment; }
private:
friend std::istream &operator >> (std::istream &is, EndOfCentralDirEntry &entry);
};
//=====================================================================================//
// std::istream &operator >> () //
//=====================================================================================//
inline std::istream &operator >> (std::istream &is, EndOfCentralDirEntry &entry)
{
is.read(reinterpret_cast<char *>(&entry.m_header), sizeof(entry.m_header));
return is;
}
}
}
#endif // !defined(__ZIP_EOCD_H_INCLUDED_7552370787048739__) | true |
3e40ff7147711bf4e8fb8fafd0deb8cdaa50bb92 | C++ | vesy53/SoftUni | /Programming Basics - C++/LabEndExercises/04.ComplexCondition/OnTimeForExam/OnTimeForExam.cpp | UTF-8 | 1,515 | 3.46875 | 3 | [
"MIT"
] | permissive | // OnTimeForExam.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int exam_hour, exam_minutes, arrival_hour, arrival_minutes;
cin >> exam_hour >> exam_minutes >> arrival_hour >> arrival_minutes;
int exam_total = exam_hour * 60 + exam_minutes;
int arrival_total = arrival_hour * 60 + arrival_minutes;
int difference = exam_total - arrival_total;
if (difference <= 30 && difference >=0)
{
int different_minutes = difference % 60;
cout << "On time" << endl;
if (different_minutes != 0)
{
cout << different_minutes << " minutes before the start" << endl;
}
}
else if (difference < 0)
{
difference = abs(difference);
int difference_hours = difference / 60;
int difference_minutes = difference % 60;
cout << "Late" << endl;
if (difference_hours !=0)
{
cout << difference_hours << ":" << setw(2) << setfill('0')
<< difference_minutes << " hours after the start" << endl;
}
else
{
cout << difference_minutes << " minutes after the start" << endl;
}
}
else if (difference > 30)
{
int different_hours = difference / 60;
int different_minutes = difference % 60;
cout << "Early" << endl;
if (different_hours != 0)
{
cout << different_hours << ":" << setw(2) << setfill('0')
<< different_minutes << " hours before the start" << endl;
}
else
{
cout << different_minutes << " minutes before the start" << endl;
}
}
return 0;
}
| true |
871db4a4889329e11022c225c63c4258d20499fd | C++ | Vlattte/kmbo-19 | /main.cpp | UTF-8 | 395 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <LinkedList.h>
using namespace std;
int main()
{
LinkedList l;
l.pushBack(1);
l.pushFront(0);
l.pushBack(2);
cout << "Stage 1: "; l.write(); cout << endl;
l.insert(1, 10);
cout << "Stage 2: "; l.write(); cout << endl;
l.erase(1);
cout << "Stage 2: "; l.write(); cout << endl;
l.reverse();
cout << "Stage 3: "; l.write(); cout << endl;
return 0;
}
| true |
59c0a35d27a32338e10fdac09e829425dca712cf | C++ | NelsonTorres/gpu | /SimpleFannData.cpp | UTF-8 | 627 | 2.828125 | 3 | [] | no_license | /*
* SimpleFannData.cpp
*
* Created on: 05/12/2017
* Author: nelson
*/
#include "SimpleFannData.h"
#include <stdio.h>
#include <stdlib.h>
unsigned readData(const char *path, float* input, float* output) {
unsigned num_data, num_input, num_output, i, j;
std::ifstream file;
file.open(path, std::ifstream::in);
file >> num_data >> num_input >> num_output;
for (i = 0; i < num_data; i++) {
for (j = 0; j < num_input; j++) {
file >> input[i * num_input + j];
}
for (j = 0; j < num_output; j++) {
file >> output[i * num_output + j];
}
}
file.close();
return num_data;
};
| true |
26ff17778cb79353fe8538709f856f1d21096cdf | C++ | nishchay121/Scaler-Academy-1 | /Contest/smallest_XOR.cpp | UTF-8 | 815 | 3.46875 | 3 | [] | no_license | // Given two Integer A and B. Find a number X such that A xor X is minimum possible and number of set bits in X equals to B.
int Solution::solve(int A, int B) {
int X = A;
int number_of_set = 0;
for(int i=0;i<=31;i++) {
if(X & (1 << i))
number_of_set++;
}
if(number_of_set == B)
return X;
if(number_of_set > B) {
int y = number_of_set - B;
for(int i=0;i<=31 && y > 0;i++) {
if(X & (1 << i)) {
X = X - (1 << i);
y--;
}
}
}
if(number_of_set < B) {
int y = B - number_of_set;
for(int i=0;i<=31 && y > 0;i++) {
if(!(X & (1 << i))) {
X = X + (1 << i);
y--;
}
}
}
return X;
}
| true |
2f76907352eb9bb722661e1f2634d79a5a076bda | C++ | Yenjamin/nibbler | /src/main.cpp | UTF-8 | 1,453 | 2.875 | 3 | [] | no_license | #include <dlfcn.h>
#include <iostream>
#include "Header.hpp"
#include "IGraphic.hpp"
void checkdimension(std::string width, std::string height)
{
std::regex num("^\\d+$");
if (std::regex_match(width, num) == true && std::regex_match(height, num) == true)
{
return ;
}
else
throw errors::typeError();
}
void checklib(std::string name)
{
std::regex libName("(ncurses|sfml|sdl)\\b");
if (std::regex_match(name, libName) == false)
throw errors::libError();
}
void checklimit(int w, int h)
{
if (w < 10 || h < 10)
throw errors::minError();
if (w > 50 || h > 50)
throw errors::maxError();
}
int main(int argc, char **argv)
{
try {
int w;
int h;
std::string lib = "sdl";
if (argc == 4)
{
checkdimension(argv[1], argv[2]);
checklib(argv[3]);
w = atoi(argv[1]);
h = atoi(argv[2]);
checklimit(w, h);
lib = argv[3];
GameEngine n(w, h);
n.gameLoop(lib);
}
else if (argc == 3)
{
checkdimension(argv[1], argv[2]);
w = atoi(argv[1]);
h = atoi(argv[2]);
std::cout << w << std::endl;
std::cout << h << std::endl;
checklimit(w, h);
GameEngine n(w, h);
n.gameLoop(lib);
}
else
{
throw errors::argumentError();
}
} catch (std::exception &e) {
std::cout << "Error: ";
std::cout << e.what() << std::endl;
} catch (std::string s) {
std::cout << "Error: " << s << std::endl;
} catch (const char* s) {
std::cout << "Error: " << s << std::endl;
}
return (0);
}
| true |
1dccb0379e4956f42da504ea95fc5fad4e44bfca | C++ | codegauravg/Basic_Programs | /main.cpp | UTF-8 | 494 | 3.3125 | 3 | [] | no_license | /* Author : Gaurav Gunjan
* Created By: Dexter's Lab
* Timestamp [16/01/2016 17:19]
* */
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
long int x=0,i=0,fact=1;
cout<<"Enter a number x to find the factorial of: ";
cin>>x;
if(x==0){
cout<<"The Factorial of "<<x<<" is: "<<1;
}
else{
for(i=x;i>=1;i--){
fact=fact*i;
}
cout<<"The Factorial of "<<x<<" is: "<<fact;
}
return 0;
} | true |
fa15a978a5bacd61db2c4ef992700875071ed68b | C++ | syed/tc | /profitcalculator-c++/ProfitCalculator.h | UTF-8 | 656 | 2.59375 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
#define FOR(i,s,e) for (int i = int(s); i != int(e); i++)
#define FORIT(i,c) for (typeof((c).begin()) i = (c).begin(); i != (c).end(); i++)
#define ISEQ(c) (c).begin(), (c).end()
class ProfitCalculator {
public: int percent(vector<string> items) {
double cp,sp;
int margin;
double t_sp,t_cp;
t_sp = t_cp = 0;
FOR(i,0,items.size())
{
istringstream input(items[i]);
input>>sp>>cp;
t_sp+=sp;
t_cp+=cp;
}
margin= ((t_sp-t_cp)/t_sp)*100;
return margin;
}
};
| true |
aba079e9522df880e97eeaba6bb7f75e01db75af | C++ | TakuyaI/FPSGame | /GameTemplate/Game/graphics/SkinModel.h | SHIFT_JIS | 5,647 | 2.765625 | 3 | [] | no_license | #pragma once
#include "Skeleton.h"
#include "SkinModelEffect.h"
/*!
*@brief FBX̏B
*/
enum EnFbxUpAxis {
enFbxUpAxisY, //Y-up
enFbxUpAxisZ, //Z-up
};
/*!
*@brief XLfNXB
*/
class SkinModel
{
public:
//bVƂ̃R[obNB
using OnFindMesh = std::function<void(const std::unique_ptr<DirectX::ModelMeshPart>&)>;
/*!
*@brief fXgN^B
*/
~SkinModel();
/*!
*@brief B
*@param[in] filePath [hcmot@C̃t@CpXB
*@param[in] enFbxUpAxis fbx̏㎲BftHgenFbxUpAxisZB
*/
void Init(const wchar_t* filePath, EnFbxUpAxis enFbxUpAxis = enFbxUpAxisZ);
/*!
*@brief f[hWnɕϊ邽߂̃[hsXVB
*@param[in] position f̍WB
*@param[in] rotation f̉]B
*@param[in] scale f̊g嗦B
*/
void UpdateWorldMatrix(CVector3 position, CQuaternion rotation, CVector3 scale);
/*!
*@brief {[B
*@param[in] boneName {[̖OB
*@return {[BȂꍇnullptrԂ܂B
*/
Bone* FindBone(const wchar_t* boneName)
{
int boneId = m_skeleton.FindBoneID(boneName);
return m_skeleton.GetBone(boneId);
}
/*!
*@brief f`B
*@param[in] viewMatrix JsB
* [hWn3DfJWnɕϊsłB
*@param[in] projMatrix vWFNVsB
* JWn3DfXN[WnɕϊsłB
*/
void Draw( EnRenderMode renderMode, CMatrix viewMatrix, CMatrix projMatrix );
/*!
*@brief XPg̎擾B
*/
Skeleton& GetSkeleton()
{
return m_skeleton;
}
/*!
*@brief bVB
*@param[in] onFindMesh bVƂ̃R[obN
*/
void FindMesh(OnFindMesh onFindMesh) const
{
for (auto& modelMeshs : m_modelDx->meshes) {
for (std::unique_ptr<DirectX::ModelMeshPart>& mesh : modelMeshs->meshParts) {
onFindMesh(mesh);
}
}
}
/*!
*@brief SRṼWX^ԍB
*/
enum EnSkinModelSRVReg {
enSkinModelSRVReg_DiffuseTexture = 0, //!<fBt[YeNX`B
enSkinModelSRVReg_BoneMatrix, //!<{[sB
};
/// <summary>
/// VhEV[o[̃tOݒ肷B
/// </summary>
/// <param name="flag">truenƃVhEV[o[ɂȂ</param>
/// <remarks>
/// VhEV[o[Ƃ͉e𗎂ƂIuWFNĝƂłB
/// VhELX^[ɂĐꂽAVhE}bv𗘗p
/// gɉe𗎂Ƃ܂B
/// IuWFNgVhEV[o[VhELX^[ɂȂĂꍇ
/// ZtVhE(̉eɗ)sƂł܂B
/// </remarks>
void SetShadowReciever(bool flag)
{
m_isShadowReciever = flag;
}
void SetNormalMap(ID3D11ShaderResourceView* srv)
{
m_normalMapSRV = srv;
}
void SetSpecularMap(ID3D11ShaderResourceView* srv)
{
m_specularMapSRV = srv;
}
private:
/*!
*@brief TvXe[g̏B
*/
void InitSamplerState();
/*!
*@brief 萔obt@̍쐬B
*/
void InitConstantBuffer();
/*!
*@brief XPg̏B
*@param[in] filePath [hcmot@C̃t@CpXB
*/
void InitSkeleton(const wchar_t* filePath);
/*
*@brief fBNVCg̏B
*/
void InitDirectionLight();
private:
//萔obt@B
struct SVSConstantBuffer {
CMatrix mWorld;
CMatrix mView;
CMatrix mProj;
CMatrix mLightView; //Cgr[sB
CMatrix mLightProj; //CgvWFNVsB
int isShadowReciever; //VhEV[o[tOB
int isHasNormalMap; //@}bṽtOB
int isHasSpecuraMap;//XyL}bṽtOB
};
static const int NUM_DIRECTION_LIGHT = 4; //fBNVCg̐B
//fBNVCgB
struct SDirectionLight {
CVector4 direction[NUM_DIRECTION_LIGHT];
CVector4 color[NUM_DIRECTION_LIGHT];
CVector4 eyePos;
CVector4 specPow[NUM_DIRECTION_LIGHT];
};
struct SLight {
SDirectionLight directionLight;
float envPow;
};
static const int NUM_POINT_LIGHT = 13; //|CgCg̐B
//|CgCgB
struct SPointLight {
CVector4 position[NUM_POINT_LIGHT]; //ʒuB
CVector4 color[NUM_POINT_LIGHT]; //J[B
CVector4 attn[NUM_POINT_LIGHT];
};
EnFbxUpAxis m_enFbxUpAxis = enFbxUpAxisZ; //!<FBX̏B
ID3D11Buffer* m_cb = nullptr; //!<萔obt@B
Skeleton m_skeleton; //!<XPgB
CMatrix m_worldMatrix; //!<[hsB
DirectX::Model* m_modelDx; //!<DirectXTK郂fNXB
ID3D11SamplerState* m_samplerState = nullptr; //!<TvXe[gB
SLight m_light;
ID3D11Buffer* m_lightCb = nullptr; //!Cgp̒萔obt@B
SPointLight m_pointLightList;
ID3D11Buffer* m_pointLightCb = nullptr;
bool m_isShadowReciever = false; //VhEV[o[̃tOB
ID3D11ShaderResourceView* m_normalMapSRV = nullptr; //@}bvSRVB
ID3D11ShaderResourceView* m_specularMapSRV = nullptr; //XyL}bvSRV
};
| true |
fd794d74c978d95ff17b41230fafc282e45cca2c | C++ | JeremyVun1/smart-plants-arduino | /WaterPump.cpp | UTF-8 | 1,477 | 2.9375 | 3 | [] | no_license | #include "WaterPump.h"
WaterPump::WaterPump(int pin, int dir1, int dir2, int mSpeed)
: _pin(pin), _dir1(dir1), _dir2(dir2), _mSpeed(mSpeed), _mode(AUTO), _isOn(false), stateChanged(false) {
pinMode(_pin, OUTPUT);
pinMode(_dir1, OUTPUT);
pinMode(_dir2, OUTPUT);
this->off();
};
void WaterPump::autoMode() {
if (!_mode == AUTO) {
_mode = AUTO;
stateChanged = true;
}
};
void WaterPump::manualMode() {
if (!_mode == MANUAL) {
_mode = MANUAL;
stateChanged = true;
}
}
void WaterPump::on(bool isUserCmd) {
if (isUserCmd && _mode == AUTO)
return;
if (!isUserCmd && _mode == MANUAL)
return;
if (!_isOn) {
digitalWrite(_dir1, HIGH);
digitalWrite(_dir2, LOW);
analogWrite(_pin, _mSpeed);
_isOn = true;
stateChanged = true;
}
};
void WaterPump::off(bool isUserCmd) {
if (isUserCmd && _mode == AUTO)
return;
if (!isUserCmd && _mode == MANUAL)
return;
if (_isOn) {
digitalWrite(_dir1, LOW);
digitalWrite(_dir2, LOW);
_isOn = false;
stateChanged = true;
}
};
WaterPumpModel WaterPump::getState() {
WaterPumpModel result;
if (_isOn)
strcpy(result.state, "1");
else strcpy(result.state, "0");
if (_mode == AUTO)
strcpy(result.mode, "a");
else strcpy(result.mode, "m");
result.mSpeed = _mSpeed;
stateChanged = false;
return result;
};
void WaterPump::changeSpeed(int newSpeed) {
_mSpeed = constrain(newSpeed, 0, 255);
analogWrite(_pin, _mSpeed);
};
| true |
34bc3163df1a84393c720fba2d41e42224251879 | C++ | AllenLiuX/My-LeetCode | /leetcode-cpp/1-99/#75 颜色分类.cpp | UTF-8 | 1,377 | 3.8125 | 4 | [] | no_license | Tags: 排序
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
进阶:
一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
你能想出一个仅使用常数空间的一趟扫描算法吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-colors
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
---
class Solution {
public:
void sortColors(vector<int>& nums) {
int p0 = 0, p2 = nums.size()-1;
int cur = 0;
while(cur<=p2){ //等于很重要!交换后最后一个也需要考虑!比如201->102,此时cur和p2都等于1.
if(nums[cur]==0){
swap(nums[p0++], nums[cur++]);
}
else if(nums[cur]==2){
swap(nums[p2--], nums[cur]);
}
else{
cur++;
}
}
}
}; | true |
66567bf5e1d80e061589d75a442dd55718f4b8f6 | C++ | pierrelux/aquaviz | /src/util/QuaternionToRotationMatrix.h | UTF-8 | 1,825 | 2.84375 | 3 | [] | no_license | /**
* @author Pierre-Luc Bacon <pbacon@cim.mcgill.ca>
*/
#ifndef QUATERNIONTOROTATIONMATRIX_H_
#define QUATERNIONTOROTATIONMATRIX_H_
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <functional>
#include "Quaternion.h"
namespace ublas = boost::numeric::ublas;
struct QuaternionToRotationMatrix : std::unary_function <boost::numeric::ublas::matrix<double>, boost::numeric::ublas::vector<double> > {
boost::numeric::ublas::matrix<double> operator() (const boost::numeric::ublas::vector<double>& q) const
{
using namespace ublas;
/**
* q_axis = q(1:3);
* Q = q_axis * q_axis';
*/
vector<double> qAxis = project(q, range(0, 3));
matrix<double> Q = outer_prod(qAxis, qAxis);
/*
qx = [ 0 -q(3) q(2);
q(3) 0 -q(1);
-q(2) q(1) 0];
*/
matrix<double> qx(3,3);
qx(0,0) = 0;
qx(0,1) = -qAxis(2);
qx(0,2) = qAxis(1);
qx(1,0) = qAxis(2);
qx(1,1) = 0;
qx(1,2) = -qAxis(0);
qx(2,0) = -qAxis(1);
qx(2,1) = qAxis(0);
qx(2,2) = 0;
/**
* Cq = (2*q(4)^2-1)*eye(3) - 2*q(4)*qx + 2*Q;
*/
identity_matrix<double> I(3);
return (2*q(3)*q(3)-1)*I - 2*q(3)*qx + 2*Q;
}
boost::numeric::ublas::matrix<double> operator() (const Quaternion &q) const
{
return this->operator()(q.getX(),q.getY(),q.getZ(),q.getW());
}
boost::numeric::ublas::matrix<double> operator() (double x, double y, double z, double w) const
{
boost::numeric::ublas::vector<double> q(4);
q(0) = x; q(1) = y; q(2) = z; q(3) = w;
return this->operator()(q);
}
};
#endif /* QUATERNIONTOROTATIONMATRIX_H_ */
| true |
3d194665adbe562c4c122aaee719eac755d9f05f | C++ | rishuverma/Solution | /Kingdom Division.cpp | UTF-8 | 2,410 | 3.375 | 3 | [] | no_license | /**
* https://www.hackerrank.com/challenges/construct-the-array/problem
*/
#include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);
/*
* Complete the 'countArray' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. INTEGER k
* 3. INTEGER x
*/
long recursol (int ** dp, int n, int k, int x) {
if (n == 2) {
return dp[n][x == 1] = (x!=1);
}
if (dp[n][x == 1] != -1) {
return dp[n][x == 1];
}
long ans = 0, mod = 1000000007;
// fixing '1' in (n-1)th position
long part1 = ((x == 1) ? 0 : ((recursol (dp, n-1, k, 1)) % mod));
// fixing anything else, say '2' in (n-1)th pos
long part2 = (x == 1 ? (k-1) : (k-2)) * (recursol (dp, n-1, k , 2) % mod);
ans += ((part1 + part2) % mod);
return dp[n][x == 1] = ans;
}
long countArray(int n, int k, int x) {
// Return the number of ways to fill in the array.
int ** dp = new int * [n+1];
for (int i = 0; i <= n; ++i) {
dp[i] = new int [2];
dp[i][0] = dp[i][1] = -1;
}
return recursol(dp, n, k, x);
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string first_multiple_input_temp;
getline(cin, first_multiple_input_temp);
vector<string> first_multiple_input = split(rtrim(first_multiple_input_temp));
int n = stoi(first_multiple_input[0]);
int k = stoi(first_multiple_input[1]);
int x = stoi(first_multiple_input[2]);
long answer = countArray(n, k, x);
fout << answer << "\n";
fout.close();
return 0;
}
string ltrim(const string &str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}
string rtrim(const string &str) {
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);
return s;
}
vector<string> split(const string &str) {
vector<string> tokens;
string::size_type start = 0;
string::size_type end = 0;
while ((end = str.find(" ", start)) != string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end + 1;
}
tokens.push_back(str.substr(start));
return tokens;
}
| true |
5e695f9f9b562660e733e08a5288cfc71acdd0b3 | C++ | greenveg/arduinoRepo | /Wordomat archive/Wordomat3/storage.ino | UTF-8 | 956 | 3.078125 | 3 | [] | no_license |
void loadFromEeprom() {
int address = 0;
float floatValue = 0.0;
int intValue = 0;
for (int i = 0; i < NUMBER_OF_SLOTS; i++) {
EEPROM.get(address, floatValue);
prices[i] = floatValue;
address += sizeof(floatValue);
}
for (int i = 0; i < NUMBER_OF_SLOTS; i++) {
EEPROM.get(address, intValue);
stash[i] = intValue;
address += sizeof(intValue);
}
for (int i = 0; i < NUMBER_OF_COINS; i++) {
EEPROM.get(address, floatValue);
coinValues[i] = floatValue;
address += sizeof(floatValue);
}
}
void writeToEeprom() {
int address = 0;
for (int i = 0; i < NUMBER_OF_SLOTS; i++) {
EEPROM.put(address, prices[i]);
address += sizeof(prices[i]);
}
for (int i = 0; i < NUMBER_OF_SLOTS; i++) {
EEPROM.put(address, stash[i]);
address += sizeof(stash[i]);
}
for (int i = 0; i < NUMBER_OF_COINS; i++) {
EEPROM.put(address, coinValues[i]);
address += sizeof(coinValues[i]);
}
}
| true |
c0bd1b0ee02a98ba9ca03c77b5f0c1ba0ef083ed | C++ | Athos06/SkyPlatforms | /src/BossAnimation.cpp | UTF-8 | 1,677 | 2.921875 | 3 | [] | no_license | #include "BossAnimation.h"
BossAnimation::BossAnimation(Ogre::Entity* entity){
m_pEntity = entity;
m_pActiveAnimation = 0;
activeAnimID = ANIM_NONE;
}
BossAnimation::~BossAnimation(){
m_pEntity = 0;
}
void BossAnimation::setupAnimations(){
m_pAnimations[ANIM_IDLE] = m_pEntity->getAnimationState("Idle");
m_pAnimations[ANIM_IDLE]->setLoop(true);
m_pAnimations[ANIM_ATTACKING] = m_pEntity->getAnimationState("Attack");
m_pAnimations[ANIM_ATTACKING]->setLoop(true);
m_pAnimations[ANIM_DIE] = m_pEntity->getAnimationState("Die");
m_pAnimations[ANIM_DIE]->setLoop(false);
//por defecto activamos la animacion idle
setAnimation(ANIM_IDLE);
activeAnimID = ANIM_IDLE;
}
void BossAnimation::setAnimation(BossAnimation::AnimID ANIM_ID){
//desactivar la anterior animacion
if( m_pActiveAnimation){
m_pActiveAnimation->setEnabled(false);
//reiniciamos a la posicion de inicio cada vez que cambiamos a una
//animacion diferente para que en el caso de que no sea loop
//no se quede siempre fija en el ultimo frame de la animacion al
//volver a ejecutarla
if( !(activeAnimID == ANIM_ID) )
{
m_pAnimations[ANIM_ID]->setTimePosition(0);
}
}
//activar la nueva animacion
m_pAnimations[ANIM_ID]->setEnabled(true);
m_pAnimations[ANIM_ID]->setWeight(1);
m_pActiveAnimation = m_pAnimations[ANIM_ID];
activeAnimID = ANIM_ID;
}
void BossAnimation::reset(){
m_pAnimations[ANIM_IDLE]->setTimePosition(0);
m_pAnimations[ANIM_ATTACKING]->setTimePosition(0);
m_pAnimations[ANIM_DIE]->setTimePosition(0);
}
void BossAnimation::update(double deltaTime){
float animationSpeed = 1.15;
m_pActiveAnimation->addTime(deltaTime/1000 * animationSpeed);
} | true |
22960ffc0e6ff2c62aee2cabbf3cb894c6df9ca8 | C++ | ddt-sawa/meikai_cpp_sawa | /6-19.cpp | UTF-8 | 1,689 | 3.75 | 4 | [] | no_license | /*
* 6-19.cpp
*
* Created on: 2018/06/24
* Author: syuka
*/
/*演習6-19 List6-21の関数rを、不正な添え字に対して安全に動作するものに書き換えよ。
*静的記憶域期間をもつint型の変数を関数内部で定義して、idxが0以上a_size未満でなければ、
*その変数への参照を返却すること
*/
#include<iostream>
using namespace std;
//配列の要素数
const int arraySize = 5;
/**
*引数として受け取った配列の要素への参照を返却する
* @param arrayIndex 配列の要素
* @return intArray[arrayIndex] 配列の要素への参照, (safetyValue 添え字が不正だった場合)
* @author Sawa
* @since 7.17
*/
int& returnArray(int arrayIndex)
{
//不正な添え字を受け取った場合に返却する数値
static int safetyValue;
//添え字が0未満もしくは要素数以上だった場合
if (arrayIndex < 0 || arrayIndex > arraySize) {
//仮の数値(0)を返す
return safetyValue;
}
//配列の宣言
static int intArray[arraySize];
//添え字によって指定された配列の要素への参照を返却
return intArray[arrayIndex];
}
int main()
{
//関数内の配列要素に値を走査代入するループ
for (int firstCounter = 0; firstCounter < arraySize; ++firstCounter) {
//添え字と同じ値を要素に代入
returnArray(firstCounter) = firstCounter;
}
//関数内の配列要素を走査表示するループ
for (int firstCounter = 0; firstCounter < arraySize; ++firstCounter) {
//関数を呼び出して、配列要素を表示
cout << "returnArray(" << firstCounter << ") = " << returnArray(firstCounter) << '\n';
}
}
| true |
27768928d6861d2bd748519ccdcbe1e48814e943 | C++ | haruto-k/PC-Same-party | /C++/やさしいC++/Sample/練習/4_2.cpp | SHIFT_JIS | 351 | 3.390625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
double height,width;
cout << "Op`̍͂ĂB\n";
cin >> height;
cout << "Op`̒ӂ͂ĂB\n";
cin >> width;
cout << "Op`̖ʐς" << height * width / 2 << "łB\n";
return 0;
}
| true |
11f99fa4a756e8ae607d9b27b824a748d2cb81b4 | C++ | AlbertoTrapiello/LAB | /Tema4_inicial_2012/Pang/src/Esfera.cpp | UTF-8 | 1,322 | 3.171875 | 3 | [] | no_license | #include "Esfera.h"
#include "glut.h"
#include <math.h>
Esfera::Esfera()
{
rojo = verde = azul = 255; //blanco
radio = 1.0f;
aceleration.y = -9.8f;
velocity.x = 5;
velocity.y = 20;
}
Esfera::Esfera(float rad, float x, float y, float vx, float vy)
{
radio = rad;
position.x = x;
position.y = y;
velocity.x = vx;
velocity.y = vy;
rojo = verde = 255;
azul = 100; //color distinto
aceleration.y = -9.8;
}
Esfera::~Esfera()
{
}
void Esfera::Dibuja()
{
glColor3ub(rojo, verde, azul);
glTranslatef(position.x, position.y, 0);
glutSolidSphere(radio, 20, 20);
glTranslatef(-position.x, -position.y, 0);
}
void Esfera::Mueve(float t)
{
position = position + velocity * t + aceleration * (0.5f*t*t);
velocity = velocity + aceleration * t;
}
void Esfera::setPos(float ix, float iy)
{
position.x = ix;
position.y = iy;
}
void Esfera::setColor(unsigned char r, unsigned char a , unsigned char v)
{
rojo = r;
azul = a;
verde = v;
}
void Esfera::setRadio(float radio)
{
this->radio = radio;
}
void Esfera::setVel(float ix, float iy)
{
velocity.x = ix;
velocity.y = iy;
}
float Esfera::distancia(Esfera & e)
{
float distancia;
float ix = (e.position.x - this->position.x);
float iy = (e.position.y - this->position.y);
distancia = sqrt(ix*ix + iy * iy)-e.radio-this->radio;
return distancia;
}
| true |
9981e7d5dd516d413c949e84cb4bf2fbe74bd396 | C++ | Lukemtesta/Cpp-openCV---Rendering-a-Scene-Described-by-a-File | /Code/CairoDisplay.cpp | UTF-8 | 3,916 | 2.65625 | 3 | [] | no_license | #include "CairoDisplay.h"
#include <math.h>
#include <iostream>
namespace SceneDisplay {
using namespace std;
//CairoDisplay::CairoDisplay() : display(NULL), surface(NULL), record(NULL), context(NULL) {}
CairoDisplay::CairoDisplay(int width, int height) throw(DisplayException) : display(XOpenDisplay(NULL)), surface(NULL), record(NULL), context(NULL) {
resize(width,height);
}
CairoDisplay::~CairoDisplay(){
if(context) cairo_destroy(context);
if(surface) cairo_surface_destroy(surface);
if(record) cairo_surface_destroy(record);
if(display) XCloseDisplay(display);
}
void CairoDisplay::resize( int width, int height ) throw(DisplayException) {
BaseDisplay::resize(width,height);
// clear up previous canvas
if(context) cairo_destroy(context);
if(surface) cairo_surface_destroy(surface);
if(record) cairo_surface_destroy(record);
if(display) XCloseDisplay(display);
// open xlib display & window
display = XOpenDisplay(NULL);
if(!display)
throw DisplayException("Could not open display (Xlib error)");
screen = DefaultScreen(display);
rootWindow = RootWindow(display, screen);
window = XCreateSimpleWindow(display,
rootWindow, 1, 1, width, height, 0,
BlackPixel(display, screen),
BlackPixel(display, screen)
);
XStoreName(display, window, "CairoDisplay");
XSelectInput(display, window, ExposureMask|ButtonPressMask);
XMapWindow(display, window);
// create Cairo surface
region.x = region.y = 0.0;
region.width = (float)width;
region.height = (float)height;
record = cairo_recording_surface_create(CAIRO_CONTENT_COLOR, ®ion);
surface = cairo_xlib_surface_create( display, window, DefaultVisual(display,0), width, height);
if(!surface)
throw DisplayException("Could not Cairo surface (Xlib front-end)!");
// initialize Cairo context for drawing
context = cairo_create(record);
cairo_rectangle(context, 0.0, 0.0, width, height);
cairo_set_source_rgb(context, 0.0, 0.0, 0.0);
cairo_fill(context);
}
void CairoDisplay::show() throw(DisplayException) {
if( display && surface ){
cairo_show_page(context);
do {
XNextEvent(display, &event);
if(event.type==Expose && event.xexpose.count<1){
if(context) cairo_destroy(context);
context = cairo_create(surface);
cairo_set_source_surface(context, record, 0.0, 0.0);
cairo_paint(context);
cairo_show_page(context);
}
} while( event.type != ButtonPress );
} else
throw DisplayException("Display front-end (Cairo+Xlib) needs to be initialised to a correct size before calling the show() method!");
if(context) cairo_destroy(context);
context = cairo_create(record);
}
void CairoDisplay::drawCircle( int x, int y, int radius, int red, int green, int blue ) throw(DisplayException) {
if( display && context ){
cairo_set_line_width( context, 0.0 );
cairo_set_source_rgb( context, (float)red/255.0, (float)green/255.0, (float)blue/255.0 );
cairo_translate(context, (float)x, (float)y);
cairo_arc(context, 0.0, 0.0, radius, 0, 2 * M_PI);
cairo_fill(context);
cairo_stroke(context);
cairo_identity_matrix(context);
} else
throw DisplayException("Display front-end (Cairo+Xlib) needs to be initialised to a correct size before drawing!");
}
void CairoDisplay::drawRectangle( int x, int y, int width, int height, int red, int green, int blue ) throw(DisplayException) {
if( display && context ){
cairo_set_line_width( context, 0.0 );
cairo_set_source_rgb( context, (float)red/255.0, (float)green/255.0, (float)blue/255.0 );
cairo_translate(context, (float)x, (float)y);
cairo_rectangle(context, 0.0, 0.0, width, height);
cairo_fill(context);
cairo_stroke(context);
cairo_identity_matrix(context);
} else
throw DisplayException("Display front-end (Cairo+Xlib) needs to be initialised to a correct size before drawing!");
}
} // SceneDisplay
| true |
79a73e78fb70718094a69fba14bf101b092021f1 | C++ | michaelbzms/System-Programming-Final-Project | /webcrawler/jobExecutor/src/textfiles_parsing.cpp | UTF-8 | 8,993 | 3.03125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cstring>
#include <fstream>
#include <dirent.h> // for directory traversing
#include "../headers/inverted_index.h"
#include "../headers/util.h"
#include "../headers/textfiles_parsing.h"
#include "../headers/map.h"
using namespace std;
/* Global variables */
extern char **subdirectories; // a table containing ONLY this worker's directory paths in C strings
extern int subdirfilesize; // its count
extern Trie *inverted_index; // the inverted_index (Trie) for this worker
extern Map *map;
/* Local Functions */
int parse_text(int subdir_num, char *name);
int count_lines(char *filepath, intnode *&line_sizes);
int parse_subdirectories(){ // parse all text (ascii) files in all your directories
if ( subdirfilesize < 0 ){
cerr << "Error parsing subdirectories: subdirectories not initialized yet" << endl;
return -3;
}
// First count how many text files at our jurisdiction
int filecount = 0;
for (int i = 0 ; i < subdirfilesize && subdirectories[i] != NULL ; i++) { // for each directory assigned to this worker
DIR *pdir = NULL;
pdir = opendir(subdirectories[i]);
if (pdir == NULL) {
cerr << "\nERROR! pdir could not be initialised correctly";
return -1;
}
struct dirent *pent = NULL;
while (pent = readdir(pdir)) { // while there is still something in the directory to list
if (strcmp(pent->d_name, ".") != 0 && strcmp(pent->d_name, "..") != 0) filecount++;
}
closedir(pdir);
}
// Create inverted_index and map structures
inverted_index = new Trie();
map = new Map(filecount);
// Parse each text file, adding its contents to inverted_index and map
for (int i = 0 ; i < subdirfilesize && subdirectories[i] != NULL ; i++) {
DIR *pdir = NULL;
pdir = opendir(subdirectories[i]);
if (pdir == NULL) {
cerr << "\nERROR! pdir could not be initialised correctly";
return -1;
}
struct dirent *pent = NULL;
while (pent = readdir(pdir)) { // while there is still something in the directory to list
if (strcmp(pent->d_name, ".") != 0 && strcmp(pent->d_name, "..") != 0) {
int feedback = parse_text(i, pent->d_name); // parse that text file
if (feedback < 0) {
cerr << "Something went wrong parsing a text file. Feedback: " << feedback << "\n"
<< "fileID: " << i << " name: " << pent->d_name << endl;
return -2;
}
}
}
closedir(pdir);
}
return 0;
}
int parse_text(int subdir_num, char *name){ // parses a single textfile
static int fileID = 0; // the fileID for each file we parse with this function
char *filepath = new char[strlen(subdirectories[subdir_num]) + strlen(name) + 2]; // +1 for '/' and +1 for '\0'
strcpy(filepath, subdirectories[subdir_num]);
strcat(filepath, "/");
strcat(filepath, name);
intnode *line_sizes = NULL; // a list of the sizes of each line (needed for the dynamic allocation of them in our "map" structure)
int linecount = count_lines(filepath, line_sizes);
if ( linecount <= 0 ) { // if count_lines failed then return error
while (line_sizes != NULL){ // after cleaning up the already created int list
intnode *tmp = line_sizes->next;
delete line_sizes;
line_sizes = tmp;
}
delete[] filepath;
return -1;
}
ifstream textfile(filepath);
if ( !line_sizes ) { // should not fail since it must have worked on count_lines()
cerr << "Unexpected error reopening a textfile!\n";
while (line_sizes != NULL){ // cleanup int list
intnode *tmp = line_sizes->next;
delete line_sizes;
line_sizes = tmp;
}
delete[] filepath;
return -2;
}
map->add_new_textfile(filepath, linecount); // add a new entry for this textfile on our map structure
intnode *l = line_sizes; // l is used to traverse the int list
char ch;
char *curline = NULL;
int curlinelen = -1;
for ( int i = 0 ; i < linecount && textfile.peek() != EOF ; i++ ){
ignore_whitespace(textfile); // ignore whitespace at the start of each line
if ( textfile.peek() == '\n' ){ // Ignore empty lines
textfile.ignore(1); // ignore it
i--; // without adding to i
continue;
}
if ( l == NULL ){ // should not happen
cerr << "Unexpected error: int list of line_sizes not complete?\n";
break;
}
curlinelen = l->val + 1; // l->val is the chars on this line as counted in the 1st pass, + 1 for '\0'
curline = new char[curlinelen];
int j = 0;
bool html_tag = false;
textfile.get(ch);
while ( ch != '\n' ){ // read char-by-char on this line and write each char to curline[j], while ignore html tages "<...>"
if ( ch == '<' ) html_tag = true;
if ( j > l->val || (j == l->val && !html_tag) ){ // should not happen
cerr << "Unexpected error: Possible wrong calculation; More chars in a document than anticipated!\n";
cerr << "j = " << j << ", l->val = " << l->val << endl;
break;
}
if (!html_tag) {
curline[j++] = ch;
map->byteCount++; // increment total number of bytes found
}
if ( ch == '>' ) html_tag = false;
textfile.get(ch);
}
curline[j] = '\0'; // add the final '\0'
l = l->next; // move to the current int node
// Add this line to our map structure
map->lineCount++; // increment total number of lines found
int fb = map->insert_line_to_textfile(fileID, i, curline, curlinelen);
if ( !fb ){
cerr << "Unexpected warning: could not insert a line to a textfile in map\n";
}
// Add each word (using white space as delimiter in strtok) to the inverted index, but only if line is not actually empty without the html tags
if ( strcmp(curline, "") != 0 ) {
char *wordptr;
wordptr = strtok(curline, " \t");
while (wordptr != NULL) {
inverted_index->insert(wordptr, fileID, i);
map->wordCount++; // increment total number of words found
wordptr = strtok(NULL, " \t");
}
}
delete[] curline;
}
// increment fileID static counter for next call
fileID++;
// cleanup int list
while (line_sizes != NULL){
intnode *tmp = line_sizes->next;
delete line_sizes;
line_sizes = tmp;
}
delete[] filepath;
return 0;
}
int count_lines(char *filepath, intnode *&line_sizes) { // This is the 1st pass of each textfile
ifstream textfile(filepath);
if (!textfile){ // if we can not open the textfile return error
cerr << "Cannot open textfile" << endl;
return -1;
}
int line_count = 0; // the number of lines aka documents
int char_count; // the count of the (C String) document in each line, which is saved on an int list
char ch;
intnode *l = line_sizes; // l is used to create & traverse a list of integers
while ( textfile.peek() != EOF ) {
ignore_whitespace(textfile); // ignore possible white space at the start of each line
if (textfile.peek() == '\n') { textfile.ignore(1); continue; } // empty line? Ignore it
line_count++; // increment line_count
if (line_sizes == NULL){
line_sizes = l = new intnode;
} else{
l->next = new intnode;
l = l->next;
}
char_count = 0;
textfile.get(ch);
bool html_tag = false;
while ( ch != '\n' ) { // read char-by-char each line, while ignore html tags "<...>"
if ( ch == '<' ) html_tag = true;
if (!html_tag) char_count++; // count how many chars in a line
if ( ch == '>' ) html_tag = false;
textfile.get(ch);
}
l->val = char_count; // save how many chars there are in each line on line_sizes int list
l->next = NULL;
}
return line_count;
}
| true |
6e86577b934d1e0cbe2014f0acde80b733752f9f | C++ | R0dri/Arduino | /sketch_mar04a/sketch_mar04a.ino | UTF-8 | 1,898 | 2.625 | 3 | [] | no_license | /*
* Simple demo, should work with any driver board
*
* Connect STEP, DIR as indicated
*
* Copyright (C)2015-2017 Laurentiu Badea
*
* This file may be redistributed under the terms of the MIT license.
* A copy of this license has been included with this distribution in the file LICENSE.
*/
#include <Arduino.h>
#include "BasicStepperDriver.h"
// Motor steps per revolution. Most steppers are 200 steps or 1.8 degrees/step
#define MOTOR_STEPS 200
#define RPM 30
// Since microstepping is set externally, make sure this matches the selected mode
// If it doesn't, the motor will move at a different RPM than chosen
// 1=full step, 2=half step etc.
#define MICROSTEPS 16
// All the wires needed for full functionality
#define DIR 8
#define STEP 9
//Uncomment line to use enable/disable functionality
#define SLEEP 13
// 2-wire basic config, microstepping is hardwired on the driver
//BasicStepperDriver stepper(MOTOR_STEPS, DIR, STEP);
//Uncomment line to use enable/disable functionality
BasicStepperDriver stepper(MOTOR_STEPS, DIR, STEP, SLEEP);
void setup() {
Serial.begin(9600);
Serial.println("Starting");
stepper.begin(RPM, MICROSTEPS);
// if using enable/disable on ENABLE pin (active LOW) instead of SLEEP uncomment next line
stepper.setEnableActiveState(LOW);
Serial.print("Waiting");
pinMode(11,INPUT_PULLUP);
stepper.setMicrostep(16);
}
int sign = 1;
bool moved = false;
void loop() {
while(!digitalRead(11)){
if(!moved){
stepper.enable();
//Direction Posting
if(sign>0)Serial.print("\nForward Rotations: ");
else Serial.print("\nBackward Rotations: ");
}
stepper.rotate(sign*360);
Serial.print("| ");
moved=true;
}
if(moved){
moved=false;
stepper.disable();
sign*=-1;
Serial.print("\nWaiting");
}
Serial.print(".");
delay(500);
}
| true |
0a41f0dd8ffd280d3fcdb9e298460afa57409a44 | C++ | JohannesLaier/jit-compiler | /src/js/jslexem.cpp | UTF-8 | 386 | 2.609375 | 3 | [
"MIT"
] | permissive | #include "jslexem.h"
#include <iostream>
JSLexem::JSLexem() {}
JSLexem::JSLexem(LexemType t) {
type = t;
}
LexemType JSLexem::getType() {
return type;
}
void JSLexem::setValue(std::string value) {
s_value = value;
}
void JSLexem::setValue(long value) {
n_value = value;
}
std::string JSLexem::getStrValue() {
return s_value;
}
long JSLexem::getValue() {
return n_value;
}
| true |
dc926959bbaac17452945a867a557ac7aba1f388 | C++ | s0217391/DifferentProjects | /SimCode/include/particle.h | UTF-8 | 1,756 | 2.96875 | 3 | [] | no_license | #ifndef PARTICLE_H
#define PARTICLE_H
#include <vector>
#include "ngl/VAOPrimitives.h"
class Particle
{
public:
inline Particle(float _rad, float _mass, ngl::Vec3 _pos, ngl::Vec3 _vel = ngl::Vec3(0, 0, 0)) :
m_radius(_rad),
m_mass(_mass),
m_invMass(1.0f / _mass),
m_position(_pos),
m_velocity(_vel),
m_forceAccumulator(ngl::Vec3()) {}
inline float getRadius() {return m_radius;}
inline float getMass() {return m_mass;}
inline float getInvMass() {return m_invMass;}
inline ngl::Vec3 getPosition() {return m_position;}
inline void updatePosition(ngl::Vec3 _newPos) {m_position = _newPos;}
inline ngl::Vec3 getVelocity() {return m_velocity;}
inline void updateVelocity(ngl::Vec3 _newVel) {m_velocity = _newVel;}
inline ngl::Vec3 getAcceleration() {return m_forceAccumulator * getInvMass();}
inline ngl::Vec3 getForceAccumulator() {return m_forceAccumulator;}
inline void exertForce(ngl::Vec3 _force) {m_forceAccumulator = _force;}
private:
// Our particles will have to have a radius, as they collide with one another
const float m_radius;
// Mass of the particle
const float m_mass;
// Inverse mass of the particle. Stored so we have to compute it only once.
const float m_invMass;
// Members for position, velocity, force accumulator
ngl::Vec3 m_position;
ngl::Vec3 m_velocity;
ngl::Vec3 m_forceAccumulator;
};
// Type definition of a vector of Particles
typedef std::vector< Particle > ParticleVector;
#endif // PARTICLE_H
| true |
b710975557eb5fa28c5695b90d61d8caa2987b02 | C++ | mateuscgc/maratonas | /ProgBase 2015/H.cpp | UTF-8 | 2,598 | 3.046875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int tickets[3][3];
int tickets2[3][3];
int diagonais(){
int total = 0;
int max_d = min(tickets[0][0], min(tickets[1][1], tickets[2][2]));
total += max_d;
for(int i = 0; i < 3; i++){
tickets[i][i] -= max_d;
}
// segunda diagonal
max_d = min(tickets[0][1], min(tickets[1][2], tickets[2][0]));
total += max_d;
tickets[0][1] -= max_d;
tickets[1][2] -= max_d;
tickets[2][0] -= max_d;
//terceira
max_d = min(tickets[0][2], min(tickets[1][0], tickets[2][1]));
total += max_d;
tickets[0][2] -= max_d;
tickets[1][0] -= max_d;
tickets[2][1] -= max_d;
//quarta
max_d = min(tickets[2][0], min(tickets[1][1], tickets[0][2]));
total += max_d;
tickets[2][0] -= max_d;
tickets[1][1] -= max_d;
tickets[0][2] -= max_d;
//quinta
max_d = min(tickets[2][1], min(tickets[1][2], tickets[0][0]));
total += max_d;
tickets[2][1] -= max_d;
tickets[1][2] -= max_d;
tickets[0][0] -= max_d;
//sexta
max_d = min(tickets[2][2], min(tickets[1][0], tickets[0][1]));
total += max_d;
tickets[2][2] -= max_d;
tickets[1][0] -= max_d;
tickets[0][1] -= max_d;
return total;
}
int linhas(){
int total = 0;
//linhas
int max_ac = min(tickets[0][0], min(tickets[0][1], tickets[0][2]));
int max_ab = min(tickets[1][0], min(tickets[1][1], tickets[1][2]));
int max_co = min(tickets[2][0], min(tickets[2][1], tickets[2][2]));
total += max_ac;
total += max_ab;
total += max_co;
for(int i = 0; i < 3; i++){
tickets[0][i] -= max_ac;
tickets[1][i] -= max_ab;
tickets[2][i] -= max_co;
}
//colunas
int max_r0 = min(tickets[0][0], min(tickets[1][0], tickets[2][0]));
int max_r1 = min(tickets[0][1], min(tickets[1][1], tickets[2][1]));
int max_r2 = min(tickets[0][2], min(tickets[1][2], tickets[2][2]));
total += max_r0;
total += max_r1;
total += max_r2;
for(int i = 0; i < 3; i++){
tickets[i][0] -= max_r0;
tickets[i][1] -= max_r1;
tickets[i][2] -= max_r2;
}
int max_cell = 0;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
max_cell = tickets[i][j] / 3;
tickets[i][j] -= max_cell;
total += max_cell;
}
}
return total;
}
int main(){
int n;
int cod;
int rest;
string food;
cin >> n;
int total = 0;
for(int i = 0; i < n; i++){
cin >> cod >> food;
rest = cod % 3;
if(food == "ACARAJE"){
tickets[0][rest]++;
tickets2[0][rest]++;
}else if(food == "ABARA"){
tickets[1][rest]++;
tickets2[1][rest]++;
}else if(food == "COCADA"){
tickets[2][rest]++;
tickets2[0][rest]++;
}
}
total += diagonais();
total += linhas();
cout << total << endl;
} | true |
a54c10066b5c8d32f7d5f91f5671f42b7b279c0c | C++ | mehrdad-shokri/wiki-2 | /src/Algorithms/Algorithms/Files/longest_increasing_subsequence.cc | UTF-8 | 611 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int LIS(const vector<int> &vec) {
int n = vec.size();
int lis[n];
int max_lis = 0;
int i, j;
for (i = 0; i < n; ++i) {
lis[i] = 1;
}
for (i = 1; i < n; ++i) {
for(j = 0; j < i; ++j) {
if (vec[i] > vec[j] && lis[i] < lis[j] + 1) {
lis[i] = lis[j] + 1;
}
max_lis = max(max_lis, lis[i]);
}
}
return max_lis;
}
int main() {
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
vector<int> vec(arr, arr + sizeof(arr) / sizeof(int));
cout << "Length of lis is " << LIS(vec) << endl;
return 0;
}
| true |
050dc015dced6aa71a3ce3ba2d44964ee3166abd | C++ | punyawat-jar/Lab-Time-punyawat-jar | /Time.h | UTF-8 | 880 | 3.59375 | 4 | [] | no_license | class Time{
private:
int m,h,s;
public:
void getTime();
Time operator-(Time);
void display();
};
void Time::getTime(){
do{
cout << "Input hours :";
cin >> h;
if(h >=24){
cout << "--- Please input hours in (0-23) ---" << endl;
}
}while(h>=24);
cout << "Input minutes :";
cin >> m;
cout << "Input seconds :";
cin >> s;
}
void Time::display(){
cout << "Time diff is ";
cout<<setfill('0')<<setw(2)<<h<<":";
cout<<setfill('0')<<setw(2)<<m<<":";
cout<<setfill('0')<<setw(2)<<s<<endl;
}
Time Time::operator-(Time t1){
Time t3;
if(t1.s > s){
s += 60;
m--;
}
if(t1.m > m){
m += 60;
h--;
}
if(t1.h > h){
h += 24;
}
t3.h = h - t1.h;
t3.m = m - t1.m;
t3.s = s - t1.s;
return t3;
} | true |
29078901f4d38a468dfa56ed43335f9fec13a607 | C++ | moevm/oop | /8383/Larin_Anton/Proj/main.cpp | UTF-8 | 402 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <clocale>
#include <iostream>
#include"Game.h"
#include "Vector.h"
int main() {
std::setlocale(LC_ALL, "xx_XX.UTF-8");
std::cout << "Hello, World!" << std::endl;
Game* game = new Game(8,8);
game->run();
Vector<int> vec;
vec.push(5);
vec.push(6);
vec.push(7);
vec.pop();
std::cout << vec.toString() << std::endl;
return 0;
} | true |
8aaa87b7879b2c2a089a9fd38b19f503ba71e304 | C++ | EmielBon/nintendo-ds-framework | /code/arm9/include/ViewPort.h | UTF-8 | 816 | 2.734375 | 3 | [] | no_license | #pragma once
#include "types.h"
#include "fixed.h"
namespace Graphics
{
struct ViewPort
{
public:
///
ViewPort();
///
ViewPort(int x, int y, int width, int height);
///
fx12 AspectRatio();
public:
int X, Y, Width, Height;
};
//-------------------------------------------------------------------------------------------------
inline ViewPort::ViewPort() : X(0), Y(0), Width(1), Height(1)
{
}
//-------------------------------------------------------------------------------------------------
inline ViewPort::ViewPort(int x, int y, int width, int height) : X(x), Y(y), Width(width), Height(height)
{
}
//-------------------------------------------------------------------------------------------------
inline fx12 ViewPort::AspectRatio()
{
return fx12(Width) / Height;
}
} | true |
39119a542aac3ddb5d6193c819a839ff278445b5 | C++ | asleonova/cpp | /.history/D06/ex01/main_20210316150835.cpp | UTF-8 | 2,843 | 3.296875 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dbliss <dbliss@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/14 20:10:43 by dbliss #+# #+# */
/* Updated: 2021/03/16 15:08:35 by dbliss ### ########.fr */
/* */
/* ************************************************************************** */
#include <iostream>
#include <stdlib.h>
struct Data
{
std::string s1;
int i;
std::string s2;
};
std::string RandomString(unsigned long len)
{
std::string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
std::string newstr;
int pos;
while(newstr.size() != len) {
pos = ((rand() % (str.size() - 1)));
newstr += str.substr(pos,1);
}
return newstr;
}
int randomInt()
{
srand (time(NULL));
int ret = rand() % 100;
return (ret);
}
void* serialize(void) // тут сделать вывод значений!!!!
{
std::string s1 = RandomString(10);
std::string s2 = RandomString(20);
int num = randomInt();
std::string all = s1 + std::to_string(num) + s2;
char *s_all = const_cast <char*> (all.c_str());
void *all_new = reinterpret_cast <void *> (s_all);
std::cout << "data we want to serialize :" << std::endl;
std::cout << "random string 1: " << s1 << std::endl;
std::cout << "interger: " << num << std::endl;
std::cout << "random string 2: " << s2 << std::endl;
return (all_new);
}
Data * deserialize(void * raw)
{
Data* d = new Data;
char* new_raw = reinterpret_cast<char*>(raw);
d->s1 = std::string(new_raw, 10);
d->i = static_cast<int>(*(new_raw + 10) - 48) * 10;
d->i += static_cast<int>(*(new_raw + 11) - 48);
d->s2 = std::string(new_raw + 12, 20); // add 12 to the adress;
std::cout << "arr size is: " << sizeof(d->s1) << std::endl;
std::cout << "arr size is: " << sizeof(d->i) << std::endl;
std::cout << "arr size is: " << sizeof(d->s2) << std::endl;
std::cout << "d->s1: " << d->s1 << std::endl;
std::cout << "d->i: " << d->i << std::endl;
std::cout << "d->s2: "<< d->s2 << std::endl;
return (d);
}
int main()
{
void *Sdata = serialize();
std::cout << "data after serializing and deserializing: " << std::endl;
deserialize(Sdata);
return 0;
} | true |
02fde607f1a0992011b4738097aca130eecd0100 | C++ | DarinM223/breakout | /src/PostProcessor.h | UTF-8 | 1,590 | 2.765625 | 3 | [] | no_license | #ifndef POSTPROCESSOR_H
#define POSTPROCESSOR_H
#include <GL/glew.h>
#include <exception>
#include "Shader.h"
#include "Texture.h"
struct MsfboInitException : public std::exception {
const char* what() const noexcept override {
return "Failed to initialize MSFBO";
}
};
struct FboInitException : public std::exception {
const char* what() const noexcept override {
return "Failed to initialize FBO";
}
};
class PostProcessor;
class RenderManager {
public:
RenderManager(PostProcessor& processor); // Begin render.
~RenderManager(); // End render.
private:
PostProcessor& processor_;
};
class PostProcessor {
public:
PostProcessor(Shader& shader, int width, int height);
~PostProcessor() { this->release(); }
PostProcessor() = delete;
PostProcessor(const PostProcessor&) = delete;
PostProcessor& operator=(const PostProcessor&) = delete;
PostProcessor(PostProcessor&& other);
PostProcessor& operator=(PostProcessor&& other);
RenderManager prepareRender() { return RenderManager{*this}; }
void render(GLfloat time);
GLboolean confuse{GL_FALSE};
GLboolean chaos{GL_FALSE};
GLboolean shake{GL_FALSE};
private:
friend class RenderManager;
void release() {
if (valid_) {
glDeleteFramebuffers(1, &msfbo_);
glDeleteFramebuffers(1, &fbo_);
glDeleteRenderbuffers(1, &rbo_);
glDeleteVertexArrays(1, &vao_);
}
}
int width_;
int height_;
Shader& shader_;
Texture texture_;
GLuint msfbo_;
GLuint fbo_;
GLuint rbo_;
GLuint vao_;
bool valid_{true};
};
#endif
| true |
526c01fc65c93be2b30e3dfb531ec7f2d8207ef6 | C++ | aczech17/serial_read | /cmake-build-debug/Port.cpp | UTF-8 | 2,927 | 2.828125 | 3 | [] | no_license | #include "Port.h"
std::string Port::readLine()
{
char tempChar;
std::string buffer;
DWORD countBytesRead = 0;
do
{
ReadFile(hComm, //file handle
&tempChar, //char buffer
sizeof(tempChar), //number of bytes to read
&countBytesRead, //number of bytes currently read
nullptr //lpOverlapped https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-readfile
);
buffer += tempChar;
}while(tempChar != '\n');
return buffer;
}
Port::Position Port::getPosFromStr(std::string str)
{
Position result;
int i = 0;
//ignore artifacts
while(str[i] < '0' || str[i] > '9')
i++;
//first number
int j = i;
while(str[j] != ' ')
j++;
std::string tmpStr = str.substr(i, j - i);
result.x = std::stoi(tmpStr);
//second number
j++;
i = j;
while(str[j] != ' ')
j++;
tmpStr = str.substr(i, j - i);
result.y = std::stoi(tmpStr);
//pushed
j++;
result.pushed = (bool)(str[j] - '0');
return result;
}
Port::Port(const char* portName, DWORD BaudRate)
{
hComm = CreateFile(
portName, //port name
GENERIC_READ, //read only
0, //share mode (0 ==> cannot be shared)
nullptr, //security attributes (nullptr ==> handle cannot be inherited) http://winapi.freetechsecrets.com/win32/WIN32CreateFile.htm
OPEN_EXISTING, //creation distribution (open only if existing)
0, //flags and attributes (link ^)
nullptr //handle to files to copy (none)
);
if (hComm == INVALID_HANDLE_VALUE)
{
std::string errMsg = "Cannot open port ";
errMsg += portName;
throw(std::ios_base::failure(errMsg));
}
serialConfig.DCBlength = sizeof(serialConfig);
serialConfig.BaudRate = BaudRate;
serialConfig.ByteSize = 8;
serialConfig.StopBits = ONESTOPBIT;
serialConfig.Parity = NOPARITY;
serialConfig.fRtsControl = RTS_CONTROL_ENABLE;
SetCommState(hComm, &serialConfig);
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 100;
timeouts.ReadTotalTimeoutMultiplier = 1;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
SetCommTimeouts(hComm, &timeouts);
}
Port::Position Port::getPosition()
{
std::string str = readLine();
return getPosFromStr(str);
}
Port::~Port()
{
CloseHandle(hComm);
} | true |
95258b63d2ff6fa88838abc171ec1d33ae0eacb4 | C++ | PubFork/SoftRenderSample | /WindowsGraphics/WindowsGraphics/Vector4.cpp | UTF-8 | 3,204 | 3.40625 | 3 | [] | no_license | #include <math.h>
#include "Vector4.h"
//w = 0时表示向量 w = 1时表示点
Vector4::Vector4()
: mX(0), mY(0), mZ(0), mW(0)
{/*empty*/}
Vector4::Vector4(double _x, double _y, double _z, double _w)
: mX(_x), mY(_y), mZ(_z), mW(_w)
{/*empty*/}
Vector4::Vector4(const Vector4& _other)
: mX(_other.mX),
mY(_other.mY),
mZ(_other.mZ),
mW(_other.mW)
{/*empty*/}
Vector4::~Vector4()
{/*empty*/}
Vector4& Vector4::Reverse()
{
mX = -mX;
mY = -mY;
mZ = -mZ;
return *this;
}
Vector4& Vector4::operator=(const Vector4& _other)
{
if (this == &_other)
{
return *this;
}
else
{
mX = _other.mX;
mY = _other.mY;
mZ = _other.mZ;
mW = _other.mW;
}
return *this;
}
Vector4& Vector4::operator+=(const Vector4& _other)
{
mX += _other.mX;
mY += _other.mY;
mZ += _other.mZ;
mW += _other.mW;
return *this;
}
Vector4& Vector4::operator+=(double _f)
{
mX += _f;
mY += _f;
mZ += _f;
mW += _f;
return *this;
}
Vector4 Vector4::operator*(double _f)
{
return Vector4(
mX * _f,
mY * _f,
mZ * _f,
mW * _f);
}
Vector4 operator+(const Vector4& _lhs, const Vector4& _rhs)
{
Vector4 newVec;
newVec.mX = _lhs.mX + _rhs.mX;
newVec.mY = _lhs.mY + _rhs.mY;
newVec.mZ = _lhs.mZ + _rhs.mZ;
newVec.mW = _lhs.mW + _rhs.mZ;
return newVec;
}
Vector4 operator-(const Vector4& _lhs, const Vector4& _rhs)
{
Vector4 newVec;
newVec.mX = _lhs.mX - _rhs.mX;
newVec.mY = _lhs.mY - _rhs.mY;
newVec.mZ = _lhs.mZ - _rhs.mZ;
newVec.mW = _lhs.mW - _rhs.mW;
return newVec;
}
double Vector4::Dot(const Vector4& _other)
{
return mX * _other.mX +
mY * _other.mY +
mZ * _other.mZ;
}
double operator*(const Vector4& _lhs, const Vector4& _rhs)
{
return _lhs.mX * _rhs.mX +
_lhs.mY * _rhs.mY +
_lhs.mZ * _rhs.mZ;
}
//实现三维叉乘算法,W不参与计算
//叉乘一个Vector4
Vector4 Vector4::CrossProduct(const Vector4& _other) const
{
return Vector4(
mY * _other.mZ - mZ * _other.mY,
mZ * _other.mX - mX * _other.mZ,
mX * _other.mY - mY * _other.mX,
mW
);
}
Vector4 Vector4::operator/(double _f)
{
return Vector4(mX / _f, mY / _f, mZ / _f, mW / _f);
}
void Vector4::DivideW()
{
if (mW == 0) return ;
mX /= mW;
mY /= mW;
mZ /= mW;
mW = 1;
}
//乘一个4x4矩阵,横向量向量在左,矩阵在右
Vector4 Vector4::MatrixMulti(Matrix4x4& _matrix)
{
return Vector4(
mX * _matrix[0] + mY * _matrix[4] + mZ * _matrix[8] + mW * _matrix[12],
mX * _matrix[1] + mY * _matrix[5] + mZ * _matrix[9] + mW * _matrix[13],
mX * _matrix[2] + mY * _matrix[6] + mZ * _matrix[10] + mW * _matrix[14],
mX * _matrix[3] + mY * _matrix[7] + mZ * _matrix[11] + mW * _matrix[15]
);
}
void Vector4::AngleToRadian()
{
mX *= PIOver180;
mY *= PIOver180;
mZ *= PIOver180;
mW *= PIOver180;
}
double Vector4::GetLength() const
{
return sqrt(mX * mX + mY * mY + mZ * mZ);
}
Vector4& Vector4::Normalize()
{
double fLength = GetLength();
if (fLength > 0.0)
{
double fInvLength = 1.0 / fLength;
mX *= fInvLength;
mY *= fInvLength;
mZ *= fInvLength;
}
return *this;
} | true |
c74a76f4c35d8ded1b89c8f9eb6f82ce883a95ba | C++ | chrwoizi/ssh-raytracing | /SkyboxMaterial.hpp | UTF-8 | 1,312 | 2.78125 | 3 | [] | no_license | #ifndef SKYBOXMATERIAL_HPP
#define SKYBOXMATERIAL_HPP
#include "Material.hpp"
#define MAX(a,b) ((a)>(b)?(a):(b))
class SkyboxMaterial : public Material
{
public:
SkyboxMaterial() : Material(false, false, 0, vec(1,1,1), vec(1,1,1)) {}
virtual void shade(vec& destination, const vec& contribution, int level, std::vector<Light*>& lights, PackedRay &ray, int index)
{
assert(ray.hit[index]);
vec rayOrigin(ray.origin.x[index], ray.origin.y[index], ray.origin.z[index]);
vec rayDirection(ray.dir.x[index], ray.dir.y[index], ray.dir.z[index]);
vec position(rayOrigin + rayDirection * ray.t[index]);
normalize(position);
position = position * 0.5f + vec(0.5f);
vec color = position*contribution;
destination += color;
}
virtual void shade(const quad<vec*>& destination, const qvec& contribution, int level, std::vector<Light*>& lights, PackedRay &ray)
{
qvec position(ray.origin + ray.dir * ray.t);
normalize(position);
position = position * qfloat(0.5f) + qvec(qfloat(0.5f));
qvec color = position*contribution;
*destination[0] += vec(color.x[0], color.y[0], color.z[0]);
*destination[1] += vec(color.x[1], color.y[1], color.z[1]);
*destination[2] += vec(color.x[2], color.y[2], color.z[2]);
*destination[3] += vec(color.x[3], color.y[3], color.z[3]);
}
};
#endif
| true |
61d170f5d2028dd1c13e8219ce22d5bb2eeb82e9 | C++ | xih108/Math155B | /Project4/DataStructs/Stack.h | UTF-8 | 3,266 | 3.28125 | 3 | [] | no_license |
// Stack.h. release 3.2. May 3, 2007.
//
// A general purpose dynamically resizable stack.
// Implemented with templates.
// Items are stored contiguously, for quick accessing.
// However, allocation may require the stack to be copied into
// new memory locations.
//
// Usage: Stack<T> or Stack<T,IdxVal>
//
// Stores a denamically resizable stack of objects of type T.
// The second, optional, class parameter long is the data type used
// to index into the array. This defaults to "IdxVal", but "int" or "int32_t",
// etc., may be used instead.
//
// Author: Sam Buss.
// Contact: sbuss@math.ucsd.edu
// All rights reserved. May be used for any purpose as long
// as use is acknowledged.
#ifndef STACK_H
#define STACK_H
#include <assert.h>
#include "../VrMath/MathMisc.h"
template <class T, class IdxVal = long> class Stack {
public:
Stack(); // Constructor
Stack(IdxVal initialSize); // Constructor
~Stack(); // Destructor
void Reset();
void Resize( IdxVal newMaxSize ); // Increases allocated size (will not decrease size)
T& Top() const { assert( !IsEmpty() ); return *TopElement; };
T* TopPtr() const { return IsEmpty() ? 0 : TopElement; }
T& Pop();
T* Push(); // New top element is arbitrary
T* Push( const T& newElt ); // Push newElt onto stack.
bool IsEmpty() const { return (SizeUsed==0); }
IdxVal Size() const { return SizeUsed; }
IdxVal SizeAllocated() const { return Allocated; }
private:
IdxVal SizeUsed; // Number of elements in the stack
T* TopElement; // Pointer to the top element of the stack
IdxVal Allocated; // Number of entries allocated
T* TheStack; // Pointer to the array of entries
};
template<class T, class IdxVal> inline Stack<T,IdxVal>::Stack()
{
SizeUsed = 0;
TheStack = 0;
Allocated = 0;
Resize( 10 );
}
template<class T, class IdxVal> inline Stack<T,IdxVal>::Stack(IdxVal initialSize)
{
SizeUsed = 0;
TheStack = 0;
Allocated = 0;
Resize( initialSize );
}
template<class T, class IdxVal> inline Stack<T,IdxVal>::~Stack()
{
delete[] TheStack;
}
template<class T, class IdxVal> inline void Stack<T,IdxVal>::Reset()
{
SizeUsed = 0;
TopElement = TheStack-1;
}
template<class T, class IdxVal> inline void Stack<T,IdxVal>::Resize( IdxVal newMaxSize )
{
if ( newMaxSize <= Allocated ) {
return;
}
IdxVal newSize = Max(2*Allocated+1,newMaxSize);
T* newArray = new T[newSize];
T* toPtr = newArray;
T* fromPtr = TheStack;
IdxVal i;
for ( i=0; i<SizeUsed; i++ ) {
*(toPtr++) = *(fromPtr++);
}
delete[] TheStack;
TheStack = newArray;
Allocated = newSize;
TopElement = TheStack+(SizeUsed-1);
}
template<class T, class IdxVal> inline T& Stack<T,IdxVal>::Pop()
{
T* ret = TopElement;
assert( SizeUsed>0 ); // Should be non-empty
SizeUsed--;
TopElement--;
return *ret;
}
// Enlarge the stack but do not update the top element.
// Returns a pointer to the top element (which is unchanged/uninitialized)
template<class T, class IdxVal> inline T* Stack<T,IdxVal>::Push( )
{
if ( SizeUsed >= Allocated ) {
Resize(SizeUsed+1);
}
SizeUsed++;
TopElement++;
return TopElement;
}
template<class T, class IdxVal> inline T* Stack<T,IdxVal>::Push( const T& newElt )
{
Push();
*TopElement = newElt;
return TopElement;
}
#endif // STACK_H | true |
9d2acd8572deb65f98a1a23ebed8dd423ba2d92c | C++ | eth42/MetagraphMatchingBenchmark | /include/Job.h | UTF-8 | 915 | 2.59375 | 3 | [] | no_license | #pragma once
#include <vector>
#include <sstream>
#include "GraphSource.h"
#include "TypeEnums.h"
namespace maxmatching {
/* Wrapper class to add additional information to a graph source */
class Job {
private:
GraphSource* source;
public:
unsigned long seed;
bool shuffle;
unsigned int iterations;
SolverType solver;
unsigned int solverArg1;
unsigned int solverArg2;
Job();
virtual ~Job();
GraphSource& getSource();
void setSource(GraphSource* source);
virtual bool isCompound();
virtual Job* nextSubJob();
std::string createCsvHeader();
std::string createCsvData();
};
/* Wrapper class to combine multiple jobs */
class JobCollection : public Job {
private:
std::vector<Job*> jobs;
public:
JobCollection();
~JobCollection();
void addJob(Job* job);
virtual bool isCompound();
virtual Job* nextSubJob();
};
}
| true |
8aea91acffb456d9e663f4679394de14019a73f6 | C++ | Cartoonman/hash-table-qq | /Source Code/hashTable.h | UTF-8 | 3,069 | 3.671875 | 4 | [] | no_license | #include <iostream> // Necessary for any type of I/O interface
/** very basic I/O functions for input and output **/
using std::string;
using std::cout;
using std::endl;
/** Description: This is the main file that contains both the string hash
function and the hash table class. This is the core of the program.**/
/**
The following hash function is an prime number based bitwise XOR function that
uses a char pointer to traverse the string while calculating a hash value
that will be used in modulo of the given hashtable size.
This function was borrowed from a source on the internet,
Author of this function: *** http://stackoverflow.com/a/8317622 ***
This function was chosen specifically for its excellent performance with
an input that wasn't uniformly distributed (e.g. input keys 'a', 'b', 'c', 'd',... etc and
have it map to pseudorandom locations while keeping collisions relatively low)
as well as it's O(n) runtime and simplicity.
**/
/**************************************************************/
#define A 71453
#define B 97861
unsigned long stringHash(const char* s,unsigned int sizeArray)
{
unsigned h = 53; // prime seed
while (*s) {
h = (h * A) ^ (s[0] * B); // bitwise XOR
s++; // increment pointer
}
return (h%sizeArray);
}
/**************************************************************/
/**This is the class that implements the static hash table**/
template <typename T>
class hashTBL
{
T* t; // Open-ended Datatype for Hash Table
unsigned int S; // size of hash table
unsigned int elemCount; // number of elements in table
public:
// constructor(size), constructs new hash table with given size, all elements set to null, and initialize element count to 0.
hashTBL(unsigned int size){t = new T[size](); S = size; elemCount = 0;}
// boolean set(key, value). Inserts data with given key. inserts and returns true if spot is empty, returns false if item exists in the spot.
bool set(T dat,string key){unsigned long keyVAL = stringHash(key.c_str(),S); return(t[keyVAL] ? false : (t[keyVAL] = dat) && ++elemCount);}
// get(key) Retrieves the item at the given key location. Returns the element in the table or 0 if its empty.
T get(string key){return t[stringHash(key.c_str(),S)];}
// delete(key). Uses key to find elemet in table and deletes it if it exists. Returns the data element if found and deleted, otherwise returns 0 if not found.
T deleteDat(string key){unsigned long keyVAL = stringHash(key.c_str(),S); T tmp; if(t[keyVAL]){t[keyVAL] = ((tmp = t[keyVAL]) == --elemCount-elemCount); return tmp;} return 0;}
// float load(). returns the load factor using elemCount and table size S.
float load(){cout << "Elements in Table: " << elemCount << endl; cout << "Size of Table: " << S << endl; return( (float)elemCount / (float)S);}
// A print function that simply prints out the table's contents to see what the hash table looks like with the elements inside.
void print(){for (unsigned int i = 0;i < S; i++){cout << i+1 << " - " << t[i] << endl;}}
}; | true |
47e78b0504c897015f1e6d10e5f55074a01cd845 | C++ | apfitzen/Wireframes-Calc | /Wireframes Calc/VerticesManager.h | UTF-8 | 608 | 2.5625 | 3 | [] | no_license | //
// VerticesManager.h
// Wireframes Calc 4.5
//
// Created by Aaron Pfitzenmaier on 4/26/15.
// Copyright (c) 2015 Aaron Pfitzenmaier. All rights reserved.
//
#ifndef __Wireframes_Calc_4_5__VerticesManager__
#define __Wireframes_Calc_4_5__VerticesManager__
#include <vector>
#include "basicshapes.h"
class Point;
class VerticesManager
{
private:
std::vector<Point> vertices;
public:
VerticesManager(int vertexNum);
void setVertex(int index, double x,double y,double z);
Point& getVertexRef(int index);
Point getVertex(int index) const;
};
#endif /* defined(__Wireframes_Calc_4_5__VerticesManager__) */
| true |
a14a3ca8ac94d10be49230e9ac7e874171a3ca20 | C++ | VJecheva/SoftTech_070421 | /SoftTechTest/SoftTechTest/Header.cpp | UTF-8 | 448 | 2.640625 | 3 | [] | no_license | #include "Header.h"
int suma(int a[], int n)
{
int s = 0;
for (int i = 0; i < n; i++)
s += a[i];
return s;
}
int max(int a[], int n)
{
int m = a[0];
for (int i = 1; i < n; i++)
if (m < a[i]) m = a[i];
return m;
}
int min(int a[], int n)
{
int m = a[0];
for (int i = 1; i < n; i++)
if (m > a[i]) m = a[i];
return m;
}
}
float average(int a[], int n)
{
return suma(a,n)/(float)n;
}
| true |
7187a06051b4e81f8f5e1e3d1d9a9e09a3db09ad | C++ | k-ishiguro/CPP_BoostMPITest | /testBroadcast.cpp | UTF-8 | 1,081 | 2.671875 | 3 | [] | no_license | /**
* Written by Katsuhiko Ishiguro <k.ishiguro.jp@ieee.org>
* Last Update: 02/09, 2016 (dd/mm, yyyy)
*/
#include <boost/mpi.hpp>
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi/collectives.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cassert>
#include <ctime>
#include <cstdlib>
namespace bmpi = boost::mpi;
int main(int argc, char **argv){
bmpi::environment env(argc, argv);
bmpi::communicator world;
const int N = 128;
std::vector<float> v(N, 0.0);
std::string s;
if(world.rank() == 0){ // maseter routine
std::srand(std::time(0));
std::generate(v.begin(), v.end(), [] () {
return double(std::rand()) / RAND_MAX;}); // v initialized
for(int i = 0;i < 10; ++i) {
std::cout << "Original v : " << v[i] << std::endl;
};
s = "Hello world";
}
/* copy the same data to all threads*/
bmpi::broadcast(world, s, 0);
bmpi::broadcast(world, v, 0);
std::cout << "Rank : " << world.rank() << ", s=" << s << ", v[0]=" << v[0] << std::endl;
}
| true |
14f91ff1ce14d4d96f9e56bbf7c2e2654df194e3 | C++ | AlexKent3141/OnePunchGo | /src/core/BitSet.h | UTF-8 | 2,593 | 3.390625 | 3 | [
"MIT"
] | permissive | #ifndef __BITSET_H__
#define __BITSET_H__
#include <cassert>
#include <cstdint>
#include <string>
typedef uint64_t Word;
const Word One = 1;
// Bit set class which is used for quick board-wise operations.
class BitSet
{
public:
BitSet() = delete;
BitSet(int);
BitSet(const BitSet&);
~BitSet();
inline int NumWords() const { return _numWords; }
inline int NumBits() const { return _numBits; }
inline Word GetWord(size_t i) const
{
assert(i < _numWords);
assert(_words != nullptr);
return _words[i];
}
inline int GetWordSize() const { return WordSize; }
void Copy(const BitSet&);
// Set the specified bit.
void Set(size_t);
void Set(const BitSet&);
// Unset the specified bit.
void UnSet(size_t);
// Unset the specified bits.
void UnSet(const BitSet&);
// Check the state of the specified bit.
bool Test(size_t) const;
// Count the number of set bits.
size_t Count() const;
// Count the number of set bits in the specified word.
size_t Count(int) const;
// Count the number of set bits in the bitwise AND of this and another BitSet.
size_t CountAnd(const BitSet&) const;
size_t CountAndSparse(const BitSet&) const;
// Invert this BitSet in place.
void Invert();
// Get the index of the n-th set bit in the word.
int BitInWord(int, int) const;
BitSet& operator|=(const BitSet&);
BitSet& operator&=(const BitSet&);
// Get a string representation of this BitSet.
std::string ToString() const;
private:
const int WordSize = 64;
// This is the internal representation of the bits.
Word* _words = nullptr;
size_t _numWords;
size_t _numBits;
// Get a string representation for the word.
std::string WordString(Word) const;
size_t Count(Word) const;
size_t CountSparse(Word) const;
};
// This object allows iteration over the positions of the set bits in a BitSet.
class BitIterator
{
public:
static const int NoBit = -2;
BitIterator(const BitSet& bs) : _bs(bs), _wi(0), _i(-1)
{
_cw = _bs.GetWord(0);
}
int Next();
private:
const BitSet& _bs;
int _wi;
int _i;
Word _cw;
};
// This object allows bits to be selected by index efficiently.
class BitSelector
{
public:
BitSelector(const BitSet& bs) : _bs(bs)
{
InitialiseCounts();
}
~BitSelector();
int operator[](int) const;
private:
const BitSet& _bs;
int* _counts = nullptr;
void InitialiseCounts();
};
#endif // __BITSET_H__
| true |
290661480b2d7951dd9a05262997eaab2109cecc | C++ | jaimelay/competitive-programming | /Reference/math/FactorsAndDivisors.cpp | UTF-8 | 703 | 3.375 | 3 | [] | no_license | // For number greater than 9*10^14 see Pollard Rho Algorithm.
// Complexity: O(sqrt(n))
vector<long long> getFactors(long long n) {
vector<long long> factors;
for (long long d = 2; d * d <= n; d++) {
while (n % d == 0) {
factors.push_back(d);
n /= d;
}
}
if (n > 1) factors.push_back(n);
return factors;
}
// Complexity: O(sqrt(n))
vector<long long> getDivisors(long long n) {
vector<long long> divisors;
for (long long d = 1 ; d * d <= n; d++) {
if (n % d == 0) {
if (n / d == d) divisors.push_back(d);
else divisors.push_back(d), divisors.push_back(n / d);
}
}
return divisors;
} | true |
f312ca11f35707bc6a93f3011416ddbb9637f341 | C++ | manideep1821/pscp-lab | /lab/4/problem5.cpp | UTF-8 | 1,406 | 3.46875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int n;
cout<<"enter the number :"<<endl;
cin>>n;
int r;
int count =0;
int count1=0;
int count2=0;
int count3=0;
int count4=0;
int count5=0;
int count6=0;
int count7=0;
int count8=0;
while(n>0)
{
r=n%10;
n=n/10;
if(r==1)
{
count =count +1;
}
else if(r==2)
{
count1 =count1+1;
}
else if(r==3)
{
count2=count2+1;
}
else if(r==4)
{
count3 =count3+1;
}
else if(r==5)
{
count4=count4+1;
}
else if(r==6)
{
count5 =count5+1;
}
else if(r==7)
{
count6=count6+1;
}
else if(r==8)
{
count7 =count7+1;
}
else if(r==9)
{
count8=count8+1;
}
}
cout<<"the occurence of "<<endl;
cout<<" 1 :"<<count<<endl;
cout<<" 2 :"<<count1<<endl;
cout<<" 3 :"<<count2<<endl;
cout<<" 4 :"<<count3<<endl;
cout<<" 5 :"<<count4<<endl;
cout<<" 6 :"<<count5<<endl;
cout<<" 7 :"<<count6<<endl;
cout<<" 8 :"<<count7<<endl;
cout<<" 9 :"<<count8<<endl;
return 0;
}
| true |
3dd8d272104a30b8fe006b6d6ae2069010cd46cf | C++ | mathieuherbert/ClavierHero | /Applications/SuperPong/Raquette.h | UTF-8 | 489 | 3.0625 | 3 | [] | no_license | #ifndef RAQUETTE_H
#define RAQUETTE_H
/**
* @file Raquette.h
* @class Raquette
* @brief Une raquette du jeu pouvant se déplacer verticalement.
*/
class Raquette {
int y;//Coordonnée
int bas,haut;//haut et bas de la raquette
public :
//Accesseurs
Raquette();
Raquette(int,int);
void init(int,int);
int getY();
int getBas();
int getHaut();
//Modifieurs
void setBas(int);
void setHaut(int);
void setY(int);
//Méthodes utiles
void monter();
void descendre();
};
#endif
| true |
b7117cdf731c21279bff282145fe2fb9443af10a | C++ | bb2002/cpp-study | /StartingCPP/110302.cpp | UTF-8 | 938 | 3.546875 | 4 | [] | no_license | #include <iostream>
class Base {
int state;
public:
Base() : state(0) {
}
Base(int a) : state(a) {
}
virtual int dummy() {
std::cout << "Base dummy() called" << std::endl;
return state;
}
};
class Derived : public Base {
public:
Derived(int i) : Base(i) {
}
void setNumber(int a) {
number = a;
}
int number;
};
int main() {
Derived *pd;
Base *pba = new Derived(23); // UP CAST
pd = dynamic_cast<Derived*>(pba); // OK.
if (pd == nullptr) {
std::cout << "pba cast failed." << std::endl;
}
pd->setNumber(10);
std::cout << pd->number << std::endl;
std::cout << pd->dummy() << std::endl;
delete pba;
std::cout << "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" << std::endl;
Base *pbb = new Base(2556);
pd = dynamic_cast<Derived*>(pbb);
if (pd == nullptr) {
std::cout << "pbb cast failed" << std::endl;
}
pd->setNumber(110);
std::cout << pd->number << std::endl;
std::cout << pd->dummy() << std::endl;
} | true |
5a9f4062681ac86d836666620f3d223252a131e0 | C++ | Roozbeh-Bazargani/twin-prime-conjecture | /Source.cpp | UTF-8 | 732 | 3.203125 | 3 | [] | no_license | #include<iostream>
#include<fstream>
bool primary(long long n);
int main()
{
std::ofstream of{ "n,n-2 are primary.txt" };
long long n{}, m{}, cnt{}, N{}, dist{};
std::cout << "n , N , cnt" << std::endl;
std::cin >> n >> N >> cnt;
m = n - 2;
while (n < N)
{
if (primary(n) && primary(m))
{
cnt++;
dist = n - dist;
std::cout << n << " , " << m << " counter : " << cnt << " distance : " << dist << std::endl;
of << n << " , " << m << " counter : " << cnt << " distance : " << dist << std::endl;
dist = n;
}
n++;
m++;
}
of.close();
return 0;
}
bool primary(long long n)
{
if (n == 1)
return false;
for (long long i{ 2 }; i*i <= n; i++)
{
if (n%i == 0)
return false;
}
return true;
} | true |
bb98887f28dcaa3c804a02c5ee561aac03714b61 | C++ | allwak/basics-of-c-plus-plus-development-white-belt | /Week_2/06 Programming Assignment/Solution/reverse.cpp | UTF-8 | 859 | 3.625 | 4 | [
"Unlicense"
] | permissive | //#include <iostream>
//#include <vector>
//-------------------------------------------------------------------------------------------------
//void Reverse(std::vector<int> & input);
//-------------------------------------------------------------------------------------------------
//int main()
//{
// std::vector<int> numbers = { 1, 5, 3, 4, 2 };
//
// Reverse(numbers);
//
// for(auto vec : numbers)
// {
// std::cout << vec << ' ';
// }
// std::cout << std::endl;
// return 0;
//}
//-------------------------------------------------------------------------------------------------
void Reverse(std::vector<int> & input)
{
std::vector<int> temp;
for (auto it = input.rbegin(); it != input.rend(); ++it)
{
temp.push_back(*it);
}
input = temp;
}
//------------------------------------------------------------------------------------------------- | true |
60bc27f9bdb427241cc2e6beb08c308e640f06fc | C++ | chebcia/Loty---Projekt- | /Drzewo.h | WINDOWS-1250 | 1,084 | 2.765625 | 3 | [] | no_license |
#include <iostream>
#include <fstream>
#include "Pasazer.h"
#ifndef STRUCT_DRZEWO
#define STRUCT_DRZEWO
/**
@param pasazerPrzechowywanyWDrzewie zmienna stuktury pasazer zawieraja informacje o pasazerze
@param lewylisc wskaznik na lewa strone drzewa
@param prawylisc wskaznik na prawa strone drzewa
*/
struct Drzewo
{
Pasazer pasazerPrzechowywanyWDrzewie;
Drzewo *lewylisc;
Drzewo *prawylisc;
};
/** Funcja dodaje elementy do drzewa
@param korzen jeli korzenia nie ma to drzewo jest puste i nie ma pasaera, tworzymy element lewy i prawy li, nastpny elementy ustawiamy na nullptr
@param przechowywatorkorzenia wskanik do przechowywania korzenia
*/
Drzewo * dodawaniedodrzewa(Drzewo * korzen, Pasazer & ktos);
/** Funcja usuwajca drzewo
@param korzen korze drzewa
*/
void usunDrzewo(Drzewo *& korzen);
/** Funcja wypisujca do pliku rekurencyjnie drzewa wartoci
@param node li drzewa
@param lewylisc lewa strona drzewa
@param prawylisc prawa strona drzewa
*/
void inorder(Drzewo * node, std::ofstream & outfile);
#endif
| true |
8cd3b6f1ce3aa5645ec4f9397f7761ab4c54d279 | C++ | gpudev0517/Fire-Simulator | /NVIS/NDYN_Debug/include/Core/Utility/NEAABB.h | UTF-8 | 3,415 | 3.0625 | 3 | [] | no_license | #pragma once
//! Axis aligned bounding box.
/*!
This is used for fast collision detection.
*/
struct AABB
{
private:
vec3f m_MinPos;
vec3f m_MaxPos;
//bool m_Empty;
public:
AABB()
{
m_MinPos = vec3f(FLT_MAX,FLT_MAX,FLT_MAX);
m_MaxPos = vec3f(-FLT_MAX,-FLT_MAX,-FLT_MAX);
}
AABB(const vec3f& min, const vec3f& max)
{
m_MinPos = min;
m_MaxPos = max;
}
//we should be able to draw the bounding box
//void draw() const;
void clear();
//! Tests if point p is inside the bounding box.
inline bool isInside(const vec3f& p) const;
inline bool isInside(const vec3f& p, double eps) const;
//! Inserts point p into the bounding box.
inline void insertPoint(const vec3f& p);
//! Inserts the bounding box into the given bounding box
inline void insert( const AABB& b );
//inline void setMinR(double &acc, double const rhs){ if(acc > rhs) acc = rhs;};
//inline void setMaxR(double &acc, double const rhs){ if(acc < rhs) acc = rhs;};
inline void setMin(const vec3f& min){ m_MinPos = min; }
inline void setMax(const vec3f& max){ m_MaxPos = max; }
const vec3f& minPos() const { return m_MinPos; }
const vec3f& maxPos() const { return m_MaxPos; }
//! For not computing something for empty AABBs. Where should we change this (?)
inline bool valid() const
{
return ( (m_MinPos.x() <= m_MaxPos.x()) &&
(m_MinPos.y() <= m_MaxPos.y()) &&
(m_MinPos.z() <= m_MaxPos.z()));
}
//! Computes if aabb2 intersects with this aabb.
inline bool intersects(const AABB& aabb2);
//! Returns the overlap of this bounding boxes with the given AABB
inline AABB overlapAABB(const AABB& aabb2) const;
//inline void setEmpty(bool b) {m_Empty = b;}
inline void translate(const vec3f& v) { m_MaxPos += v; m_MinPos += v; }
};
//bool AABBOverlapTest(const AABB& a, const AABB& b);
//bool AABBContainmentTest(const AABB& mother, const AABB& child);
struct VoxelGridExtent
{
AABB aabb;
uint xNumCells, yNumCells, zNumCells;
void computeNrOfCells(double cellSize)
{
// If the bounding box is empty, then
if(aabb.valid())
{
const double offset = 0.5;
xNumCells = (uint)floor(((aabb.maxPos().x() - aabb.minPos().x()) / cellSize) + offset)+1;
yNumCells = (uint)floor(((aabb.maxPos().y() - aabb.minPos().y()) / cellSize) + offset)+1;
zNumCells = (uint)floor(((aabb.maxPos().z() - aabb.minPos().z()) / cellSize) + offset)+1;
}
}
void clear()
{
aabb.clear();
xNumCells = yNumCells = zNumCells = 0;
}
};
class OBB
{
public:
OBB();
OBB(const vec3f &position, const quatf &orientation, const vec3f &extents);
virtual ~OBB();
void setOrientationQuat( const quatf& orientation );
void setCenter( const vec3f& position );
void setExtents(const vec3f& extents);
const quatf& getOrientationQuat() const;
const vec3f& getCenter() const;
const vec3f& getExtents() const;
const vec3f& getAxis(unsigned int axis) const; //0 = X, 1 = Y, 2 = Z
void sync(const vec3f &position, const quatf &orientation);
bool intersects(const OBB &obb2);
bool isInside( vec3f& p );
private:
quatf m_orientationQuat;
vec3f m_center;
vec3f m_extents;
vec3f m_axes[3]; //axes, left, up and forward, calculate from orientation
void updateAxes(const quatf &orientation);
};
#include "Utility/NEAABB.inl"
| true |
bf575c3d2cd1b4491062ee73ce7f691c9e69b00d | C++ | wakairo/cutb | /include/cutb/parser/core.h | UTF-8 | 4,241 | 2.84375 | 3 | [
"MIT"
] | permissive | #ifndef CUTB_PARSER_CORE_H
#define CUTB_PARSER_CORE_H
#include <cstddef>
#include <list>
#include "cutb/exceptions.h"
/** @file
* API for parsing CUTB tests.
*/
namespace cutb {
/**
* API class for parsing CUTB tests.
*
* To parse tests, first define a subclass of Parser overriding callback
* functions, and then call parse() with an object of the subclass.
* Not all the callback functions need to be overridden.
*/
class Parser {
public:
class TestFile;
class TestGrp;
class TestDef;
/**
* Parses all test files.
*
* @param parser an object of a subclass of Parser
*/
static void parse(Parser &parser);
/**
* Parses a test file.
*
* @param parser an object of a subclass of Parser
* @param filepath the file path to the test file to be parsed
*/
static void parse(Parser &parser, const char *filepath);
/**
* The callback function called at the start of each file
*
* @param file file information
*/
virtual void start(const TestFile *file) {}
/**
* The callback function called at the end of each file
*
* @param file file information
*/
virtual void end(const TestFile *file) {}
/**
* The callback function called at the start of each test group
*
* @param grp test group information
* @param file file information
*/
virtual void start(const TestGrp *grp, const TestFile *file) {}
/**
* The callback function called at the end of each test group
*
* @param grp test group information
* @param file file information
*/
virtual void end(const TestGrp *grp, const TestFile *file) {}
/**
* The callback function called at each test definition
*
* @param testdef test definition information
* @param grp test group information
* @param file file information
*/
virtual void at(const TestDef *testdef, const TestGrp *grp,
const TestFile *file)
{
}
Parser() : file_(NULL), grp_(NULL) {}
virtual ~Parser() = 0;
private:
const TestFile *file_;
const TestGrp *grp_;
void traverseTestdefs(const TestGrp *grp);
void traverseTestgrps(const TestFile *file);
void operator()(const TestDef *testdef);
void operator()(const TestGrp *grp);
void operator()(const TestFile *file);
static void addTest(TestGrp *grp, const TestDef *testdef);
static void addGrp(TestFile *file, const TestGrp *grp);
public:
/**
* Test definition
*/
class TestDef {
public:
/** @returns the test name. */
const char *testname() const { return testname_; }
/** @returns the line number of the test. */
int lineno() const { return lineno_; }
TestDef(const char *testname, const char *filepath, int lineno);
private:
const char *const testname_;
const int lineno_;
};
/**
* Test group
*/
class TestGrp {
public:
/** @returns the test group name. */
const char *grpname() const { return grpname_; }
/** @returns the line number of the test group. */
int lineno() const { return lineno_; }
TestGrp(const char *grpname, const char *filepath, int lineno);
private:
typedef std::list<const TestDef *> ListTestdef;
ListTestdef list_;
const char *const grpname_;
const int lineno_;
friend void Parser::addTest(TestGrp *grp, const TestDef *testdef);
friend void Parser::traverseTestdefs(const TestGrp *grp);
};
/**
* Test file
*/
class TestFile {
public:
/** @returns the file path to the test file. */
const char *filepath() const { return filepath_; }
TestFile(const char *filepath) : list_(), filepath_(filepath) {}
private:
typedef std::list<const TestGrp *> ListTestgrp;
ListTestgrp list_;
const char *const filepath_;
friend void Parser::addGrp(TestFile *file, const TestGrp *grp);
friend void Parser::traverseTestgrps(const TestFile *file);
};
class TestGrpEnd {
public:
TestGrpEnd(const char *filepath, int lineno);
};
};
}
#endif
| true |
32b1a646f0ebad6501f557bbb2f49dc9defa40c8 | C++ | hua19971997/Computer-vision | /cse576_sp20_hw1-master/src/test/test0.cpp | UTF-8 | 3,546 | 2.796875 | 3 | [] | no_license | #include "../image.h"
#include "../utils.h"
#include <string>
#include <iostream>
using namespace std;
void test_get_pixel()
{
Image im = load_image("data/dots.png");
// Test within image
TEST(within_eps(0, im.clamped_pixel(0,0,0)));
TEST(within_eps(1, im.clamped_pixel(1,0,1)));
TEST(within_eps(0, im.clamped_pixel(2,0,1)));
// Test padding
TEST(within_eps(1, im.clamped_pixel(0,3,1)));
TEST(within_eps(1, im.clamped_pixel(7,8,0)));
TEST(within_eps(0, im.clamped_pixel(7,8,1)));
TEST(within_eps(1, im.clamped_pixel(7,8,2)));
}
void test_set_pixel()
{
Image im = load_image("data/dots.png");
Image d(4,2,3);
d.set_pixel(0,0,0,0); d.set_pixel(0,0,1,0); d.set_pixel(0,0,2,0);
d.set_pixel(1,0,0,1); d.set_pixel(1,0,1,1); d.set_pixel(1,0,2,1);
d.set_pixel(2,0,0,1); d.set_pixel(2,0,1,0); d.set_pixel(2,0,2,0);
d.set_pixel(3,0,0,1); d.set_pixel(3,0,1,1); d.set_pixel(3,0,2,0);
d.set_pixel(0,1,0,0); d.set_pixel(0,1,1,1); d.set_pixel(0,1,2,0);
d.set_pixel(1,1,0,0); d.set_pixel(1,1,1,1); d.set_pixel(1,1,2,1);
d.set_pixel(2,1,0,0); d.set_pixel(2,1,1,0); d.set_pixel(2,1,2,1);
d.set_pixel(3,1,0,1); d.set_pixel(3,1,1,0); d.set_pixel(3,1,2,1);
// Test images are same
TEST(same_image(im, d));
}
void test_grayscale()
{
Image im = load_image("data/colorbar.png");
Image gray = rgb_to_grayscale(im);
Image g = load_image("data/gray.png");
TEST(same_image(gray, g));
}
void test_copy()
{
Image im = load_image("data/dog.jpg");
Image c = im;
TEST(same_image(im, c));
}
void test_shift()
{
Image im = load_image("data/dog.jpg");
Image c = im;
shift_image(c, 1, .1);
TEST(within_eps(im.data[0], c.data[0]));
TEST(within_eps(im.data[im.w*im.h+13] + .1, c.data[im.w*im.h + 13]));
TEST(within_eps(im.data[2*im.w*im.h+72], c.data[2*im.w*im.h + 72]));
TEST(within_eps(im.data[im.w*im.h+47] + .1, c.data[im.w*im.h + 47]));
}
void test_rgb_to_hsv()
{
Image im = load_image("data/dog.jpg");
rgb_to_hsv(im);
Image hsv = load_image("data/dog.hsv.png");
TEST(same_image(im, hsv));
}
void test_hsv_to_rgb()
{
Image im = load_image("data/dog.jpg");
Image c = im;
rgb_to_hsv(im);
hsv_to_rgb(im);
TEST(same_image(im, c));
}
void test_rgb2lch2rgb()
{
Image im = load_image("data/dog.jpg");
Image c = im;
rgb_to_lch(im);
lch_to_rgb(im);
TEST(same_image(im, c));
}
void run_tests()
{
test_get_pixel();
test_set_pixel();
test_copy();
test_shift();
test_grayscale();
test_rgb_to_hsv();
test_hsv_to_rgb();
test_rgb2lch2rgb();
printf("%d tests, %d passed, %d failed\n", tests_total, tests_total-tests_fail, tests_fail);
}
int main(int argc, char **argv)
{
// Image manipulation for fun testing.
Image im2 = load_image("data/dog.jpg");
for (int i=0; i<im2.w; i++)
for (int j=0; j<im2.h; j++)
im2(i, j, 0) = 0;
im2.save_image("output/pixel_modifying_output");
//Running example tests
run_tests();
/*
Image im = load_image("C:/Users/24078/Desktop/576Cv/cse576_sp20_hw1-master/data/dog.jpg");
Image c = im;
cout << "1" << im(29, 142, 0) << endl;
cout << "1" << im(29, 142, 1) << endl;
cout << "1" << im(29, 142, 2) << endl;
rgb_to_lch(im);
lch_to_rgb(im);
cout << "1" << im(29, 142, 0) << endl;
cout << "1" << im(29, 142, 1) << endl;
cout << "1" << im(29, 142, 2) << endl;
im.save_image("C:/Users/24078/Desktop/576Cv/cse576_sp20_hw1-master/output/pixel_modifying_output3");
TEST(same_image(im, c));
*/
return 0;
}
| true |
2e63faaaf18064d1f42e4c6ba40fe088b3e3e423 | C++ | Caceresenzo/42 | /webserv/source/json/JsonArray.hpp | UTF-8 | 2,040 | 2.796875 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* JsonArray.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ecaceres <ecaceres@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/11 21:55:45 by ecaceres #+# #+# */
/* Updated: 2020/11/11 21:55:45 by ecaceres ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef JSONARRAY_HPP_
# define JSONARRAY_HPP_
#include <json/JsonStructure.hpp>
#include <string>
#include <vector>
class JsonArray :
public JsonStructure
{
public:
typedef std::vector<JsonValue*> Container;
typedef Container::size_type size_type;
typedef Container::iterator iterator;
typedef Container::const_iterator const_iterator;
private:
Container m_value;
public:
JsonArray(void);
JsonArray(std::vector<JsonValue*> value);
JsonArray(const JsonArray &other);
virtual
~JsonArray(void);
JsonArray&
operator =(const JsonArray &other);
JsonValue&
operator [](int index);
const JsonValue&
operator [](int index) const;
operator Container(void);
operator Container(void) const;
void
add(JsonValue *value);
iterator
begin();
iterator
end();
const_iterator
begin() const;
const_iterator
end() const;
virtual void
clear(void);
bool
empty() const;
Container::size_type
size() const;
JsonValue*
clone(void) const;
Type
type(void) const;
const std::string
toJsonString(void) const;
bool
equals(const JsonValue &other) const;
};
#endif /* JSONARRAY_HPP_ */
| true |
3d504439a5b2222187b7b2a6b46d478d4cc7c84b | C++ | HolySmoke86/blobs | /src/ui/Widget.hpp | UTF-8 | 1,243 | 2.71875 | 3 | [] | no_license | #ifndef BLOBS_UI_WIDGET_HPP_
#define BLOBS_UI_WIDGET_HPP_
#include "../math/glm.hpp"
namespace blobs {
namespace app {
struct Assets;
}
namespace graphics {
class Viewport;
}
namespace ui {
class Widget {
public:
Widget();
virtual ~Widget();
Widget(const Widget &) = delete;
Widget &operator =(const Widget &) = delete;
Widget(Widget &&) = delete;
Widget &operator =(Widget &&) = delete;
public:
void SetParent(Widget &) noexcept;
bool HasParent() const noexcept { return parent; }
Widget &GetParent() noexcept { return *parent; }
const Widget &GetParent() const noexcept { return *parent; }
Widget *Position(const glm::vec2 &p) noexcept { pos = p; return this; }
const glm::vec2 &Position() const noexcept { return pos; }
Widget *ZIndex(float z) noexcept { z_index = z; return this; }
float ZIndex() const noexcept { return z_index; }
bool DirtyLayout() const noexcept { return dirty_layout; }
void BreakLayout() noexcept;
void BreakParentLayout() noexcept;
void Layout();
virtual glm::vec2 Size() = 0;
virtual void Draw(app::Assets &, graphics::Viewport &) noexcept = 0;
private:
virtual void FixLayout() { }
private:
Widget *parent;
glm::vec2 pos;
float z_index;
bool dirty_layout;
};
}
}
#endif
| true |
6188621ad0bf0e65223094593a6581bdfd6230e4 | C++ | HarukaFujisawa/themetraining2017 | /Arduino/TangibleCube/nzVector.cpp | UTF-8 | 2,667 | 2.890625 | 3 | [] | no_license |
#include "nzVector.h"
template<typename TYPE>
bool nzIntersection(const _nzVector3<TYPE> &ptLine1, const _nzVector3<TYPE> &ptLine2, const _nzVector3<TYPE> &ptPlane1, const _nzVector3<TYPE> &ptPlane2, const _nzVector3<TYPE> &ptPlane3, _nzVector3<TYPE> &ptIntersection)
{
bool err = false;
_nzVector3<TYPE> planeNormal(cross(ptPlane2 - ptPlane1, ptPlane3 - ptPlane1));
_nzVector3<TYPE> lineDirection(ptLine2 - ptLine1);
TYPE d = dot(planeNormal, lineDirection);
if(0 != d){
ptIntersection = ptLine1 - (dot(planeNormal, ptLine1 - ptPlane1) / d) * lineDirection;
err = true;
}
return err;
}
template<typename TYPE>
bool nzIntersection(const _nzVector2<TYPE> &pt1Line1, const _nzVector2<TYPE> &pt2Line1, const _nzVector2<TYPE> &pt1Line2, const _nzVector2<TYPE> &pt2Line2, _nzVector2<TYPE> &ptIntersection)
{
bool err = false;
TYPE a1 = pt2Line1.y - pt1Line1.y;
TYPE b1 = pt1Line1.x - pt2Line1.x;
TYPE d1 = a1 * pt1Line1.x + b1 * pt1Line1.y;
TYPE a2 = pt2Line2.y - pt1Line2.y;
TYPE b2 = pt1Line2.x - pt2Line2.x;
TYPE d2 = a2 * pt1Line2.x + b2 * pt1Line2.y;
TYPE denom = a1 * b2 - a2 * b1;
if(denom != 0){
ptIntersection = _nzVector2<TYPE>((b2 * d1 - b1 * d2) / denom, (a1 * d2 - a2 * d1) / denom);
err = true;
}
return err;
}
template <typename TYPE>
TYPE nzDistance(const _nzVector3<TYPE> &point, const _nzVector3<TYPE> &ptLine1, const _nzVector3<TYPE> &ptLine2)
{
TYPE ret = 0;
TYPE f1 = dot(point - ptLine1, ptLine2 - ptLine1);
TYPE f2 = dot(ptLine2 - ptLine1, ptLine2 - ptLine1);
if(f1 <= 0){
ret = (point - ptLine1).length();
} else if(f1 >= f2){
ret = (point - ptLine2).length();
} else {
TYPE d1 = (point - ptLine1).length();
TYPE d2 = f1 / (ptLine2 - ptLine1).length();
ret = (TYPE)sqrt((float)(d1 * d1 - d2 * d2));
}
return ret;
}
// �ソスe�ソス�ソス�ソスv�ソス�ソス�ソス[�ソスg�ソス�ソス�ソス�ソス�ソスp�ソス}�ソスN�ソス�ソス.
#define REALIZE_TEMPLATE_NZ_VECTOR(TYPE) \
template bool nzIntersection(const _nzVector3<TYPE> &ptLine1, const _nzVector3<TYPE> &ptLine2, const _nzVector3<TYPE> &ptPlane1, const _nzVector3<TYPE> &ptPlane2, const _nzVector3<TYPE> &ptPlane3, _nzVector3<TYPE> &ptIntersection); \
template bool nzIntersection(const _nzVector2<TYPE> &pt1Line1, const _nzVector2<TYPE> &pt2Line1, const _nzVector2<TYPE> &pt1Line2, const _nzVector2<TYPE> &pt2Line2, _nzVector2<TYPE> &ptIntersection); \
template TYPE nzDistance(const _nzVector3<TYPE> &point, const _nzVector3<TYPE> &ptLine1, const _nzVector3<TYPE> &ptLine2); \
REALIZE_TEMPLATE_NZ_VECTOR(double)
REALIZE_TEMPLATE_NZ_VECTOR(float)
REALIZE_TEMPLATE_NZ_VECTOR(int)
| true |
614a3705cea453c2e7332dc8e185889a840f1f53 | C++ | c00188916/Data-Structures-and-Algorithms | /templates/templates/NodeSearchCostComparer.h | UTF-8 | 308 | 2.828125 | 3 | [] | no_license | #pragma once
#include "GraphNode.h"
typedef GraphNode<std::pair<std::string, int>, int> Node;
class NodeSearchCostComparer {
public:
bool operator()(Node * n1, Node * n2) {
std::pair<std::string, int> p1 = n1->data();
std::pair<std::string, int> p2 = n2->data();
return p1.second > p2.second;
}
}; | true |
4115d25fe175473378743aad230366213c4a49c0 | C++ | deneb42/lemme | /tp2/src/station.hpp | UTF-8 | 2,399 | 3.109375 | 3 | [] | no_license |
#ifndef __STATION_HPP__
#define __STATION_HPP_
/*!
* \file station.hpp
* \brief Classe representant une station
* \author {Jean BADIE, Benjamin BLOIS}
* \date 17 janvier 2013
*/
#include <vector>
#include <string>
#include "transition.hpp"
class Station {
public :
Station(std::string name, int age); /*! constructeur d'une station*/
void addSuccesseur(Station* stat, std::string ligne, std::string heure); /*!<ajout dune station à la liste des successeurs*/
double calculerPoidCorrespondance(int age); /*!<calcul le temps pour changer d'un train à l'autre
* en fonction de l'heure et de l'age du voyageur*/
std::string stringStationParParcours() const; /*!< Format special pour afficher le parcours correctement.*/
std::string toString() const; /*!<Retourne une chaine de caracteres contenant les informations de la station*/
std::vector<Transition>* getListeSuccesseurs() { return &listeSuccesseurs; }; /*!<Getter de la liste des successeurs de la station*/
double getCoutMin() const {return coutMin;} /*!<Getter de le coutMin, cout minimum renvoye par dijkstra*/
double getCoutCh(std::string ligne); /*!<Getter sur coutCh, cout du changement de ligne dans la station*/
Transition getPrec() const {return prec;} /*!<Getter surPrec, transition qui mene à la station precedente par dijkstra*/
std::string getName() const {return nomStation;} /*!<Getter sur le nom de la station*/
void setCoutMin(double p) {coutMin=p;} /*!<Setter sur coutMin*/
void setPrec(Transition p) {prec=p;} /*!<Setter sur Prec*/
void setHeure(std::string h); /*!< Recalcule les temps de changement en fonction de la nouvelle heure */
private :
std::string nomStation; /*!<Nom de la station*/
std::vector<Transition> listeSuccesseurs; /*!<Nom des stations vers lesquelles on peut aller*/
int ageVoyageur; /*!< age du Voyageur, genere a l'appel du constructeur du plan*/
double coutCh; /*!<cout du changement de ligne dans la station (correspondance)*/
double coutMin; /*!<cout minimum renvoye par dijkstra pour venir à la station*/
Transition prec; /*!<transition qui mene à la station precedente par dijkstra*/
};
bool operator==(const Station& s1, const Station& s2); /*!<Surcharge de l'operateur == */
#endif // __STATION_HPP__
| true |
f92fcfcf72209d5b793e74e64d4ebf9a4f476ea6 | C++ | minigo/simpleai | /src/ai/aggro/AggroMgr.h | UTF-8 | 1,514 | 3.328125 | 3 | [
"Zlib"
] | permissive | #pragma once
#include <vector>
#include <aggro/Entry.h>
namespace ai {
class AI;
typedef std::shared_ptr<AI> AIPtr;
/**
* @brief Manages the aggro values for one @c AI instance. There are several ways to degrade the aggro values.
*/
class AggroMgr {
public:
typedef std::vector<Entry> Entries;
typedef Entries::iterator EntriesIter;
protected:
mutable Entries _entries;
mutable bool _dirty;
/**
* @brief Remove the entries from the list that have no aggro left.
* This list is ordered, so we will only remove the first X elements.
*/
void cleanupList();
inline void sort() const;
public:
AggroMgr(std::size_t expectedEntrySize = 0u);
virtual ~AggroMgr();
/**
* @brief this will update the aggro list according to the reduction type of an entry.
* @param[in] deltaMillis The current milliseconds to use to update the aggro value of the entries.
*/
void update(long deltaMillis);
/**
* @brief will increase the aggro
* @param[in,out] entity The entity to increase the aggro against
* @param[in] amount The amount to increase the aggro for
* @return The aggro @c Entry that was added or updated. Useful for changing the reduce type or amount.
*/
EntryPtr addAggro(const AIPtr& entity, float amount);
/**
* @return All the aggro entries
*/
const Entries& getEntries() const {
return _entries;
}
/**
* @brief Get the entry with the highest aggro value.
*
* @note Might execute a sort on the list if its dirty
*/
EntryPtr getHighestEntry() const;
};
}
| true |
dc9f54d407722749f933452e5c0ee6698a1cba8c | C++ | Mati5/Sea-Battle-game | /SeaBattle/CheckboxBtn.cpp | UTF-8 | 1,024 | 2.921875 | 3 | [] | no_license | #include "CheckboxBtn.h"
CheckboxBtn::CheckboxBtn():GridField()
{
m_width = 45;
m_height = 45;
m_isChecked = false;
loadTexture("../images/field.png");
if (!m_checkedTexture.loadFromFile("../images/checked.png"))
std::cout << "Error load craft texture!" << std::endl;
}
CheckboxBtn::CheckboxBtn(bool isChecked):m_isChecked(isChecked)
{
m_width = 45;
m_height = 45;
loadTexture("../images/field.png");
if (!m_checkedTexture.loadFromFile("../images/checked.png"))
std::cout << "Error load craft texture!" << std::endl;
checkIsChecked();
}
void CheckboxBtn::setChecked(bool isChecked)
{
m_isChecked = isChecked;
}
bool CheckboxBtn::getChecked() const
{
return m_isChecked;
}
void CheckboxBtn::checkIsChecked()
{
if (m_isChecked)
m_sprite.setTexture(m_checkedTexture);
else
m_sprite.setTexture(m_texture);
}
void CheckboxBtn::updateCoordinate()
{
auto x = float(m_coordinate[0]);
auto y = float(m_coordinate[1]);
m_sprite.setPosition(x, y);
}
| true |
5571708b01a75f2c8b8d9fd2aac2ac4c02f76ff0 | C++ | j-ss-h/ProjectRobot | /Project Roomba/driver.cpp | UTF-8 | 4,462 | 3.015625 | 3 | [] | no_license | #include "States.h"
#include <iostream>
#include <fstream>// for input file
using namespace std;
/*
These are the probabilities for each negatively impacting category for the robot.
The user can modify these through the menu.
*/
void menu(StateMachine& bot);
void probability(StateMachine& bot);
int main()
{
StateMachine wall_e;
// menu options. NOT CURRENTLY IN USE. Enter 0 to bypass.
cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
<< "!!!!!Menu is not currently in use. Enter 0 to bypass.!!!!!\n"
<< "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n"; // TEMPORARY
menu(wall_e);
//testing Building printRoom function
/*
Building test1("f1r110.txt");
test1.add("f1r210.txt");
test1.add("f1r209.txt");
test1.add("f1r211.txt");
test1.add("f1r309.txt");
test1.add("f1r311.txt");
test1.add("f1r410.txt");
test1.printRoom("f1r110.txt");
test1.printRoom("f1r209.txt");
test1.printRoom("f1r210.txt");
test1.printRoom("f1r211.txt");
test1.printRoom("f1r309.txt");
test1.printRoom("f1r311.txt");
test1.printRoom("f1r410.txt");
*/
//test1.printFloor(); // used to confirm pointer functionality
return 0;
}
void menu(StateMachine &bot)
{
int choice = 1;
bool prob = false;
bool deployed = false;
while (choice != 0)
{
cout << "***STARTING MENU***\n"
<< "1.) Set probabilities\n"
<< "2.) Deploy Robot (run program)\n"
<< "3.) View Mission Log\n"
<< "4.) Review Reconnaissance Info\n"
<< "0.) Exit\n"
<< "Selection: ";
cin >> choice;
switch (choice)
{
case 1:
if (prob == false)
{
probability(bot);
prob = true;
}
else cout << "Probabilities have been set. Exit and restart to set new values...\n";
break;
case 2:
if (prob == true)
{
cout << "Not yet implemented...\n"; // PLACEHOLDER!!!!!!!!!!!!!!!!!!!!!!!!!!!!
deployed = true;
}
else cout << "Probabilities have not been set...\n";
break;
case 3:
if (deployed == true)
{
cout << "Not yet implemented...\n"; // PLACEHOLDER!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
else cout << "Robot has not been deployed...\n";
break;
case 4:
if (deployed == true)
{
cout << "Not yet implemented...\n"; // PLACEHOLDER!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
else cout << "Robot has not been deployed...\n";
break;
case 0:
cout << "Exiting program...\n";
break;
default:
cout << "Invalid entry...\n";
break;
}
puts("");
}
}
void probability(StateMachine& bot)
{
int prob = 1;
while (prob != 0)
{
cout << "\n***PROBABILITY MENU***\n"
<< "1.) Entity armed\n"
<< "2.) Obstruction threat\n"
<< "3.) Doors locked\n"
<< "4.) Entity unarmed\n"
//<< "5.) Robot compromised after found\n"
<< "0.) Save changes (unchanged values default to 0)\n"
<< "Selection: ";
cin >> prob;
switch (prob)
{
case 1:
cout << "Enter the probability of entities being armed (1-100): ";
cin >> prob;
if (prob > 0 && prob < 101)
{
bot.setArmedProbability(prob);
}
else
{
prob = 1;
cout << "Invalid entry...\nPlease enter a value between 1 and 100.\n";
}
break;
case 2:
cout << "Enter the probability of obstructions being a threat (1-100): ";
cin >> prob;
if (prob > 0 && prob < 101)
{
bot.setObstructionProbability(prob);
}
else
{
prob = 1;
cout << "Invalid entry...\nPlease enter a value between 1 and 100.\n";
}
break;
case 3:
cout << "Enter the probability of doors being locked (1-100): ";
cin >> prob;
if (prob > 0 && prob < 101)
{
bot.setLockedDoorProbability(prob);
}
else
{
prob = 1;
cout << "Invalid entry...\nPlease enter a value between 1 and 100.\n";
}
break;
case 4:
cout << "Enter the probability of being found by unarmed entities (1-100): ";
cin >> prob;
if (prob > 0 && prob < 101)
{
bot.setUnarmedProbability(prob);
}
else
{
prob = 1;
cout << "Invalid entry...\nPlease enter a value between 1 and 100.\n";
}
break;
/*case 5:
cout << "Enter the probability of being compromised after being found (1-100): ";
cin >> prob;
if (prob > 0 && prob < 101)
{
ROBOT_COMPROMISED = prob;
}
else
{
prob = 1;
cout << "Invalid entry...\nPlease enter a value between 1 and 100.\n";
}
break;*/
case 0:
cout << "Returning to previous menu...\n";
break;
default:
cout << "Invalid entry...\n";
break;
}
}
} | true |
5ef291e139bb2c39370132120606782d5b740218 | C++ | Shakadak/cpp | /pool/d03/ex01/ScavTrap.hpp | UTF-8 | 1,656 | 3.109375 | 3 | [] | no_license | #ifndef SCAVTRAP_HPP
# define SCAVTRAP_HPP
# include <string>
class ScavTrap {
public:
ScavTrap(std::string Name);
ScavTrap(ScavTrap const & src);
~ScavTrap(void);
ScavTrap & operator=(ScavTrap const & rhs);
void rangedAttack(std::string const & target);
void meleeAttack(std::string const & target);
void takeDamage(unsigned int amount);
void beRepaired(unsigned int amount);
void challengeNewcomer(std::string const & target);
int getHitPoints(void) const;
int getMaxHitPoints(void) const;
int getEnergyPoints(void) const;
int getMaxEnergyPoints(void) const;
int getLevel(void) const;
std::string getName(void) const;
int getMeleeAttackDamage(void) const;
int getRangedAttackDamage(void) const;
int getArmorDamageReduction(void) const;
private:
int _HitPoints;
int _MaxHitPoints;
int _EnergyPoints;
int _MaxEnergyPoints;
int _Level;
std::string _Name;
int _MeleeAttackDamage;
int _RangedAttackDamage;
int _ArmorDamageReduction;
ScavTrap(void);
protected:
void setHitPoints(int HP);
void setMaxHitPoints(int MHP);
void setEnergyPoints(int EP);
void setMaxEnergyPoints(int MEP);
void setLevel(int LVL);
void setName(std::string Name);
void setMeleeAttackDamage(int Dmg);
void setRangedAttackDamage(int Dmg);
void setArmorDamageReduction(int Shield);
};
#endif
| true |
9047c80b1bde648a52b7cf01214b2e089d985db0 | C++ | peng53/failure | /chunkreader/ireader_extf.cpp | UTF-8 | 1,106 | 2.953125 | 3 | [] | no_license | #include "ireader_extf.h"
#include <stack>
using std::stack;
void reader2stdout(IReader* reader,ostream& out){
while (!reader->empty()){
out << reader->get();
reader->advance();
}
out << '\n';
}
static unordered_map<char,char> BRACKETS = {
{'[',']'}, {']','['},
{'{','}'}, {'}','{'},
{'"','"'},
};
template <typename T>
T& closure(IReader* reader,T& s,unordered_map<char,char>* match){
// Looks at current char, if its in BRACKETS,
// collects all characters to string until
// its counterpart is encountered.
if (reader->empty()){
return s;
}
if (!match){
match = &BRACKETS;
}
char c = reader->get();
if (match->count(c)==0){
return s;
}
reader->advance();
stack<char> stk;
stk.emplace(match->at(c));
while (!stk.empty() && (!reader->empty())){
c = reader->get();
if (match->count(c)>0){
if (c==stk.top()){
if (stk.size()<=1){
return s;
} else {
stk.pop();
}
} else {
stk.emplace(match->at(c));
}
}
s += c;
reader->advance();
}
return s;
}
string closure(IReader* reader){
string output;
return closure(reader,output);
}
| true |
8207170c7038d3bd7f726fed81339338ba756761 | C++ | yaoweiliu/work | /widora/BoardService/Appl/Process.cpp | UTF-8 | 1,029 | 2.71875 | 3 | [] | no_license | #include "Process.h"
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
extern char **environ;
Process::Process()
{
}
Process::~Process()
{
}
/*
* param: path is file's path
*
* return 0 is success, -1 is failed.
*/
int Process::run(const char *path)
{
return execBin(path);
}
/*
* param: path is file's path
*
* return 0 is success, -1 is failed.
*/
int Process::kill(const char *path)
{
return systemCmd(path);
}
/*
* param: path is file's path
*
* return 0 is success, -1 is failed.
*/
int Process::execBin(const char *path)
{
pid_t pid;
pid = fork();
if(pid < 0) {
perror("fork()");
return -1;
}
else if(pid == 0) {
execle(path, path, NULL, environ);
exit(0);
}
return 0;
}
/*
* param: cmd is
*
* return 0 is success, -1 is failed.
*/
int Process::systemCmd(const char *cmd)
{
char shellCmd[SYS_CMD_LEN];
memset(shellCmd, 0, SYS_CMD_LEN);
sprintf(shellCmd, "ps | grep %s | grep -v 'grep' | awk '{print $1}' | xargs kill -s 9", cmd);
return system(shellCmd);
}
| true |
984a69187fa30c601bfc672f3da708ec7dea0209 | C++ | divsriv111/semester-programs | /sem1/lab 13/lab13 10.cpp | UTF-8 | 196 | 2.546875 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
int main()
{
char a[100],i;
printf("enter a string\n");
gets(a);
for(i=0;a[i]!='\0';++i){
if(a[i]==' ')
a[i]=a[i+1];}
a[i]='\0';
printf("%s",a);
}
| true |
de5a63dc9fbe4ed64c10530256cc0a714dcb9b43 | C++ | njuHan/OJcodes | /nowcoder/coding-interviews/不用加减乘除做加法.cpp | UTF-8 | 382 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<unordered_map>
#include<unordered_set>
#include<set>
#include<list>
#include<ctime>
using namespace std;
class Solution {
public:
int Add(int num1, int num2)
{
if (num2 == 0) return num1;
int a = num1^num2;
num2 = (num1&num2) << 1;
return Add(a, num2);
}
};
| true |
e9be202e5df766985bd3092aff9c9c7a261a4867 | C++ | alexsunday/espush-dc1 | /lib/espush/os_impl.cpp | UTF-8 | 1,878 | 2.5625 | 3 | [] | no_license | #include <Arduino.h>
#include <Esp.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include "frame.h"
#include "board.h"
static char chip_imei[32];
/*
signal to espush-rssi ,signal 的值,为 0~5 共 6 个等级,返回 0~31 的 平台值
平台rssi值与信号等级对应关系
0 => 0
1 => 1
[2, 15] => 2
[16, 25] => 3
[26, 30] => 4
31 => 5
*/
int signal_to_esp_rssi(int signal)
{
switch (signal)
{
case 0:
return 0;
case 1:
return 1;
case 2:
return 2;
case 3:
return 16;
case 4:
return 26;
case 5:
return 31;
default:
return 0;
}
}
/*
rssi to signal 返回 0~5 共6个等级
[-126, -88) 或者 [156, 168) 为 0 格
[-88, -78) 或者 [168, 178) 为 1 格
[-78, -67) 或者 [178, 189) 为 2 格
[-67, -55) 或者 [189, 200) 为 3 格
[-55, -45) 或者 为 4 格
[-45, 0] 为 第 5 格
*/
int rssi_to_signal(int rssi)
{
if(rssi > 0) {
return 5;
} else if(rssi >= -45) {
return 5;
} else if(rssi >= -55) {
return 4;
} else if(rssi >= -67) {
return 3;
} else if(rssi >= -78) {
return 2;
} else if(rssi >= -88) {
return 1;
} else {
return 0;
}
return 0;
}
// 返回的 rssi,必须格式化为 类似 GPRS 形式
int getRSSI(void)
{
int32_t rssi = WiFi.RSSI();
return signal_to_esp_rssi(rssi_to_signal(rssi));
}
const char* get_imei(void)
{
uint32_t chip = ESP.getChipId();
#ifdef BOARD_TYPE_DC1
sprintf(chip_imei, "WED%X", chip);
#else
sprintf(chip_imei, "WE1%X", chip);
#endif
return chip_imei;
}
void show_imei(void)
{
const char* imei = get_imei();
Serial.printf("IMEI:[%s]\r\n", imei);
}
| true |
5dac64b9e760c2d2cfcb83110feee7a700b8e5e7 | C++ | WZC961007/Clanguage | /eex5-9.cpp | UTF-8 | 266 | 2.765625 | 3 | [] | no_license | #include <stdio.h>
int a[50];
int fun(int m)
{
int n=0;
for(int i=1;i<=m;i++)
{
if((i%7==0)||(i%11==0))
{
a[n]=i;
n++;
}
}
return n;
}
main()
{
int m;
scanf("%d",&m);
for(int i=0;i<fun(m);i++)
{
printf("%d\n",a[i]);
}
} | true |
1f036a3a7a88ba84151534fccd869c3e4d7e2438 | C++ | kokfahad/Problems-Solving- | /Special__Interview Questions/Array Interview questions/02_negative_first_element.cpp | UTF-8 | 366 | 2.671875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int arr[]={-1,2,-3,4,-5};
int n=sizeof(arr)/sizeof(arr[0]);
int j=0;
for(int i=0;i<n;i++)
{
if(arr[i]<0)
{
if(i!=j)
swap(arr[i],arr[j]);
j++;
}
}
for(int j=0;j<n;j++)
{
cout<<arr[j]<<" ";
}
} | true |
6a5b97fb0c3a893aef70559aca0aeda9383de22a | C++ | qiulx026/leetcode | /tic toc toe.cpp | UTF-8 | 5,079 | 3.578125 | 4 | [] | no_license | // ConsoleApplication7.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
class Board { //For each game, there is only one Board object.
public:
void show(); //To show the board
int judge(); //judge whether game is over, return 1 when there is a winner, return 0 when draw, return -1 when the game is not over
bool validmove(int i); //check the step player(or computer) want to place is valid or not
void move(char ch,int i); //after check that the step is valid, the board could do the step.
void initiate();
private: //stand for the board
vector <char> myboard;
};
class player { //a class for player
public:
char getmark(){ //get player's mark
return 'o';
}
int pick(){ //get a step the player want to move
cout << "Player enter a number: ";
cin >> move_index;
return move_index;
}
private:
int move_index;
};
class computer { //a class for computer
public:
char getmark(){ //get player's mark
return 'x';
}
int pick(){ //get a random step from 1 to 9
move_index = rand() % 9 +1;
return move_index;
}
private:
int move_index;
};
int main()
{
Board board;
board.initiate();
board.show();
player you; //player
computer com; //computer
int stopat=0; //a mark that stands for who goes the last one step when game is stop(to judge who is winner)
int move_step; //move step number
char mark; //player or computer's mark('o' or 'x')
char who_first=0; // stands for who is first, 'y' for computer, others for player
cout << "Computer first? y/n\n";
cin >> who_first;
if(who_first=='y'){ //if computer is first, then computer goes a step before the while loop
mark=com.getmark();
move_step=com.pick();
while(board.validmove(move_step)==false){
move_step=com.pick();
}
board.move(mark,move_step);
}
while(board.judge()==-1){ // while loop, end when there is winner or no step to go
board.show();
mark=you.getmark(); //player goes first
move_step=you.pick();
while(board.validmove(move_step)==false){ //while loop to get a valid move step
cout<<"invalid number"<<endl;
move_step=you.pick();
}
board.move(mark,move_step);
if(board.judge()!=-1) {stopat=1;break;} //judge after player goes
else {
mark=com.getmark(); //computer goes
move_step=com.pick();
while(board.validmove(move_step)==false){ //while loop to get a valid move step
move_step=com.pick();
}
board.move(mark,move_step);
}
}
board.show();
if(board.judge()==0) cout<<"you and computer get a draw"<<endl;
if(board.judge()==1&&stopat==1) cout<<"congratulation! you win!"<<endl;
if(board.judge()==1&&stopat==0) cout<<"sorry, computer win."<<endl;
return 0;
}
int Board::judge() //check every row,colon and diagonal, if there is winner, return 1;if every step is full, return 0;else return -1.
{
if (myboard[0] == myboard[1] && myboard[1] == myboard[2])
return 1;
else if (myboard[3] == myboard[4] && myboard[4] == myboard[5])
return 1;
else if (myboard[6] == myboard[7] && myboard[7] == myboard[8])
return 1;
else if (myboard[0] == myboard[3] && myboard[3] == myboard[6])
return 1;
else if (myboard[1] == myboard[4] && myboard[4] == myboard[7])
return 1;
else if (myboard[2] == myboard[5] && myboard[5] == myboard[8])
return 1;
else if (myboard[0] == myboard[4] && myboard[4] == myboard[8])
return 1;
else if (myboard[2] == myboard[4] && myboard[4] == myboard[6])
return 1;
else if (myboard[0] != '1' && myboard[1] != '2' && myboard[2] != '3'
&& myboard[3] != '4' && myboard[4] != '5' && myboard[5] != '6'
&& myboard[6] != '7' && myboard[7] != '8' && myboard[8] != '9')
return 0;
else
return -1;
}
void Board::show(){
system("cls");
cout << "Lianxiao Qiu's Game";
cout << "\nYou (o) - Computer (x)\n"<< endl;
cout << "\t*\t*\t" << endl;
cout << " " << myboard[0] << "\t* " << myboard[1] << "\t* " << myboard[2] << endl;
cout << "\t*\t*\t" << endl;
cout << "* * * * * * * * * * * * *" << endl;
cout << "\t*\t*\t" << endl;
cout << " " << myboard[3] << "\t* " << myboard[4] << "\t* " << myboard[5] << endl;
cout << "\t*\t*\t" << endl;
cout << "* * * * * * * * * * * * *" << endl;
cout << "\t*\t*\t" << endl;
cout << " " << myboard[6] << "\t* " << myboard[7] << "\t* " << myboard[8] << endl;
cout << "\t*\t*\t" << endl;
}
bool Board::validmove(int i){
char ch=(char)i+48;
if(ch==myboard[i-1]) return true; //if myboard[index] hasn't been changed, it is valid
else return false;
}
void Board::initiate(){ //initiate the borad vector<char> myboard
for(int i=0;i<9;i++){
myboard.push_back(i+49);
}
}
void Board::move(char ch,int i){ //change myboard[index] to mark(player's or computer's)
myboard[i-1]=ch;
} | true |
03050888a9ca9ab5d24731f53a7c2338a579985c | C++ | odganzorig/Binary_tree_lab | /binary_tree_tests.cpp | UTF-8 | 11,469 | 3.203125 | 3 | [] | no_license | // FILE: binary_tree_tests.cpp
// CS 223 Winter 2018, Lab 8
// Tree tests for a binary tree class
//
// Barb Wahl & Theresa Wilson, 4-3-18
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <vector>
#include "binary_tree.h" // provides both node classes, plus tree class
#include "gtest/gtest.h" // declares the testing framework
using namespace std;
using namespace binary_tree_lab;
namespace
{
/* TESTING PLAN:
TestDefaultConstructor_isEmpty
- construct_empty_tree
TestSecondConstructor_contains_isEmpty
- size_one_tree
- size_two_tree
- size_three_tree
- size_eight_tree
Test_insert_and_size
- empty_tree_size_zero
- insert_into_empty_tree
- insert_into_left_subtree_of_size_one_tree
- insert_into_right_subtree_of_size_one_tree
- inserting_duplicate_has_no_effect
- insert_5_3_2_4_8_7_9_6_in_that_order
Test_getMax_getMin
- size_one_tree
- size_two_tree
- size_three_tree
- size_eight_tree
- exception_thrown_getMax_of_empty_tree
- exception_thrown_getMin_of_empty_tree
Test_height_and_clear
- empty_tree
- size_one_tree
- size_two_tree
- size_three_tree_height_one
- size_three_tree_height_two
- size_eight_tree
Test_preorder
- empty_tree
- size_one_tree
- size_two_tree
- size_three_tree_height_one
- size_three_tree_height_two
- size_eight_tree
Test_inorder
- empty_tree
- size_one_tree
- size_two_tree
- size_three_tree_height_one
- size_three_tree_height_two
- size_eight_tree
*/
// TestDefaultConstructor_isEmpty
// - construct_empty_tree
TEST(TestDefaultConstructor_isEmpty, construct_empty_tree)
{
binary_tree t1;
EXPECT_TRUE(t1.isEmpty());
}
// TestSecondConstructor_contains_isEmpty
// - size_one_tree
// - size_two_tree
// - size_three_tree
// - size_eight_tree
TEST(TestSecondConstructor_contains_isEmpty, size_one_tree)
{
vector <int> v;
v.push_back(5);
binary_tree t1(v);
EXPECT_TRUE(t1.contains(5));
EXPECT_FALSE(t1.contains(4));
EXPECT_FALSE(t1.contains(6));
EXPECT_FALSE(t1.isEmpty());
}
TEST(TestSecondConstructor_contains_isEmpty, size_two_tree)
{
vector <int> v;
v.push_back(5);
v.push_back(2);
binary_tree t1(v);
EXPECT_TRUE(t1.contains(5));
EXPECT_TRUE(t1.contains(2));
EXPECT_FALSE(t1.contains(1));
EXPECT_FALSE(t1.contains(3));
EXPECT_FALSE(t1.isEmpty());
}
TEST(TestSecondConstructor_contains_isEmpty, size_three_tree)
{
vector <int> v;
v.push_back(5);
v.push_back(2);
v.push_back(8);
binary_tree t1(v);
EXPECT_TRUE(t1.contains(5));
EXPECT_TRUE(t1.contains(2));
EXPECT_TRUE(t1.contains(8));
EXPECT_FALSE(t1.contains(7));
EXPECT_FALSE(t1.contains(9));
EXPECT_FALSE(t1.isEmpty());
}
TEST(TestSecondConstructor_contains_isEmpty, size_eight_tree)
{
vector <int> v;
v.push_back(5);
v.push_back(3);
v.push_back(4);
v.push_back(8);
v.push_back(2);
v.push_back(9);
v.push_back(6);
v.push_back(7);
binary_tree t1(v);
for (int i = 2; i < 10; i++)
{
EXPECT_TRUE(t1.contains(i));
}
EXPECT_FALSE(t1.isEmpty());
}
// Test_insert_and_size
// - empty_tree_size_zero
// - insert_into_empty_tree
// - insert_into_left_subtree_of_size_one_tree
// - insert_into_right_subtree_of_size_one_tree
// - inserting_duplicate_has_no_effect
// - insert_5_3_2_4_8_7_9_6_in_that_order
TEST(Test_insert_and_size, empty_tree_size_zero)
{
binary_tree t1;
EXPECT_EQ(t1.size(), 0);
}
TEST(Test_insert_and_size, insert_into_empty_tree)
{
binary_tree t1;
t1.insert(5);
EXPECT_EQ(t1.size(), 1);
}
TEST(Test_insert_and_size, insert_into_left_subtree_of_size_one_tree)
{
binary_tree t1;
t1.insert(5);
t1.insert(2);
EXPECT_EQ(t1.size(), 2);
}
TEST(Test_insert_and_size, insert_into_right_subtree_of_size_one_tree)
{
binary_tree t1;
t1.insert(5);
t1.insert(8);
EXPECT_EQ(t1.size(), 2);
}
TEST(Test_insert_and_size, inserting_duplicate_has_no_effect)
{
binary_tree t1;
t1.insert(5);
t1.insert(7);
t1.insert(3);
t1.insert(4);
t1.insert(6);
for (int i = 3; i < 8; i++)
{
t1.insert(i);
EXPECT_EQ(t1.size(), 5);
}
}
TEST(Test_insert_and_size, insert_5_3_2_4_8_7_9_6_in_that_order)
{
binary_tree t1;
t1.insert(5);
EXPECT_EQ(t1.size(), 1);
t1.insert(3);
EXPECT_EQ(t1.size(), 2);
t1.insert(2);
EXPECT_EQ(t1.size(), 3);
t1.insert(4);
EXPECT_EQ(t1.size(), 4);
t1.insert(8);
EXPECT_EQ(t1.size(), 5);
t1.insert(7);
EXPECT_EQ(t1.size(), 6);
t1.insert(9);
EXPECT_EQ(t1.size(), 7);
t1.insert(6);
EXPECT_EQ(t1.size(), 8);
}
// Test_getMax_getMin
// - size_one_tree
// - size_two_tree
// - size_three_tree
// - size_eight_tree
// - exception_thrown_getMax_of_empty_tree
// - exception_thrown_getMin_of_empty_tree
TEST(Test_getMax_getMin, size_one_tree)
{
binary_tree t1;
t1.insert(5);
EXPECT_EQ(t1.getMax(), 5);
EXPECT_EQ(t1.getMin(), 5);
}
TEST(Test_getMax_getMin, size_two_tree)
{
binary_tree t1;
t1.insert(5);
t1.insert(2);
EXPECT_EQ(t1.getMax(), 5);
EXPECT_EQ(t1.getMin(), 2);
}
TEST(Test_getMax_getMin, size_three_tree)
{
binary_tree t1;
t1.insert(5);
t1.insert(2);
t1.insert(8);
EXPECT_EQ(t1.getMax(), 8);
EXPECT_EQ(t1.getMin(), 2);
}
TEST(Test_getMax_getMin, size_eight_tree)
{
vector <int> v;
v.push_back(5);
v.push_back(3);
v.push_back(4);
v.push_back(8);
v.push_back(2);
v.push_back(9);
v.push_back(6);
v.push_back(7);
binary_tree t1(v);
EXPECT_EQ(t1.getMax(), 9);
EXPECT_EQ(t1.getMin(), 2);
}
TEST(Test_getMax_getMin, exception_thrown_getMax_of_empty_tree)
{
try
{
binary_tree t1;
t1.getMax();
EXPECT_TRUE(false);
}
catch (domain_error e)
{
cout << "Exception thrown: " << endl;
cout << e.what() << endl;
}
}
TEST(Test_getMax_getMin, exception_thrown_getMin_of_empty_tree)
{
try
{
binary_tree t1;
t1.getMin();
EXPECT_TRUE(false);
}
catch (domain_error e)
{
cout << "Exception thrown: " << endl;
cout << e.what() << endl;
}
}
// Test_height_and_clear
// - empty_tree
// - size_one_tree
// - size_two_tree
// - size_three_tree_height_one
// - size_three_tree_height_two
// - size_eight_tree
TEST(Test_height_and_clear, empty_tree)
{
binary_tree t1;
EXPECT_EQ(t1.height(), -1);
t1.clear();
EXPECT_TRUE(t1.isEmpty());
}
TEST(Test_height_and_clear, size_one_tree)
{
binary_tree t1;
t1.insert(5);
EXPECT_EQ(t1.height(), 0);
t1.clear();
EXPECT_TRUE(t1.isEmpty());
}
TEST(Test_height_and_clear, size_two_tree)
{
binary_tree t1;
t1.insert(5);
t1.insert(2);
EXPECT_EQ(t1.height(), 1);
t1.clear();
EXPECT_TRUE(t1.isEmpty());
}
TEST(Test_height_and_clear, size_three_tree_height_one)
{
binary_tree t1;
t1.insert(5);
t1.insert(2);
t1.insert(8);
EXPECT_EQ(t1.height(), 1);
t1.clear();
EXPECT_TRUE(t1.isEmpty());
}
TEST(Test_height_and_clear, size_three_tree_height_two)
{
binary_tree t1;
t1.insert(5);
t1.insert(2);
t1.insert(3);
EXPECT_EQ(t1.height(), 2);
t1.clear();
EXPECT_TRUE(t1.isEmpty());
}
TEST(Test_height_and_clear, size_eight_tree)
{
binary_tree t1;
t1.insert(5);
t1.insert(3);
t1.insert(8);
t1.insert(2);
t1.insert(4);
t1.insert(6);
t1.insert(9);
t1.insert(7);
EXPECT_EQ(t1.height(), 3);
t1.clear();
EXPECT_TRUE(t1.isEmpty());
}
// Test_preorder
// - empty_tree
// - size_one_tree
// - size_two_tree
// - size_three_tree_height_one
// - size_three_tree_height_two
// - size_eight_tree
TEST(Test_preorder, empty_tree)
{
binary_tree t1;
string correct = "<empty tree>";
EXPECT_EQ(correct, t1.preorder());
}
TEST(Test_preorder, size_one_tree)
{
binary_tree t1;
t1.insert(5);
string correct = "5 ";
EXPECT_EQ(correct, t1.preorder());
}
TEST(Test_preorder, size_two_tree)
{
binary_tree t1;
t1.insert(5);
t1.insert(3);
string correct = "5 3 ";
EXPECT_EQ(correct, t1.preorder());
}
TEST(Test_preorder, size_three_tree_height_one)
{
binary_tree t1;
t1.insert(5);
t1.insert(2);
t1.insert(8);
string correct = "5 2 8 ";
EXPECT_EQ(correct, t1.preorder());
}
TEST(Test_preorder, size_three_tree_height_two)
{
binary_tree t1;
t1.insert(5);
t1.insert(2);
t1.insert(3);
string correct = "5 2 3 ";
EXPECT_EQ(correct, t1.preorder());
}
TEST(Test_preorder, size_eight_tree)
{
binary_tree t1;
t1.insert(5);
t1.insert(3);
t1.insert(8);
t1.insert(2);
t1.insert(4);
t1.insert(6);
t1.insert(9);
t1.insert(7);
string correct = "5 3 2 4 8 6 7 9 ";
EXPECT_EQ(correct, t1.preorder());
}
// Test_inorder
// - empty_tree
// - size_one_tree
// - size_two_tree
// - size_three_tree_height_one
// - size_three_tree_height_two
// - size_eight_tree
TEST(Test_inorder, empty_tree)
{
binary_tree t1;
string correct = "<empty tree>";
EXPECT_EQ(correct, t1.inorder());
}
TEST(Test_inorder, size_one_tree)
{
binary_tree t1;
t1.insert(5);
string correct = "5 ";
EXPECT_EQ(correct, t1.inorder());
}
TEST(Test_inorder, size_two_tree)
{
binary_tree t1;
t1.insert(5);
t1.insert(3);
string correct = "3 5 ";
EXPECT_EQ(correct, t1.inorder());
}
TEST(Test_inorder, size_three_tree_height_one)
{
binary_tree t1;
t1.insert(5);
t1.insert(2);
t1.insert(8);
string correct = "2 5 8 ";
EXPECT_EQ(correct, t1.inorder());
}
TEST(Test_inorder, size_three_tree_height_two)
{
binary_tree t1;
t1.insert(5);
t1.insert(2);
t1.insert(3);
string correct = "2 3 5 ";
EXPECT_EQ(correct, t1.inorder());
}
TEST(Test_inorder, size_eight_tree)
{
binary_tree t1;
t1.insert(5);
t1.insert(3);
t1.insert(8);
t1.insert(2);
t1.insert(4);
t1.insert(6);
t1.insert(9);
t1.insert(7);
string correct = "2 3 4 5 6 7 8 9 ";
EXPECT_EQ(correct, t1.inorder());
}
} // namespace
// main() for testing -- boilerplate
int main(int argc, char* argv[]){
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| true |
1987e2c824702b19ef363f8998eb4d9dc6a79d7c | C++ | TheNsBhasin/CodeChef | /GERMANDE/main.cpp | UTF-8 | 807 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
using namespace std;
int printPresident(int arr[],int n,int k)
{
int d=n*k;
int counter=0;
int cases[k];
for(int i=0;i<k;i++)
{
cases[i]=0;
if(arr[i]==1)
counter++;
}
if(counter>k/2)
cases[0]++;
for(int i=k;i<d+k;i++)
{
if(arr[i%d]==1 && arr[i-k]==0)
counter++;
else if(arr[i%d]==0 && arr[i-k]==1)
counter--;
if(counter>k/2)
cases[i%k]++;
if(cases[i%k]>n/2)
return 1;
}
return 0;
}
int main()
{
int t,n,k;
cin>>t;
while(t--)
{
cin>>n>>k;
int arr[n*k];
for(int i=0;i<n*k;i++)
cin>>arr[i];
cout<<printPresident(arr,n,k)<<endl;
}
return 0;
}
| true |
a01a06d645b675c77398942c65476cc9479ab211 | C++ | GuAntunes/excercises-language-C | /Lista 6 (STRUCT)/Exercicio_09.cpp | WINDOWS-1250 | 1,970 | 3.203125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <iostream>
using namespace std;
typedef struct info{
char nome[30],sexo,cargo[30];
int idade,CPF,nascimento,setor,salario;
};
int main(){
setlocale(LC_ALL,"portuguese");
FILE *file;
info *dados;
int n;
printf("Digite quantos funcionrios deseja cadastrar: ");
scanf("%d",&n);
dados = (info*) malloc (sizeof(info)*n);
file = fopen("Exercicio_09.txt","w");
for(int cont=0;cont<n;cont++){
printf("Digite o nome do funcionrio: ");
fflush(stdin);
gets(dados[cont].nome);
do{
printf("Digite o sexo do funcionrio[M/F]: ");
scanf("%c",&dados[cont].sexo);
fflush(stdin);
}while(dados[cont].sexo!='m'&&dados[cont].sexo!='f');
printf("Digite o cargo do funcionrio: ");
fflush(stdin);
gets(dados[cont].cargo);
do{
printf("Digite a idade do funcionrio: ");
scanf("%d",&dados[cont].idade);
}while(dados[cont].idade<16);
printf("Digite o CPF: ");
scanf("%d",&dados[cont].CPF);
printf("Digite o nascimento: ");
scanf("%d",&dados[cont].nascimento);
do{
printf("Digite o setor que o funcionrio trabalha: ");
scanf("%d",&dados[cont].setor);
}while(dados[cont].setor>99||dados[cont].setor<0);
do{
printf("Digite o salrio do funcionrio: ");
scanf("%d",&dados[cont].salario);
}while(dados[cont].salario<788);
}
for(int cont=0;cont<n;cont++){
fprintf(file,"Funcionrio %d:\n\n",cont+1);
fprintf(file,"Nome: %s\n",dados[cont].nome);
fprintf(file,"Sexo: %c\n",dados[cont].sexo);
fprintf(file,"Cargo: %s\n",dados[cont].cargo);
fprintf(file,"Idade: %d\n",dados[cont].idade);
fprintf(file,"CPF: %d\n",dados[cont].CPF);
fprintf(file,"Nascimento: %d\n",dados[cont].nascimento);
fprintf(file,"Setor: %d\n",dados[cont].setor);
fprintf(file,"Salrio: %d\n\n",dados[cont].salario);
}
getchar();
return 0;
}
| true |
734648543a2231de59c484f220565e1a8e97751c | C++ | vivekzhere/learning_cpp | /SAPS/Assorted/patrn1.cpp | UTF-8 | 238 | 2.75 | 3 | [] | no_license | #include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
void pat(int);
cout<<"Enter limit : ";
int n;
cin>>n;
pat(n);
getch();
}
void pat(int n)
{
for(int i=n;i>0;i--)
cout<<i<<"\t";
cout<<"\n";
if(n>1)
pat(n-1);
}
| true |
8e9e6514ca251bcecaf8b5ddd787e9295670e2c2 | C++ | likegreen/algocourse | /9/sieve.cc | UTF-8 | 493 | 3.21875 | 3 | [] | no_license | #include <iostream>
using namespace std;
const int LIM = 100001;
bool prime[LIM];
void sieve(int n) {
prime[1] = false;
for (int i = 2; i <= n; ++i) {
prime[i] = true;
}
for (int i = 2; i * i <= n; ++i) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i) {
prime[j] = false;
}
}
}
}
int main() {
int n = 100;
sieve(n);
for (int i = 1; i <= n; ++i) {
if (prime[i]) {
cout << i << ' ';
}
}
cout << endl;
return 0;
}
| true |
2ac539f86dde089c83bbcc331bf968b7eef76dc5 | C++ | Saurabh2711/Code | /spojISELECT.cpp | UTF-8 | 776 | 2.703125 | 3 | [] | no_license | #include<cstdio>
#include<iostream>
using namespace std;
int fun_take(bool tof,int energy,int i,bool f);
int a[1001],b[1001];
int n;
main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(int i=0;i<n;i++)
{
scanf("%d",&b[i]);
}
if(n==1)
printf("%d\n",a[0]);
else
printf("%d\n",max(fun_take(true,a[0],0,true),fun_take(false,-1*b[0],0,false)));
}
return 0;
}
int fun_take(bool tof,int i,bool f)
{
if(i+1==n)
return 0;
if(i+1==n-1)
{
if(f==true)
{
return -b[n-1];
}
}
if(tof==true)
{
return fun_take(false,i+1,f)-b[i+1];
}
else
{
return max(fun_take(true,i+1,f)+a[i+1],fun_take(false,i+1,f)-b[i+1]);
}
}
| true |
d0bb51b2162b133b267d2df4e0b63fccb34fa831 | C++ | esenti/labshooter | /src/Entities/Explosion.cpp | UTF-8 | 1,854 | 3 | 3 | [
"MIT"
] | permissive | //
// Explosion.cpp
// labshooter
//
// Created by Pawel Miniszewski on 08.12.2014.
// Copyright (c) 2014 Pawel Miniszewski. All rights reserved.
//
#include "Explosion.h"
#include "ResourceCache.h"
#include <time.h>
Explosion::Explosion()
{
}
Explosion::~Explosion()
{
}
void Explosion::Draw(sf::RenderWindow* window)
{
for(auto& p : particles)
{
if(p)
{
window->draw(p->sprite);
}
}
}
void Explosion::Update(float dt)
{
for(auto& p : particles)
{
p->sprite.move(p->velocity * dt);
p->elapsedTime += dt/1000.0f;
if(p->elapsedTime > p->timeToLive)
{
spawnedParticles--;
}
}
if(spawnedParticles <= 0)
{
Destroy();
}
}
std::string Explosion::GetTag()
{
return "Particles";
}
void Explosion::OnParticleDie(ExplosionParticle* particle)
{
delete particle;
}
void Explosion::Fire(sf::Vector2f& origin)
{
Origin = origin;
int particleNum = rand() & 60 + 35;
spawnedParticles = particleNum;
const sf::Texture* particleTexture = ResourceCache::LoadTexture("assets/particle.png");
for(int i=0;i<particleNum;i++)
{
float rand01Scale = FLOAT_RAND;
float scale = rand01Scale * 7.0f + 1;
ExplosionParticle* particle = new ExplosionParticle;
particle->sprite.setScale(scale, scale);
particle->sprite.setTexture(*particleTexture);
particle->sprite.setPosition(Origin.x, Origin.y);
sf::Transform tr;
tr.rotate(FLOAT_RAND * 359.0f);
float randomSpeed = FLOAT_RAND * 0.4;
particle->elapsedTime = 0;
particle->velocity = sf::Vector2f(tr.transformPoint(1, 0))*randomSpeed;
particle -> timeToLive = FLOAT_RAND * 2 + 2;
particles.push_back(particle);
}
}
| true |
161522d484a7f44fb9f9a9c66a6a5adcbae83a6b | C++ | bennybroseph/aie-FuzzyLogic | /BehaviouralAI/UtilityNPC.cpp | UTF-8 | 2,092 | 2.65625 | 3 | [] | no_license | #include "UtilityNPC.h"
namespace UtilitySystem
{
UtilityNPC::UtilityNPC(World *pWorld) : BaseNPC(pWorld)
{
m_waterValue.setNormalizationType(UtilityValue::INVERSE_LINEAR);
m_waterValue.setMinMaxValues(0, 15);
m_waterValue.setValue(getWaterValue());
auto pWaterScore = new UtilityScore();
pWaterScore->addUtilityValue(&m_waterValue, 2.f);
m_pUtilityScoreMap["collectWater"] = pWaterScore;
m_foodValue.setNormalizationType(UtilityValue::INVERSE_LINEAR);
m_foodValue.setMinMaxValues(0, 10);
m_foodValue.setValue(getFoodValue());
auto pFoodScore = new UtilityScore();
pFoodScore->addUtilityValue(&m_foodValue, 1.f);
m_pUtilityScoreMap["collectFood"] = pFoodScore;
m_restValue.setNormalizationType(UtilityValue::INVERSE_LINEAR);
m_restValue.setMinMaxValues(0, 5);
m_restValue.setValue(getRestValue());
auto pRestScore = new UtilityScore();
pRestScore->addUtilityValue(&m_restValue, 0.5f);
m_pUtilityScoreMap["aquireRest"] = pRestScore;
m_logValue.setNormalizationType(UtilityValue::INVERSE_LINEAR);
m_logValue.setMinMaxValues(0, 2);
m_logValue.setValue(getNumberOfLogs());
auto pLogScore = new UtilityScore();
pLogScore->addUtilityValue(&m_logValue, 0.5f);
m_pUtilityScoreMap["collectLog"] = pLogScore;
}
void UtilityNPC::selectAction(float a_fdeltaTime)
{
m_waterValue.setValue(getWaterValue());
m_foodValue.setValue(getFoodValue());
m_restValue.setValue(getRestValue());
m_logValue.setValue(getNumberOfLogs());
auto fBestScore = 0.f;
std::string strBestAction;
for (auto score : m_pUtilityScoreMap)
{
auto fThisScore = score.second->getUtilityScore();
if (fThisScore > fBestScore)
{
fBestScore = fThisScore;
strBestAction = score.first;
}
}
if (strBestAction == "collectWater")
collectWater(a_fdeltaTime);
else if (strBestAction == "collectFood")
collectFood(a_fdeltaTime);
else if (strBestAction == "aquireRest")
rest(a_fdeltaTime);
else if (strBestAction == "collectLog")
chopTree(a_fdeltaTime);
else
buildHouse(a_fdeltaTime);
}
UtilityNPC::~UtilityNPC() { }
}
| true |
4397bc1e3e0f43d3f0380202002912855cdc922e | C++ | BFavier/GameEngine | /src/GameEngine/graphics/RGB.cpp | UTF-8 | 1,012 | 3.546875 | 4 | [] | no_license | #include <GameEngine/graphics/RGB.hpp>
using namespace GameEngine;
RGB::RGB()
{
}
RGB::RGB(unsigned char r, unsigned char g, unsigned char b)
{
R = r;
G = g;
B = b;
}
RGB::RGB(const RGB& other)
{
*this = other;
}
RGB::RGB(const std::initializer_list<unsigned char>& init)
{
if (init.size() != 3)
{
THROW_ERROR("Expected 3 values to define an RGB color, but got "+std::to_string(init.size()))
}
std::vector<unsigned char> data = init;
R = data[0];
G = data[1];
B = data[2];
}
RGB::~RGB()
{
}
namespace GameEngine
{
std::ostream& operator<<(std::ostream& os, const RGB& rgb)
{
unsigned int r, g, b;
r = static_cast<unsigned int>(rgb.R);
g = static_cast<unsigned int>(rgb.G);
b = static_cast<unsigned int>(rgb.B);
os << "(R=" << r << ", G=" << g << ", B=" << b << ")";
return os;
}
}
RGB& RGB::operator=(const RGB& other)
{
R = other.R;
G = other.G;
B = other.B;
return *this;
}
| true |
5865c0cde1baee44cf29cb7062da3c0305f2923d | C++ | ramaym13/Arduino | /Modul 7/Kasus_Percobaan/Kasus_Percobaan.ino | UTF-8 | 4,251 | 2.5625 | 3 | [] | no_license | const int ledPin4 = 4;
const int ledPin3 = 3;
const int ledPin2 = 2;
const int pingPin = 13;
const int echoPin = 12;
const int buzzerPin = A4;
void setup(){
Serial.begin(9600);
Serial.print ("___________PBS 2019___________");
Serial.println ();
Serial.print ("________NIM:6706174021________");
Serial.println ();
Serial.print ("_____________MENU_____________"); Serial.println ();
Serial.print("| 1. Automatic Traffic Light |"); Serial.println ();
Serial.print ("| 2. Manual Traffic Light |"); Serial.println ();
Serial.print ("| 3. Sensor Ultrasonic |"); Serial.println ();
Serial.print ("| 4. Kembali ke menu |"); Serial.println ();
Serial.print ("______________________________"); Serial.println ();
pinMode(ledPin4, OUTPUT); // set this pin as output
pinMode(ledPin3, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(pingPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
}
long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2;
}
void loop(){
if(Serial.available() > 0){ //read the incoming
byte tombol = Serial.read() - 48;
if(tombol >= 1 &&tombol <= 4){
Serial.print("Input Pilihan: ");
Serial.println(tombol);
switch(tombol){
case 1:
Serial.print("| 1. Automatic Traffic Light |"); Serial.println ();
digitalWrite(ledPin4, HIGH);
delay(250);
digitalWrite(ledPin4, LOW);
delay(250);
digitalWrite(ledPin3, HIGH);
delay(250);
digitalWrite(ledPin3, LOW);
delay(250);
digitalWrite(ledPin2, HIGH);
delay(250);
digitalWrite(ledPin2, LOW);
delay(250);
digitalWrite(ledPin4, HIGH);
delay(250);
digitalWrite(ledPin4, LOW);
delay(250);
digitalWrite(ledPin3, HIGH);
delay(250);
digitalWrite(ledPin3, LOW);
delay(250);
digitalWrite(ledPin2, HIGH);
delay(250);
digitalWrite(ledPin2, LOW);
delay(250);
digitalWrite(ledPin4, HIGH);
delay(250);
digitalWrite(ledPin4, LOW);
delay(250);
digitalWrite(ledPin3, HIGH);
delay(250);
digitalWrite(ledPin3, LOW);
delay(250);
digitalWrite(ledPin2, HIGH);
delay(250);
digitalWrite(ledPin2, LOW);
delay(250);
break;
case 2:
break;
case 3:
long duration, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
duration = pulseIn(echoPin, HIGH);
cm = microsecondsToCentimeters(duration);
if(cm < 50){
Serial.print("Jarak :");
Serial.print("\t");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(500);
Serial.println("Buzzer Active!");
delay(1000);
digitalWrite(buzzerPin, HIGH);
delay(5000);
}else{
digitalWrite(buzzerPin, LOW);
Serial.print("Jarak :");
Serial.print("\t");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(500);
}
break;
case 4:
Serial.print ("___________PBS 2019___________");
Serial.println ();
Serial.print ("________NIM:6706174021________");
Serial.println ();
Serial.print ("_____________MENU_____________"); Serial.println ();
Serial.print("| 1. Automatic Traffic Light |"); Serial.println ();
Serial.print ("| 2. Manual Traffic Light |"); Serial.println ();
Serial.print ("| 3. Sensor Ultrasonic |"); Serial.println ();
Serial.print ("| 4. Kembali ke menu |"); Serial.println ();
Serial.print ("______________________________"); Serial.println ();
break;
}
}
}
}
| true |
012ac42b89d2e60259706ec6a576ba191a96bd8d | C++ | jtran93/AIAssignment1 | /Genetic.cpp | UTF-8 | 2,587 | 3.203125 | 3 | [] | no_license | #include "Genetic.h"
void Genetic::createInitialPopulation(std::vector< std::vector<int> > &chromosomePopulation)
{
int m = 20, n = 10;
chromosomePopulation.resize(m);
for(int i =0; i < m; i++)
{
chromosomePopulation[i].resize(n);
}
for( int i = 0; i < m; i++)
{
//std::cout<<i<<": ";
for( int j = 0; j < n; j++)
{
int dna = rand() % 2;
//std::cout<<dna;
chromosomePopulation[i][j] = dna;
}
//std::cout<<"\n";
}
}
/*
Find chromosome with all 1s
*/
bool Genetic::findChromosome(std::vector< std::vector<int> > chromosomePopulation)
{
int m = 20, n = 10;
int count = 0;
for (int i =0; i <m; i++)
{
count = 0;
for(int j = 0; j<n; j++)
{
if(chromosomePopulation[i][j] == 1)
{
count ++;
if(count==10 && j ==9)
{
return true;
}
}
else if(chromosomePopulation[i][j] != 0)
{
j = 20;
}
}
}
return false;
}
void Genetic::printPopulation(std::vector< std::vector<int> > &chromosomePopulation)
{
int m = 20, n = 10;
int fitnessV = 0;
for( int i = 0; i < m; i++)
{
fitnessV = 0;
std::cout<<i<<": ";
for (int j = 0; j <10; j++)
{
//std::cout<<chromosomePopulation[i][j];
if(chromosomePopulation[i][j] == 1)
fitnessV++;
}
std::cout<<" | Fitness Value: "<<fitnessV<<"\n";
}
}
void Genetic::printToFile(std::vector<std::vector<int> > &chromosomePopulation) {
int fitnessV = 0;
std::ofstream outfile;
outfile.open("1st_2nd_SecondToLast_Last_GenerationsPCO7_And_0.txt", std::ios_base::app);
outfile<<"==================================\n";
for( int i = 0; i < 20; i++)
{
fitnessV = 0;
outfile<<i<<": ";
for(int j = 0; j < 10; j++)
{
outfile << chromosomePopulation[i][j];
if(chromosomePopulation[i][j] == 1)
fitnessV++;
}
outfile <<" | Fitness Value: "<<fitnessV<< std::endl;
}
outfile.close() ;
}
void Genetic::printAvg(int numGenPerRun[], int pco)
{
std::ofstream outfile;
outfile.open("AverageNumberOfGenerations.txt", std::ios_base::app);
int sum = 0;
for(int i = 0; i<20; i++)
{
sum = sum + numGenPerRun[i];
}
outfile<<"Average number of generations at PCO " <<pco<<": "<<sum/20<<"\n";
outfile.close();
}
void Genetic::printNumGen(int numGenPerRun[], int rate)
{
std::ofstream outfile;
outfile.open("NumberGenerationsPerRun.txt", std::ios_base::app);
outfile<<"===================================\n";
outfile<<"PCO = "<<rate<<"\n";
outfile<<"===================================\n";
for(int i = 0; i < 20; i++)
{
outfile<<"Run #"<<i<<": "<<numGenPerRun[i]<<"\n";
}
outfile.close();
}
| true |
dbea4b2c41b16d3159ab92f3142aed76445404dc | C++ | kester-lin/acm_backup | /src/ZOJ/ZOJ1260 POJ1364 HDU1531 King.cpp | GB18030 | 2,184 | 2.59375 | 3 | [] | no_license | /*******************************************************************************
# Author : Neo Fung
# Email : neosfung@gmail.com
# Last modified: 2012-04-24 20:35
# Filename: ZOJ1260 POJ1364 HDU1531 King.cpp
# Description :
******************************************************************************/
#ifdef _MSC_VER
#define DEBUG
#define _CRT_SECURE_NO_DEPRECATE
#endif
#include <fstream>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
#include <limits.h>
#include <algorithm>
#include <math.h>
#include <numeric>
#include <functional>
#include <ctype.h>
#define MAX 110
using namespace std;
// ߣ
typedef struct Edge{
int u, v; // 㣬ص
int weight; // ߵȨֵ
}Edge;
Edge edge[MAX]; // ߵֵ
int dist[MAX]; // 㵽ԴС
int nodenum, edgenum, source; // Դ
// ɳڼ
void relax(int u, int v, int weight)
{
if(dist[v] < dist[u] + weight)
dist[v] = dist[u] + weight;//sourcevľsourceuvľ룬֮
}
bool Bellman_Ford()
{
for(int i=0; i<=nodenum; ++i)
for(int j=0; j<edgenum; ++j)
relax(edge[j].u, edge[j].v, edge[j].weight);
bool flag = 1;
// жǷи·,1Ϊڸ
for(int i=0; i<edgenum; ++i)
if(dist[edge[i].v] < dist[edge[i].u] + edge[i].weight)
{
flag = 0;
break;
}
return flag;
}
int main(void)
{
#ifdef DEBUG
freopen("../stdin.txt","r",stdin);
freopen("../stdout.txt","w",stdout);
#endif
// int n,ncase=1;
int u,v,d;
char str[5];
// scanf("%d",&ncase);
while(~scanf("%d",&nodenum) && nodenum)
{
scanf("%d",&edgenum);
for(int i=0;i<edgenum;++i)
{
scanf("%d %d %s %d",&u,&v,str,&d);
if(str[0]=='g')
{
edge[i].u=u;
edge[i].v=u+v+1;
edge[i].weight=d+1;
}
else
{
edge[i].u=u+v+1;
edge[i].v=u;
edge[i].weight=1-d;
}
}
for(int i=0;i<=nodenum;++i)
dist[i]=-100000000;
if(Bellman_Ford())
printf("lamentable kingdom\n");
else
printf("successful conspiracy\n");
}
return 0;
}
| true |
dd49c0d2dbfd4f752ae39dd3b7ca4425ca228b84 | C++ | cealvar/Lab-Work | /lab02/MysteryDuck.h | UTF-8 | 342 | 2.515625 | 3 | [] | no_license | #ifndef LAB02_MYSTERYDUCK_H_
#define LAB02_MYSTERYDUCK_H_
#include <string>
#include "Duck.h"
class MysteryDuck : public Duck {
private:
std::string sound;
std::string description;
public:
MysteryDuck(std::string inputDescription, std::string inputSound);
std::string getDescription();
void performQuack();
};
#endif
| true |
5a4f7bbf2958e31e18ea0e32fa7a4403109fddd6 | C++ | SwansonRoss/infix-evaluator | /proj5.h | UTF-8 | 2,114 | 2.890625 | 3 | [] | no_license | /* This file contains the user interface code for the Infix Evaluation Project
* Project 5 for CS 211 for Fall 2017
*
* Date: 10/21/17
*
* Author: Pat Troy
*
*/
/**************************************************************/
/* */
/* The Code below this point should NOT need to be modified */
/* for this program. If you feel you must modify the code */
/* below this point, you are probably trying to solve a */
/* more difficult problem that you are being asked to solve */
/* */
/**************************************************************/
#include <cstdio>
#include <cstring>
#include <cctype>
// Enumarated Type specifying all of the Tokens
enum TokenType{
ERROR, OPERATOR, VALUE, EOLN, QUIT, HELP, EOFILE
};
//Class for tokens
class Token
{
private:
TokenType type;
char op; // using '$' as undefined/error
int val; // using -999 as undefined/error
public:
Token();
Token (TokenType t);
void setToType(TokenType t);
void setToOperator(char c);
void setToValue(int v);
bool equalsType(TokenType t);
bool equalsOperator(char c);
char getOperator ();
int getValue();
};
//Class for token reader
class TokenReader
{
private:
char inputline[300]; // this assumes that all input lines are 300 characters or less in length
bool needline;
int pos;
public:
TokenReader();
void clearToEoln();
Token getNextToken();
};
//Class for values
class valStack
{
private:
int size;
int* vals;
public:
int stackTop;
valStack();
bool isEmpty();
void push(int val);
int topPop();
void reset();
};
class opStack
{
private:
int size;
char* vals;
public:
int stackTop;
opStack();
bool isEmpty();
void push(char val);
int topPop();
void reset();
};
//Outside of class function declarations
void processExpression (Token inputToken, TokenReader *tr);
bool dbgOn(int numArgs, char** args);
void printCommands();
| true |
16d5169f7b5abbc622c557282d0d3a0f4ec85dd9 | C++ | Jia-Joe/OJ_hihoCoder_LeetCode_Sword2Offer | /LeetCode28_83_101_141_142/L101.cpp | UTF-8 | 1,222 | 3.453125 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//Recursive
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
else
return ok(root->left,root->right);
}
bool ok(TreeNode* r1,TreeNode* r2){
if(r1==NULL&&r2==NULL) return true;
if(r1&&r2&&r1->val==r2->val)
return ok(r1->right,r2->left)&&ok(r1->left,r2->right);
else
return false;
}
};
//BFS
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
bool ret=true;
TreeNode* v[9000];
int fr=0,ta=2;
v[0]=root;v[1]=root;
while(fr!=ta){
TreeNode* now1=v[fr++];
TreeNode* now2=v[fr++];
if(!now1&&!now2)
continue;
if(now1==NULL||now2==NULL||now1->val!=now2->val)
return false;
v[ta++]=now1->left;
v[ta++]=now2->right;
v[ta++]=now1->right;
v[ta++]=now2->left;
}
return ret;
}
}; | true |
ad9732426672218ddf6d88796909be8b985e5e38 | C++ | CzechMateQQ/IntroToCpp | /DeepShallowCopyTutorial/DeepClass.h | UTF-8 | 269 | 2.90625 | 3 | [] | no_license | #pragma once
class DeepClass
{
public:
DeepClass();
DeepClass(int value);
DeepClass(const DeepClass& other);
~DeepClass();
DeepClass& operator = (const DeepClass& other);
void print();
void setValue(int value) { *m_data = value; }
private:
int* m_data;
};
| true |
28253471fb49e5d470bdd64e59177dc98befd102 | C++ | nohhyeonjin/BOJ | /그래프/2623.cpp | UTF-8 | 1,060 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int n,m;
int inDegree[1001];
vector<int> edges[1001];
void topologySort(){
queue<int> q;
vector<int> result;
for(int i=1;i<=n;i++) if(inDegree[i]==0) q.push(i);
while(!q.empty()){
int cur=q.front();
q.pop();
result.push_back(cur);
for(int i=0;i<edges[cur].size();i++){
inDegree[edges[cur][i]]--;
if(inDegree[edges[cur][i]]==0) q.push(edges[cur][i]);
}
}
if(result.size()!=n) printf("0");
else{
for(int i=0;i<result.size();i++) printf("%d\n",result[i]);
}
}
int main(){
scanf("%d %d",&n,&m);
for(int i=0;i<m;i++){
int cnt;
scanf("%d",&cnt);
vector<int> v;
for(int j=0;j<cnt;j++){
int num;
scanf("%d",&num);
v.push_back(num);
}
for(int a=0;a<cnt;a++){
for(int b=a+1;b<cnt;b++){
inDegree[v[b]]++;
edges[v[a]].push_back(v[b]);
}
}
}
topologySort();
} | true |
d02c1e864b634bd9d9729d7949508da5de339dad | C++ | py4/instagholam | /parser/node.h | UTF-8 | 748 | 2.796875 | 3 | [] | no_license | #ifndef NODE_H_
#define NODE_H_
#include <string>
#include <map>
#include <vector>
#include "parser.h"
using namespace std;
class Node
{
friend class XML;
friend class DB;
public:
Node() : depth(0) {}
Node(string, string = "", int = -1);
Node* add_node(Node*);
Node* add_node(string, string = "", int = -1);
string operator[](string);
vector<Node*>& get_children();
Node* get_parent();
void set_attribute(string,string);
void set_attributes(map<string,string>&);
void set_value(string);
string dump();
Node* get_child_node(string);
string get_value() { return value; }
void delete_children();
private:
string name;
map <string,string> attributes;
vector <Node*> children;
Node* parent;
string value;
int depth;
};
#endif
| true |
b26a5c835fb1080fd86c162f321ee633dd726f98 | C++ | wildstang/2018_robot_software | /libs/libwshardware/src/simulation/outputs/WsSimulatedOutput.cpp | UTF-8 | 1,030 | 2.8125 | 3 | [] | no_license | #include "WsSimulatedOutput.h"
#include "WsSimulation.h"
#ifndef __WSSIMULATEDOUTPUT_H__TEMPLATE__
WsSimulatedOutput::WsSimulatedOutput( std::string name )
: a_simulatedName( name )
, a_simulatorEnabled( true )
{
WsSimulation* p_sim = WsSimulation::getInstance();
p_sim->addSimulatedOutput( this );
}
WsSimulatedOutput::~WsSimulatedOutput( void )
{
}
#else
template< typename T >
WsSimulatedOutputTemplate< T >::WsSimulatedOutputTemplate( std::string name, T default_value )
: OutputTemplate< T >( name, default_value )
, WsSimulatedOutput( name )
{
}
template< typename T >
WsSimulatedOutputTemplate< T >::~WsSimulatedOutputTemplate( void )
{
}
template< typename T >
void WsSimulatedOutputTemplate< T >::sendDataToOutput( void )
{
std::string s = toString( this->getValue() );
if( a_simulatorEnabled )
printf( "@@ Output %s: %s\n", this->getName().c_str(), s.c_str() );
}
template< typename T >
int WsSimulatedOutputTemplate< T >::instantiate( void )
{
return 0;
}
#endif
| true |
1bc68490bac9781d04037ecd57ecaeaffe9e73f4 | C++ | cms-ttH/BoostedTTH | /BoostedAnalyzer/src/ResourceMonitor.cpp | UTF-8 | 2,721 | 2.578125 | 3 | [] | no_license | #include "BoostedTTH/BoostedAnalyzer/interface/ResourceMonitor.hpp"
ResourceMonitor::ResourceMonitor(){
PID=(long)getpid();
std::cout<<"this process pid" << PID<<std::endl;
procfilename="/proc/";
procfilename+=std::to_string(PID);
procfilename+="/status";
}
ResourceMonitor::~ResourceMonitor(){}
void ResourceMonitor::PrintMemoryUsage(){
std::ifstream procFile;
procFile.open(procfilename);
std::string buffer;
std::string sVMsize;
bool lastWasVMsize=false;
// std::cout<<procfilename<<std::endl;
while(!procFile.eof()){
procFile>>buffer;
// std::cout<<buffer<<std::endl;
// break;
if(lastWasVMsize){
sVMsize=buffer;
lastWasVMsize=false;
}
if(buffer.find("VmSize")!=std::string::npos){
lastWasVMsize=true;
}
else{
lastWasVMsize=false;
}
}
std::cout<<"Memory Usage"<<std::endl;
std::cout<<"VMsize "<<sVMsize<<std::endl;
procFile.close();
}
void ResourceMonitor::PrintSystemMemory(){
std::ifstream meminfoFile;
meminfoFile.open("/proc/meminfo");
std::string buffer;
std::string sFreeMem="0";
std::string sTotalMem="0";
std::string sBufferedMem="0";
std::string sCachedMem="0";
bool lastWasMEMTotal=false;
bool lastWasMEMFree=false;
bool lastWasMEMBuffered=false;
bool lastWasMEMCached=false;
// std::cout<<procfilename<<std::endl;
while(!meminfoFile.eof()){
meminfoFile>>buffer;
// std::cout<<buffer<<std::endl;
// break;
if(lastWasMEMFree){
sFreeMem=buffer;
lastWasMEMFree=false;
}
if(lastWasMEMTotal){
sTotalMem=buffer;
lastWasMEMTotal=false;
}
if(lastWasMEMBuffered){
sBufferedMem=buffer;
lastWasMEMBuffered=false;
}
if(lastWasMEMCached){
sCachedMem=buffer;
lastWasMEMCached=false;
}
if(buffer.find("MemTotal")!=std::string::npos){
lastWasMEMTotal=true;
}
else if(buffer.find("MemFree")!=std::string::npos){
lastWasMEMFree=true;
}
else if(buffer.find("Buffers")!=std::string::npos){
lastWasMEMCached=true;
}
else if(buffer.find("Cached")!=std::string::npos){
lastWasMEMBuffered=true;
}
else{
lastWasMEMFree=false;
lastWasMEMTotal=false;
lastWasMEMBuffered=false;
lastWasMEMCached=false;
}
}
long realFree = std::stol(sFreeMem) - std::stol(sBufferedMem) + std::stol(sCachedMem);
std::cout<<"Total system memory: "<<std::stoi(sTotalMem)/ 1000 << " MB" << std::endl;
std::cout<<"Free system memory: "<<realFree/1000 << " MB" << std::endl;
std::cout<<"Used system memory: "<<std::stoi(sTotalMem)/ 1000 - realFree/1000 << " MB" << std::endl;
meminfoFile.close();
}
| true |
88fcd020e0b1b07b94fd506b4774174f5b8911ca | C++ | Abhinav1997/josephus-algorithm | /josephus-cpp.cpp | UTF-8 | 1,789 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
std::vector<int> eliminate(std::vector<int> nPeople, int kill, int nSurvivor) {
unsigned int left = 0, num;
while(nPeople.size() > nSurvivor) {
num = kill - left;
if(num > nPeople.size()) {
while(num > nPeople.size()) {
num = num - nPeople.size();
}
}
while(num <= nPeople.size()) {
nPeople[num - 1] = 0;
num = num + kill;
}
for(int j = nPeople.size() - 1; j >= 0; j--) {
if (nPeople[j] == 0) {
left = nPeople.size() - (j + 1);
break;
}
}
nPeople.erase(std::remove(nPeople.begin(), nPeople.end(), 0), nPeople.end());
}
return nPeople;
}
int main() {
unsigned int people, killfreq, survivor;
std::cout << "Enter the initial number of people : ";
std::cin >> people;
std::cout << "Enter the person number to be killed : ";
std::cin >> killfreq;
std::cout << "Enter the number of survivor : ";
std::cin >> survivor;
if(survivor == 0) {
std::cout << "\nEveryone is dead";
return 0;
} else if(survivor < 0) {
survivor = 1;
}
std::vector<int> peopleList, survivorList;
peopleList.reserve(people);
for(unsigned int i = 1; i <= people; ++i) {
peopleList.push_back(i);
}
survivorList = eliminate(peopleList, killfreq, survivor);
if(survivor == 1) {
std::cout << "\nThe survivor is number " << survivorList[0];
} else {
std::cout << "\nThe survivors are numbers ";
for(unsigned int k = 0; k < survivorList.size(); ++k) {
std::cout << survivorList[k] << " ";
}
}
return 0;
}
| true |
19afbbe61b50507bdd2e9c532eb2a83f37daa7ac | C++ | ricardofdc/CAL_20-21 | /src/Utils/exceptions.h | UTF-8 | 367 | 2.578125 | 3 | [] | no_license | #ifndef EXCEPTIONS_H
#define EXCEPTIONS_H
// Generic Exception Class
class Exception {
public:
Exception() {}
};
// Exception Class that represents an invalid node ID
class GraphLoadFailed : public Exception {
public:
GraphLoadFailed(const std::string & fileName) : fileName(fileName) {}
std::string fileName;
};
#endif //EXCEPTIONS_H | true |
c37d330b65254ae1a5d977e2c15161492d41e289 | C++ | tekikesyo/PAT | /PAT乙级/1051. 复数乘法 (15).cpp | GB18030 | 1,185 | 3.625 | 4 | [] | no_license | /*
1051. ˷ (15)
д(A + Bi)ijʽAʵB鲿iλi2 = -1
Ҳдɼµָʽ(R*e(Pi))RǸģPǷǣiλȼʽ R(cos(P) + isin(P))
ָRPҪ˻ijʽ
ʽ
һθR1, P1, R2, P2ּԿոָ
ʽ
һаաA+Biĸʽ˻ijʽʵ鲿2λСע⣺BǸӦдɡA-|B|iʽ
2.3 3.5 5.2 0.4
-8.68-8.23i
*/
//A=(R1*R2)cos(P1+P2)B=(R1*R2)sin(P1+P2)
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
using namespace std;
int main(){
double r1, p1, r2, p2;
cin>>r1>>p1>>r2>>p2;
double a,b;
a = (r1*r2)*cos(p1+p2);
b = (r1*r2)*sin(p1+p2);
if(abs(a)<0.01)
a=0;
if(abs(b)<0.01)
b=0;
if(b<0)
printf("%.2lf-%.2lfi\n",a, abs(b));
else
printf("%.2lf+%.2lfi\n",a, b);
system("pause");
return 0;
} | true |
4b1b7b3aa825df4ff0f955d85911723ed967fb1b | C++ | ueane/my_code_repository | /my data structure/string/kmp.cpp | UTF-8 | 1,336 | 2.90625 | 3 | [] | no_license | /*************************************************************************
> File Name: kmp.cpp
> Author:
> Mail:
> Created Time: 二 8/15 08:05:58 2017
************************************************************************/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void get_next(char *t, int *next) {
next[0] = -1;
int j = 1, match = -1;
while(t[j]) {
while(match != -1 && t[match + 1] != t[j]) {
match = next[match];
}
if(t[match + 1] == t[j]){
next[j] = match + 1;
match++;
} else {
next[j] = match;
}
j++;
}
return 0;
}
void kmp_match(char *s, char *t, int *next) {
int i = 0, j = 0;
int times = 0;
while(s[i]) {
while(j != -1 && t[j + 1] != s[i]) {
times++;
j = next[j];
}
if(t[j + 1] == s[i]) {
times++;
j++;
}
i++;
if(t[j + 1] == '\0') {
printf("yes\n");
return;
}
}
printf("no\n");
}
int main() {
int next[100];
char s[] = "aecaeaecaed";
char t[] = "aecaed";
get_next(t, next);
for(int i = 0; t[i]; i++) {
printf("%d ", next[i]);
}
printf("\n");
kmp_match(s, t, next);
return 0;
}
| true |
97558fd3242c2c918962a5deb6bb84bbe6623f3e | C++ | zzhyzzh/MiniSQL | /minisql/Interpreter.h | GB18030 | 1,437 | 2.640625 | 3 | [] | no_license | #pragma once
#include<string>
using namespace std;
#include"stdafx.h"
//ָ룺
//create table 1 index 2
//drop table 3,drop index 4
//select * 5 select ԣΪԣ 6
//insert 7
//delete 8 where 9
//execfile 10
//quit 0
//error 99
class Interpret {
public:
friend class API;
int m_iOp; //ҪִеIJ
string m_strTablename; //
string m_strIndexname; //
string m_strFilename; //ļ,execfileõ
attribute *m_attr; //,create,selectõ
condition *m_condi; //where־delete,selectõ
insertVal *m_values; //ֵinsertõ
Interpret();
~Interpret() {};
void handle(string& sql);
protected:
void initAttr(attribute *p);
void initCond(condition *p);
void initValue(insertVal *p);
void initAll();
string intTo16(string s);
//Ϊintfloat͵ֵstringŵģҪһб
int isInt(string str);//int1
int isFloat(string str);//float1
int getWord(string& src, string& des);//srcַеõһʣոسTAB'''''*'''''ȡʧܷ0
int getStr(string& src, string& des);//ȡַոȣҪǻȡ֮
};
| true |
6d15d09edd35fb382b8cd42ace5a123879d07dac | C++ | nannz/cci-advanced-physical-computing | /week2-sensor/test-IRreceiveDemo/test-IRreceiveDemo.ino | UTF-8 | 1,957 | 2.578125 | 3 | [] | no_license | /*
IRremote: IRreceiveDemo - demonstrates receiving IR codes with IRrecv
An IR detector/demodulator must be connected to the input RECV_PIN.
Initially coded 2009 Ken Shirriff http://www.righto.com/
*/
#include <IRremote.h>
#if defined(ESP32)
int IR_RECEIVE_PIN = 15;
#elif defined(ARDUINO_AVR_PROMICRO)
int IR_RECEIVE_PIN = 10;
#else
int IR_RECEIVE_PIN = 11;
#endif
IRrecv IrReceiver(IR_RECEIVE_PIN);
// On the Zero and others we switch explicitly to SerialUSB
#if defined(ARDUINO_ARCH_SAMD)
#define Serial SerialUSB
#endif
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
//Serial.begin(115200);
Serial.begin(9600);
#if defined(__AVR_ATmega32U4__) || defined(SERIAL_USB) || defined(SERIAL_PORT_USBVIRTUAL)
delay(2000); // To be able to connect Serial monitor after reset and before first printout
#endif
// Just to know which program is running on my Arduino
Serial.println(F("START " __FILE__ " from " __DATE__));
// In case the interrupt driver crashes on setup, give a clue
// to the user what's going on.
Serial.println("Enabling IRin");
IrReceiver.enableIRIn(); // Start the receiver
IrReceiver.blink13(true); // Enable feedback LED
Serial.print(F("Ready to receive IR signals at pin "));
Serial.println(IR_RECEIVE_PIN);
}
void loop() {
// if (IrReceiver.decode()) {
// Serial.println(IrReceiver.decode());
// IrReceiver.printResultShort(&Serial);
// Serial.println();
// IrReceiver.resume(); // Receive the next value
// }
if (IrReceiver.decode()) //this checks to see if a code has been received
{
//Serial.println(IrReceiver.results.value);
if (IrReceiver.results.value == 0xFD30CF) //if the button press equals "0" on my remote
{
//do something useful here
Serial.println("you pressed something!");
} else {
IrReceiver.printResultShort(&Serial);
Serial.println();
}
IrReceiver.resume(); //receive the next value
}
delay(100);
}
| true |
0f48bccb9b48beb5b772cde95accc043c5c313bc | C++ | Forrest-Z/Carbrain | /res/example/ros_node_example1.cpp | UTF-8 | 1,148 | 3.046875 | 3 | [] | no_license | /**
* @file ros_node_example.cpp
*
* @brief This file is an small example of a ROS node with a publisher and subscriber.
*
* The chatter_subscriber subscribes to the topic of the chatter_publisher.
* Usually a node does not subscribe to its own topic, but to topics of other nodes.
*/
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
ros::Publisher chatter_publisher;
int count = 0;
void publishMessage(const ros::TimerEvent& event)
{
std_msgs::String msg;
std::stringstream ss;
ss << "hello world " << count++;
msg.data = ss.str();
ROS_INFO("%s", msg.data.c_str());
chatter_publisher.publish(msg);
}
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO("I heard: [%s]", msg->data.c_str());
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "ros_node_example1");
ros::NodeHandle node;
chatter_publisher = node.advertise<std_msgs::String>("chatter", 1000);
ros::Subscriber chatter_subscriber = node.subscribe("chatter", 1000, chatterCallback);
ros::Timer publish_timer = node.createTimer(ros::Duration(0.1), publishMessage);
ros::spin();
return 0;
}
| true |
c1cdfc9a687d4b9b9fee1a8fbac58def18f1269d | C++ | qxuan521/Coding | /YFileOS/YFileOS/y_tool.cpp | UTF-8 | 3,451 | 2.875 | 3 | [] | no_license | #include "y_tool.h"
#include <regex>
#include<sstream>
namespace YPathRegex
{
std::regex rRealPathRegex("^[@][. ]*");
};
std::vector<std::string> splitStrByCharacter(const std::string& srcStr, char spliter)
{
size_t startIndex = 0;
std::vector<std::string> resultArr;
for (size_t index = 0; index < srcStr.size(); ++index)
{
if (spliter == srcStr[index])
{
resultArr.push_back(srcStr.substr(startIndex, index - startIndex));
if (srcStr.size() > index + 1)
startIndex = index + 1;
}
}
resultArr.push_back(srcStr.substr(startIndex, srcStr.size() - startIndex));
return resultArr;
}
std::string getParentPath(const std::string & szPath)
{
size_t ParentNameEnd = szPath.find_last_of("/");
if (std::string::npos == ParentNameEnd)
return std::string("");
std::string DstParent = szPath.substr(0, ParentNameEnd);
return DstParent;
}
std::string getNameFromFullPath(const std::string & szPath)
{
size_t nNameIndex = szPath.find_last_of('/');
if (std::string::npos == nNameIndex)
return szPath;
else
return szPath.substr(nNameIndex + 1, szPath.size() - nNameIndex - 1);
}
std::string getPathFromRealPath(const std::string & szPath)
{
if (szPath.empty() || '@' != szPath[0])
{
return std::string();
}
return szPath.substr(1, szPath.size() - 1);
}
bool isRealPath(const std::string & szPath)
{
return !szPath.empty() && '@' == szPath[0];
}
bool isHaveWildCard(const std::string & szPath)
{
return std::string::npos != szPath.find('?') || std::string::npos != szPath.find('*');
}
std::regex makeRegexByPath(const std::string & szPath)
{
std::string szRegexStr;
for (size_t index = 0; index < szPath.size(); ++index)
{
if ('*' == szPath[index])
{
szRegexStr.append("[\\w_\\.]*");
}
else if ('?' == szPath[index])
{
szRegexStr.append("[\\w_\\.]?");
}
else
{
szRegexStr += szPath[index];
}
}
return std::regex(szRegexStr);
}
std::regex makeRepaceRegexByPath(const std::string& szPath, std::string& szRepaceStr)
{
std::string szRegexStr;
std::string szIndex;
std::stringstream rStringStream;
for (size_t index = 0; index < szPath.size(); ++index)
{
std::string szIndexBuffer;
if ('*' == szPath[index])
{
szRegexStr.append("([\\w_\\.]*)");
rStringStream << (index + 1);
szRepaceStr.append("$");
rStringStream >> szIndex;
szRepaceStr.append(szIndex);
}
else if ('?' == szPath[index])
{
szRegexStr.append("([\\w_\\.]?)");
rStringStream << (index + 1);
szRepaceStr.append("$");
rStringStream >> szIndex;
szRepaceStr.append(szIndex);
}
else
{
if (index == 0)
{
szRegexStr.append("(^[\\w_\\.])");
}
else if (index == szPath.size() - 1)
{
szRegexStr.append("([\\w_\\.]$)");
}
else
{
szRegexStr.append("([\\w_\\.])");
}
szRepaceStr += szPath[index];
}
}
return std::regex(szRegexStr);
}
std::string makeStringFromBuffer(std::vector<char>& rBuffer, int size)
{
std::string szPath;
// int asdasd = 0;
// if (rBuffer.size() > size)
// {
// rBuffer[size] = '\0';
// }
for (size_t index = 0 , asdasd = index;(int)index < size && index < rBuffer.size();++index)
{
szPath += rBuffer[index];
}
return szPath;
}
bool equalOrLowerWithCurPath(const std::string & szCurPath, const std::string & szPath)
{
std::string szTempPath = szCurPath;
while (!szTempPath.empty())
{
if (szPath == szTempPath)
{
return true;
}
szTempPath = getParentPath(szTempPath);
}
return false;
}
| true |
5450153803811b81e3821fe8f5ab7fbefdf913cd | C++ | conchino/C-_study | /__编程练习__/运算符重载/类-运算符重载/main.cpp | GB18030 | 2,157 | 4 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
/*
// Ա
[] operator[]([]& );
// dzԱ
[] operator[] ([]& [], []& []);
*/
class Person{
int aa;
int bb;
public:
Person();
Person(int aa,int bb);
Person(int aa);
int getA() const{
return aa;
}
int getB() const{
return bb;
}
void setA(int aa){
this->aa = aa;
}
void setB(int bb){
this->bb = bb;
}
void show();
string toString();
// Ա Ӻ(+)
Person operator+(const Person& psn);
};
Person :: Person(int aa,int bb){
this->aa = aa;
this->bb = bb;
}
Person :: Person(int aa){
this->aa = aa;
this->bb = 0;
}
Person :: Person(){}
void Person :: show(){
cout << "aa: " << this->aa << " | bb: " << this->bb << endl;
}
string Person :: toString(){
return "aa: "+to_string(this->aa)+" | bb: "+to_string(this->bb);
}
// غ Ӻ(+)
Person Person :: operator+(const Person& psn){
Person person;
person.aa = this->aa + psn.aa;
person.bb = this->bb + psn.bb;
return person;
}
// dzԱ (-)
Person operator-(const Person& p1, const Person& p2){
Person p3;
p3.setA(p1.getA()-p2.getA());
p3.setB(p1.getB()-p2.getB());
return p3;
}
// أԷ
Person operator+(const Person &person, int val){
Person psn;
psn.setA(person.getA()+val);
psn.setB(person.getB()+val);
return psn;
}
int main()
{
Person p1(1, 2);
cout << "p1: ";
p1.show();
Person p2(4, 5);
cout << "p2: ";
p2.show();
cout << "\np3 = p1 + p2 ... " << endl;
// Person p3 = p1 + p2;
cout << "p3: " << (p1+p2).toString() << endl;
// p3.show();
cout << "\np4 = p2 + p1 ... " << endl;
cout << "p4: " << (p2-p1).toString() << endl;
cout << "p2 + 2 : " << (p2+2).toString() << endl;
return 0;
}
| true |