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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
5bfe7b1166980361b0f21624e195742d117e4e5b | C++ | avencat/cpp_r-type | /client/inc/AComponent.hpp | ISO-8859-1 | 675 | 2.90625 | 3 | [] | no_license | #ifndef ACOMPONENT_HPP_
# define ACOMPONENT_HPP_
# include "Sprite.hpp"
class AComponent
{
public:
AComponent();
AComponent(int);
virtual ~AComponent();
void setId(const int &);
void setPosition(int, int);
void setSprite(const Sprite::TypeSpriteEnum &, int);
const int &getId() const;
const Sprite &getCSprite() const;
// getPos ne peut tre marqu const car elle modifie pos avant de return.
const sf::Vector2i &getPos();
const bool &getVisible() const;
void setVisible(const bool &);
private:
int id;
Sprite sprite;
Sprite::TypeSpriteEnum type;
sf::Vector2i pos;
bool visible;
};
#endif /* !ACOMPONENT_HPP_ */
| true |
3ff61be118582d31328836f79b7561cdeec6da60 | C++ | 8Observer8/PlotAndTable | /PlotWindow.cpp | UTF-8 | 1,118 | 2.515625 | 3 | [] | no_license |
#include <QVector>
#include <QSqlRecord>
#include "PlotWindow.h"
#include "ui_PlotWindow.h"
PlotWindow::PlotWindow(QWidget *parent) :
QDialog(parent),
ui(new Ui::PlotWindow)
{
ui->setupUi(this);
}
PlotWindow::~PlotWindow()
{
delete ui;
}
void PlotWindow::slotUpdatePlot(const QSqlTableModel &model)
{
int rowCount = model.rowCount();
QVector<double> x( rowCount ), y( rowCount ); // initialize with entries 0..100
QSqlRecord record;
for ( int row = 0; row < rowCount; ++row ) {
record = model.record( row );
x[row] = record.fieldName( 0 ).toDouble();
y[row] = record.fieldName( 1 ).toDouble();
}
// create graph and assign data to it:
ui->plotWidget->addGraph();
ui->plotWidget->graph( 0 )->setData( x, y );
// give the axes some labels:
ui->plotWidget->xAxis->setLabel( "x" );
ui->plotWidget->yAxis->setLabel( "y" );
// set axes ranges, so we see all data:
ui->plotWidget->xAxis->setRange( -1, 1 );
ui->plotWidget->yAxis->setRange( 0, 1 );
ui->plotWidget->update();
}
| true |
5a2736189bba04c285cc737ee89649544d408fa7 | C++ | bss9395/bss9395.github.io | /_en/Computer/Data_Structure/Node/BalanceNode.cpp | UTF-8 | 1,679 | 3.203125 | 3 | [] | no_license | /* BalanceNode.cpp
Author: BSS9395
Update: 2018-07-02T19:16:00 +08
*/
#ifndef BalanceNode_h
#define BalanceNode_h
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
using std::ostream;
#include <string>
using std::string;
template <typename T>
class BalanceNode {
friend auto operator<<(ostream &os, const BalanceNode &node) -> ostream & {
os << node._element;
return os;
}
friend auto operator<(const BalanceNode &lhs, const BalanceNode &rhs) -> bool {
return (lhs._element < rhs._element);
}
friend auto operator==(const BalanceNode &lhs, const BalanceNode &rhs) -> bool {
return (lhs._element == rhs._element);
}
friend auto operator!=(const BalanceNode &lhs, const BalanceNode &rhs) -> bool {
return !operator==(lhs, rhs);
}
friend auto operator>(const BalanceNode &lhs, const BalanceNode &rhs) -> bool {
return (lhs._element > rhs._element);
}
public:
BalanceNode(const T &element = T(), long balance = 0, BalanceNode *left = nullptr, BalanceNode *right = nullptr)
: _element(element), _balance(balance), _left(left), _right(right) {
}
BalanceNode(const BalanceNode &node)
: _element(node._element), _balance(node._balance), _left(node._left), _right(node._right) {
}
auto operator=(const BalanceNode &node) -> bool {
if (this != &node) {
_clear();
_element = node._element;
_balance = node._balance;
_left = node._left;
_right = node._right;
}
return *this;
}
~BalanceNode() {
_clear();
}
protected:
auto _clear() -> void {
_element.~T();
}
public:
T _element;
long _balance;
BalanceNode *_left;
BalanceNode *_right;
};
template class BalanceNode<string>;
#endif // BalanceNode_h
| true |
7f2887ddf23afff19b2f53834c15d0ab26ce4b4f | C++ | eassuncao/my-first-calculator | /Calculator/main.cpp | UTF-8 | 1,613 | 4.53125 | 5 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
string sign;
double num1;
double num2;
cout<<"Welcome to my c++ simple calculator!"<<endl;
cout<<"This calculator supports two numbers at a time and four operators."<<endl<<endl;
cout<<"Please type the first number in your calculation, then hit Enter:"<<endl;
cin>>num1;
cout<<"Now enter the operator:"<<endl<<"+ for addition"<<endl<<"- for subtraction"<<endl<<"* for multiplication"<<endl<<"/ for division"<<endl<<
"^ for power"<<endl<<"v for root"<<endl<<"then hit Enter:"<<endl;
cin>>sign;
cout<<"Please type the number that will be used by the operator, then hit Enter:"<<endl;
cin>>num2;
cout<<endl;
if(sign == "+"){
cout<<"Your result is: "<<num1+num2;
}
else if(sign == "-"){
cout<<"Your result is: "<<num1-num2;
}
else if(sign == "*"){
cout<<"Your result is: "<<num1*num2;
}
else if(sign == "/"){
cout<<"Your result is: "<<num1/num2;
}
else if(sign == "^"){
double resultPower = 1;
for(double exponent = num2; exponent != 0; exponent --){
resultPower *= num1;
}
cout<< "Your result is: " << resultPower << endl;
}
else if(sign == "v"){
double resultRoot = 1;
for(double exponent = num2; exponent != 0; exponent --){
resultRoot /= num1;
}
cout<< "Your result is: " << resultRoot << endl;
}
else {
cout<<"The operator you entered is either not valid or not supported."<<endl;
}
return 0;
}
| true |
85293526751cc4d6aed947299d576b4b37b13d7e | C++ | royalneverwin/Codes-in-Sophormore | /模拟机考题/现代艺术.cpp | UTF-8 | 2,686 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
/*普通方法:模拟画图——result:超时
struct Paint{
int color;//最终颜色
int laser;//层数
};
struct Paint p[100001];//记录图画的颜色和出度
int N[100001];//记录图画
int color_start[100001] = {0};//记录该颜色的开始
int color_end[100001] = {0};//记录该颜色的结束
int main(){
ios::sync_with_stdio(false); cin.tie(0);//加速C++输入输出流
int n;
cin >> n;
for(int i = 1; i <= n; i++){
cin >> N[i];
color_end[N[i]] = i;
if(color_start[N[i]] == 0){
color_start[N[i]] = i;
}
p[i].color = 0;
p[i].laser = 0;
}
for(int i = 1; i <= n; i++){
for(int j = color_start[i]; j <= color_end[i]; j++){
p[j].color = i;
p[j].laser++;
}
}
int maxLaser = 0;
for(int i = 1; i <= n; i++){
if(p[i].color != N[i]){
cout << -1;
return 0;
}
maxLaser = max(p[i].laser, maxLaser);
}
cout << maxLaser << endl;
return 0;
}
*/
/*改进:利用栈*/
int N[100001];//记录图画
int color_start[100001] = {0};//记录该颜色的开始
int color_end[100001] = {0};//记录该颜色的结束
int start_color[100001] = {0};//该点是否是某个颜色的开始点,如果是是哪个颜色
int end_color[100001] = {0};//该点是否是某个颜色的结束点,如果是是哪个颜色
stack<int> s;
int main(){
ios::sync_with_stdio(false); cin.tie(0);//加速C++输入输出流
int n;
size_t maxLaser = 0;
cin >> n;
for(int i = 1; i <= n; i++){//i代表点
cin >> N[i];
color_end[N[i]] = i;
if(color_start[N[i]] == 0){
color_start[N[i]] = i;
}
}
for(int i = 1; i <= n; i++){//i代表颜色
if(color_start[i] != 0){
start_color[color_start[i]] = i;
}
if(color_end[i] != 0){
end_color[color_end[i]] = i;
}
}
for(int i = 1; i <= n; i++){//i代表点
if(start_color[i] != 0){//遇到了某个颜色的开头,该颜色入栈
s.push(start_color[i]);
maxLaser = max(maxLaser, s.size());
}
if(!s.empty() && s.top() != N[i]){//注意开头可能有未涂色,所以要先判断栈是否为空,否则N[i]的颜色应该始终与栈顶颜色相同
cout << -1 << endl;
return 0;
}
if(end_color[i] != 0){//遇到了某个颜色的结尾,栈顶颜色出栈
s.pop();
}
}
cout << maxLaser << endl;
return 0;
} | true |
8dcb2a4cd1bbe3b3fc345fdfb1aa537162c7d70e | C++ | SimKyuSung/Algorithm | /BeakJoon C++ Algorithm/1012Farming.cpp | UHC | 1,236 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <utility>
#include <algorithm>
#include <memory.h>
using namespace std;
int field[50][50];
int M, N, K;
int counter;
int moveX[4] = { 1, -1, 0, 0};
int moveY[4] = { 0, 0, 1, -1};
queue< pair< int, int> > q;
void bugMove(int, int);
bool range_error1(int, int);
int main()
{
int T;
cin >> T;
while (T > 0) {
// Է
T--;
cin >> M >> N >> K;
memset(field, 0, sizeof(field));
while (K > 0) {
K--;
int X, Y;
cin >> X >> Y;
field[Y][X] = 1;
}
// !
counter = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (field[i][j] == 0)
continue;
q.push(make_pair(j, i));
field[i][j] = 0;
while (!q.empty()) {
bugMove(q.front().first, q.front().second);
q.pop();
}
counter++;
}
}
cout << counter << endl;
}
}
void bugMove(int x, int y) {
for (int i = 0; i < 4; i++) {
// ƿ 迭 ˻ && ij ˻.
int X = x + moveX[i];
int Y = y + moveY[i];
if (range_error1(X, Y)) {
field[Y][X] = 0;
q.push(make_pair(X, Y));
}
}
}
bool range_error1(int x, int y) {
return ((x < M) &&
(x >= 0) &&
(y < N) &&
(y >= 0) &&
(field[y][x] != 0));
} | true |
c5e395295bdbb3eba26677da9914439609d6d043 | C++ | dotrado/TDEngine2 | /TDEngine2/source/core/memory/CPoolAllocator.cpp | UTF-8 | 3,675 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | #include "./../../../include/core/memory/CPoolAllocator.h"
namespace TDEngine2
{
CPoolAllocator::CPoolAllocator():
CBaseAllocator(), mObjectSize(0), mObjectAlignment(0),
mppNextFreeBlock(nullptr)
{
}
E_RESULT_CODE CPoolAllocator::Init(U32 objectSize, U32 objectAlignment, U32 totalMemorySize, U8* pMemoryBlock)
{
E_RESULT_CODE result = CBaseAllocator::Init(totalMemorySize, pMemoryBlock);
if (result != RC_OK)
{
return result;
}
mObjectSize = objectSize;
mObjectAlignment = objectAlignment;
return Clear();
}
void* CPoolAllocator::Allocate(U32 size, U8 alignment)
{
if (!mppNextFreeBlock)
{
return nullptr;
}
void* pObjectPtr = mppNextFreeBlock;
mppNextFreeBlock = reinterpret_cast<void**>(*mppNextFreeBlock);
mUsedMemorySize += mObjectSize;
++mAllocationsCount;
return pObjectPtr;
}
E_RESULT_CODE CPoolAllocator::Deallocate(void* pObjectPtr)
{
if (!pObjectPtr)
{
return RC_INVALID_ARGS;
}
*(reinterpret_cast<void**>(pObjectPtr)) = mppNextFreeBlock;
mppNextFreeBlock = reinterpret_cast<void**>(pObjectPtr);
mUsedMemorySize -= mObjectSize;
--mAllocationsCount;
return RC_OK;
}
E_RESULT_CODE CPoolAllocator::Clear()
{
U8 padding = CBaseAllocator::GetPadding(mpMemoryBlock, mObjectAlignment);
mppNextFreeBlock = reinterpret_cast<void**>(reinterpret_cast<U32Ptr>(mpMemoryBlock) + static_cast<U32Ptr>(mObjectAlignment));
U32 numOfObjects = (mTotalMemorySize - padding) / mObjectSize;
void** pCurrBlock = mppNextFreeBlock;
for (U32 i = 0; i < numOfObjects - 1; ++i)
{
*pCurrBlock = reinterpret_cast<void*>(reinterpret_cast<U32Ptr>(pCurrBlock) + mObjectSize);
pCurrBlock = reinterpret_cast<void**>(*pCurrBlock);
}
return RC_OK;
}
TDE2_API IAllocator* CreatePoolAllocator(U32 objectSize, U32 objectAlignment, U32 totalMemorySize, U8* pMemoryBlock, E_RESULT_CODE& result)
{
CPoolAllocator* pPoolAllocatorInstance = new (std::nothrow) CPoolAllocator();
if (!pPoolAllocatorInstance)
{
result = RC_OUT_OF_MEMORY;
return nullptr;
}
result = pPoolAllocatorInstance->Init(objectSize, objectAlignment, totalMemorySize, pMemoryBlock);
if (result != RC_OK)
{
delete pPoolAllocatorInstance;
pPoolAllocatorInstance = nullptr;
}
return dynamic_cast<IAllocator*>(pPoolAllocatorInstance);
}
CPoolAllocatorFactory::CPoolAllocatorFactory() :
CBaseAllocatorFactory()
{
}
TResult<IAllocator*> CPoolAllocatorFactory::Create(const TBaseAllocatorParams* pParams) const
{
const TPoolAllocatorParams* pPoolParams = dynamic_cast<const TPoolAllocatorParams*>(pParams);
if (!pPoolParams)
{
return TErrorValue<E_RESULT_CODE>(RC_INVALID_ARGS);
}
E_RESULT_CODE result = RC_OK;
IAllocator* pAllocator = CreatePoolAllocator(pPoolParams->mPerObjectSize, pPoolParams->mObjectAlignment,
pPoolParams->mMemoryBlockSize, pPoolParams->mpMemoryBlock, result);
if (result != RC_OK)
{
return TErrorValue<E_RESULT_CODE>(result);
}
return TOkValue<IAllocator*>(pAllocator);
}
TypeId CPoolAllocatorFactory::GetAllocatorType() const
{
return CPoolAllocator::GetTypeId();
}
TDE2_API IAllocatorFactory* CreatePoolAllocatorFactory(E_RESULT_CODE& result)
{
CPoolAllocatorFactory* pPoolAllocatorFactoryInstance = new (std::nothrow) CPoolAllocatorFactory();
if (!pPoolAllocatorFactoryInstance)
{
result = RC_OUT_OF_MEMORY;
return nullptr;
}
result = pPoolAllocatorFactoryInstance->Init();
if (result != RC_OK)
{
delete pPoolAllocatorFactoryInstance;
pPoolAllocatorFactoryInstance = nullptr;
}
return dynamic_cast<IAllocatorFactory*>(pPoolAllocatorFactoryInstance);
}
} | true |
b2da69808d7a99e08649885536392aa0f1b0ea53 | C++ | IanFinlayson/tetra | /source/ide/console.cpp | UTF-8 | 3,360 | 2.921875 | 3 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | /* console.cpp
* A text editor component that is designed specifically for Tetra code
* */
#include <QtWidgets>
#include "console.h"
#include "settingsmanager.h"
#include "ui_mainwindow.h"
Console::Console(MainWindow* parent)
: QPlainTextEdit(parent) {
setContentsMargins(50, 50, 50, 50);
ensureCursorVisible();
setCenterOnScroll(false);
setReadOnly(true);
this->parent = parent;
/* update all settings for the console */
updateSettings();
}
void Console::setUpConnections(MainWindow* parent) {
this->parent = parent;
/* set it up so that console can pass input to main window */
connect(this, SIGNAL(enterPressed(QString)), parent,
SLOT(receiveInput(QString)));
}
void Console::updateSettings() {
/* set colors */
setStyleSheet(
"QPlainTextEdit {"
"background-color: " +
SettingsManager::termBackground().name() +
";"
"color: " +
SettingsManager::termForeground().name() +
";"
"}");
/* set font */
QFont font = SettingsManager::font();
setFont(font);
/* set the cursor to be a block */
QFontMetrics fm(font);
setCursorWidth(fm.averageCharWidth());
}
/* remember the position in the console so that we can't change it */
void Console::beginInput() {
inputStart = textCursor().positionInBlock();
}
/* when keys are pressed in the widget */
void Console::keyPressEvent(QKeyEvent* e) {
/* if we push left or backspace, we can only handle it if there is room */
if (e->key() == Qt::Key_Left || e->key() == Qt::Key_Backspace) {
if (textCursor().positionInBlock() > inputStart) {
QPlainTextEdit::keyPressEvent(e);
}
}
/* if we push home, then we go to the original start */
else if (e->key() == Qt::Key_Home) {
QTextCursor cursor = textCursor();
cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor, 1);
cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor,
inputStart);
setTextCursor(cursor);
}
/* enter returns the input back to the main window which passes to the program
*/
else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
/* get the last line of text */
QString text = textCursor().block().text();
/* remove what was there at start */
text.remove(0, inputStart);
/* handle the enter so the line break is put in */
QPlainTextEdit::keyPressEvent(e);
/* return this back to the program */
emit enterPressed(text);
}
/* we ignore all of these keys altogether */
else if (e->key() == Qt::Key_Up || e->key() == Qt::Key_Down ||
e->key() == Qt::Key_Insert || e->key() == Qt::Key_PageUp ||
e->key() == Qt::Key_PageDown) {
}
/* else, just pass it */
else {
QPlainTextEdit::keyPressEvent(e);
}
}
/* we must ignore these so the user does not click to a new position */
void Console::mousePressEvent(QMouseEvent*) {
}
void Console::resizeEvent(QResizeEvent* e) {
QPlainTextEdit::resizeEvent(e);
}
void Console::write(QString text) {
QTextCursor* cursor = new QTextCursor(document());
cursor->movePosition(QTextCursor::End);
cursor->insertText(text);
ensureCursorVisible();
}
| true |
f1918fdcc57a7e371f230bd60889de239558dbbb | C++ | dianaachim/Object-Oriented-Programming | /lab14/DynamicVector.h | UTF-8 | 2,712 | 3.5625 | 4 | [] | no_license | #pragma once
#include "Comparator.h"
template <typename T>
class DynamicVector
{
private:
T * elems;
int size;
int capacity;
public:
DynamicVector<T>(int capacity = 10);
//copy constructor for a DynamicVector
DynamicVector<T>(const DynamicVector& v);
~DynamicVector<T>();
//overload the operator -
DynamicVector<T>& operator-(const T& e);
//adds an element to the current DynamicVector
void add(const T& e);
//removes and element from the current DynamicVector
void remove(const T& e);
int getSize() const;
T* getAllElems() const;
int getCapacity() const;
void sort(Comparator<T>& cmp);
private:
//Resizes the current DynamicVector, multiplying its capacity by a given factor (real number).
void resize(double factor = 2);
};
template <typename T>
DynamicVector<T>::DynamicVector(int capacity)
{
this->size = 0;
this->capacity = capacity;
this->elems = new T[capacity];
}
template <typename T>
DynamicVector<T>::DynamicVector(const DynamicVector<T>& v)
{
this->size = v.size;
this->capacity = v.capacity;
this->elems = new T[this->capacity];
for (int i = 0; i < this->size; i++)
this->elems[i] = v.elems[i];
}
template <typename T>
DynamicVector<T>::~DynamicVector()
{
delete[] this->elems;
}
template <typename T>
void DynamicVector<T>::add(const T& e)
{
if (this->size == this->capacity)
this->resize();
this->elems[this->size] = e;
this->size++;
}
template <typename T>
void DynamicVector<T>::remove(const T & e)
{
int index;
for (int i = 0; i < this->getSize(); i++)
if (this->elems[i] == e)
index = i;
for (int i = index; i < (this->getSize() - 1); i++)
this->elems[i] = this->elems[i + 1];
this->size--;
}
template <typename T>
DynamicVector<T> &DynamicVector<T>::operator-(const T& e)
{
this->remove(e);
return *this;
}
template <typename T>
void DynamicVector<T>::resize(double factor)
{
this->capacity *= static_cast<int>(factor);
T* els = new T[this->capacity];
for (int i = 0; i < this->size; i++)
els[i] = this->elems[i];
delete[] this->elems;
this->elems = els;
}
template <typename T>
T* DynamicVector<T>::getAllElems() const
{
return this->elems;
}
template <typename T>
int DynamicVector<T>::getSize() const
{
return this->size;
}
template <typename T>
int DynamicVector<T>::getCapacity() const
{
return this->capacity;
}
template <typename T>
void DynamicVector<T>::sort(Comparator<T>& cmp)
{
int i, j;
Gowns aux;
//CompareDescendingByPrice <Gowns> cmp;
for (i = 0; i < this->getSize()-1; i++)
{
for (j = i+1; j < this->getSize(); j++)
{
if (cmp.compare(this->elems[i], this->elems[j]) == false)
{
aux = this->elems[i];
this->elems[i] = this->elems[j];
this->elems[j] = aux;
}
}
}
} | true |
d70d3e276bd345b2fee0abf02412169a7856e674 | C++ | tonyhan18/MicroProcessor2016_Arduino | /Practice/TimeInterruptPractice/TimeInterruptPractice_DotMatrix.ino | UTF-8 | 1,251 | 3.0625 | 3 | [] | no_license | #include <TimerOne.h>
//ROWS : R1 ~ R8 <-> PIN 36 ~ 43
//COLS : C1 ~ C8 <-> PIN 46 ~ 49,9,8
// 윗방향 화살표를 올라가도록 하는 프로그램
int row_pin[] = {36, 37, 38, 39, 40, 41, 42, 43};
int col_pin[] = {46, 47, 48, 49, 6, 7, 9, 8};
int led[][8] = {{1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 0, 0, 1, 1, 1},
{1, 1, 0, 0, 0, 0, 1, 1},
{1, 0, 0, 1, 1, 0, 0, 1},
{0, 0, 1, 1, 1, 1, 0, 0},
{0, 1, 1, 1, 1, 1, 1, 0}
};
int temp[8] = {0, 0, 0, 0, 0, 0, 0, 0};
void setup() {
int i;
for (i = 0; i < 8; i++) pinMode(row_pin[i], OUTPUT);
for (i = 0; i < 8; i++) pinMode(col_pin[i], OUTPUT);
for (i = 0; i < 8; i++) digitalWrite(row_pin[i], LOW);
for (i = 0; i < 8; i++) digitalWrite(col_pin[i], HIGH);
Timer1.initialize(300000);
Timer1.attachInterrupt(up);
}
void loop() {
int i, j;
for (i = 0; i < 8; i++) {
digitalWrite(row_pin[i], HIGH);
for (j = 0; j < 8; j++) {
digitalWrite(col_pin[j], led[i][j]);
}
delay(2);
digitalWrite(row_pin[i], LOW);
}
}
void up() {
for (int i = 1; i < 8; i++) {
for (int j = 0; j < 8; j++) {
temp[j] = led[i - 1][j];
led[i - 1][j] = led[i][j];
led[i][j] = temp[j];
}
}
}
| true |
10f7c0a115ab55e74ad8b3d72003b1c82fa5cd02 | C++ | zbs/Pedestrian-Detection | /Feature.cpp | UTF-8 | 11,151 | 2.578125 | 3 | [] | no_license | #include "Feature.h"
void
FeatureExtractor::operator()(const ImageDatabase& db, FeatureSet& featureSet) const
{
int n = db.getSize();
featureSet.resize(n);
for(int i = 0; i < n; i++) {
CByteImage img;
ReadFile(img, db.getFilename(i).c_str());
featureSet[i] = (*this)(img);
}
}
CByteImage
FeatureExtractor::render(const Feature& f, bool normalizeFeat) const
{
if(normalizeFeat) {
CShape shape = f.Shape();
Feature fAux(shape);
float fMin, fMax;
f.getRangeOfValues(fMin, fMax);
for(int y = 0; y < shape.height; y++) {
float* fIt = (float*) f.PixelAddress(0,y,0);
float* fAuxIt = (float*) fAux.PixelAddress(0,y,0);
for(int x = 0; x < shape.width * shape.nBands; x++, fAuxIt++, fIt++) {
*fAuxIt = (*fIt) / fMax;
}
}
return this->render(fAux);
} else {
return this->render(f);
}
}
FeatureExtractor*
FeatureExtractorNew(const char* featureType)
{
if(strcasecmp(featureType, "tinyimg") == 0) return new TinyImageFeatureExtractor();
if(strcasecmp(featureType, "hog") == 0) return new HOGFeatureExtractor();
// Implement other features or call a feature extractor with a different set
// of parameters by adding more calls here.
if(strcasecmp(featureType, "myfeat1") == 0) throw CError("not implemented");
if(strcasecmp(featureType, "myfeat2") == 0) throw CError("not implemented");
if(strcasecmp(featureType, "myfeat3") == 0) throw CError("not implemented");
else {
throw CError("Unknown feature type: %s", featureType);
}
}
// ============================================================================
// TinyImage
// ============================================================================
TinyImageFeatureExtractor::TinyImageFeatureExtractor(int targetWidth, int targetHeight):
_targetW(targetWidth), _targetH(targetHeight)
{
}
Feature
TinyImageFeatureExtractor::operator()(const CByteImage& img_) const
{
CFloatImage tinyImg(_targetW, _targetH, 1);
/******** BEGIN TODO ********/
// Compute tiny image feature, output should be _targetW by _targetH a grayscale image
// Steps are:
// 1) Convert image to grayscale (see convertRGB2GrayImage in Utils.h)
// 2) Resize image to be _targetW by _targetH
//
// Useful functions:
// convertRGB2GrayImage, TypeConvert, WarpGlobal
CFloatImage floatImage;
CFloatImage grayImage;
TypeConvert(img_, floatImage);
convertRGB2GrayImage(floatImage, grayImage);
CTransform3x3 scaleXform = CTransform3x3::Scale(_targetW / (float)img_.Shape().width, _targetH / (float)img_.Shape().height);
WarpGlobal(grayImage, tinyImg, scaleXform.Inverse(), eWarpInterpLinear, 1.0f);
return tinyImg;
}
CByteImage
TinyImageFeatureExtractor::render(const Feature& f) const
{
CByteImage viz;
TypeConvert(f, viz);
return viz;
}
// ============================================================================
// HOG
// ============================================================================
static float derivKvals[3] = { -1, 0, 1};
HOGFeatureExtractor::HOGFeatureExtractor(int nAngularBins, bool unsignedGradients, int cellSize):
_nAngularBins(nAngularBins),
_unsignedGradients(unsignedGradients),
_cellSize(cellSize)
{
_kernelDx.ReAllocate(CShape(3, 1, 1), derivKvals, false, 1);
_kernelDx.origin[0] = 1;
_kernelDy.ReAllocate(CShape(1, 3, 1), derivKvals, false, 1);
_kernelDy.origin[0] = 1;
// For visualization
// A set of patches representing the bin orientations. When drawing a hog cell
// we multiply each patch by the hog bin value and add all contributions up to
// form the visual representation of one cell. Full HOG is achieved by stacking
// the viz for individual cells horizontally and vertically.
_oriMarkers.resize(_nAngularBins);
const int ms = 11;
CShape markerShape(ms, ms, 1);
// First patch is a horizontal line
_oriMarkers[0].ReAllocate(markerShape, true);
_oriMarkers[0].ClearPixels();
for(int i = 1; i < ms - 1; i++) _oriMarkers[0].Pixel(/*floor(*/ ms/2 /*)*/, i, 0) = 1;
#if 0 // debug
std::cout << "DEBUG:" << __FILE__ << ":" << __LINE__ << std::endl;
for(int i = 0; i < ms; i++) {
for(int j = 0; j < ms; j++) {
std::cout << _oriMarkers[0].Pixel(j, i, 0) << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
char debugFName[2000];
sprintf(debugFName, "/tmp/debug%03d.tga", 0);
PRINT_EXPR(debugFName);
WriteFile(_oriMarkers[0], debugFName);
#endif
// The other patches are obtained by rotating the first one
CTransform3x3 T = CTransform3x3::Translation((ms - 1) / 2.0, (ms - 1) / 2.0);
for(int angBin = 1; angBin < _nAngularBins; angBin++) {
double theta;
if(unsignedGradients) theta = 180.0 * (double(angBin) / _nAngularBins);
else theta = 360.0 * (double(angBin) / _nAngularBins);
CTransform3x3 R = T * CTransform3x3::Rotation(theta) * T.Inverse();
_oriMarkers[angBin].ReAllocate(markerShape, true);
_oriMarkers[angBin].ClearPixels();
WarpGlobal(_oriMarkers[0], _oriMarkers[angBin], R, eWarpInterpLinear);
#if 0 // debug
char debugFName[2000];
sprintf(debugFName, "/tmp/debug%03d.tga", angBin);
PRINT_EXPR(debugFName);
WriteFile(_oriMarkers[angBin], debugFName);
#endif
}
}
/*
- Standing questions:
- Do you take the max gradient, or do you perform operations for each channel?
- How do you use orientation to weigh a pixel's contribution?
- Normalization?
- Is unsigned between 0 and 180, or between PI/2 and -PI/2? Arctan naturally suggests the latter.
- Am I doing gaussian correctly?
- Thresholding
- Change bins based on signed/unsigned
- Divide by square root of sum, not just sum
*/
Feature
HOGFeatureExtractor::operator()(const CByteImage& img_) const
{
float sigma = _cellSize;
/******** BEGIN TODO ********/
// Compute the Histogram of Oriented Gradients feature
// Steps are:
// 1) Compute gradients in x and y directions. We provide the
// derivative kernel proposed in the paper in _kernelDx and
// _kernelDy.
CFloatImage convertedImg;
TypeConvert(img_, convertedImg);
CFloatImage derivX;
CFloatImage derivY;
CFloatImage magnitudeImg(convertedImg.Shape());
CFloatImage orientationImg(convertedImg.Shape());
Convolve(convertedImg, derivX, _kernelDx);
Convolve(convertedImg, derivY, _kernelDy);
int numCellsX = floor(((convertedImg.Shape().width)/((float)_cellSize)));
int numCellsY = floor(((convertedImg.Shape().height)/((float)_cellSize)));
Feature feature(numCellsX, numCellsY, _nAngularBins);
feature.ClearPixels();
// 2) Compute gradient magnitude and orientation
for (int row = 0; row < convertedImg.Shape().height; row++)
{
for (int column = 0; column < convertedImg.Shape().width; column++)
{
float maxMag = 0;
int maxBand = 0;
for (int band = 0; band < 3; band++)
{
float currentMag = sqrt(pow(derivX.Pixel(column, row, band), 2.f) + pow(derivY.Pixel(column, row, band), 2.f));
if (currentMag > maxMag)
{
maxBand = band;
maxMag = currentMag;
}
}
magnitudeImg.Pixel(column, row, 0) = maxMag;
float maxX = derivX.Pixel(column, row, maxBand);
float maxY = derivY.Pixel(column, row, maxBand);
if (maxX == 0)
{
orientationImg.Pixel(column, row, 0) = (maxY >= 0 || _unsignedGradients)? PI/2. : 3.*PI/2.;
}
else
{
float angle = atan(abs(maxY / maxX));
angle = (maxX < 0)? PI - angle: angle;
angle = (maxY < 0)? 2.f * PI - angle: angle;
if (_unsignedGradients)
{
angle = fmod(angle, (float)PI);
}
orientationImg.Pixel(column, row, 0) = angle;
}
if (row >= feature.Shape().height * _cellSize || column >= feature.Shape().width * _cellSize)
{
continue;
}
//Add contribution
float angleUpperBound = ((_unsignedGradients)? PI : 2.*PI );
float angleUnit = angleUpperBound/ (float)_nAngularBins;
float angle = orientationImg.Pixel(column, row, 0);
float binAngle;
if (_unsignedGradients)
{
if (angle < angleUnit/2.f || angle >= PI - angleUnit/2.f)
{
binAngle = 0;
}
else
{
binAngle = (int)((angle + angleUnit/2.f)/angleUnit);
}
}
else
{
float binAngle = (int)((orientationImg.Pixel(column, row, 0) + angleUnit/2.)/angleUnit);
}
// Iterate over center, left, right, up, down
int cellX = (int) column / _cellSize;
int cellY = (int) row / _cellSize;
for (int relX = -1; relX <= 1; relX++)
{
for (int relY = -1; relY <= 1; relY++)
{
if (abs(relX) + abs(relY) == 2)
{
continue;
}
int currentCellX = cellX + relX;
int currentCellY = cellY + relY;
if (currentCellX < 0 || currentCellY < 0 || currentCellX >= feature.Shape().width
|| currentCellY >= feature.Shape().height)
{
continue;
}
int cellCenterX = currentCellX*_cellSize + _cellSize/2.-1;
int cellCenterY = currentCellY*_cellSize + _cellSize/2.-1;
float distance = pow(cellCenterX - column, 2.) + pow(cellCenterY - row, 2.);
float gaussianDistance = 1/(pow(sigma, 2)*2*PI) * exp(-distance/(2.* pow(sigma, 2.f)));
float featureVal = feature.Pixel(cellX, cellY, binAngle);
if (featureVal < 0){
auto stop = 1;
}
feature.Pixel(cellX, cellY, binAngle) += gaussianDistance * magnitudeImg.Pixel(column, row, 0);
float mag = magnitudeImg.Pixel(column, row, 0);
}
}
}
}
float epsilon = .1;
float threshold = .3;
for (int y = 0; y < feature.Shape().height; y++)
{
for (int x = 0; x < feature.Shape().width; x++)
{
float sum = 0;
for (int bin = 0; bin < _nAngularBins; bin++)
{
sum += pow(feature.Pixel(x, y, bin), 2.f);
}
//as per the wikipedia article, we add an e of .1
sum += pow(epsilon, 2.f);
float thresholdedSum = 0;
for (int bin = 0; bin < _nAngularBins; bin++)
{
if (sum <= 0){
auto stop = 1;
}
feature.Pixel(x, y, bin) /= sqrt(sum);
if (feature.Pixel(x, y, bin) > threshold)
{
feature.Pixel(x, y, bin) = threshold;
}
thresholdedSum += pow(feature.Pixel(x, y, bin), 2.f);
}
thresholdedSum += pow(epsilon, 2.f);
for (int bin = 0; bin < _nAngularBins; bin++)
{
feature.Pixel(x, y, bin) /= sqrt(thresholdedSum);
}
}
}
return feature;
}
CByteImage
HOGFeatureExtractor::render(const Feature& f) const
{
CShape cellShape = _oriMarkers[0].Shape();
CFloatImage hogImgF(CShape(cellShape.width * f.Shape().width, cellShape.height * f.Shape().height, 1));
hogImgF.ClearPixels();
float minBinValue, maxBinValue;
f.getRangeOfValues(minBinValue, maxBinValue);
// For every cell in the HOG
for(int hi = 0; hi < f.Shape().height; hi++) {
for(int hj = 0; hj < f.Shape().width; hj++) {
// Now _oriMarkers, multiplying contribution by bin level
for(int hc = 0; hc < _nAngularBins; hc++) {
float v = f.Pixel(hj, hi, hc) / maxBinValue;
for(int ci = 0; ci < cellShape.height; ci++) {
float* cellIt = (float*) _oriMarkers[hc].PixelAddress(0, ci, 0);
float* hogIt = (float*) hogImgF.PixelAddress(hj * cellShape.height, hi * cellShape.height + ci, 0);
for(int cj = 0; cj < cellShape.width; cj++, hogIt++, cellIt++) {
(*hogIt) += v * (*cellIt);
}
}
}
}
}
CByteImage hogImg;
TypeConvert(hogImgF, hogImg);
return hogImg;
}
| true |
66fcd56af3819bf20aaec59be7e9a39e717f66cd | C++ | yydaor/OtterUI | /API/src/Math/Vector3.cpp | UTF-8 | 255 | 2.71875 | 3 | [
"MIT"
] | permissive | #include "Math/Vector3.h"
namespace VectorMath
{
const Vector3 Vector3::ZERO (0.0f, 0.0f, 0.0f);
const Vector3 Vector3::UNIT_X (1.0f, 0.0f, 0.0f);
const Vector3 Vector3::UNIT_Y (0.0f, 1.0f, 0.0f);
const Vector3 Vector3::UNIT_Z (0.0f, 0.0f, 1.0f);
} | true |
8933b936befd3dc037e41c894ed8b2ac9d144c9b | C++ | diluises/TShine | /TShine/include/TSHistogramFld.h | UTF-8 | 2,650 | 2.671875 | 3 | [] | no_license | /*
* TSHistogramFld.h
*
* Created on: Jun 2, 2014
* Author: Silvestro di Luise
* Silvestro.Di.Luise@cern.ch
*
*
* Class to create a folder of Histograms (TH1,TH2, TH2Poly...)
*
* Each histogram-axis has associated the name of the corresponding TSVariable.
* Those names are to be provided when the histogram is added to the folder
* via the Add method.
*
* Several Fill methods are provided to fill all the histograms
* at the same time from a given set of TSVariable values.
*
*
* Folder is the Owner of the Added Objects
*
*
*
*/
#ifndef TSHISTOGRAMFLD_H_
#define TSHISTOGRAMFLD_H_
#include <string>
#include <map>
#include <TString.h>
#include <TFile.h>
#include <TH2Poly.h>
#include <TList.h>
class TSHistogramFld: public TList {
public:
TSHistogramFld();
TSHistogramFld(TString name);
virtual ~TSHistogramFld();
void Add(TObject*, TString, TString="");
int AddPolyBinContent(TH2Poly &,int bin, double w=1);
TSHistogramFld* Clone(TString name="") const;
void AppendToAllNames(TString, TString sep="_");
void AppendToAllTitles(TString, TString sep=" ");
void Clear(Option_t* opt="");
void Copy(TSHistogramFld&);
int Fill(int N, TString* list, double* values);
int Fill(std::vector<TString>&, std::vector<double>&);
int Fill(TString vx, TString vy, double x, double y, double w=1, int opt=0);
int Fill(TString vx, double x, double w=1, int opt=0);
int FillPoly(TH2Poly *h, double x, double y, double w=1, int opt=1);
int FillHistosFromFile(TFile *,TString opt="");
int GetHistoDim(int) const;
TString GetHistoName(int) const;
TString GetHistoNameX(int) const;
TString GetHistoNameY(int) const;
TList *GetListOf(TString) const;
TObject* GetObject(int) const;
float GetOutliersFrac(TString, TString ="") const;
TObject* GetTagHisto(TString, TString ="") const;
int Import(TSHistogramFld&);
bool IsSumw2() const {return fSumw2;}
void Init();
bool IsTH1(const TObject& ) const;
bool IsTH2(const TObject& ) const;
bool IsTH2Poly(const TObject& ) const;
void PrependToAllNames(TString,TString sep="_");
void PrependToAllTitles(TString,TString sep=" ");
void ReplaceToAllTitles(TString);
void RenameAllWithBase(TString,TString sep="_");
void ResetHistos();
void SetSumw2(bool =false);
private:
bool fSumw2;
void ApplyTH2Style(TH2 *);
struct fHistoSettings{
int Position;
TString Name;
int Dim;
TString NameX;
TString NameY;
};
std::map<int,fHistoSettings*> fHistoSetsList;
std::map<TString,int> fObjPos;
std::map<int,TString> fObjName;
std::map<int,TString> fObjNameX;
std::map<int,TString> fObjNameY;
};
#endif /* TSHISTOGRAMFLD_H_ */
| true |
a23de8a609e2d4e06404bcf70ddc0d8148bbabea | C++ | Cabahamaru/PRO1-FIB | /Llista_08/regla_horner/P50036.cc | UTF-8 | 535 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <math.h>
using namespace std;
//Llegeix una seq. de nombres reals i els gaurda a v
void read(vector<int>& v) {
int n = v.size();
for (int i = 0; i < n; ++i) cin >> v[i];
}
int avalua(const vector<int>& p, int x) {
int n = p.size();
int horner = 0;
for (int i = 0; i < n; ++i) {
horner = horner + p[i]*pow(x,i);
}
return horner;
}
int main() {
int n, x;
cin >> n >> x;
vector<int> p(n);
read(p);
cout << avalua(p,x) << endl;
}
| true |
68f5986af0dfbf0b711ed8ee4716146a3ef9e0d9 | C++ | google/orbit | /third_party/libutils/RefBase_test.cpp | UTF-8 | 13,792 | 2.640625 | 3 | [
"BSD-2-Clause",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <utils/StrongPointer.h>
#include <utils/RefBase.h>
#include <thread>
#include <atomic>
#include <sched.h>
#include <errno.h>
// Enhanced version of StrongPointer_test, but using RefBase underneath.
using namespace android;
static constexpr int NITERS = 1000000;
static constexpr int INITIAL_STRONG_VALUE = 1 << 28; // Mirroring RefBase definition.
class Foo : public RefBase {
public:
Foo(bool* deleted_check) : mDeleted(deleted_check) {
*mDeleted = false;
}
~Foo() {
*mDeleted = true;
}
private:
bool* mDeleted;
};
// A version of Foo that ensures that all objects are allocated at the same
// address. No more than one can be allocated at a time. Thread-hostile.
class FooFixedAlloc : public RefBase {
public:
static void* operator new(size_t size) {
if (mAllocCount != 0) {
abort();
}
mAllocCount = 1;
if (theMemory == nullptr) {
theMemory = malloc(size);
}
return theMemory;
}
static void operator delete(void *p) {
if (mAllocCount != 1 || p != theMemory) {
abort();
}
mAllocCount = 0;
}
FooFixedAlloc(bool* deleted_check) : mDeleted(deleted_check) {
*mDeleted = false;
}
~FooFixedAlloc() {
*mDeleted = true;
}
private:
bool* mDeleted;
static int mAllocCount;
static void* theMemory;
};
int FooFixedAlloc::mAllocCount(0);
void* FooFixedAlloc::theMemory(nullptr);
TEST(RefBase, StrongMoves) {
bool isDeleted;
Foo* foo = new Foo(&isDeleted);
ASSERT_EQ(INITIAL_STRONG_VALUE, foo->getStrongCount());
ASSERT_FALSE(isDeleted) << "Already deleted...?";
sp<Foo> sp1(foo);
wp<Foo> wp1(sp1);
ASSERT_EQ(1, foo->getStrongCount());
// Weak count includes both strong and weak references.
ASSERT_EQ(2, foo->getWeakRefs()->getWeakCount());
{
sp<Foo> sp2 = std::move(sp1);
ASSERT_EQ(1, foo->getStrongCount())
<< "std::move failed, incremented refcnt";
ASSERT_EQ(nullptr, sp1.get()) << "std::move failed, sp1 is still valid";
// The strong count isn't increasing, let's double check the old object
// is properly reset and doesn't early delete
sp1 = std::move(sp2);
}
ASSERT_FALSE(isDeleted) << "deleted too early! still has a reference!";
{
// Now let's double check it deletes on time
sp<Foo> sp2 = std::move(sp1);
}
ASSERT_TRUE(isDeleted) << "foo was leaked!";
ASSERT_TRUE(wp1.promote().get() == nullptr);
}
TEST(RefBase, WeakCopies) {
bool isDeleted;
Foo* foo = new Foo(&isDeleted);
EXPECT_EQ(0, foo->getWeakRefs()->getWeakCount());
ASSERT_FALSE(isDeleted) << "Foo (weak) already deleted...?";
wp<Foo> wp1(foo);
EXPECT_EQ(1, foo->getWeakRefs()->getWeakCount());
{
wp<Foo> wp2 = wp1;
ASSERT_EQ(2, foo->getWeakRefs()->getWeakCount());
}
EXPECT_EQ(1, foo->getWeakRefs()->getWeakCount());
ASSERT_FALSE(isDeleted) << "deleted too early! still has a reference!";
wp1 = nullptr;
ASSERT_FALSE(isDeleted) << "Deletion on wp destruction should no longer occur";
}
TEST(RefBase, Comparisons) {
bool isDeleted, isDeleted2, isDeleted3;
Foo* foo = new Foo(&isDeleted);
Foo* foo2 = new Foo(&isDeleted2);
sp<Foo> sp1(foo);
sp<Foo> sp2(foo2);
wp<Foo> wp1(sp1);
wp<Foo> wp2(sp1);
wp<Foo> wp3(sp2);
ASSERT_TRUE(wp1 == wp2);
ASSERT_TRUE(wp1 == sp1);
ASSERT_TRUE(wp3 == sp2);
ASSERT_TRUE(wp1 != sp2);
ASSERT_TRUE(wp1 <= wp2);
ASSERT_TRUE(wp1 >= wp2);
ASSERT_FALSE(wp1 != wp2);
ASSERT_FALSE(wp1 > wp2);
ASSERT_FALSE(wp1 < wp2);
ASSERT_FALSE(sp1 == sp2);
ASSERT_TRUE(sp1 != sp2);
bool sp1_smaller = sp1 < sp2;
wp<Foo>wp_smaller = sp1_smaller ? wp1 : wp3;
wp<Foo>wp_larger = sp1_smaller ? wp3 : wp1;
ASSERT_TRUE(wp_smaller < wp_larger);
ASSERT_TRUE(wp_smaller != wp_larger);
ASSERT_TRUE(wp_smaller <= wp_larger);
ASSERT_FALSE(wp_smaller == wp_larger);
ASSERT_FALSE(wp_smaller > wp_larger);
ASSERT_FALSE(wp_smaller >= wp_larger);
sp2 = nullptr;
ASSERT_TRUE(isDeleted2);
ASSERT_FALSE(isDeleted);
ASSERT_FALSE(wp3 == sp2);
// Comparison results on weak pointers should not be affected.
ASSERT_TRUE(wp_smaller < wp_larger);
ASSERT_TRUE(wp_smaller != wp_larger);
ASSERT_TRUE(wp_smaller <= wp_larger);
ASSERT_FALSE(wp_smaller == wp_larger);
ASSERT_FALSE(wp_smaller > wp_larger);
ASSERT_FALSE(wp_smaller >= wp_larger);
wp2 = nullptr;
ASSERT_FALSE(wp1 == wp2);
ASSERT_TRUE(wp1 != wp2);
wp1.clear();
ASSERT_TRUE(wp1 == wp2);
ASSERT_FALSE(wp1 != wp2);
wp3.clear();
ASSERT_TRUE(wp1 == wp3);
ASSERT_FALSE(wp1 != wp3);
ASSERT_FALSE(isDeleted);
sp1.clear();
ASSERT_TRUE(isDeleted);
ASSERT_TRUE(sp1 == sp2);
// Try to check that null pointers are properly initialized.
{
// Try once with non-null, to maximize chances of getting junk on the
// stack.
sp<Foo> sp3(new Foo(&isDeleted3));
wp<Foo> wp4(sp3);
wp<Foo> wp5;
ASSERT_FALSE(wp4 == wp5);
ASSERT_TRUE(wp4 != wp5);
ASSERT_FALSE(sp3 == wp5);
ASSERT_FALSE(wp5 == sp3);
ASSERT_TRUE(sp3 != wp5);
ASSERT_TRUE(wp5 != sp3);
ASSERT_TRUE(sp3 == wp4);
}
{
sp<Foo> sp3;
wp<Foo> wp4(sp3);
wp<Foo> wp5;
ASSERT_TRUE(wp4 == wp5);
ASSERT_FALSE(wp4 != wp5);
ASSERT_TRUE(sp3 == wp5);
ASSERT_TRUE(wp5 == sp3);
ASSERT_FALSE(sp3 != wp5);
ASSERT_FALSE(wp5 != sp3);
ASSERT_TRUE(sp3 == wp4);
}
}
// Check whether comparison against dead wp works, even if the object referenced
// by the new wp happens to be at the same address.
TEST(RefBase, ReplacedComparison) {
bool isDeleted, isDeleted2;
FooFixedAlloc* foo = new FooFixedAlloc(&isDeleted);
sp<FooFixedAlloc> sp1(foo);
wp<FooFixedAlloc> wp1(sp1);
ASSERT_TRUE(wp1 == sp1);
sp1.clear(); // Deallocates the object.
ASSERT_TRUE(isDeleted);
FooFixedAlloc* foo2 = new FooFixedAlloc(&isDeleted2);
ASSERT_FALSE(isDeleted2);
ASSERT_EQ(foo, foo2); // Not technically a legal comparison, but ...
sp<FooFixedAlloc> sp2(foo2);
wp<FooFixedAlloc> wp2(sp2);
ASSERT_TRUE(sp2 == wp2);
ASSERT_FALSE(sp2 != wp2);
ASSERT_TRUE(sp2 != wp1);
ASSERT_FALSE(sp2 == wp1);
ASSERT_FALSE(sp2 == sp1); // sp1 is null.
ASSERT_FALSE(wp1 == wp2); // wp1 refers to old object.
ASSERT_TRUE(wp1 != wp2);
ASSERT_TRUE(wp1 > wp2 || wp1 < wp2);
ASSERT_TRUE(wp1 >= wp2 || wp1 <= wp2);
ASSERT_FALSE(wp1 >= wp2 && wp1 <= wp2);
ASSERT_FALSE(wp1 == nullptr);
wp1 = sp2;
ASSERT_TRUE(wp1 == wp2);
ASSERT_FALSE(wp1 != wp2);
}
TEST(RefBase, AssertWeakRefExistsSuccess) {
bool isDeleted;
sp<Foo> foo = sp<Foo>::make(&isDeleted);
wp<Foo> weakFoo = foo;
EXPECT_EQ(weakFoo, wp<Foo>::fromExisting(foo.get()));
EXPECT_EQ(weakFoo.unsafe_get(), wp<Foo>::fromExisting(foo.get()).unsafe_get());
EXPECT_FALSE(isDeleted);
foo = nullptr;
EXPECT_TRUE(isDeleted);
}
TEST(RefBase, AssertWeakRefExistsDeath) {
// uses some other refcounting method, or none at all
bool isDeleted;
Foo* foo = new Foo(&isDeleted);
// can only get a valid wp<> object when you construct it from an sp<>
EXPECT_DEATH(wp<Foo>::fromExisting(foo), "");
delete foo;
}
// Set up a situation in which we race with visit2AndRremove() to delete
// 2 strong references. Bar destructor checks that there are no early
// deletions and prior updates are visible to destructor.
class Bar : public RefBase {
public:
Bar(std::atomic<int>* delete_count) : mVisited1(false), mVisited2(false),
mDeleteCount(delete_count) {
}
~Bar() {
EXPECT_TRUE(mVisited1);
EXPECT_TRUE(mVisited2);
(*mDeleteCount)++;
}
bool mVisited1;
bool mVisited2;
private:
std::atomic<int>* mDeleteCount;
};
static sp<Bar> buffer;
static std::atomic<bool> bufferFull(false);
// Wait until bufferFull has value val.
static inline void waitFor(bool val) {
while (bufferFull != val) {}
}
cpu_set_t otherCpus;
// Divide the cpus we're allowed to run on into myCpus and otherCpus.
// Set origCpus to the processors we were originally allowed to run on.
// Return false if origCpus doesn't include at least processors 0 and 1.
static bool setExclusiveCpus(cpu_set_t* origCpus /* out */,
cpu_set_t* myCpus /* out */, cpu_set_t* otherCpus) {
if (sched_getaffinity(0, sizeof(cpu_set_t), origCpus) != 0) {
return false;
}
if (!CPU_ISSET(0, origCpus) || !CPU_ISSET(1, origCpus)) {
return false;
}
CPU_ZERO(myCpus);
CPU_ZERO(otherCpus);
CPU_OR(myCpus, myCpus, origCpus);
CPU_OR(otherCpus, otherCpus, origCpus);
for (unsigned i = 0; i < CPU_SETSIZE; ++i) {
// I get the even cores, the other thread gets the odd ones.
if (i & 1) {
CPU_CLR(i, myCpus);
} else {
CPU_CLR(i, otherCpus);
}
}
return true;
}
static void visit2AndRemove() {
if (sched_setaffinity(0, sizeof(cpu_set_t), &otherCpus) != 0) {
FAIL() << "setaffinity returned:" << errno;
}
for (int i = 0; i < NITERS; ++i) {
waitFor(true);
buffer->mVisited2 = true;
buffer = nullptr;
bufferFull = false;
}
}
TEST(RefBase, RacingDestructors) {
cpu_set_t origCpus;
cpu_set_t myCpus;
// Restrict us and the helper thread to disjoint cpu sets.
// This prevents us from getting scheduled against each other,
// which would be atrociously slow.
if (setExclusiveCpus(&origCpus, &myCpus, &otherCpus)) {
std::thread t(visit2AndRemove);
std::atomic<int> deleteCount(0);
if (sched_setaffinity(0, sizeof(cpu_set_t), &myCpus) != 0) {
FAIL() << "setaffinity returned:" << errno;
}
for (int i = 0; i < NITERS; ++i) {
waitFor(false);
Bar* bar = new Bar(&deleteCount);
sp<Bar> sp3(bar);
buffer = sp3;
bufferFull = true;
ASSERT_TRUE(bar->getStrongCount() >= 1);
// Weak count includes strong count.
ASSERT_TRUE(bar->getWeakRefs()->getWeakCount() >= 1);
sp3->mVisited1 = true;
sp3 = nullptr;
}
t.join();
if (sched_setaffinity(0, sizeof(cpu_set_t), &origCpus) != 0) {
FAIL();
}
ASSERT_EQ(NITERS, deleteCount) << "Deletions missed!";
} // Otherwise this is slow and probably pointless on a uniprocessor.
}
static wp<Bar> wpBuffer;
static std::atomic<bool> wpBufferFull(false);
// Wait until wpBufferFull has value val.
static inline void wpWaitFor(bool val) {
while (wpBufferFull != val) {}
}
static void visit3AndRemove() {
if (sched_setaffinity(0, sizeof(cpu_set_t), &otherCpus) != 0) {
FAIL() << "setaffinity returned:" << errno;
}
for (int i = 0; i < NITERS; ++i) {
wpWaitFor(true);
{
sp<Bar> sp1 = wpBuffer.promote();
// We implicitly check that sp1 != NULL
sp1->mVisited2 = true;
}
wpBuffer = nullptr;
wpBufferFull = false;
}
}
TEST(RefBase, RacingPromotions) {
cpu_set_t origCpus;
cpu_set_t myCpus;
// Restrict us and the helper thread to disjoint cpu sets.
// This prevents us from getting scheduled against each other,
// which would be atrociously slow.
if (setExclusiveCpus(&origCpus, &myCpus, &otherCpus)) {
std::thread t(visit3AndRemove);
std::atomic<int> deleteCount(0);
if (sched_setaffinity(0, sizeof(cpu_set_t), &myCpus) != 0) {
FAIL() << "setaffinity returned:" << errno;
}
for (int i = 0; i < NITERS; ++i) {
Bar* bar = new Bar(&deleteCount);
wp<Bar> wp1(bar);
bar->mVisited1 = true;
if (i % (NITERS / 10) == 0) {
// Do this rarely, since it generates a log message.
wp1 = nullptr; // No longer destroys the object.
wp1 = bar;
}
wpBuffer = wp1;
ASSERT_EQ(bar->getWeakRefs()->getWeakCount(), 2);
wpBufferFull = true;
// Promotion races with that in visit3AndRemove.
// This may or may not succeed, but it shouldn't interfere with
// the concurrent one.
sp<Bar> sp1 = wp1.promote();
wpWaitFor(false); // Waits for other thread to drop strong pointer.
sp1 = nullptr;
// No strong pointers here.
sp1 = wp1.promote();
ASSERT_EQ(sp1.get(), nullptr) << "Dead wp promotion succeeded!";
}
t.join();
if (sched_setaffinity(0, sizeof(cpu_set_t), &origCpus) != 0) {
FAIL();
}
ASSERT_EQ(NITERS, deleteCount) << "Deletions missed!";
} // Otherwise this is slow and probably pointless on a uniprocessor.
}
| true |
ebc6a79a60954c7d6a811f4d8b4a79fa01815fdd | C++ | adityarbhatia/C-C-1 | /TwosAndOnesNested.cpp | UTF-8 | 322 | 2.8125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int a = 1, b = 2;
for(int i = 0; i<7; i ++)
{
for(int j = 0; j <i; j++)
{
cout << b;
}
for(int k = 0; k < 6-i; k++)
{
cout << a;
}
cout << endl;
}
return 0;
}
| true |
f08e5a82121aa383036082dd54c7a8bd03ecbccd | C++ | XsnTrcK/AdventOfCode | /2020/main.cpp | UTF-8 | 2,748 | 3.375 | 3 | [] | no_license | #include <iostream>
#include "dayOne.h"
#include "dayTwo.h"
#include "dayThree.h"
#include "dayFour.h"
#include "dayFive.h"
#include "daySix.h"
#include "daySeven.h"
#include "dayEight.h"
#include "dayNine.h"
using namespace std;
using namespace AdventOfCode2020;
int main() {
string inputPath;
cout << "Path to Day 1 input:" << endl;
cin >> inputPath;
if (inputPath != "s") {
cout << "Answer Day 1 Part 1: " << dayOnePartOne(inputPath) << endl;
cout << "Answer Day 1 Part 2: " << dayOnePartTwo(inputPath) << endl;
}
cout << "Path to Day 2 input:" << endl;
cin >> inputPath;
if (inputPath != "s") {
cout << "Answer Day 2 Part 1: " << dayTwo(inputPath, DayPart::One) << endl;
cout << "Answer Day 2 Part 2: " << dayTwo(inputPath, DayPart::Two) << endl;
}
cout << "Path to Day 3 input:" << endl;
cin >> inputPath;
if (inputPath != "s") {
cout << "Answer Day 3 Part 1: " << dayThreePartOne(inputPath) << endl;
cout << "Answer Day 3 Part 2: " << dayThreePartTwo(inputPath) << endl;
}
cout << "Path to Day 4 input:" << endl;
cin >> inputPath;
if (inputPath != "s") {
cout << "Answer Day 4 Part 1: " << dayFourPartOne(inputPath, DayPart::One) << endl;
cout << "Answer Day 4 Part 2: " << dayFourPartOne(inputPath, DayPart::Two) << endl;
}
cout << "Path to Day 5 input:" << endl;
cin >> inputPath;
if (inputPath != "s") {
cout << "Answer Day 5 Part 1: " << dayFive(inputPath, DayPart::One) << endl;
cout << "Answer Day 5 Part 2: " << dayFive(inputPath, DayPart::Two) << endl;
}
cout << "Path to Day 6 input:" << endl;
cin >> inputPath;
if (inputPath != "s") {
cout << "Answer Day 6 Part 1: " << daySix(inputPath, DayPart::One) << endl;
cout << "Answer Day 6 Part 2: " << daySix(inputPath, DayPart::Two) << endl;
}
cout << "Path to Day 7 input:" << endl;
cin >> inputPath;
if (inputPath != "s") {
cout << "Answer Day 7 Part 1: " << daySeven(inputPath, DayPart::One) << endl;
cout << "Answer Day 7 Part 2: " << daySeven(inputPath, DayPart::Two) << endl;
}
cout << "Path to Day 8 input:" << endl;
cin >> inputPath;
if (inputPath != "s") {
cout << "Answer Day 8 Part 1: " << dayEight(inputPath, DayPart::One) << endl;
cout << "Answer Day 8 Part 2: " << dayEight(inputPath, DayPart::Two) << endl;
}
cout << "Path to Day 9 input:" << endl;
cin >> inputPath;
if (inputPath != "s") {
cout << "Answer Day 9 Part 1: " << dayNine(inputPath, DayPart::One) << endl;
cout << "Answer Day 9 Part 2: " << dayNine(inputPath, DayPart::Two) << endl;
}
return 0;
} | true |
18fcf5b015e9ba0ee6f360336f6d82e8c7bcbbeb | C++ | kinshukk/competitive_programming | /USACO/CowTipper.cpp | UTF-8 | 1,048 | 2.984375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
bool arr[11][11];
void flip(int y, int x){
// for(int i=0; i<=y; i++){
// for(int j=0; j<=x; j++){
// cout << arr[i][j] << " ";
// }
// cout << endl;
// }
//
// cout << "becomes" << endl;
for(int i=0; i<=y; i++){
for(int j=0; j<=x; j++){
arr[i][j] = !arr[i][j];
//cout << arr[i][j] << " ";
}
//cout << endl;
}
}
int main(){
freopen("cowtip.in", "r", stdin);
freopen("cowtip.out", "w", stdout);
int n;
cin >> n;
string inp;
for(int i=0; i<n; i++){
cin >> inp;
for(int j=0; j<n; j++){
arr[i][j] = (inp[j] - '0');
}
}
int cnt = 0;
for(int i=n-1; i>=0; i--){
for(int j=i; j>=0; j--){
if(arr[i][j]){
flip(i, j);
cnt++;
}
if(arr[j][i]){
flip(j, i);
cnt++;
}
}
}
cout << cnt << endl;
}
| true |
0fd1325387d698dc5469d018f2ae31f559d16395 | C++ | 0x7DD/Maratones | /gameTheory/crazyCalendar.cpp | UTF-8 | 665 | 2.625 | 3 | [
"MIT"
] | permissive | # include <cstdio>
# include <cstdlib>
# include <iostream>
# include <cmath>
using namespace std;
int main(){
int t,cont = 0;
scanf("%d", &t);
while(t--){
int n,m;
scanf("%d %d", &n, &m);
int nim = 0;
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j){
int pile;
scanf("%d", &pile);
int dis = (n - i - 1) + (m - j -1);
if(dis%2)
nim ^= pile;
}
}
cont++;
if(nim) printf("Case %d: win\n", cont);
else printf("Case %d: lose\n", cont);
}
return 0;
}
| true |
1c63f062e648f8d4fd6193fbe68879154c203663 | C++ | McCampins/LightAndDarkness | /LightAndDarkness/LightAndDarkness/Exit.cpp | UTF-8 | 1,084 | 3.015625 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <assert.h>
#include "Exit.h"
#include "Room.h"
using namespace std;
Exit::Exit(const char* name, const char* oppositeName, const char* description, Room* origin, Room* dest,
bool oneWay, bool locked, Entity* key) :
Entity(name, description, (Entity*)origin),
oppositeName(oppositeName), destination(dest), oneWay(oneWay), locked(locked), key(key)
{
type = EntityType::EXIT;
if (oneWay == false)
{
destination->container.push_back(this);
}
}
Exit::~Exit()
{
}
void Exit::Look() const
{
cout << "\nExit to the " << name << endl;
cout << description << endl;
}
const string & Exit::GetNameFrom(const Room * room) const
{
assert(room != nullptr);
if (room == (Room*)parent)
return name;
if (room == destination)
return oppositeName;
return name; //Error, hopefully we will never reach this statement
}
Room * Exit::GetDestinationFrom(const Room * room) const
{
assert(room != nullptr);
if (room == (Room*)parent)
return destination;
if (room == destination && !oneWay)
return (Room*)parent;
return nullptr; //Error
}
| true |
4a8a0f169fff9e6bbf72605f064c1c15a29c781b | C++ | kandouss/monospace | /science/cpp/monospace_math.cpp | UTF-8 | 1,834 | 2.8125 | 3 | [] | no_license | void Matrix2f::svd(Matrix2f* w, Vector2f* e, Matrix2f* v) const{
//If it is diagonal, SVD is trivial
if (fabs(data[0][1] - data[1][0]) < EPSILON && fabs(data[0][1]) < EPSILON){
w->setData(data[0][0] < 0 ? -1 : 1, 0, 0, data[1][1] < 0 ? -1 : 1);
e->setData(fabs(data[0][0]), fabs(data[1][1]));
v->loadIdentity();
}
//Otherwise, we need to compute A^T*A
else{
float j = data[0][0]*data[0][0] + data[0][1]*data[0][1],
k = data[1][0]*data[1][0] + data[1][1]*data[1][1],
v_c = data[0][0]*data[1][0] + data[0][1]*data[1][1];
//Check to see if A^T*A is diagonal
if (fabs(v_c) < EPSILON){
float s1 = sqrt(j),
s2 = fabs(j-k) < EPSILON ? s1 : sqrt(k);
e->setData(s1, s2);
v->loadIdentity();
w->setData(
data[0][0]/s1, data[1][0]/s2,
data[0][1]/s1, data[1][1]/s2
);
}
//Otherwise, solve quadratic for eigenvalues
else{
float jmk = j-k,
jpk = j+k,
root = sqrt(jmk*jmk + 4*v_c*v_c),
eig = (jpk+root)/2,
s1 = sqrt(eig),
s2 = fabs(root) < EPSILON ? s1 : sqrt((jpk-root)/2);
e->setData(s1, s2);
//Use eigenvectors of A^T*A as V
float v_s = eig-j,
len = sqrt(v_s*v_s + v_c*v_c);
v_c /= len;
v_s /= len;
v->setData(v_c, -v_s, v_s, v_c);
//Compute w matrix as Av/s
w->setData(
(data[0][0]*v_c + data[1][0]*v_s)/s1,
(data[1][0]*v_c - data[0][0]*v_s)/s2,
(data[0][1]*v_c + data[1][1]*v_s)/s1,
(data[1][1]*v_c - data[0][1]*v_s)/s2
);
}
}
}
| true |
e7c968b6acc535a0b886de9a64ce660ddd268c75 | C++ | a-cha/cpp_beginning | /mod08/ex01/main.cpp | UTF-8 | 2,090 | 3.203125 | 3 | [] | no_license |
#include "Span.hpp"
#include "print.hpp"
#include <list>
#include <vector>
#define INSERT_LEN 100000
int randNumberGenerator() { return rand() ; }
int main() {
srand(time(nullptr));
{
Span sp = Span(5);
try {
std::cout << GREEN BOLD "Sbj tests" STD << std::endl;
sp.addNumber(5);
sp.addNumber(3);
sp.addNumber(17);
sp.addNumber(9);
sp.addNumber(11);
sp.addNumber(15);
} catch (std::exception & exc) {
std::cout << RED << exc.what() << STD << std::endl;
}
std::cout << sp.shortestSpan() << std::endl;
std::cout << sp.longestSpan() << std::endl;
std::cout << std::endl;
}
{
std::cout << GREEN BOLD "Test constructors" STD << std::endl;
std::cout << BOLD "Default + addNumber" STD << std::endl;
Span span(5);
try {
span.addNumber(5231);
span.addNumber(10432);
span.addNumber(-12123);
span.addNumber(-12123);
span.addNumber(8);
} catch (std::exception &exc) {
std::cout << RED << exc.what() << STD << std::endl;
}
span.printSpan();
std::cout << BOLD "Assignation operator" STD << std::endl;
Span span1 = Span(1);
span1.printSpan();
try {
span1.longestSpan();
} catch (std::exception &exc) {
std::cout << RED << exc.what() << STD << std::endl;
}
std::cout << BOLD "Copy constructor" STD << std::endl;
Span span2(span);
span2.printSpan();
}
{
std::cout << std::endl << GREEN BOLD "Test insert" STD << std::endl;
try {
Span span(INSERT_LEN + 8);
span.addNumber(5);
span.addNumber(-20);
span.addNumber(15);
std::cout << "Span len before insert: " << span.getSize() << std::endl;
std::cout << "Inserting " << INSERT_LEN << " nodes..." << std::endl;
span.addNumber(INSERT_LEN, randNumberGenerator);
std::cout << "Span len after insert: " << span.getSize()
<< std::endl;
std::cout << "Shortest span: " << span.shortestSpan() << std::endl;
std::cout << "Longest span: " << span.longestSpan() << std::endl;
// span.printSpan();
} catch (std::exception &exc) {
std::cout << RED << exc.what() << STD << std::endl;
}
}
return 0;
}
| true |
d3e1201e805dfaab00a826ebf4178c08a2859929 | C++ | ankitsumitg/mrnd-c | /Step_6_New/spec/getSubstringSpec.cpp | UTF-8 | 2,728 | 3.0625 | 3 | [] | no_license | #include "stdafx.h"
#include "../src/getSubstring.cpp"
using namespace System;
using namespace System::Text;
using namespace System::Collections::Generic;
using namespace Microsoft::VisualStudio::TestTools::UnitTesting;
namespace spec
{
[TestClass]
public ref class getSubstringSpec
{
private:
TestContext^ testContextInstance;
public:
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
property Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ TestContext
{
Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ get()
{
return testContextInstance;
}
System::Void set(Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ value)
{
testContextInstance = value;
}
};
#pragma region Additional test attributes
#pragma endregion
[TestMethod, Timeout(1000)]
void TC1_SubString()
{
char str[] = "abcdefgh";
int i = 0;
int j = 2;
int k;
for (i = 0; i <= 1; i++){
for (j = 3; j < 7; j++){
char *new_str = get_sub_string(str, i, j);
if (i <= j){
for (k = i; k <= j; k++){
Assert::AreEqual(new_str[k - i], str[k], L"Error in NormalString", 1,2);
}
}
else{
if (new_str != NULL) {
Assert::AreEqual(1, 2, L"should be null for i > j", 1, 2);
}
}
}
}
}
[TestMethod, Timeout(1000)]
void TC2_SubString()
{
char *str = NULL;
char *new_str = get_sub_string(str, 0, 2); if (new_str != NULL) {
Assert::AreEqual(1, 2, L"should be null for nullstring", 1, 2);
}
}
[TestMethod, Timeout(1000)]
void TC3_SubString()
{
char str[] = "abcdefgh.,812639";
int i = 0;
int j = 2;
int k;
for (i = 0; i <= 8; i++){
for (j = 5; j < 12; j++){
char *new_str = get_sub_string(str, i, j);
if (i <= j){
for (k = i; k <= j; k++){
Assert::AreEqual(new_str[k - i], str[k], L"Error in NormalString", 1, 2);
}
}
else{
//Logger::WriteMessage("I > J ");
if (new_str != NULL) {
Assert::AreEqual(1,2, L"should be null for i > j", 1, 2);
}
}
}
}
}
[TestMethod, Timeout(1000)]
void TC4_SubString()
{
char str[] = "a jhas AB";
int i = 0;
int j = 2;
int k;
for (i = 0; i <= 1; i++){
for (j = 3; j < 7; j++){
char *new_str = get_sub_string(str, i, j);
if (i <= j){
for (k = i; k <= j; k++){
Assert::AreEqual(new_str[k - i], str[k], L"Error in NormalString", 1, 2);
}
}
else{
if (new_str != NULL) {
Assert::AreEqual(1, 2, L"should be null for i > j", 1, 2);
}
}
}
}
}
};
} | true |
6fe179182475bdac50f4554cea827d85b37e2165 | C++ | slerbalenkki/koulu_1 | /Binaarilaskuri_A/Binaarilaskuri_A.ino | UTF-8 | 1,669 | 2.734375 | 3 | [] | no_license | #define LED1 13
#define LED2 12
#define LED3 11
#define LED4 10
#define LEDON HIGH
#define LEDOFF LOW
#define viive 1000
void setup() {
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);
Serial.begin(9600);
}
void turnOn(int led){
digitalWrite(led, LEDON);
}
void turnOff(int led){
digitalWrite(led, LEDOFF);
}
void nolla (){
turnOff (LED1);
turnOff (LED2);
turnOff (LED3);
turnOff (LED4);
}
void yksi(){
turnOn (LED1);
turnOff (LED2);
turnOff (LED3);
turnOff (LED4);
}
void kaksi(){
turnOff (LED1);
turnOn (LED2);
turnOff (LED3);
turnOff (LED4);
}
void kolme(){
turnOn (LED1);
turnOn (LED2);
turnOff (LED3);
turnOff (LED4);
}
void nelja(){
turnOff (LED1);
turnOff (LED2);
turnOn (LED3);
turnOff (LED4);
}
void viisi(){
turnOn (LED1);
turnOff (LED2);
turnOn (LED3);
turnOff (LED4);
}
void kuusi(){
turnOff (LED1);
turnOn (LED2);
turnOn (LED3);
turnOff (LED4);
}
void seiska(){
turnOn (LED1);
turnOn (LED2);
turnOn (LED3);
turnOff (LED4);
}
void kasi(){
turnOff (LED1);
turnOff (LED2);
turnOff (LED3);
turnOn (LED4);
}
void ysi(){
turnOn (LED1);
turnOff (LED2);
turnOff (LED3);
turnOn (LED4);
}
void kymppi() {
turnOn (LED1);
turnOn (LED2);
turnOn (LED3);
turnOn (LED4);
}
void loop() {
nolla();
delay(viive);
yksi();
delay(viive);
kaksi();
delay(viive);
kolme();
delay(viive);
nelja();
delay(viive);
viisi();
delay(viive);
kuusi();
delay(viive);
seiska();
delay(viive);
kasi();
delay(viive);
ysi();
delay(viive);
kymppi();
delay(viive);
}
| true |
85295e620f2c383a4366a74cda019836726e6f05 | C++ | kurobaron/AtCoder | /cpp/practice/abc132c.cpp | UTF-8 | 246 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int n,i;
cin >> n;
vector<int> d(n);
for(i=0;i<n;++i) cin >> d.at(i);
sort(d.begin(),d.end());
cout << d.at(n/2)-d.at(n/2-1) << endl;
return 0;
}
| true |
056f3cecea10d74f47882fde6f5d66038b55a896 | C++ | xclusive43/c-pragramming | /pointer.cpp | UTF-8 | 191 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | #include<stdio.h>
int main()
{ int a=12;
int *s;
s=&a;
printf("s=%d\n",s);
s=s+1;
printf("s=%d\n", s);
float c=3.1;
float *b;
b=&c;
*b=3.10;
printf("c=%f\n", c);
}
| true |
424f771543008c7d144272788c02399a4d1c0d53 | C++ | HyunWoooo/Tiger | /호색전/The Golem/menu.cpp | UTF-8 | 1,378 | 2.53125 | 3 | [] | no_license | #include "stdafx.h"
#include "menu.h"
CMenu::CMenu()
{
SelectNum = 1;
WorldNum = 0;
}
void CMenu::Init(CTexture Texture, CTexture Texture2, D3DXVECTOR3 vPos, D3DXVECTOR3 vPos2)
{
m_DxSprite = new CSprite;
m_DxSprite->Create(CDevice::GetSprite());
m_Texture = Texture;
m_Texture2 = Texture2;
m_vPos = vPos;
m_vPos2 = vPos2;
m_rect.left = 0;
m_rect.top = 0;
m_rect.right = 200;
m_rect.bottom = 100;
m_rect2.left = 0;
m_rect2.top = 0;
m_rect2.right = 1024;
m_rect2.bottom = 768;
}
void CMenu::Render(int left, int top, int right, int bottom, D3DXVECTOR3 vPos)
{
m_rect.left = left;
m_rect.top = top;
m_rect.right = right;
m_rect.bottom = bottom;
m_vPos = vPos;
D3DCOLOR color;
color = D3DCOLOR_ARGB(255,255,255,255);
m_DxSprite->Draw(m_Texture.GetTexture(), &m_rect, NULL, NULL, 0, &m_vPos, color);
}
void CMenu::B_Render()
{
D3DCOLOR color;
color = D3DCOLOR_ARGB(255,255,255,255);
m_DxSprite->Draw(m_Texture2.GetTexture(), &m_rect2, NULL, NULL, 0, &m_vPos2, color);
}
void CMenu::Check()
{
WorldNum = 0;
}
void CMenu::KeyDown()
{
if((GetAsyncKeyState(VK_DOWN) & 0x8000) && SelectNum == 1)
SelectNum++;
if((GetAsyncKeyState(VK_UP) & 0x8000) && SelectNum == 2)
SelectNum--;
if(GetAsyncKeyState('Z') & 0x8000)
{
switch(SelectNum) {
case 1:
WorldNum = 1;
break;
case 2:
PostQuitMessage(0);
break;
}
}
} | true |
300b6b902b3cd85f6d2996b50d6a9f4f6985d315 | C++ | OndraSlama/Strategy_simlation-old | /StrategyGUI_Simulator/StrategyC.cpp | UTF-8 | 5,715 | 2.734375 | 3 | [] | no_license | #include "StrategyC.h"
StrategyC::StrategyC()
{
mode = defense;
cameraTolerance = 0.7;
kickAreaLength = 350;
kickAreaWidth = 200;
kickAreaStart = 300;
kickYSpeedLimit = 5;
kickXSpeedLimit = 20;
advanceFactor = 50;
}
StrategyC::~StrategyC()
{
}
void StrategyC::Process()
{
cyclesSinceLastCameraInput++;
if (ball.state == known) {
if (ball.vector.X > 0) { // ball is heading to opponent goal
mode = attack;
}
else{ // ball is heading to own goal
mode = defense;
}
}
Defend(); // Performs defending action
Attack(); // Performs attack
Block(); // Block if infront of opponent with ball
GoalKeeper(); // Special behaviour for goal keeper
Forward(); // Special behaviour for forwarder
CalculateDesiredAxisPositions(); // Calculate where the axis should move based on desired positions of dummies
}
void StrategyC::Defend() {
if (mode == defense && ball.state == known) {
PyramidDefence();
}
else {
for (int i = 0; i < 4; i++) {
NormalDefence(i);
}
}
}
void StrategyC::Attack() {
for (int i = 1; i < 4; i++) { // every axis except goalkeeper
if (ball.vector.X > 0 && ball.center.X < axes[i].X){
RaisedAttack(i);
}else if (ball.state == unknown && ball.center.X - ball.radius < axes[i].X) {
RaisedAttack(i);
}
Kick(i);
}
}
void StrategyC::Block(){
if (ball.state == unknown) {
for (int i = 1; i < 4; i++) {
BlockOpponent(i);
}
}
}
void StrategyC::GoalKeeper() {
if (ball.center.X < axes[0].X) {
GetBehindBall(0);
}
Kick(0);
}
void StrategyC::Forward() {
int axis = 2;
if(ball.center.X < axes[axis].X + axes[axis].xDisplacement)
return;
if (ball.speed > kickXSpeedLimit)
return;
if(!BallInArea(axis, 1.5))
return;
axes[axis].mode = forwardShoot;
mode = attack;
}
bool StrategyC::BallInArea(int i, float scale){
// check if in area of kick
if (ball.center.X > axes[i].X + scale*kickAreaLength)
return false;
if (ball.center.X < axes[i].X - kickAreaStart)
return false;
// check for individual dummy
for (int j = 0; j < axes[i].dummies.size(); j++) {
if (abs(axes[i].dummies[j].realPos - ball.center.Y) < scale * kickAreaWidth) {
return true;
}
}
return false;
}
void StrategyC::PyramidDefence() {
int pyrLayer = 0;
for (int i = 3; i >= 0; i--) // from forwards to goalkeeper
{
int y = axes[i].intersectionY;
int sign = Sign(y);
axes[i].desiredIntercept = ball.center.Y;
if (ball.center.X > axes[i].X && y != -10000) // If ball is in front of axis and the direction is overlapping with the axis
{
switch (pyrLayer)
{
case 0:
axes[i].desiredIntercept = y;
break;
case 1:
axes[i].desiredIntercept = y - sign * DummyY;
break;
case 2:
axes[i].desiredIntercept = y + sign * DummyY;
break;
case 3:
axes[i].desiredIntercept = y - 2 * sign *DummyY;
break;
default:
break;
}
pyrLayer++;
axes[i].mode = forwardDefense;
}
}
}
void StrategyC::NormalDefence(int i) {
axes[i].desiredIntercept = ball.center.Y;
if (ball.center.X > axes[i].X + (axes[i].xDisplacement < -kickAreaStart ? -kickAreaStart : axes[i].xDisplacement)) {
axes[i].mode = forwardDefense;
}
else {
axes[i].mode = backwardDefense;
}
if (ball.state == unknown) {
axes[i].mode = straight;
}
if (abs(ball.vector.Y * ball.speed) > kickYSpeedLimit) {
axes[i].desiredIntercept = ball.center.Y + Sign(ball.vector.Y) * ball.speed * advanceFactor;
}
}
void StrategyC::RaisedAttack(int i) {
if(!BallInArea(i, 1)){
axes[i].mode = raised;
}
int y;
int sign = Sign(ball.center.Y);
if (ball.state == known && mode == attack) {
y = axes[i].intersectionY;
}
else {
y = ball.center.Y;
}
// to avoid blocking view of the ball
axes[i].desiredIntercept = y + 2 * sign * ball.radius;
if (ball.center.X > axes[i].X + (axes[i].xDisplacement < -kickAreaStart ? -kickAreaStart : axes[i].xDisplacement)) {
axes[i].desiredIntercept = ball.center.Y + Sign(ball.vector.Y) * ball.speed * advanceFactor;
}
}
void StrategyC::Kick(int i){
// check speed limits
if (abs(ball.speed * ball.vector.Y) > kickYSpeedLimit || abs(ball.speed * ball.vector.X) > kickXSpeedLimit)
return;
if(ball.center.X < axes[i].X + axes[i].xDisplacement)
return;
if(!BallInArea(i, 1))
return;
axes[i].mode = forwardShoot;
mode = attack;
}
void StrategyC::BlockOpponent(int i) {
if (abs(ball.center.X - opponentAxes[i].X) > kickAreaLength) {
return;
}
// check for individual dummy
int gap = abs(opponentAxes[i].dummies[0].realPos - opponentAxes[i].dummies[1].realPos);
for (int j = 0; j < opponentAxes[i].dummies.size(); j++) {
if (abs(opponentAxes[i].dummies[j].realPos - ball.center.Y) <= gap/2) {
axes[4 - i].desiredIntercept = opponentAxes[i].dummies[j].realPos;
axes[4 - i].mode = forwardDefense;
break;
}
}
}
void StrategyC::GetBehindBall(int i) {
axes[i].mode = exactAngle;
if (ball.center.X < axes[i].X + axes[i].xDisplacement) {
axes[i].desiredIntercept = ball.center.Y - 3 * Sign(ball.center.Y) * ball.radius;
axes[i].mode = straight;
if (abs(axes[i].dummies[0].realPos - ball.center.Y) > 2 * ball.radius) {
axes[i].mode = exactAngle;
axes[i].desiredAngle < -270 ? axes[i].desiredAngle = -270 : axes[i].desiredAngle -= 30;
}
}
if (ball.center.X > axes[i].X + axes[i].xDisplacement) {
axes[i].desiredIntercept = ball.center.Y;
}
if (ball.center.X > axes[i].X) {
axes[i].desiredAngle = 0;
}
}
void StrategyC::BackwardKick(int i) {
/*axes[index].mode = backwardShoot;
for (int i = index + 1; i < 4; i++) {
axes[i].mode = raised;
}*/
}
int StrategyC::Sign(double arg) {
if (arg > 0) return 1;
if (arg < 0) return -1;
return 0;
}
| true |
7e156d7c5664367cb53721acc3235a97eb7e75e9 | C++ | bmegli/footprint-collision-checker | /examples/simple_example.cpp | UTF-8 | 1,913 | 2.859375 | 3 | [] | no_license | // Copyright (c) 2021 Bartosz Meglicki <meglickib@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <iostream>
#include "../footprint_collision_checker.hpp"
class MapMock
{
public:
bool worldToMap(double wx, double wy, unsigned int &mx, unsigned int &my)
{
mx = wx;
my = wy;
return true;
}
double getCost(int x, int y)
{
if(x < 0)
return 0;
return 100;
}
static constexpr double OCCUPIED = 254;
};
struct PointMock
{
double x;
double y;
};
using namespace fcc;
using namespace std;
int main(int argc, char **argv)
{
MapMock *map = new MapMock();
FootprintCollisionChecker<MapMock, PointMock> checker(map);
//initialize some footprint, just a vector<PointMock> here
FootprintCollisionChecker<MapMock, PointMock>::Footprint footprint;
footprint.push_back( {-1, -1} );
footprint.push_back( {1, -1} );
footprint.push_back( {1, 1});
footprint.push_back( {-1, 1} );
cout << "footprint (in the middle) cost " << checker.footprintCost(footprint) << endl;
cout << "footprint (on the left) cost " << checker.footprintCostAtPose(-5, 0, 0, footprint) << endl;
cout << "footprint (on the right) cost " << checker.footprintCostAtPose(55, 0, 0, footprint) << endl;
cout << "line (-1,-1) -> (1,1) cost " << checker.lineCost(-1, 1, -1, 1) << endl;
unsigned int x,y;
checker.worldToMap(0, 0, x, y);
//set new map
checker.setCostmap(map);
delete map;
return 0;
}
| true |
05cdc0f76fc5c8aac7b7dbe740f45a2e346de9ec | C++ | llyr-who/MassStiff | /Matrix.cpp | UTF-8 | 4,564 | 3.15625 | 3 | [] | no_license | #include<iostream>
#include "Vector.hpp"
#include"Matrix.hpp"
Matrix::Matrix(int rows, int cols)
{
mRows = rows;
mCols = cols;
mData = new double[rows*cols];
for(int i=0; i <mRows;i++)
{
for(int j=0;j<mCols;j++)
{
mData[j*mRows+i] = 0;
}
}
}
Matrix::Matrix(const Matrix&m1)
{
mRows = m1.mRows;
mCols = m1.mCols;
mData = new double[mRows*mCols];
for(int i = 0; i<mRows;i++)
{
for(int j = 0; j<mCols;j++)
{
mData[j*mRows+i] = m1(i,j);
}
}
}
Matrix::~Matrix()
{
delete[] mData;
}
Matrix operator*( const Matrix &A,const Matrix &B)
{
if(A.mCols != B.mRows)
{
throw Exception("index mismatch","the number of collums in the first matrix needs to equal the number of rows in the second");
}
Matrix result(A.mRows,B.mCols);
for(int i = 0; i<A.mRows;i++)
{
for (int j = 0; j<B.mCols;j++)
{
double entry = 0;
for(int k = 0; k < A.mCols;k++)
{
entry += A(i,k)*B(k,j);
}
result(i,j) = entry;
}
}
return result;
}
Vector operator*( const Matrix &A,const Vector &b)
{
Vector result(A.mRows);
for(int i = 0; i<A.mRows;i++)
{
double entry = 0;
for (int j = 0; j<A.mCols;j++)
{
entry += A(i,j)*b(j);
}
result(i) = entry;
}
return result;
}
Matrix operator*( const double &a,const Matrix &A)
{
Matrix result(A.mRows,A.mCols);
for(int i = 0; i<A.mRows;i++)
{
for (int j = 0; j<A.mCols;j++)
{
result(i,j) = A(i,j)*a;
}
}
return result;
}
Matrix operator+(const Matrix& A, const Matrix& B)
{
//need to check size.
Matrix result(A.mRows,A.mCols);
for(int i = 0; i<A.mRows;i++)
{
for (int j = 0; j<A.mCols;j++)
{
result(i,j) = A(i,j) + B(i,j);
}
}
return result;
}
Vector operator/(const Vector &b, const Matrix &A)
{
//Call Guassian Elimination (return LU)
if(A.mCols != A.mRows)
{
throw Exception("index mismatch","non-square matrix");
}
//This will solve the matrix using guasian ellimination with partial pivoting
int m = A.mCols;
Matrix U=A,L = eye(m),P=eye(m);
for(int k =0; k < m-1;k++)
{
//select i to max u{ik}
int i = 0;
double max = 0;
for(int l = 0; l < m;l++)
{
if(U(l,k) > max){i=l;max = U(l,k);}
}
U.interchangeRows(i,k,k,m);
L.interchangeRows(k,i,0,k-1);
P.interchangeRows(i,k,0,m);
for(int j =k+1; j < m;j++)
{
L(j,k) = U(j,k)/U(k,k);
for(int s = k; s<m;s++)
{
U(j,s) = U(j,s) - L(j,k)*U(k,s);
}
}
}
Vector bb = P*b;
Vector y(m),x(m);
//Call forward substitution (returns vector) to solve "Ly=bb"
y(0) = bb(0)/L(0,0);
for(int j = 1;j<m;j++)
{
double SUM = 0;
for(int k = 0;k<j;k++)
{
SUM += y(k)*L(j,k);
}
y(j) = (bb(j)-SUM)/L(j,j);
}
// Call backward substitution Ux = y
x(m-1) = y(m-1)/U(m-1,m-1);
for(int j = m-1;j > -1;j--)
{
double SUM = 0;
for(int k = j+1;k<m;k++)
{
SUM += x(k)*U(j,k);
}
x(j) = (y(j)-SUM)/U(j,j);
}
return x;
}
std::ostream& operator<<(std::ostream& os, const Matrix& M)
{
for(int i = 0; i < M.mRows; i++)
{
for(int j =0; j < M.mCols;j++)
{
os << M(i,j) << " ";
}
os << std::endl;
}
return os;
}
Matrix& Matrix::operator=(const Matrix& M)
{
for(int i = 0; i < mRows;i++)
{
for(int j = 0;j<mCols;j++)
{
mData[j*mRows + i] = M(i,j);
}
}
return *this;
}
double& Matrix::operator()(int i, int j) const
{
return mData[i+j*mRows];
}
void Matrix::interchangeRows(int i,int j,int I, int J)
{
double temp[mCols];
for(int k =I; k< J;k++)
{
temp[k]= mData[k*mRows + i];
mData[k*mRows + i] = mData[k*mRows + j];
mData[k*mRows+j] = temp[k];
}
}
Matrix Matrix::transpose()
{
Matrix At(mCols,mRows);
for(int i =0;i<mRows;i++)
{
for(int j=0;j<mCols;j++)
{
At.mData[i*mCols +j] = mData[j*mRows+i];
}
}
return At;
}
void Matrix::print()
{
for(int i =0;i<mRows;i++)
{
for(int j=0;j<mCols;j++)
{
std::cout << mData[j*mRows + i] << " ";
}
std::cout << std::endl;
}
}
Vector Matrix::size()
{
Vector sz(2);
sz(0)=mRows;
sz(1)=mCols;
return sz;
}
void Matrix::setMatrix(Matrix A)
{
mCols = A.mCols;
mRows = A.mRows;
mData = new double[mCols*mRows];
for(int i =0;i<mRows;i++)
{
for(int j=0;j<mCols;j++)
{
mData[j*mRows+i]=A.mData[j*mRows+i];
}
}
}
Matrix eye(int n)
{
Matrix a(n,n);
for(int i = 0;i<n;i++)
{
a(i,i)=1.0;
}
return a;
}
Matrix ones(int n)
{
Matrix a(n,n);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
a(i,j) = 1.0;
return a;
}
| true |
0831d4a5dac11ba2273f66d6780f62a462ac9fca | C++ | dineshkwal/DS-algo-codes | /DisjointSet.cpp | UTF-8 | 1,320 | 3.546875 | 4 | [
"MIT"
] | permissive | #include <unordered_map>
#include <vector>
class DisjointSet
{
public:
// nodes from 1 to N
DisjointSet(int N)
{
for (int i = 1; i <= N; ++i)
{
parent[i] = i;
rank[i] = 0;
size[i] = 1;
}
}
// nodes as given in vector
DisjointSet(const std::vector<int>& v)
{
for (auto i : v)
{
parent[i] = i;
rank[i] = 0;
size[i] = 1;
}
}
void Find(int i)
{
if (parent[i] != i)
{
parent[i] = Find(parent[i]);
}
return parent[i];
}
void UnionByRank(int i, int j)
{
const int pi = Find(i);
const int pj = Find(j);
if (pi == pj)
{
return; // already part of same set
}
const int ri = rank[pi];
const int rj = rank[pj];
if (ri == rj)
{
parent[pi] = pj;
rank[pj]++;
}
else if (ri < rj)
{
parent[pi] = pj;
}
else
{
parent[pj] = pi;
}
}
void UnionBySize(int i, int j)
{
const int pi = Find(i);
const int pj = Find(j);
if (pi == pj)
{
return; // already part of same set
}
const int si = size[pi];
const int sj = size[pj];
if (si <= sj)
{
parent[pi] = pj;
size[pj] += size[pi];
}
else
{
parent[pj] = pi;
size[pi] += size[pj];
}
}
private:
std::unordered_map<int, int> parent;
// use either union by rank or size
std::unordered_map<int, int> rank;
std::unordered_map<int, int> size;
};
| true |
9d0883b8945b8603902954df3b46b808c68d6c00 | C++ | MrFunBarn/Assignments | /Assignment11/Assignment11.cpp | UTF-8 | 2,093 | 3.5 | 4 | [] | no_license | /*
* Brandon Bell
* Assignment10
* Recitation: Th 1030am
* Guogui Ding
*/
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include "Graph.h"
using namespace std;
// The basic structure of this main function was taken from my assignments 5.
int main(int argc, char *argv[]){
// instantiate Graph instance, and menu selection variables.
Graph zombies(argv[1]);
int option = 0;
// The main loop. runs until quit is selected.
while( option != 6 ){
// Print the main menu.
cout<<"======Main Menu======"<< endl
<<"1. Print vertices"<< endl
<<"2. Find districts"<< endl
<<"3. Find shortest path"<< endl
<<"4. Find shortest distance"<<endl
<<"5. Road trip"<<endl
<<"6. Quit"<< endl;
// Grab the option and convert to int with stringstream.
string s;
// this get line prevents a stray \n from hanging around messing up
// latter getline calls.
getline( cin, s );
stringstream ss(s);
ss >> option;
// Processes option and apply the relevent method.
if( option == 1 ){
zombies.displayEdges();
}
else if( option == 2 ){
zombies.assignDistricts();
}
else if( option == 3 ){
string start;
string end;
cout<<"Enter a starting city:"<<endl;
getline( cin, start );
cout<<"Enter an ending city:"<<endl;
getline( cin, end );
zombies.shortestPath(start, end, false);
}
else if( option == 4 ){
string start;
string end;
cout<<"Enter a starting city:"<<endl;
getline( cin, start );
cout<<"Enter an ending city:"<<endl;
getline( cin, end );
zombies.shortestPath(start, end, true);
}
else if( option == 5 ){
zombies.roadTrip();
}
else if( option == 6 ){
cout << "Goodbye!" << endl;
}
}
return 0;
}
| true |
c1d82d1a11c88053a3aa23608532304a8b038765 | C++ | NimishaGarg/competitive-programming | /algos/seg_tree(my variant).cpp | UTF-8 | 1,392 | 3.078125 | 3 | [] | no_license | // call build in main function with v = 1, l = 0, r = n - 1
const int N = 2e5 + 100;
struct data{
int val;
int lev;
};
data seg_tree[4*N];
int arr[N], n, q;
data combine(data l, data r){
data res;
if(l.lev == 0){
res.val = l.val|r.val;
res.lev = 1;
}
else{
res.val = l.val^r.val;
res.lev = 0;
}
return res;
}
void build(int v, int l, int r){
if(l == r){
// base case
seg_tree[v].val = arr[l];
seg_tree[v].lev = 0;
return;
}
int m = (l + r) / 2;
build(2*v, l, m);
build(2*v + 1, m + 1, r);
seg_tree[v] = combine(seg_tree[2*v], seg_tree[2*v + 1]);
return;
}
void update(int v, int l, int r, int pos, int new_val){
if(l == r){
seg_tree[v].val = new_val;
return;
}
int m = (l + r) / 2;
if(pos <= m){
update(2*v, l, m, pos, new_val);
}
else{
update(2*v + 1, m + 1, r, pos, new_val);
}
seg_tree[v] = combine(seg_tree[2*v], seg_tree[2*v + 1]);
}
data query(int v, int l, int r, int ql, int qr){
if(ql > qr){
data ans;
ans.val = 0;
ans.lev = seg_tree[v].lev;
return ans;
}
if(ql == l and qr == r){
return seg_tree[v];
}
int m = (l + r) / 2;
return combine(query(2*v, l, m, ql, min(qr, m)), query(2*v + 1, m + 1, r, max(ql, m + 1), qr));
}
| true |
ffc8418b70547748865e1f458f342eadd241ac2e | C++ | coin-or/Gravity | /thirdparty/mp/rstparser.h | UTF-8 | 2,941 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | /*
A reStructuredText parser written in C++.
Copyright (c) 2013, Victor Zverovich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RSTPARSER_H_
#define RSTPARSER_H_
#include <memory>
#include <string>
#include <vector>
namespace rst {
enum BlockType {
PARAGRAPH,
LINE_BLOCK,
BLOCK_QUOTE,
BULLET_LIST,
LIST_ITEM,
LITERAL_BLOCK
};
// Receive notification of the logical content of a document.
class ContentHandler {
public:
virtual ~ContentHandler();
// Receives notification of the beginning of a text block.
virtual void StartBlock(BlockType type) = 0;
// Receives notification of the end of a text block.
virtual void EndBlock() = 0;
// Receives notification of text.
virtual void HandleText(const char *text, std::size_t size) = 0;
// Receives notification of a directive.
virtual void HandleDirective(const char *type) = 0;
};
// A parser for a subset of reStructuredText.
class Parser {
private:
ContentHandler *handler_;
const char *ptr_;
// Skips whitespace.
void SkipSpace();
// Parses a directive type.
std::string ParseDirectiveType();
// Parses a paragraph.
void ParseParagraph();
// Changes the current block type sending notifications if necessary.
void EnterBlock(rst::BlockType &prev_type, rst::BlockType type);
// Parses a block of text.
void ParseBlock(rst::BlockType type, rst::BlockType &prev_type, int indent);
// Parses a line block.
void ParseLineBlock(rst::BlockType &prev_type, int indent);
public:
explicit Parser(ContentHandler *h) : handler_(h), ptr_(0) {}
// Parses a string containing reStructuredText and returns a document node.
void Parse(const char *s);
};
}
#endif // RSTPARSER_H_
| true |
cf27f591fe4fb1b47d675e51cb9e68a658554153 | C++ | PaytonWu/LeetCode | /Remove Duplicates from Sorted Array.cpp | UTF-8 | 1,390 | 3.078125 | 3 | [] | no_license | // Remove Duplicates from Sorted Array.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
class Solution {
public:
int removeDuplicates(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n <= 1)
{
return n;
}
int i = 0;
for (; i < n; ++i)
{
int j = i + 1;
int gap = j - i;
for (; j < n; ++j)
{
if (A[i] == A[j])
{
continue;
}
gap = j - i;
if (gap == 1)
{
break;
}
// move elements forward...
for (; j < n; ++j)
{
A[j - gap + 1] = A[j];
}
// narrow the upper bound after eniminateing the duplicates.
n -= gap - 1;
}
// special case: duplicates appear at the tail of the array.
if (j == n)
{
break;
}
}
// i is the index of last unique element, thus returns plus one.
return i+1;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
| true |
e7af4038074901defe657ed9e330b22f7c66a939 | C++ | phuduong85/yangsj | /code/cocos/Classes/app/astar/Astar.cpp | UTF-8 | 6,905 | 2.796875 | 3 | [] | no_license | //
// Astar.cpp
// snake222
//
// Created by yangsj on 14-3-26.
//
//
#include "Astar.h"
Astar::Astar()
{
}
Astar::~Astar()
{
VecAstarItemMap::iterator iter = mapAry.begin();
while (iter != mapAry.end())
{
VecAstarItem items = *iter;
VecAstarItem::iterator iter1 = items.begin();
while (iter1 != items.end())
{
delete *iter1;
iter1++;
}
iter++;
}
}
void Astar::initMapList(VecMap args)
{
int x = 0;
int y = 0;
if ( args.empty())
{
return ;
}
lengx = args.size();
lengy = args[0].size();
mapAry.clear();
CCLog("???????????????????????????????????????");
for ( VecMap::iterator iter = args.begin(); iter != args.end(); ++iter )
{
VecChild tempChild = *iter;
VecAstarItem tempItems;
for ( VecChild::iterator iter2 = tempChild.begin(); iter2 != tempChild.end(); ++iter2)
{
int val = (int)*iter2;
AstarNodeItem* item = new AstarNodeItem();
item->isBlock = val == 0;
item->isCan = val != 0;
item->x = x;
item->y = y++;
tempItems.push_back(item);
CCLog("Astar [ x=%d , y=%d] num = %d", item->x, item->y, val);
}
y = 0;
x++;
mapAry.push_back(tempItems);
}
}
VecAstarPoint Astar::find(AstarNodePoint* sPoint, AstarNodePoint* ePoint)
{
initSets();
startPos = sPoint;
endPos = ePoint;
CCLog("start point (x = % d , y = %d) ______ end point (x = % d , y = %d)", startPos->x, startPos->y, endPos->x, endPos->y);
// if (sPoint->x != ePoint->x && sPoint->y != ePoint->y)
// {
loop();
// }
return getResult();
}
void Astar::initSets()
{
openAry.clear();
closeAry.clear();
curItem = NULL;
endItem = NULL;
}
void Astar::loop()
{
AstarNodeItem* item = getAstarItem(startPos->x, startPos->y);
while ( item && toFind(item->x, item->y) == false)
{
if ( openAry.empty() == false )
{
item = openAry.back();
openAry.pop_back();
}
else
{
return ;
}
}
}
VecAstarPoint Astar::getResult()
{
VecAstarPoint temp;
if ( endItem )
{
temp.push_back(new AstarNodePoint(endItem->x, endItem->y));
AstarNodeItem* item = endItem->parentNode;
while ( item )
{
temp.push_back( new AstarNodePoint( item->x, item->y ));
item = item->parentNode;
}
clearCheckMark();
}
else
{
temp.push_back(new AstarNodePoint(startPos->x, startPos->y));
}
return temp;
}
AstarNodeItem* Astar::getAstarItem(int x, int y)
{
if ( x >= 0 && x < lengx && y >= 0 && y < lengy)
{
return mapAry[x][y];
}
return NULL;
}
bool Astar::toFind(int x, int y)
{
AstarNodeItem* item = getAstarItem(x, y);
if (item )
{
if ( closeAry.empty() )
{
item->parentNode = NULL;
}
curItem = item;
closeAry.push_back(item);
return check(item);
}
else
{
return true;
}
}
bool Astar::check(AstarNodeItem *item)
{
int itemx = item->x;
int itemy = item->y;
int x, y;
bool canLeft = false;
bool canRight = false;
bool canUp = false;
bool canDown = false;
CCLog("checking x = %d , y = %d", itemx, itemy);
// 中左
x = itemx - 1;
y = itemy;
item = getAstarItem( x, y );
canLeft = item && item->isCan;
if ( addToOpenAry( item, 10 ))
return true;
// 中右
x = itemx + 1;
item = getAstarItem( x, y );
canRight = item && item->isCan;
if ( addToOpenAry( item, 10 ))
return true;
// 中上
x = itemx;
y = itemy - 1;
item = getAstarItem( x, y );
canUp = item && item->isCan;
if ( addToOpenAry( item, 10 ))
return true;
// 中下
y = itemy + 1;
item = getAstarItem( x, y );
canDown = item && item->isCan;
if ( addToOpenAry( item, 10 ))
return true;
// 左上
x = itemx - 1;
if ( canLeft && canUp )
{
y = itemy - 1;
item = getAstarItem( x, y );
if ( addToOpenAry( item, 14 ))
return true;
}
// 左下
if ( canLeft && canDown )
{
y = itemy + 1;
item = getAstarItem( x, y );
if ( addToOpenAry( item, 14 ))
return true;
}
x = itemx + 1;
// 右上
if ( canRight && canUp )
{
y = itemy - 1;
item = getAstarItem( x, y );
if ( addToOpenAry( item, 14 ))
return true;
}
// 右下
if ( canRight && canDown )
{
y = itemy + 1;
item = getAstarItem( x, y );
if ( addToOpenAry( item, 14 ))
return true;
}
return openAry.empty();
}
bool Astar::addToOpenAry(AstarNodeItem *item, int g)
{
if ( item && item->isCan && !checkInCloseAry(item) && !checkInOpenAry(item))
{
int endx = endPos->x;
int endy = endPos->y;
int h = 10 * ( abs(endx - item->x) + abs(endy - item->y));
int temp_g = curItem->g + g;
int temp_f = temp_g + h;
if ( item->parentNode == NULL || temp_f < item->f )
{
item->h = h;
item->g = temp_g;
item->f = temp_f;
item->parentNode = curItem;
}
if ( h == 0)
{
endItem = item;
return true;
}
openAry.push_back(item);
openAryMinToFirst();
}
return false;
}
bool sortFunForOpenAry(AstarNodeItem* a, AstarNodeItem* b)
{
return a->f >= b->f;
}
void Astar::openAryMinToFirst()
{
std::sort(openAry.begin(), openAry.end(), sortFunForOpenAry);
}
bool Astar::checkInCloseAry(AstarNodeItem *item)
{
for ( VecAstarItem::iterator iter = closeAry.begin(); iter != closeAry.end(); ++iter )
{
AstarNodeItem* temp = *iter;
if ( temp->x == item->x && temp->y == item->y )
{
return true;
}
}
return false;
}
bool Astar::checkInOpenAry(AstarNodeItem *item)
{
for ( VecAstarItem::iterator iter = openAry.begin(); iter != openAry.end(); ++iter )
{
AstarNodeItem* temp = *iter;
if ( temp->x == item->x && temp->y == item->y )
{
return true;
}
}
return false;
}
void Astar::clearCheckMark()
{
for (VecAstarItemMap::iterator iter = mapAry.begin(); iter != mapAry.end(); ++iter)
{
VecAstarItem temp = *iter;
for (VecAstarItem::iterator iter2 = temp.begin(); iter2 != temp.end(); ++iter2)
{
AstarNodeItem* item = *iter2;
if ( item ) item->parentNode = NULL;
}
}
}
| true |
7e631575eb93286a9054ce5be75e9ec335865340 | C++ | KimJeaIn/KirbyGame | /KirbyProject/GameDev/Callable.hpp | UTF-8 | 534 | 3.15625 | 3 | [] | no_license | #pragma once
template<typename ReturnType, typename Cls, typename FunctionPointer>
struct Callable
{
typedef FunctionPointer action_type;
Callable(FunctionPointer fp):act(fp){}
template<typename Derived,
typename Arg1,
typename Arg2,
typename Arg3,
typename Arg4>
ReturnType operator ()(Derived* obj, Arg1 a1, Arg2 a2, Arg3 a3, Arg4 a4)
{
return (get_pointer(obj)->*act)(a1,a2,a3,a4);
}
template<typename Derived>
Cls* get_pointer(Derived* obj)
{
return dynamic_cast<Cls*>(obj);
}
FunctionPointer act;
}; | true |
3376128542c360324b61d82def62536839b8fc3b | C++ | kankanla/Cjiajia | /p220---stack_c/stack_e1.cpp | UTF-8 | 3,197 | 4.03125 | 4 | [] | no_license | /********************************************************
* Stack *
* A file implementing a simple stack class *
********************************************************/
#include <cstdlib>
#include <iostream>
#include <assert.h>
const int STACK_SIZE = 100; // Maximum size of a stack
/********************************************************
* bound_err -- a class used to handle out of bounds *
* execeptions. *
********************************************************/
class bound_err {
public:
const string what; // What caused the error
// Initialize the bound error with a message
bound_err(const string& i_what) what(i_what) {}
// Assignment operator defaults
// bound_err(bound_err) -- default copy constructor
// ~ bound_err -- default destructor
};
/********************************************************
* Stack class *
* *
* Member functions *
* init -- initialize the stack. *
* push -- put an item on the stack. *
* pop -- remove an item from the stack. *
********************************************************/
// The stack itself
class stack {
private:
int count; // Number of items in the stack
int data[STACK_SIZE]; // The items themselves
public:
// Initialize the stack
stack(): count(0) {};
// Copy constructor defaults
// Assignment operator defaults
// Push an item on the stack
void push(const int item) throw(bound_err);
// Pop an item from the stack
int pop() throw(bound_err);
};
/********************************************************
* stack::push -- push an item on the stack. *
* *
* Warning: We do not check for overflow. *
* *
* Parameters *
* item -- item to put in the stack *
********************************************************/
inline void stack::push(const int item) throw(bound_err)
{
if ((count < 0) &&
(count >= sizeof(data)/sizeof(data[0]))) {
throw("Push overflows stack");
}
data[count] = item;
++count;
}
/********************************************************
* stack::pop -- get an item off the stack. *
* *
* Warning: We do not check for stack underflow. *
* *
* Returns *
* The top item from the stack. *
********************************************************/
inline int stack::pop() throw(bound_err)
{
// Stack goes down by one
--count;
if ((count < 0) &&
(count >= sizeof(data)/sizeof(data[0]))) {
throw("Pop underflows stack");
}
// Then we return the top value
return (data[count]);
}
static stack test_stack; // Define a stack for our bounds checking
/********************************************************
* push_a_lot -- Push too much on to the stack *
********************************************************/
static void push_a_lot() {
int i; // Push counter
for (i = 0; i < 5000; i++) {
test_stack.push(i);
}
}
int main()
{
try {
push_a_lot();
}
catch (bound_err& err) {
cerr << "Error: Bounds exceeded\n";
cerr << "Reason: " << err.what << '\n';
exit (8);
}
catch (...) {
cerr << "Error: Unexpected exception occurred\n";
exit (8);
}
return (0);
}
| true |
99af7c687e0208fc74dd03e6bf075f46b2ace48a | C++ | stynosen/CHIBI-Engine | /CHIBI-Engine/Materials/PosColorMaterial.h | UTF-8 | 1,162 | 2.515625 | 3 | [] | no_license | #pragma once
#include "BaseMaterial.h"
//-----------------------------------------------------
// PosNormTexMaterial Class
//-----------------------------------------------------
//!A material that uses the flat color shader
class PosColorMaterial : public BaseMaterial
{
public:
PosColorMaterial(const D3DXCOLOR& color); // Constructor
virtual ~PosColorMaterial(); // Destructor
void SetColor(const D3DXCOLOR& color);
//-------------------------------------------------
// Inherited Methods
//-------------------------------------------------
virtual void SetEffectVariables();
virtual void LoadEffectVariables();
virtual HRESULT CreateInputLayout();
private:
//-------------------------------------------------
// Datamembers
//-------------------------------------------------
D3DXCOLOR m_Color;
ID3D10EffectVectorVariable *m_ColorEffectVariable;
// -------------------------
// Disabling default copy constructor and default
// assignment operator.
// -------------------------
PosColorMaterial(const PosColorMaterial& yRef);
PosColorMaterial& operator=(const PosColorMaterial& yRef);
}; | true |
85c19b74c4086ae3df0233a9d28a66cfa9452d5f | C++ | solareenlo/cpp | /atcoder/05_AtCoder-Beginner-Contest/abc002/B/main.cpp | UTF-8 | 438 | 2.9375 | 3 | [] | no_license | #include <iostream>
#define REP(i, n) for (int i = 0; i < (n); i++)
using namespace std;
void solve(std::string W){
REP(i, W.size()) {
if (W[i] == 'a' || W[i] == 'i' || W[i] == 'u' || W[i] == 'e' || W[i] == 'o')
continue ;
printf("%c", W[i]);
}
cout << '\n';
}
int main(){
// cin.tie(0);
// ios::sync_with_stdio(false);
std::string W;
std::cin >> W;
solve(W);
return 0;
}
| true |
7ceb1ef689b302fc231f47729433cd746bdf2a37 | C++ | Neverous/individual | /TIMUS/URSPC2011/i.cpp | UTF-8 | 539 | 2.9375 | 3 | [] | no_license | /* 2011
* Maciej Szeptuch
* II UWr
*/
#include<cstdio>
#include<cstring>
int linesPerPage,
width,
words,
wordLen,
actual,
lines = 1;
char word[128];
bool first = true;
int main(void)
{
scanf("%d %d %d", &linesPerPage, &width, &words);
for(int w = 0; w < words; ++ w)
{
scanf("%s", word);
wordLen = strlen(word);
if(actual + wordLen + !first > width)
{
++ lines;
first = true;
actual = 0;
}
actual += wordLen + !first;
first = false;
}
printf("%d\n", (lines + linesPerPage - 1) / linesPerPage);
return 0;
}
| true |
fedf83923075274f9658dfee91711a20206d3397 | C++ | gizmomogwai/cpplib | /lang/WIN32SyncMutex.cpp | UTF-8 | 493 | 2.53125 | 3 | [
"MIT"
] | permissive | #include <lang/SyncMutex.h>
#include <assert.h>
#ifdef WIN32
SyncMutex::SyncMutex() : waiting(false) {
}
SyncMutex::~SyncMutex() {
}
void SyncMutex::lock() {
m.lock();
}
void SyncMutex::unlock() {
m.unlock();
}
void SyncMutex::wait() {
assert(waiting == false);
waiting = true;
m.unlock();
e.wait();
m.lock();
}
void SyncMutex::notify() {
if (waiting == true) {
waiting = false;
e.setEvent();
}
}
#endif
| true |
bb94d096a3a17e172d607d3fb7ad22ed845f75bf | C++ | wycissiily/BP | /readdata.h | UTF-8 | 1,380 | 2.703125 | 3 | [] | no_license | #include<algorithm>
#include<cstdio>
using namespace std;
const int BATCH_SIZE=20;
const int BATCH_COUNT=3000;
const int TRAIN_COUNT=60000;
const int TEST_COUNT=10000;
unsigned char tmp[784*TRAIN_COUNT];
FILE *traini,*trainl,*testi,*testl;
struct Data{
float image[784];
unsigned char label;
};
void _read(FILE *fi,FILE *fl,Data* data,int n){
fread(tmp,sizeof(char),784*n,fi);
for(int i=0;i<n;i++)for(int j=0;j<784;j++)data[i].image[j]=float(tmp[784*i+j])/256;
fread(tmp,sizeof(char),n,fl);
for(int i=0;i<n;i++)data[i].label=tmp[i];
}
struct Batch{Data data[BATCH_SIZE];};
struct Test{
Data data[TEST_COUNT];
void init(){_read(testi,testl,data,TEST_COUNT);fclose(testi);fclose(testl);}
};
struct MNIST{
Data data[TRAIN_COUNT];
void init(){_read(traini,trainl,data,TRAIN_COUNT);fclose(traini);fclose(trainl);}
void reinit(){random_shuffle(data,data+TRAIN_COUNT);}
Batch getbatch(int x){
Batch r;
for(int i=0;i<BATCH_SIZE;i++)r.data[i]=data[BATCH_SIZE*x+i];
return r;
}
};
void inittrain(){
traini=fopen("mnist\\train-images.idx3-ubyte","rb");
fread(tmp,sizeof(char),16,traini);
trainl=fopen("mnist\\train-labels.idx1-ubyte","rb");
fread(tmp,sizeof(char),8,trainl);
}
void inittest(){
testi=fopen("mnist\\t10k-images.idx3-ubyte","rb");
fread(tmp,sizeof(char),16,testi);
testl=fopen("mnist\\t10k-labels.idx1-ubyte","rb");
fread(tmp,sizeof(char),8,testl);
} | true |
5b3e2ceda7b5bfba3622f735ba2ea13c0744e1a7 | C++ | bbvch13531/algorithm | /Baekjoon/backtracking/2580-sudoku.cpp | UTF-8 | 902 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int map[10][10];
bool validate(void){
//check rows
int check[10]={0,}, flag;
for(int i=0; i<9; i++){
for(int j=0; j<9; j++) check[j] = 0;
for(int j=0; j<9; j++){
if(map[i][j]){
if(check[j]==0){
}
}
}
}
}
void dfs(int x, int y){
for(int i=0; i<9; i++){
map[x][y] == i+1;
if(validate()){
for(int j=0; j<9; j++){
for(int k=0; k<9; k++){
if(map[j][k] == 0){
dfs(j, k);
}
}
}
}
}
}
int main(void){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
cin >> map[i][j];
}
}
return 0;
} | true |
d71e3d32aac90507dfe982d1b7cb385e897e49c8 | C++ | Asteip/KaboSolve | /src/solver/constraints/cSupOrEqual.cpp | UTF-8 | 2,783 | 2.890625 | 3 | [] | no_license | #include "cSupOrEqual.hpp"
#include <iostream>
using namespace std;
CSupOrEqual::CSupOrEqual(int *coefficients, int rightMember, Domain **domains, int size) : Constraint(domains, size){
_coefficients = coefficients;
_rightMember = rightMember;
}
CSupOrEqual::~CSupOrEqual(){}
bool CSupOrEqual::applyConstraint(int id) {
int t;
double td = 0.0;
double coef;
bool modification = false;
double somme = _rightMember;
for(int i = 0; i < _size; ++i) {
coef = _coefficients[i];
if (_domains[i]->getIsSet()) {
somme -= coef*_domains[i]->getValue();
} else if (coef > 0) {
somme -= coef*_domains[i]->getMax();
} else {
somme -= coef*_domains[i]->getMin();
}
}
for (int i = 0; i < _size; ++i) {
if (!_domains[i]->getIsSet()) {
coef = _coefficients[i];
if (coef > 0) {
t = somme + coef*_domains[i]->getMax();
} else {
t = somme + coef*_domains[i]->getMin();
}
td = t;
t /= _coefficients[i];
td /= _coefficients[i];
if (td < 0) {
--t;
}
if (t == td) {
if (_coefficients[i] > 0) {
modification = _domains[i]->prunerInf(id, t-1) || modification;
} else {
modification = _domains[i]->prunerSup(id, t+1) || modification;
}
} else {
if (_coefficients[i] > 0) {
modification = _domains[i]->prunerInf(id, t) || modification;
} else {
modification = _domains[i]->prunerSup(id, t+1) || modification;
}
}
}
}
return modification;
}
/*bool CSupOrEqual::applyConstraint(int id){
double td = 0.0;
double coef;
bool modification = false;
for(int i = 0; i < _size; ++i) {
int t = _rightMember;
if (!_domains[i]->getIsSet()) {
for(int j = 0; j < _size; ++j) {
if (i!=j) {
coef = _coefficients[j];
if(_domains[j]->getIsSet()) {
t -= coef*_domains[j]->getValue();
} else if (coef > 0) {
t -= coef*_domains[j]->getMax();
} else {
t -= coef*_domains[j]->getMin();
}
}
}
td = t;
t /= _coefficients[i];
td /= _coefficients[i];
if (td < 0) {
--t;
}
if (t == td) {
if (_coefficients[i] > 0) {
modification = _domains[i]->prunerInf(id, t-1) || modification;
} else {
modification = _domains[i]->prunerSup(id, t+1) || modification;
}
} else {
if (_coefficients[i] > 0) {
modification = _domains[i]->prunerInf(id, t) || modification;
} else {
modification = _domains[i]->prunerSup(id, t+1) || modification;
}
}
}
}
return modification;
}*/
void CSupOrEqual::display() {
cout << "size=" << _size << endl;
cout << "rightMember=" << _rightMember << endl;
cout << endl << "contrainte : ";
for (int i = 0; i < _size; ++i) {
cout << _coefficients[i] << "*X" << _domains[i]->getId() << " + ";
}
cout << " <= " << _rightMember << endl;
} | true |
f8d38743449a5119770f2be6e1ab943f96d5a611 | C++ | jackschu/Connect4Players | /src/board.h | UTF-8 | 1,233 | 3.046875 | 3 | [] | no_license | #pragma once
#include "tile.h"
#include <algorithm>
#include <bitset>
#include <iostream>
#include <unordered_set>
#include <vector>
#include <queue>
class Board {
public:
const static int BOARD_WIDTH = 7;
const static int WIN_LEN = 4;
const static int BOARD_HEIGHT = 6;
Board();
void print() const;
static void printBitset(std::bitset<BOARD_HEIGHT * BOARD_WIDTH> bs);
bool checkWin(Tile player) const;
int countConsecutive(Tile player) const;
bool checkTie() const;
bool isLegalMove(int column, Tile player, bool quiet=false) const ;
char ** toChar() const;
// return if succeed, col is 0 indexed
bool makeMove(int column, Tile player, bool quiet=false);
bool unmakeMove(int column);
private:
Tile board[BOARD_HEIGHT * BOARD_WIDTH] = {Tile::EMPTY};
int nextEmpty[BOARD_WIDTH] = {};
std::bitset<BOARD_HEIGHT * BOARD_WIDTH> toBitset(Tile match) const;
static std::vector<std::bitset<BOARD_HEIGHT * BOARD_WIDTH>>
initializeWinlist(bool consecutive_counter = false);
const static std::vector<std::bitset<BOARD_HEIGHT * BOARD_WIDTH>> &
getWinlist();
static std::vector<std::vector<int>> initializeConsecutiveList();
const static std::vector<std::vector<int>> &getConsecutiveList();
};
| true |
f75fe7737575b5338e1ccd3b9a2c6e27e5130f52 | C++ | mvwicky/Jack-of-all-Calculators | /CPP_CALC/OPERATION.h | UTF-8 | 676 | 3.203125 | 3 | [] | no_license | #ifndef OPERATION_H_INCLUDED
#define OPERATION_H_INCLUDED
class operation {
protected:
float *input1;
float *input2;
float *input3;
float *result;
public:
operation();
operation(float);
operation(float , float);
operation(float , float , float);
};
operation::operation()
{
}
operation::operation(float i1)
{
input1 = new float;
*input1 = i1;
}
operation::operation(float i1 , float i2)
{
input1 = new float;
input2 = new float;
*input1 = i1;
*input2 = i2;
}
operation::operation(float i1 , float i2 , float i3)
{
input1 = new float;
input2 = new float;
input3 = new float;
*input1 = i1;
*input2 = i2;
*input3 = i3;
}
#endif // OPERATION_H_INCLUDED | true |
fa8170c447d0c40b883ce718ee9255762c12e58d | C++ | Carolusian/learn-prog-lang | /clang/03_conan_sample/src/main.cc | UTF-8 | 173 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <fmt/format.h>
int main(int argc, char **argv)
{
std::string s = fmt::format("{:d}", 10);
std::cout << s << std::endl;
return 0;
}
| true |
3a9ba2a74da64ad8373d7a7158692b64dd8b20f5 | C++ | farnazkohankhaki/CPP-Codes-Archive | /USACO/Name That Number.cpp | UTF-8 | 1,148 | 2.578125 | 3 | [] | no_license | /*
ID: fkohank1
PROG: namenum
LANG: C++
*/
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin ("namenum.in");
ofstream fout ("namenum.out");
ifstream ifs ("dict.txt");
const int maxN = 5000 + 8;
string s[maxN];
int main()
{
bool k =
0;
string n, a[10];
fin >> n;
a[2] = "ABC";
a[3] = "DEF";
a[4] = "GHI";
a[5] = "JKL";
a[6] = "MNO";
a[7] = "PRS";
a[8] = "TUV";
a[9] = "WXY";
for (int i = 0; i < 5000; i++)
ifs >> s[i];
for (int i = 0; i < 5000; i++)
{
string c;
for (int j = 0; j < s[i].size(); j++)
{
for (int l = 2; l <= 9; l++)
{
if (s[i][j] == a[l][0])
c += (l + '0');
if (s[i][j] == a[l][1])
c += (l + '0');
if (s[i][j] == a[l][2])
c += (l + '0');
}
}
if (c == n)
{
fout << s[i] << endl;
k = 1;
}
}
if (!k)
fout << "NONE" << endl;
return 0;
}
| true |
d0e6becd87639ba21c3083f21420247e1da4f3c1 | C++ | fcomuniz/my-lib | /source/structures/set/MySet.h | UTF-8 | 939 | 3.140625 | 3 | [] | no_license | #ifndef MY_LIB_MY_SET
#define MY_LIB_MY_SET
#include <functional>
#include <algorithm>
#include <list>
#include <array>
namespace my_lib{
template<class T, int m, class hashF = std::hash<T>>
class MySet{
public:
void insert(const T & value){
if(!hasValue(value)){
v[getPosition(value)].push_back(value);
}
}
void remove(const T & value){
auto & list = v[getPosition(value)];
typename std::list<T>::iterator iter = std::find(list.begin(),list.end(),value);
list.erase(iter);
}
bool hasValue(const T & value){
bool hasFound = false;
for(auto & elem : v[getPosition(value)]){
if(elem == value){
hasFound = true;
break;
}
}
return hasFound;
}
private:
int getPosition( const T & value ){
return hashFunction(value)%m;
}
std::array<std::list<T>,m> v;
hashF hashFunction;
};
}
#endif
| true |
96f2a81365ddabe3af6bd9ae42688e9dd6bab138 | C++ | WinstonMoh/LinuxShellProject | /shell.cpp | UTF-8 | 12,056 | 3.171875 | 3 | [] | no_license | /*
* CS 460 Assignment 2
* Winston Moh T.
* Linux shell program
* 3/29/2018
*/
#include <iostream> // I/O fcns like cout
#include <string> // for getline fcn
#include <stdexcept> // throw exceptions.
#include <vector> // for vector data structure.
#include <fstream> // for File I/O
#include <sstream> // for stringstream
#include <unistd.h> // for running OS commands - ex. create processes, cd etc.
#include <sys/wait.h> // for wait command
#include <sys/param.h> // cd
#include <sys/types.h> // print error fcn
using namespace std;
/* Global variable storing the history size. Default size is 4 */
int HISTORY_SIZE = 4;
/* Global variable storing the list of commands executed */
vector<string> history;
/*Hold individual tokens in each line.*/
vector<string> tokens;
/* Return status for process. */
bool RETURNSTATUS = true;
/* Variables for $HOME, $PWD and $PATH */
string home, pwd, PATH;
string getFirstToken(string str)
{
string tok="";
unsigned int i=0;
while (str[i] != ' ' && i != str.length())
{
tok += str[i++];
}
return tok;
} // getFirstToken()
void extract(string str, string &env_var, string &prompt)
{
bool flag_dollar = false; int dollar_i=0;
bool flag_equals = false; int equals_i=0;
bool env_var_flag = false;
env_var="", prompt="";
for (unsigned int i=2; i<str.length() && !flag_dollar; i++)
{
if (str[i] == '$')
{
flag_dollar = true;
dollar_i = i;
}
}
if (flag_dollar)
{
for (unsigned int i=dollar_i; str[i] != '"' && !flag_equals; i++)
{
for (int j=dollar_i; str[j] != '=' && !env_var_flag; j++)
{
env_var += str[j];
}
if (env_var.length() > 0)
env_var_flag = true;
if (str[i] == '=')
{
flag_equals = true;
equals_i = i;
}
}
}
if (flag_equals)
{
for (unsigned int i=equals_i+1; i<str.length(); i++)
{
if (str[i] == '"')
{
for (unsigned int j=i+1; j<str.length()-1; j++)
{
prompt += str[j];
}
}
}
}
} // extract()
void printHistory(vector<string> vec)
{
int vec_size = vec.size() - 1;
for (int i=vec_size; i>vec_size-HISTORY_SIZE; i--)
{
cout<<"- "<<vec[i]<<endl;
}
} // printHistory()
string getNextToken(string s)
{
static unsigned int i=0;
static string oldString = s;
string t="";
if (oldString != s)
{
i=0;
oldString = s;
}
while ((s[i]==' ' or s[i]=='"') && i<s.length())
i++;
while ((s[i]!=' ' && s[i]!='"') && i<s.length())
{
t += s[i];
i++;
}
i++;
return t;
} // getNextToken()
string getValue(string s)
{
string tok = getNextToken(s);
while (tok.length() > 0)
{
if (getNextToken(s).length() > 0)
{
tok = getNextToken(s);
break;
}
}
return tok;
} // getValue()
string getString(string s)
{
unsigned int i=0, j;
string str="";
while (s[i] != '"')
i++;
for (j=i+1; j<s.length()-1; j++)
str += s[j];
return str;
} // getString()
void readFile(string &prompt, int &size)
{
ifstream myfile;
string text="", tok="";
myfile.open ("shell.config");
while (getline(myfile, text))
{
tok = getFirstToken(text);
if (tok == "history")
{
stringstream geek(getValue(text)); // object from the class stringstream
geek >> size; // object has the value and then stream it to size.
}
if (tok == "prompt")
{
prompt = getString(text);
}
// Get $HOME, $PWD and $PATH values.
if (tok == "home")
{
home = getString(text);
}
if (tok == "pwd")
{
pwd = getString(text);
}
if (tok == "PATH")
{
PATH = getString(text);
}
}
myfile.close();
} // readFile()
bool accExec(string s)
{
if (access(s.c_str(), F_OK) == 0) // File exists
{
if (access(s.c_str(), X_OK) == 0) // File is executable
return true;
else
perror("exec"); // print error message
}
return false;
} // accExec()
void execute(string s)
{
int status;
pid_t pid = fork(); // create process and get process id.
char* args[] = {(char*)s.c_str(), NULL}; // NULL terminated char pointer array
if (pid < 0)
{
cout<<"Process could not be created..."<<endl;
return;
}
else if (pid == 0) // child process
{
execv(args[0], args); // execute command.
}
else
{
// parent process
if ( waitpid(pid, &status, 0) == -1 )
{
perror("waitpid failed");
return;
}
if ( WIFEXITED(status) && RETURNSTATUS ) // return status for the child
{
cout<<" "<<s<<" ("<<pid<<") returned status: "<<WEXITSTATUS(status)<<endl;
}
wait(NULL); // wait for child process to terminate.
}
} // execute()
void flushTokens()
{
if (tokens.size() > 0)
{
tokens.clear(); // clear the vector.
}
} // flushTokens()
void loadTokens(string str)
{
string s="";
unsigned int i;
for (i=0; i<str.length(); i++)
{
if ( str[i] == ' ')
{
tokens.push_back(s);
s="";
}
else if (i == str.length()-1 && str[i] != ' ')
{
s += str[i];
tokens.push_back(s);
}
else if (i < str.length() && str[i] != ' ')
{
s += str[i];
}
}
} // loadTokens()
string getReturnStatus(string str)
{
string t="";
unsigned int i;
for (i=0; i<str.length(); i++)
{
if (str[i] == '=')
break;
}
i++; // move i to next character.
while (i <str.length())
{
t += str[i]; //populate string with returnSTATUS
i++;
}
return t;
} // getReturnStatus()
void upOneDir()
{
unsigned int i,j;
string temp="";
for (i=pwd.length()-1; i>0; i--)
{
if (pwd[i] == '/')
break; // we know stop index position.
}
for (j=0; j<i; j++)
{
temp += pwd[j];
}
if (temp.length() == 0) // give home dir '/'
temp = "/";
pwd = temp; // give pwd new directory.
} // upOneDir()
void changeDir(string dir)
{
string s="", temp="";
vector<string> vec;
unsigned int i;
stringstream err_msg; // hold error message.
err_msg<<" shell: cd: "<<dir<<": No such file or directory";
s = pwd + '/' + dir; // crete new directory string.
if (access(s.c_str(), F_OK) == 0) // check if directory exists
{
if (dir[0] == '/') // absolute path is given.
{
pwd += dir; // move to new directory.
}
else if (dir[0] == '.') // the destination has to be calculated.
{
for (i=0; i<dir.length(); i++) // loop thru entire directory string
{
if (dir[i] == '/') // check for delimiter.
{
vec.push_back(temp); // put string into vector.
temp = "";
}
else if (i == dir.length()-1 && dir[i] != '/')
{
temp += dir[i];
vec.push_back(temp);
}
else if (i < dir.length() && dir[i] != '/')
{
temp += dir[i]; // create string.
}
} // end of loop.
for (i=0; i<vec.size(); i++) // loop thru vector with directory strngs.
{
if (vec[i] == ".")
{
// do nothing - stay in current directory.
}
else if (vec[i] == "..")
{
s = pwd + '/' + vec[i];
if (s != "//..") // File or directory exists
{
upOneDir(); // move up one directory.
}
}
else
{
pwd += '/' + vec[i];
}
}
}
else // directory is relative to current working directory.
{
pwd += '/' + dir;
}
}
else if (s == "//..")
{
// do nothing.
}
else
{
cout<<err_msg.str()<<endl;
}
// Working cd.
/*int rc = chdir(dir.c_str()); // change directory
if (rc == 0) // change of directory was successful.
{
char buffer[MAXPATHLEN];
char *path = getcwd(buffer, MAXPATHLEN);
if (!path)
{
// error.
}
else
{
pwd = path;
}
}
else
{
cout<<" shell: cd: "<<dir<<": No such file or directory"<<endl;
} */
} // changeDir()
void runLS()
{
string s = "/bin/ls";
pid_t pid = fork(); // create process and get process id.
/* char pointer array for ls commands and populate it. */
char* args[100];
unsigned int i;
args[0] = (char*)s.c_str();
for (i=1; i<tokens.size(); i++)
{
args[i] = (char*)tokens[i].c_str();
}
args[i] = (char*)pwd.c_str(); // add current working directory to list of arguments.
args[i+1] = NULL; // end pointer array with NULL character.
/* pid checks. */
if (pid < 0)
{
cout<<"Process could not be created..."<<endl;
return;
}
else if (pid == 0) // child process
{
execv(args[0], args); // execute command.
}
else
{
// parent process
wait(NULL); // wait for child process to terminate.
}
} // runLS()
void searchPATH()
{
// tokenize the paths with ':' as delimiter.
vector<string> paths;
string t=""; unsigned int i=0;
while (i < PATH.length())
{
if (PATH[i] == ':')
{
paths.push_back(t);
t="";
}
else if (PATH[i] != ':' && i==PATH.length()-1)
{
t+=PATH[i];
paths.push_back(t);
}
else if (PATH[i] != ':' && i<PATH.length())
{
t+=PATH[i];
}
i++;
}
bool flag = false;
string s="";
// load up paths.
for (unsigned int j=0; j<paths.size(); j++)
{
/* char pointer array for commands and populate it. */
char* args[100];
s = paths[j] + "/" + tokens[0];
args[0] = (char*)s.c_str();
for (i=1; i<tokens.size(); i++)
{
args[i] = (char*)tokens[i].c_str();
}
if (accExec(s) && !flag) // file exists and is executable.
{
args[i] = NULL; // insert NULL character at end of array.
pid_t pid = fork(); // create process and get process id.
/* pid checks. */
if (pid < 0)
{
cout<<"Process could not be created..."<<endl;
return;
}
else if (pid == 0) // child process
{
execv(args[0], args); // execute command.
}
else
{
// parent process
wait(NULL); // wait for child process to terminate.
}
flag = true;
}
}
stringstream err_msg; // hold error message.
err_msg<<"-shell: "<<tokens[0]<<": command not found";
if (!flag)
cout<<err_msg.str()<<endl;
} // searchPATH()
int main(int argc, char **argv)
{
string prompt="", cmd="", env_name="", str_name="";
/* Read shell.config file and retrieve ENVIRONMENTAL VARIABLES */
readFile(prompt, HISTORY_SIZE);
/* execute shell UI */
do
{
cout<<prompt<<" ";
getline(cin, cmd);
flushTokens(); // clear tokens vector.
history.push_back(cmd); // update the history.
loadTokens(cmd); // update tokens vector.
stringstream err_msg; // hold error message.
err_msg<<"-shell: "<<cmd<<": command not found";
if (getFirstToken(cmd) == "set") // change prompt variable
{
extract(cmd, env_name, str_name);
if (env_name == "$RETURNSTATUS")
{
// get RETURNSTATUS Value.
getReturnStatus(tokens[1]) == "false" ? RETURNSTATUS = false : RETURNSTATUS = true;
}
else
{
prompt = str_name; // change prompt string
}
}
else if (getFirstToken(cmd) == "echo") // print out something
{
if (tokens[1] == "$RETURNSTATUS")
{
RETURNSTATUS ? cout<<"TRUE"<<endl : cout<<"FALSE"<<endl;
}
else if (tokens[1] == "$PWD")
{
cout<<pwd<<endl;
}
else if (tokens[1] == "$HOME")
{
cout<<home<<endl;
}
else if (tokens[1] == "$PROMPT")
{
cout<<prompt<<endl;
}
else if (tokens[1] == "$PATH")
{
cout<<PATH<<endl;
}
}
else if (tokens[0] == "pwd")
{
cout<<pwd<<endl;
}
else if (getFirstToken(cmd) == "history") // print out history of commands entered.
{
printHistory(history);
}
else if (cmd[0] == '/') // absolute directory
{
if (accExec(cmd)) // directory exists and is executable
{
execute(cmd); // then execute command
}
else
{
perror("exec"); // print error message.
}
}
else if (tokens[0] == "cd") // change directory.
{
if (tokens.size() == 1)
{
cout<<pwd<<endl;
}
else
{
changeDir(tokens[1]); // change directory.
}
}
else if (tokens[0] == "ls") // list directory contents.
{
runLS(); // run ls command.
}
else if (tokens[0] == "addpath") // Modify $PATH variable.
{
if (tokens.size() == 2) // make sure second parameter exists
{
if (access(tokens[1].c_str(), F_OK) == 0) // File or path exists
PATH += ":" + tokens[1];
else
perror("access");
}
else
cout<<err_msg.str()<<endl;
}
else if (cmd == "exit") // exit shell program.
{
return 0;
}
/* For any other command, run it thru the SearchPath */
else
{
searchPATH();
}
}while (true);
return 0;
} // main()
| true |
99f2338dde94dd70b281305133f7c0a8ee36e30f | C++ | InvincibleSarthak/Competitive-Programming | /Trees/Remove Half Nodes.cpp | UTF-8 | 844 | 3.328125 | 3 | [] | no_license | // half node - node with only one child
void removeNodes(TreeNode* root){
if(!root) return;
if(root->left){
if(root->left->left && !root->left->right){
root->left = root->left->left;
}
if(!root->left->left && root->left->right){
root->left = root->left->right;
}
}
if(root->right){
if(root->right->left && !root->right->right){
root->right = root->right->left;
}
if(!root->right->left && root->right->right){
root->right = root->right->right;
}
}
removeNodes(root->left);
removeNodes(root->right);
}
TreeNode* Solution::solve(TreeNode* A) {
if(!A) return NULL;
if(!A->left && A->right) A = A->right;
if(A->left && !A->right) A = A->left;
removeNodes(A);
return A;
}
| true |
4039d8ce3d19db560b9c298d6b2ff5dae2332950 | C++ | LeeReeve/WaveSimulation | /WaveSim/main.cpp | UTF-8 | 8,615 | 2.59375 | 3 | [] | no_license | //OpenGL includes
#include <glad/glad.h>
#include <GLFW/glfw3.h>
//Shader class
#include "ShaderClass.h"
#include <iostream>
#include <math.h>
#include <chrono>
#include <thread>
//For handling changes in window size
void framebufferSizeCallback(GLFWwindow* window, int width, int height) {
glViewport(0, 0, width, height);
}
//For handling inputs
void processInput(GLFWwindow *window) {
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
glfwSetWindowShouldClose(window, true);
}
}
//Settings
const unsigned int WindowWidth = 800;
const unsigned int WindowHeight = 800;
//Simulation parameters
const int N = 50; //Number of divisions along x axis for displaying sine wave
const float Np = 5000; //Divisions to split platform into when performing calculations
//Constants
const float g = 9.81f; //Acceleration due to gravity in ms-2
const float Pp = 70.0f; //Density of platform in kgm-3
const float Pw = 997.0f; //Density of water in kgm-3
const float Spv = 1.0f; //Mass per unit area of solar panels in kgm-2
const float pi = 3.141592654f; //Pi
//Wave parameters
const float L = 5.0f; //Half width of wave displayed (1.0f is half the window) in m divided by 3.35
const float K = pi/L; //Wavenumber of the wave in m-1 multiplied by 3.35
const float V = 0.5f * sqrt(9.81 * L / pi); //Velocity of the wave in ms-1 divided by 3.35
const float W = V * K; //Frequency of the wave in ms-1 divided by 3.35
const float A = 0.2f; //Amplitude of the wave in m divided by 3.35
//Platform parameters
const float width = 1.5f; //Width of platform in m divided by 3.35
const float breadth = 1.5f; //Breadth of platform in m divided by 3.35
const float depth = 0.12f; //Depth of platform in m divided by 3.35
const float Apv = 1.0f; //Fractional surface area covered in solar panels
const float dx = width / Np; //Small change in distance when numerically integrating along the platform to find the force and couple in m divided by 3.35
// Mass of the platform and solar panels / kg
const float mass = Pp * width * breadth * depth * 3.35 * 3.35 * 3.35 + Spv * Apv * width * breadth * 3.35 * 3.35;
//Moment of inertia about the horizontal axis (out of the plane of the screen) of the platform and solar panels:
const float Ix = mass * (width * width + depth * depth) * 3.35 * 3.35/12 + (Spv * Apv *width * breadth * 3.35 * 3.35) * ((width * width * 3.35 * 3.35)/12 + (depth * depth *3.35 * 3.35)/4);
//Initial height, set so as to minimise undamped (as of yet) transient oscillations.
const float initialHeight = A + depth / 5;
int main() {
//Setup glfw:
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//Make a window:
GLFWwindow* window = glfwCreateWindow(800, 600, "WaveSim", NULL, NULL);
//Check for errors:
if (window == NULL) {
std::cout << "Failed to create a GLFW window" << std::endl;
glfwTerminate();
return -2;
}
//Set context and size callback
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebufferSizeCallback);
//Load OpenGL function pointers with glad
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
std::cout << "Failed to initialise GLAD" << std::endl;
return -1;
}
//Shader program,
Shader aShader("vertex.vs", "fragment.fs");
//Initial vertex data, units: m divided by 3.35
float wavevertices[3 * N];
int waveindices[2 * N];
for (int i = 0; i < N; i++) {
float x = -L + 2 * i * L / N;
wavevertices[3 * i] = x;
wavevertices[3 * i + 1] = 0.0f;
wavevertices[3 * i + 2] = 0.0f;
waveindices[2 * i] = i;
waveindices[2 * i + 1] = i + 1;
}
float platvertices[12] = {
-width / 2, -depth / 2 + initialHeight, 0.0f,
-width / 2, depth / 2 + initialHeight, 0.0f,
width / 2, -depth / 2 + initialHeight, 0.0f,
width / 2, depth / 2 + initialHeight, 0.0f
};
int platindices[6] = {
0, 1, 2,
1, 2, 3
};
//Centre of mass of the platform, and angle of platform to horizontal
float platCoM[3] = { 0.0f, initialHeight, 0.0f };
float theta = 0.0f;
//Buffer and array objects
unsigned int VBO, VAO, EBO, VBOP, EBOP, VAOP;
glGenVertexArrays(1, &VAO);
glGenVertexArrays(1, &VAOP);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glGenBuffers(1, &VBOP);
glGenBuffers(1, &EBOP);
//VAO for the wave
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(wavevertices), wavevertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(waveindices), waveindices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
//VAO for the platform
glBindVertexArray(VAOP);
glBindBuffer(GL_ARRAY_BUFFER, VBOP);
glBufferData(GL_ARRAY_BUFFER, sizeof(platvertices), platvertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBOP);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(platindices), platindices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
//Initialise time and change in time variables
float t = 0.0f;
float deltat = 0.001f;
float oldt = 0.0f;
//Velocities to use in iteration
float oldvel = 0.0f;
float newvel = 0.0f;
float oldangvel = 0.0f;
float newangvel = 0.0f;
//Render loop:
while (!glfwWindowShouldClose(window)) {
//Get the time
//deltat = (glfwGetTime() - t);
t += deltat;
if (t > glfwGetTime()) {
int waitfor = round((t - glfwGetTime())*1000000);
std::this_thread::sleep_for(std::chrono::microseconds(waitfor));
}
if (t < glfwGetTime()) {
glfwSetTime(t);
}
//Move the wave
for (int i = 0; i < N; i++) {
wavevertices[3 * i + 1] = A * cos(K * wavevertices[3 * i] - W*t);
}
//Calculate the force and couple on the platform
float force = -mass * g;
float couple = 0.0f;
for (int i = 0; i < Np + 1; i++) {
float x = (platCoM[0] - width / 2 + i*dx) * 3.35f; //Iterate along the platform, parallel to its bottom face
float horizpos = (platCoM[0] + (-width / 2 + i * dx) * cos(theta))*3.35f;
float hplat = (platCoM[1] - (depth / 2)*cos(theta) + x*sin(theta)) * 3.35f;
float hwater = (A * cos(K * horizpos - W * t)) * 3.35f;
if (hplat < hwater) {
force += Pw * dx * (hwater - hplat) * breadth * 3.35f * g/ cos(theta); //Add dF
couple += x * Pw * dx * (hwater - hplat) * breadth * 3.35f * g; //Add dF * cos(theta) * x
}
}
//Calculate vertical acceleration
float acc = force / mass;
newvel = oldvel + acc * deltat;
std::cout << t << std::endl;
//Calculate angular acceleration
float angaccx = couple / Ix;
newangvel = oldangvel + angaccx * deltat;
theta += newangvel * deltat;
//Move (update vertex positions)
platCoM[1] += newvel * deltat / 3.35f;
platvertices[0] = platCoM[0] - (width / 2) * cos(theta) + (depth/2) * sin(theta);
platvertices[1] = platCoM[1] - (width / 2) * sin(theta) - (depth / 2)*cos(theta);
platvertices[3] = platCoM[0] - (width / 2) * cos(theta) - (depth / 2) * sin(theta);
platvertices[4] = platCoM[1] - (width / 2) * sin(theta) + (depth / 2)*cos(theta);
platvertices[6] = platCoM[0] + (width / 2) * cos(theta) + (depth / 2) * sin(theta);
platvertices[7] = platCoM[1] + (width / 2) * sin(theta) - (depth / 2)*cos(theta);
platvertices[9] = platCoM[0] + (width / 2) * cos(theta) - (depth / 2) * sin(theta);
platvertices[10] = platCoM[1] + (width / 2) * sin(theta) + (depth / 2)*cos(theta);
//Reset old velocities
oldvel = newvel;
oldangvel = newangvel;
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(wavevertices), wavevertices, GL_STATIC_DRAW);
//Process inputs
processInput(window);
//Render everything
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
aShader.use();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glDrawElements(GL_LINES, 2 * N - 1, GL_UNSIGNED_INT, 0);
glBindVertexArray(VAOP);
glBindBuffer(GL_ARRAY_BUFFER, VBOP);
glBufferData(GL_ARRAY_BUFFER, sizeof(platvertices), platvertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBOP);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
//Swap buffers, poll input/output events:
glfwSwapBuffers(window);
glfwPollEvents();
//std::cout << deltat << std::endl;
}
//De-allocate resources
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
//Terminate glfw to clear all glfw resources
glfwTerminate();
return 0;
} | true |
891c28cf9feed04349e6fecd5c7e81c500208197 | C++ | leebohee/problem-solving | /leetcode/482.cpp | UTF-8 | 1,119 | 2.578125 | 3 | [] | no_license | class Solution {
public:
string licenseKeyFormatting(string S, int K) {
int len = S.length(), idx = 0;
char* new_str = new char [len+1];
for(int i=0; i<len; i++){
if(S.at(i) == '-'){
// skip
}
else if(S.at(i) >= 'a' && S.at(i) <= 'z'){ // lower case
new_str[idx] = S.at(i) - 'a' + 'A'; // convert to upper case
idx++;
}
else{ // number or upper case
new_str[idx] = S.at(i);
idx++;
}
}
new_str[idx] = '\0';
int q = strlen(new_str) / K;
int r = strlen(new_str) % K;
idx = 0;
string license_key;
for(int i=0; i<r; i++, idx++){
license_key += new_str[idx];
}
if((r != 0) && (q != 0)) license_key += '-';
cout << q;
for(int i=0; i<q; i++){
for(int j=0; j<K; j++, idx++){
license_key += new_str[idx];
}
if(i != q-1) license_key += '-';
}
return license_key;
}
};
| true |
03352ef59f229177d9fd4b59f33d8d9e027b0c58 | C++ | mengarena/Leetcode | /com/leet_cpp/LongestUnivaluePath.cpp | UTF-8 | 1,833 | 3.65625 | 4 | [] | no_license | /*
687. Longest Univalue Path
Given a binary tree, find the length of the longest path where each node in the path has the same value.
This path may or may not pass through the root.
The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5
/ \
4 5
/ \ \
1 1 5
Output: 2
Example 2:
Input:
1
/ \
4 5
/ \ \
4 4 5
Output: 2
Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
Easy
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// 95%
// Attention: Path could include both left and right, not necessary one leg
// Final result requires length, not number of nodes
int longestUnivaluePath(TreeNode* root) {
if (!root) return 0;
int maxLen = 0;
postOrder(root, maxLen);
return maxLen-1;
}
int postOrder(TreeNode* root, int& maxLen) {
if (!root) return 0;
int leftLen = postOrder(root->left, maxLen);
int rightLen = postOrder(root->right, maxLen);
int myLen = 1;
int finalLeftLen = 0;
int finalRightLen = 0;
if (root->left && root->val == root->left->val) {
finalLeftLen = leftLen;
}
if (root->right && root->val == root->right->val) {
finalRightLen = rightLen;
}
maxLen = max(maxLen, 1 + finalLeftLen + finalRightLen);
return myLen + max(finalLeftLen, finalRightLen);
}
};
| true |
c6ea44d0cede625e391b06597a076b762ed10f4d | C++ | chuckcranor/frontlevel | /src/include/frontlevel/backend.h | UTF-8 | 3,021 | 2.703125 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef STORAGE_FRONTLEVEL_INCLUDE_BACKEND_H_
#define STORAGE_FRONTLEVEL_INCLUDE_BACKEND_H_
#include <string>
namespace frontlevel {
class WriteBatch;
/*
* frontlevel users create their backing store using their favorite
* key/value system. then they wrap it up in a Backend object and
* pass that to frontlevel when opening the frontlevel database.
*
* this is the generic pure virtual class for Backend. this is
* based on a simplified version of the leveldb API.
*/
class Backend {
public:
/*
* frontlevel dtor will call the backend dtor to release the backend.
*/
virtual ~Backend() {/* base class dtor is a no-op */};
/*
* batch a set of key/value mods to the backend. if the backend
* doesn't support batch ops, it can unpack and do them one at a time.
*
* error handling: level db WriteBatch builds the batch into a
* string buffer ("rep_") that has a seq#, count, and set of records.
* that entire buffer gets passed down into the write-ahead log
* system. if the write (AddRecord) to the write-ahead log fails,
* then the Write is failed. If the write to the write-ahead log
* is ok, but we've been asked to sync() and the sync fails, then
* we are in a bad state and disable all future writes (so you are
* basically hosed in this case). Once the log is done, then the
* data is inserted into the memtable. if that insert fails, the
* Write operation fails (but the data is already in the write-ahead
* log so what does that mean?).
*
* looking at the log write (Writer::AddRecord), for large batches
* it is going to break the rep_ buffer up into a First, some Middle,
* and a Last record. It is going to call EmitPhysicalRecord() for
* each of those. if there is an error, it is going to break out
* of the loop and return the error (meaning that Last record may
* not be emitted, but the earlier stuff will already be down in the
* file). that error will get detected when the log is read
* via ReportCorruption().
*
* so if we have multiple ops and we get a failure part way in,
* what should we do? stop on first error, but do the previous
* changes that went through happen or not?
*
* what about memory in leveldb?
* Put->WriteBatch::Put(kv) COPIES ->Write()
* Write->InsertInto mem->memtable Add->arena malloc/memcpy
*/
virtual Status Write(const WriteOptions &options,
WriteBatch *updates) = 0;
/*
* read key from store. rets IsNotFound if not found...
*/
virtual Status Get(const ReadOptions &options,
const Slice &key, std::string *value) = 0;
/*
* iterator
*/
virtual Iterator *NewIterator(const ReadOptions &options) = 0;
/*
* Load: load a table into the backend (e.g. memtable to backend).
*/
virtual Status Load(const WriteOptions &options, Tablewalker *tw) = 0;
};
} // namespace frontlevel
#endif // STORAGE_FRONTLEVEL_INCLUDE_BACKEND_H_
| true |
2adcd34f804832f22c2831b6831c635380dc6f07 | C++ | Quentin-Anthony/5800_Holography | /SuperHolo/cube.cpp | UTF-8 | 4,462 | 2.828125 | 3 | [] | no_license | #include "cube.h"
#include <cmath>
#include <ruined_math/matrix.h>
#include <GLFW/glfw3.h>
#include "dmd.h"
#define CUBE_DEPTH 0.25f
#define CUBE_X (PATTERN_WIDTH * 0.5f)
#define CUBE_Y (PATTERN_HEIGHT * 0.5f)
#define TWO_PI 6.28318530718f
#define CUBE_EDGES 12
void fillPoints(Ruined::Math::Vector4f * points,
int point_count,
Ruined::Math::Vector4f start_pt,
Ruined::Math::Vector4f end_pt)
{
using namespace Ruined::Math;
float step = 1.0f / point_count;
for(int i = 0; i < point_count; i++)
{
points[i] = Vector4f::Lerp(start_pt, end_pt, i * step);
}
}
void CubeDemo::generatePoints()
{
using namespace Ruined::Math;
free(this->points);
this->points = (Vector4 *) malloc(sizeof(Vector4) * CUBE_EDGES * point_count);
float power = 1.0f / (point_count * CUBE_EDGES);
// Bottom
fillPoints(points + 0 * point_count, point_count, Vector4f( 1.0f,-1.0f, 1.0f, power), Vector4f( 1.0f,-1.0f,-1.0f, power));
fillPoints(points + 1 * point_count, point_count, Vector4f( 1.0f,-1.0f,-1.0f, power), Vector4f(-1.0f,-1.0f,-1.0f, power));
fillPoints(points + 2 * point_count, point_count, Vector4f(-1.0f,-1.0f,-1.0f, power), Vector4f(-1.0f,-1.0f, 1.0f, power));
fillPoints(points + 3 * point_count, point_count, Vector4f(-1.0f,-1.0f, 1.0f, power), Vector4f( 1.0f,-1.0f, 1.0f, power));
// Top
fillPoints(points + 4 * point_count, point_count, Vector4f( 1.0f, 1.0f, 1.0f, power), Vector4f( 1.0f, 1.0f,-1.0f, power));
fillPoints(points + 5 * point_count, point_count, Vector4f( 1.0f, 1.0f,-1.0f, power), Vector4f(-1.0f, 1.0f,-1.0f, power));
fillPoints(points + 6 * point_count, point_count, Vector4f(-1.0f, 1.0f,-1.0f, power), Vector4f(-1.0f, 1.0f, 1.0f, power));
fillPoints(points + 7 * point_count, point_count, Vector4f(-1.0f, 1.0f, 1.0f, power), Vector4f( 1.0f, 1.0f, 1.0f, power));
// Sides
fillPoints(points + 9 * point_count, point_count, Vector4f( 1.0f,-1.0f, 1.0f, power), Vector4f( 1.0f, 1.0f, 1.0f, power));
fillPoints(points + 9 * point_count, point_count, Vector4f( 1.0f, 1.0f,-1.0f, power), Vector4f( 1.0f,-1.0f,-1.0f, power));
fillPoints(points + 10 * point_count, point_count, Vector4f(-1.0f,-1.0f,-1.0f, power), Vector4f(-1.0f, 1.0f,-1.0f, power));
fillPoints(points + 11 * point_count, point_count, Vector4f(-1.0f, 1.0f, 1.0f, power), Vector4f(-1.0f,-1.0f, 1.0f, power));
}
CubeDemo::CubeDemo(float radius, int point_count)
: point_count(point_count), radius(radius), points(nullptr), playing(true), last_time(0.0)
{
velocity = Ruined::Math::Vector3f::Zero();
times = Ruined::Math::Vector3f::Zero();
generatePoints();
}
CubeDemo::~CubeDemo()
{
free(this->points);
this->points = nullptr;
}
void CubeDemo::Update(Simulation * sim, double time)
{
using namespace Ruined::Math;
float delta = (playing ? time - last_time : 0.0f);
times += velocity * delta;
Matrix mat = Matrix::CreateTranslation(CUBE_X, CUBE_Y, CUBE_DEPTH) *
Matrix::CreateRotationZ(times.y ) *
Matrix::CreateRotationX(times.x) *
Matrix::CreateScale(radius * cosf(times.z) * 3.5f);
sim->SetTransformation(mat);
sim->setPoints(this->points, this->point_count * CUBE_EDGES);
sim->generateImage();
last_time = time;
}
void CubeDemo::KeyPress(int key, int scancode, int action, int mods)
{
if(key == GLFW_KEY_UP && action == GLFW_PRESS){
point_count++;
generatePoints();
} else if(key == GLFW_KEY_DOWN && action == GLFW_PRESS){
point_count = (point_count <= 1 ? 1 : point_count - 1);
generatePoints();
}else if(key == GLFW_KEY_W && action == GLFW_PRESS) {
velocity.x += 0.2f;
}else if(key == GLFW_KEY_S && action == GLFW_PRESS) {
velocity.x -= 0.2f;
}else if(key == GLFW_KEY_D && action == GLFW_PRESS) {
velocity.y += 0.2f;
}else if(key == GLFW_KEY_A && action == GLFW_PRESS) {
velocity.y -= 0.2f;
}else if(key == GLFW_KEY_E && action == GLFW_PRESS) {
velocity.z += 0.2f;
}else if(key == GLFW_KEY_Q && action == GLFW_PRESS) {
velocity.z -= 0.2f;
}else if(key == GLFW_KEY_R && action == GLFW_PRESS) {
if(velocity.LengthSquared() > 0.01f)
velocity = Ruined::Math::Vector3::Zero();
else
times = Ruined::Math::Vector3f::Zero();
}
} | true |
08fd2310879c574eba26f7880c7f6e4c6e6d3f45 | C++ | Winterpuma/bmstu_OOP | /lab2/my_errors.h | UTF-8 | 2,343 | 3.171875 | 3 | [
"MIT"
] | permissive | #ifndef _errors_h
#define _errors_h
#include <exception>
#include <string.h>
class baseError : public std::exception
{
public:
baseError(std::string filename, std::string classname, int line, const char *time,
std::string info = "Error")
{
err_info = "\nFile name: " + filename + "\nClass: " + classname +
"\nLine#: " + std::to_string(line) +
"\nTime: " + time + "Info: " + info;
}
virtual const char* what() const noexcept override
{
return err_info.c_str();
}
protected:
std::string err_info;
};
class memError : public baseError
{
public:
memError(std::string filename, std::string classname, int line, const char *time,
std::string info = "Memory error") :
baseError(filename, classname, line, time, info) {};
virtual const char* what() const noexcept
{
return err_info.c_str();
}
};
class emptyError : public baseError
{
public:
emptyError(std::string filename, std::string classname, int line, const char *time,
std::string info = "Try to use empty vector") :
baseError(filename, classname, line, time, info) {};
virtual const char* what() const noexcept
{
return err_info.c_str();
}
};
class indexError : public baseError
{
public:
indexError(std::string filename, std::string classname, int line, const char *time,
std::string info = "Index out of range") :
baseError(filename, classname, line, time, info) {};
virtual const char* what() const noexcept
{
return err_info.c_str();
}
};
class zero_divError : public baseError
{
public:
zero_divError(std::string filename, std::string classname, int line, const char *time,
std::string info = "Zero division error") :
baseError(filename, classname, line, time, info) {};
virtual const char* what() const noexcept
{
return err_info.c_str();
}
};
class deletedObj : public baseError
{
public:
deletedObj(std::string filename, std::string classname, int line, const char *time,
std::string info = "Work with deleted object") :
baseError(filename, classname, line, time, info) {};
virtual const char* what() const noexcept
{
return err_info.c_str();
}
};
#endif /* _errors_h */
| true |
ea5524efffd52438a1e5125fd969e0bd702ff7db | C++ | MayankTripathi01/programs | /prime_recursion.cpp | UTF-8 | 448 | 2.703125 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
int rec(int,int);
int main()
{
int n;
printf("Enter a value: ");
scanf("%d",&n);
rec(n,2);
}
int rec(int x, int y){
int i;
if(x<y)
exit(0);
else{
if(x%y==0){
if(y+1>x&&y!=x)
printf(" %d",y);
else
printf(" %d x",y);
x=x/y;
rec(x,y);
}
else{
y++;
for(i=2;i<y/2;i++){
if(y%i==0){
y++;
continue;
}
}
rec(x,y);
exit(0);
}
}
}
| true |
949449b8cf666a9eac0adf6af85da54804b0df5f | C++ | HiQiang/CPP-Note | /引用/引用作为函数的返回值.cpp | UTF-8 | 559 | 3.640625 | 4 | [] | no_license | #include <iostream>
using namespace std;
//1.不要返回局部变量的引用
/*
int& test01() {
int a = 10;
return a;
}
*/
//2.函数的调用可以作为左值
int& test02()
{
static int a = 10;//静态变量,存放在全局区,全局区上的数据在程序结束后由系统释放
return a;
}
int main()
{
//引用做函数的返回值
int& ref2 = test02();
cout << ref2 << endl;
cout << ref2 << endl;
cout << ref2 << endl;
test02() = 20;
cout << ref2 << endl;
std::cout << "Hello World!\n";
}
| true |
5a37ca3e8e975c86c988e1aaaaa6a74c3fc6b795 | C++ | mpgarate/pedometer-shirt | /pedometer_shirt.ino | UTF-8 | 3,576 | 3.078125 | 3 | [] | no_license | #include <Adafruit_NeoPixel.h>
const int pedometerPin = 9;
const int neoPin = 6;
// number of LEDs in the strip
const int ledCount = 10;
// neopixel LED series
Adafruit_NeoPixel strip = Adafruit_NeoPixel(ledCount, neoPin, NEO_GRB + NEO_KHZ800);
// total number of steps counted today
int steps = 0;
// desired step count
int stepGoal = 5;
void setup(){
Serial.begin(9600);
strip.begin();
strip.show();
}
void loop(){
updateStepCount();
// if goal has been reached
// celebrate and start over
if (steps > stepGoal){
playCelebration();
steps = 0;
}
updateProgressBar();
}
// keep track of current time and time of last successful elapse
int ledCurrentMillis;
int ledPreviousMillis = 0;
boolean elapsedTimeForLed(int interval){
ledCurrentMillis = millis();
if (ledCurrentMillis - ledPreviousMillis > interval){
ledPreviousMillis = ledCurrentMillis;
return true;
}
else{
return false;
}
}
// analog value of pedometer sensor set each loop
int pedoVal;
// keep the previous pedoVal to detect changes
int lastPedoVal = 0;
// remember the time of the last counted step
int stepFoundTime = 0;
// keep track of time since last found step
int stepElapsedTime = 0;
void updateStepCount(){
pedoVal = analogRead(pedometerPin);
if (pedoVal != lastPedoVal){
Serial.println(pedoVal);
stepElapsedTime = millis() - stepFoundTime;
if (stepElapsedTime > 100){
steps++;
}
stepFoundTime = millis();
//Serial.println(elapsedTime);
Serial.println(steps);
}
//lastPedoVal = pedoVal;
}
// arrays for led values, index is led index
int red[ledCount];
int green[ledCount];
int blue[ledCount];
void updateProgressBar(){
float percentComplete = (float)steps / (float)stepGoal;
float activeLeds = (float) ledCount * percentComplete;
//Serial.println(activeLeds);
for(int i=ledCount;i>=0;i--){
if (activeLeds > 0){
activeLeds -= 1;
red[i] = 0;
green[i] = 0;
blue[i] = 200;
}
else{
red[i] = 140;
green[i] = 80;
blue[i] = 0;
}
}
drawToStrip();
}
int frameLength = 80;
int rgbGreen[] = {0,200,0};
int rgbBlue[] = {0,0,200};
int rgbBlack[] = {0,0,0};
void playCelebration(){
swipeColor(rgbGreen, 1);
swipeColor(rgbBlue, -1);
swipeColor(rgbGreen, 1);
swipeColor(rgbBlue, -1);
flashColors(rgbBlue, rgbBlack, 5);
}
void flashColors(int rgbVals_1[], int rgbVals_2[], int flashCount){
while(flashCount > 0){
flashCount--;
for (int i = 0; i < ledCount; i++){
red[i] = rgbVals_1[0];
green[i] = rgbVals_1[1];
blue[i] = rgbVals_1[2];
}
drawToStrip();
delay(frameLength);
for (int i = 0; i < ledCount; i++){
red[i] = rgbVals_2[0];
green[i] = rgbVals_2[1];
blue[i] = rgbVals_2[2];
}
drawToStrip();
delay(frameLength);
}
}
void swipeColor(int rgbVals[], int swipeDirection){
if (swipeDirection == 1){
for(int i = 0; i < ledCount; i++){
red[i] = rgbVals[0];
green[i] = rgbVals[1];
blue[i] = rgbVals[2];
drawToStrip();
delay(frameLength);
}
}
else if (swipeDirection == -1){
for(int i = ledCount-1; i >= 0; i--){
red[i] = rgbVals[0];
green[i] = rgbVals[1];
blue[i] = rgbVals[2];
drawToStrip();
delay(frameLength);
}
}
}
void drawToStrip(){
for(int i=0;i<ledCount;i++){
strip.setPixelColor(i, strip.Color(red[i], green[i], blue[i]));
}
strip.show();
}
| true |
56874ffb5c1293c020c2521bd2732554a06af5ff | C++ | toberole/cdemo | /demo/TraceNew.h | UTF-8 | 1,909 | 3.296875 | 3 | [] | no_license | #ifndef PROJECT_TRACENEW_H
#define PROJECT_TRACENEW_H
// 通过重载 new/delete 来检测内存泄漏的简易实现
using namespace std;
class TraceNew {
public:
class TraceInfo {
private:
const char *file;
size_t line;
public:
TraceInfo();
TraceInfo(const char *File, size_t Line);
~TraceInfo();
const char *File() const;
size_t Line();
};
TraceNew();
~TraceNew();
void Add(void *, const char *, size_t);
void Remove(void *);
void Dump();
private:
map<void *, TraceInfo> mp;
} trace;
TraceNew::TraceInfo::TraceInfo() {
}
TraceNew::TraceInfo::TraceInfo(const char *File, size_t Line) : file(File), line(Line) {
}
TraceNew::TraceInfo::~TraceInfo() {
delete file;
}
const char *TraceNew::TraceInfo::File() const {
return file;
}
size_t TraceNew::TraceInfo::Line() {
return line;
}
TraceNew::TraceNew() {
mp.clear();
}
TraceNew::~TraceNew() {
Dump();
mp.clear();
}
void TraceNew::Add(void *p, const char *file, size_t line) {
mp[p] = TraceInfo(file, line);
}
void TraceNew::Remove(void *p) {
auto it = mp.find(p);
if (it != mp.end()) mp.erase(it);
}
void TraceNew::Dump() {
for (auto it : mp) {
cout << it.first << " " << "memory leak on file: " << it.second.File() << " line: " << it.second.Line() << endl;
}
}
void *operator new(size_t size, const char *file, size_t line) {
void *p = malloc(size);
trace.Add(p, file, line);
return p;
}
void *operator new[](size_t size, const char *file, size_t line) {
return operator new(size, file, line);
}
void operator delete(void *p) {
trace.Remove(p);
free(p);
}
void operator delete[](void *p) {
operator delete(p);
}
#define new new(__FILE__,__LINE__)
int main() {
int *p = new int;
int *q = new int[10];
return 0;
}
#endif //PROJECT_TRACENEW_H
| true |
bd52f70c8a86e8df4ba04ea335ca287fbe881cba | C++ | Daniel-M/BioTools | /muskin/include/numberStrings.hpp | UTF-8 | 298 | 2.84375 | 3 | [] | no_license | //#include "headers.hpp"
template <typename T>
std::string NumberToString ( T Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
template <typename T>
T StringToNumber ( const std::string &Text )
{
std::istringstream ss(Text);
T result;
return ss >> result ? result : 0;
}
| true |
030580814bf141639b2978d657980527bfa8e7bb | C++ | hdamron17/CSCE240 | /04hw/test/test_quad_rotor.cc | UTF-8 | 5,548 | 2.875 | 3 | [] | no_license | /* Copyright */
#include <cstdlib>
// using atoi
#include <iostream>
using std::cout;
using std::endl;
#include <string>
#include "quad_rotor.h" // NOLINT(build/include_subdir)
#include "point.h" // NOLINT(build/include_subdir)
bool TestCreateQuadRotor() {
std::cout << "\tTestCreateQuadRotor" << std::endl;
csce240::three_dim::Point p(0.0, 0.0, 0.0);
csce240::QuadRotor r1(&p), r2(0.0, 0.0, 0.0, 3.14159);
if (!r1.location()->Equals(&p)) {
std::cout << "\t FAILED" << std::endl;
std::cout << "\t Point expected: " << p << ", actual: " << r1.location()
<< std::endl;
return false;
}
if (!r2.location()->Equals(&p)) {
std::cout << "\t FAILED" << std::endl;
std::cout << "\t Point expected: " << p << ", actual: " << r1.location()
<< std::endl;
return false;
}
// Coordinate* loc = r1.location();
return true;
}
bool TestIsUniqueQuadRotorId() {
std::cout << "\tTestIsUniqueQuadRotorId" << std::endl;
if (!csce240::QuadRotor::IsUnique("id")) {
std::cout << "\t FAILED" << std::endl;
std::cout << "\t csce240::QuadRotor::IsUnique(\"id\")"
<< " Expected: 1, Actual: " << !csce240::QuadRotor::IsUnique("id")
<< std::endl;
return false;
}
csce240::QuadRotor r(0.0, 0.0, 0.0);
std::string id = r.id();
if (csce240::QuadRotor::IsUnique(id)) {
std::cout << "\t FAILED" << std::endl;
std::cout << "\t csce240::QuadRotor::IsUnique(" << id
<< ") Expected: 0, Actual: " << csce240::QuadRotor::IsUnique(id)
<< std::endl;
return false;
}
return true;
}
bool TestSetQuadRotorId() {
std::cout << "\tTestSetQuadRotorId" << std::endl;
csce240::QuadRotor r1(0.0, 0.0, 0.0), r2(0.0, 0.0, 0.0);
if (!r1.id("id")) {
std::cout << "\t FAILED" << std::endl;
std::cout << "\t r1.id(\"id\") Expected: 1, Actual: " << !r1.id("id")
<< std::endl;
return false;
}
if (r2.id("id")) {
std::cout << "\t FAILED" << std::endl;
std::cout << "\t r2.id(\"id\") Expected: 0, Actual: " << r2.id("id")
<< std::endl;
return false;
}
return true;
}
bool TestQuadRotorCanTranslateTo() {
std::cout << "\tTestQuadRotorCanTranslateTo" << std::endl;
csce240::QuadRotor r(0.0, 0.0, 0.0, 5.0);
csce240::three_dim::Point p(3.0, 3.5, 1.0);
if (!r.CanTranslateTo(&p)) {
std::cout << "\t FAILED" << std::endl;
std::cout << "\t Translate from " << r.location() << ", to " << p
<< " with speed " << r.speed()
<< " Expected: 1, Actual: " << r.CanTranslateTo(&p)
<< std::endl;
return false;
}
p = csce240::three_dim::Point(3.1, 4.1, 0.9);
if (r.CanTranslateTo(&p)) {
std::cout << "\t FAILED" << std::endl;
std::cout << "\t Translate from " << r.location() << ", to " << p
<< " with speed " << r.speed()
<< " Expected: 1, Actual: " << r.CanTranslateTo(&p)
<< std::endl;
return false;
}
return true;
}
bool TestQuadRotorTranslate() {
std::cout << "\tTestQuadRotorTranslate" << std::endl;
csce240::QuadRotor r(0.0, 0.0, 0.0, 5.0);
csce240::three_dim::Point p(3.0, 3.2, 0.4);
const csce240::three_dim::Vector v(3.0, 3.2, 0.4), v1(1.1, 0.6, 2.2);
if (!r.CanTranslateTo(&p)) {
std::cout << "\t FAILED" << std::endl;
std::cout << "\t Translate from " << *(r.location()) << ", to " << p
<< " with speed " << r.speed()
<< " Expected: 1, Actual: " << r.CanTranslateTo(&p)
<< std::endl;
return false;
} else {
r.Translate(&v);
}
if (!r.location()->Equals(&p)) {
std::cout << "\t FAILED" << std::endl;
std::cout << "\t Translate to " << *(r.location())
<< " with speed " << r.speed()
<< " Expected: " << p << ", Actual: " << r.location()
<< std::endl;
return false;
}
p = csce240::three_dim::Point(4.1, 3.8, 2.6);
if (!r.CanTranslateTo(&p)) {
std::cout << "\t FAILED" << std::endl;
std::cout << "\t Translate from " << *(r.location()) << ", to " << p
<< " with speed " << r.speed()
<< " Expected: 1, Actual: " << r.CanTranslateTo(&p)
<< std::endl;
return false;
} else {
r.Translate(&v1);
}
if (!r.location()->Equals(&p)) {
std::cout << "\t FAILED" << std::endl;
std::cout << "\t Translate to " << *(r.location())
<< " with speed " << r.speed()
<< " Expected: " << p << ", Actual: " << r.location()
<< std::endl;
return false;
}
return true;
}
int main_(int i) {
std::cout << "TESTING csce240::QuadRotor CLASS" << std::endl;
switch (i) {
case 0:
if (TestCreateQuadRotor()) {
std::cout << "\t PASSED" << std::endl;
return 0;
} else {
return 1;
}
case 1:
if (TestIsUniqueQuadRotorId()) {
std::cout << "\t PASSED" << std::endl;
return 0;
} else {
return 1;
}
case 2:
if (TestSetQuadRotorId()) {
std::cout << "\t PASSED" << std::endl;
return 0;
} else {
return 1;
}
case 3:
if (TestQuadRotorCanTranslateTo()) {
std::cout << "\t PASSED" << std::endl;
return 0;
} else {
return 1;
}
case 4:
if (TestQuadRotorTranslate()) {
std::cout << "\t PASSED" << std::endl;
return 0;
} else {
return 1;
}
default:
assert(false && "Only args 0, 1, 2, 3 allowed.");
}
return 0;
}
int main(int argc, char* argv[]) {
if (argc <= 1) {
bool res = 0;
for (int i = 0; i <= 4; ++i) {
res |= main_(i);
}
return res;
} else {
main_(atoi(argv[1]));
}
}
| true |
4f9cef025829eb28b4b95462b8a7179a49dce3f9 | C++ | acton393/incubator-weex | /weex_core/Source/include/JavaScriptCore/bytecode/ExpressionRangeInfo.h | UTF-8 | 3,404 | 2.515625 | 3 | [
"Apache-2.0",
"MIT",
"BSD-3-Clause"
] | permissive | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#pragma once
#include <wtf/StdLibExtras.h>
namespace JSC {
struct ExpressionRangeInfo {
// Line and column values are encoded in 1 of 3 modes depending on the size
// of their values. These modes are:
//
// 1. FatLine: 22-bit line, 8-bit column.
// 2. FatColumn: 8-bit line, 22-bit column.
// 3. FatLineAndColumn: 32-bit line, 32-bit column.
//
// For the first 2 modes, the line and column will be encoded in the 30-bit
// position field in the ExpressionRangeInfo. For the FatLineAndColumn mode,
// the position field will hold an index into a FatPosition vector which
// holds the FatPosition records with the full 32-bit line and column values.
enum {
FatLineMode,
FatColumnMode,
FatLineAndColumnMode
};
struct FatPosition {
uint32_t line;
uint32_t column;
};
enum {
FatLineModeLineShift = 8,
FatLineModeLineMask = (1 << 22) - 1,
FatLineModeColumnMask = (1 << 8) - 1,
FatColumnModeLineShift = 22,
FatColumnModeLineMask = (1 << 8) - 1,
FatColumnModeColumnMask = (1 << 22) - 1
};
enum {
MaxOffset = (1 << 7) - 1,
MaxDivot = (1 << 25) - 1,
MaxFatLineModeLine = (1 << 22) - 1,
MaxFatLineModeColumn = (1 << 8) - 1,
MaxFatColumnModeLine = (1 << 8) - 1,
MaxFatColumnModeColumn = (1 << 22) - 1
};
void encodeFatLineMode(unsigned line, unsigned column)
{
ASSERT(line <= MaxFatLineModeLine);
ASSERT(column <= MaxFatLineModeColumn);
position = ((line & FatLineModeLineMask) << FatLineModeLineShift | (column & FatLineModeColumnMask));
}
void encodeFatColumnMode(unsigned line, unsigned column)
{
ASSERT(line <= MaxFatColumnModeLine);
ASSERT(column <= MaxFatColumnModeColumn);
position = ((line & FatColumnModeLineMask) << FatColumnModeLineShift | (column & FatColumnModeColumnMask));
}
void decodeFatLineMode(unsigned& line, unsigned& column) const
{
line = (position >> FatLineModeLineShift) & FatLineModeLineMask;
column = position & FatLineModeColumnMask;
}
void decodeFatColumnMode(unsigned& line, unsigned& column) const
{
line = (position >> FatColumnModeLineShift) & FatColumnModeLineMask;
column = position & FatColumnModeColumnMask;
}
uint32_t instructionOffset : 25;
uint32_t startOffset : 7;
uint32_t divotPoint : 25;
uint32_t endOffset : 7;
uint32_t mode : 2;
uint32_t position : 30;
};
} // namespace JSC
| true |
97c8e39d584e48a3e10f5d62c10ddfb9d777f65b | C++ | alivcor/leetcode | /561. array-partition/main.cpp | UTF-8 | 1,093 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include "vector"
using namespace std;
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
int maxSum = 0;
int holder = 0;
std::sort(nums.begin(), nums.end());
std::reverse(nums.begin(),nums.end());
std::vector<int> pairs;
bool insFlag = true;
for(auto it = nums.begin(); it != nums.end(); ++it){
if(insFlag){
cout<<"Storing "<<*it<<" \n";
holder = *it;
insFlag = false;
} else {
pairs.insert(pairs.begin(), min(holder,*it));
insFlag = true;
}
}
// for(auto it = pairs.begin(); it!=pairs.end(); ++it){
// cout << *it;
// cout << " ";
// }
for(std::vector<int>::iterator it = pairs.begin(); it != pairs.end(); ++it)
maxSum += *it;
return maxSum;
}
};
int main() {
Solution sol;
int myints[] = {1,4,3,2};
std::vector<int> myvector (myints, myints+4);
sol.arrayPairSum(myvector);
return 0;
} | true |
49f0c1fb9963a6bec2db110fdcc15beb15c0fd75 | C++ | heftyy/simple-qt-chat | /src/chatlib/communication/MessageSerializer.h | UTF-8 | 578 | 2.9375 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <memory>
#include <string>
namespace SimpleChat {
class AbstractMessage;
/*!
* MessageSerializer holds the AbstractMessage interface.
* You can use serialize() method multiple times.
*/
class MessageSerializer {
public:
explicit MessageSerializer(std::unique_ptr<AbstractMessage> abstractMessage);
/*!
* Returns:
* - bool success
* - std::string serialized message
*/
std::tuple<bool, std::string> serialize() const;
private:
std::unique_ptr<AbstractMessage> abstractMessage_;
};
} // SimpleChat namespace
| true |
322ddb105a599cae7d88c7bf1ac3035a85897ddb | C++ | jasong-ovo/JiShiShuaTi | /Sort/3_4OlympicSort.cpp | UTF-8 | 5,273 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
void dump(float*p, int N);
struct country
{
int goldenMedal, medal, rank, way, idx;
float population;
country(){
idx = 0;
goldenMedal = 0;
medal = 0;
population = 0;
rank = 100;
way = 0;
}
};
void gatherRanks(int N, int way, country *players, int* pi = NULL, float* pf = NULL){
//1,2
if(pi != NULL) {
int idx = 1;
int last = -1;
int counter = 0;
//1
if (way == 1){
for (int i=0; i<N; i++){
// printf("i:%d\t%d\t%d\n", i, pi[i], last);
//skip same nums
if (last == pi[i]) continue;
//refresh
for (int j=0; j<N; j++){
// printf("j:%d\trank:%d\n", j, players[j].rank);
if (players[j].goldenMedal == pi[i]) {
// printf("%d",idx);
counter ++;
if(players[j].rank > idx ){
players[j].rank = idx;
players[j].way = way;
}
}
}
idx += counter;
counter = 0;
last = pi[i];
}
}
//2
if (way == 2){
for (int i=0; i<N; i++){
//skip same nums
if (last == pi[i]) continue;
//refresh
for (int j=0; j<N; j++){
if ( players[j].medal == pi[i]) {
counter ++;
if(players[j].rank > idx ){
players[j].rank = idx;
players[j].way = way;
}
}
}
idx += counter;
counter = 0;
last = pi[i];
}
}
}
//3,4
else {
// printf("mark0\n");
int idx = 1;
int last = -1;
int counter = 0;
//3
if (way == 3){
for (int i=0; i<N; i++){
//skip same nums
// printf("i:%d\n", i);
if (last == pf[i]) continue;
//refresh
for (int j=0; j<N; j++){
// printf("j:%d\n", j);
if ( (players[j].goldenMedal / players[j].population) == pf[i]) {
counter ++;
if(players[j].rank > idx ){
players[j].rank = idx;
players[j].way = way;
}
}
}
idx += counter;
counter = 0;
last = pf[i];
}
}
//4
if (way == 4){
// dump(pf, N);
for (int i=0; i<N; i++){
//skip same nums
if (last == pf[i]) continue;
//refresh
for (int j=0; j<N; j++){
if ((players[j].medal / players[j].population) == pf[i]) {
// printf("j:%d\tpf[i]:%f\n", j, pf[i]);
counter ++;
if(players[j].rank > idx ){
players[j].rank = idx;
players[j].way = way;
}
}
}
idx += counter;
counter = 0;
last = pf[i];
}
}
}
// printf("ranking:%d\n", way);
}
bool compare1(int a, int b){
if (a>b) return true;
return false;
}
bool compare2(float a, float b){
if (a>b) return true;
return false;
}
void dump(float *p, int N){
for (int i=0; i < N; i++){
printf("%f\t", p[i]);
}
printf("\n");
}
int main(){
//init
int N, M;
scanf("%d %d", &N, &M);
country players[N];
for (int i=0; i<N; i++){
players[i].idx = i;
scanf("%d", &players[i].goldenMedal);
scanf("%d", &players[i].medal);
scanf("%f", &players[i].population);
}
int prints[M];
for (int i=0; i<M; i++){
scanf("%d", &prints[i]);
}
//sort
int gMedals[N];
int medals[N];
float gMedalsPropertion[N];
float medalsPropertion[N];
for (int i=0; i<N; i++){
gMedals[i] = players[i].goldenMedal;
medals[i] = players[i].medal;
gMedalsPropertion[i] = float(players[i].goldenMedal) / players[i].population;
medalsPropertion[i] = float(players[i].medal) / players[i].population;
}
// dump(gMedalsPropertion, N);
sort(gMedals, gMedals+N, compare1);
gatherRanks(N, 1, players, gMedals);
sort(medals, medals+N, compare1);
gatherRanks(N, 2, players, medals);
sort(gMedalsPropertion, gMedalsPropertion+N, compare2);
gatherRanks(N, 3, players, NULL, gMedalsPropertion);
sort(medalsPropertion, medalsPropertion+N, compare2);
gatherRanks(N, 4, players, NULL, medalsPropertion);
//print
for (int i=0; i<M; i++){
printf("%d:%d\n", players[prints[i]].rank, players[prints[i]].way);
}
return 0;
} | true |
08ddc482a4e2606c7aeef5afac357a508346c006 | C++ | Mooophy/159302 | /A2/nodes.cpp | UTF-8 | 1,652 | 2.984375 | 3 | [
"MIT"
] | permissive | #include "nodes.h"
#include <cmath>
using namespace std;
int Node::calcManhattanDistance(int xG, int yG){
return (abs(x-xG) + abs(y-yG));
}
void Node::updateHCost(heuristicFunction hFunction, int xG, int yG){
hCost = h(hFunction, xG, yG);
}
void Node::updateFCost(){
fCost = hCost + pathLength;
}
int Node::getFCost(){
return fCost;
}
int Node::h(heuristicFunction hFunction, int xG, int yG){
int hValue;
switch(hFunction){
case misplacedTiles:
break;
case manhattanDistance:
hValue = (abs(x-xG) + abs(y-yG));
break;
case euclidean:
hValue = int(pow((x-xG),2) + pow((y-yG),2));
break;
}
return hValue;
}
//constructor
Node::Node(const Node &p) : path(p.path){
x = p.x;
y = p.y;
weight = p.weight;
//path = p.path;
pathLength = p.pathLength;
hCost = p.hCost;
fCost = p.fCost;
gCost = p.gCost;
gradation = p.gradation;
goalX = p.goalX;
goalY = p.goalY;
}
//constructor
Node::Node(int _x, int _y, int _weight, int _goalX, int _goalY){
int n;
//dMap = dMap;
path = "";
pathLength=0;
hCost = 0;
fCost = 0;
x = _x;
y = _y;
weight = _weight;
goalX = _goalX;
goalY = _goalY;
}
void Node::clear(){
x = 0;
y = 0;
weight = 0;
pathLength = 0;
hCost = 0;
fCost = 0;
gCost = 0;
gradation = 0;
goalX = 0;
goalY = 0;
}
//checks if the current state matches the goal state
bool Node::goalMatch(int xG, int yG){
return (x == xG && y == yG);
}
const string Node::getPath(){
return path;
}
int Node::getPathLength(){
return pathLength;
}
| true |
15fb1d23b00070ee44e82b1c7bfaccab5a4d4fc4 | C++ | AsheeshKumar34/Hackerrank | /Data-Structures/Linked Lists/Insert a node at the tail of a Linked List.cpp | UTF-8 | 468 | 3.71875 | 4 | [] | no_license | /*
Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* Insert(Node *head,int data)
{
Node *ptr= new Node;
ptr->data=data;
ptr->next=NULL;
if (head==NULL)
head=ptr;
else{
Node *temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
}
return head;
}
| true |
28a1007623793588d74f687cf506efd8e72b0507 | C++ | awasae/File-Sharing-System | /SharedCode/TextFile.cpp | UTF-8 | 1,124 | 2.828125 | 3 | [] | no_license | // Define the TextFile class here
#include "TextFile.h"
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <deque>
#include <sstream>
#include <string>
#include "AbstractFileVisitor.h"
class AbstractFileVisitor;
using namespace std;
TextFile::TextFile(std::string fileName) {
this->name = fileName;
}
unsigned int TextFile::getSize() {
return (unsigned int)this->contents.size();
}
std::string TextFile::getName() {
return this->name;
}
int TextFile::write(std::vector<char> param) {
this->contents.swap(param);
return 0;
}
int TextFile::append(std::vector<char> add) {
for (unsigned int i = 0; i < add.size(); i++) {
this->contents.push_back(add[i]);
}
return 0;
}
vector<char> TextFile::read() {
std::vector<char> v;
for (unsigned int i = 0; i < this->contents.size(); i++) {
v.push_back(this->contents[i]);
}
return v;
}
void TextFile::accept(AbstractFileVisitor* po) {
AbstractFileVisitor* file =po;
file->visit_TextFile(this);
}
AbstractFile* TextFile::clone(std::string name) {
TextFile* file = new TextFile(*this);
file->name = name;
return file;
}
| true |
4ba76bd65cd1f5b255fd26922fed4ae79375bade | C++ | jubeemer/iess_robotprogramming | /pid_control_drive/main.cpp | UTF-8 | 1,251 | 2.5625 | 3 | [] | no_license | #include "mbed.h"
#include "m3pi_ng.h"
#include "PIDLineFollower.h"
#include "RaceTracker.h"
m3pi robot;
Timer timer;
DigitalIn mypin(p21, PullUp);
const float dt = .008;
const int BLACK_TOLERANCE = 100;
const int WHITE_TOLERANCE = 400;
int main() {
robot.cls();
robot.sensor_auto_calibrate();
PIDLineFollower controller(robot, .95, 1.1, 0, 0.035);
RaceTracker race(robot, 5, BLACK_TOLERANCE, WHITE_TOLERANCE);
timer.start();
while(1) {
// Quit and print race summary if button is pressed or the race
// is completed.
if(race.is_finished() || !mypin){
robot.stop();
race.print_summary();
break;
}
// Lap counter
race.get_raw_sensors();
if(race.is_black_surface()) {
if(!race.get_line_flag()) {
race.record_lap();
race.set_line_flag(true);
}
}
else {
race.set_line_flag(false);
}
// Wait until dt has passed to run the control algorithm
if(timer.read() < dt) {
continue;
}
controller.drive(dt);
timer.reset();
}
race.print_exit();
}
| true |
2a09e5a8e826ab00200b6ffcf92858ac9b73b96f | C++ | dave-msk/calculator-cpp | /third_party/fsm/state.h | UTF-8 | 1,717 | 3.515625 | 4 | [] | no_license | #ifndef FSM_CORE_STATE_H
#define FSM_CORE_STATE_H
#include <map>
#include <sstream>
#include "exceptions.h"
namespace fsm {
template <typename K, typename T>
class State {
private:
std::map<T, K> tr_map_;
K id_;
bool is_terminal_ = false;
public:
State() = default;
explicit State(const K &id) : id_(id) {};
State(const K &id, const bool is_terminal)
: id_(id), is_terminal_(is_terminal) {};
bool IsTerminal() const;
void SetTerminal();
bool HasTransition(const T &t) const;
void AddTransition(const T &t, const K &id);
const K& GetId() const;
const K& Transit(const T &t) const;
};
template <typename K, typename T>
void State<K, T>::AddTransition(const T &t, const K &id) {
auto it = tr_map_.find(t);
if (it != tr_map_.end()) {
std::stringstream ss;
ss << "Duplicated transition:\"" << t << "\"" << std::endl;
throw fsm::DuplicatedKeyException(ss.str());
}
tr_map_[t] = id;
}
template <typename K, typename T>
const K& State<K, T>::GetId() const {
return id_;
}
template <typename K, typename T>
bool State<K, T>::IsTerminal() const{
return is_terminal_;
}
template <typename K, typename T>
void State<K, T>::SetTerminal() {
is_terminal_ = true;
}
template <typename K, typename T>
const K& State<K, T>::Transit(const T& t) const {
auto it = tr_map_.find(t);
if (it == tr_map_.end()) {
std::stringstream ss;
ss << "Transition key \"" << t << "\" not found." << std::endl;
throw fsm::InvalidTransitionException(ss.str());
}
return it->second;
}
template <typename K, typename T>
bool State<K, T>::HasTransition(const T &t) const {
auto it = tr_map_.find(t);
return it != tr_map_.end();
}
}
#endif // FSM_CORE_STATE_H
| true |
e4572902fb7ef38a8e68394c7ba170674d2f4417 | C++ | thenohatcat/Angler | /Angler/DrawNode.cpp | UTF-8 | 1,343 | 2.6875 | 3 | [] | no_license | //Version: 0.1.12
//Author: Jakob Pipping
//Contributors:
#ifndef ANGLER_0_1_12
#error DrawNode.cpp: Wrong Version 0.1.12
#endif
#include "DrawNode.h"
using namespace Angler;
using namespace Angler::Nodes;
DrawNode::DrawNode(unsigned long id, Node *parent, int layer, float ox, float oy)
: Node(id, parent), mLayer(layer), mOX(ox), mOY(oy)
{
}
DrawNode::DrawNode(unsigned long id, Node *parent, int layer, sf::Vector2f origo)
: Node(id, parent), mLayer(layer), mOX(origo.x), mOY(origo.y)
{
}
DrawNode::DrawNode(unsigned long id, int layer, float ox, float oy)
: Node(id), mLayer(layer), mOX(ox), mOY(oy)
{
}
DrawNode::DrawNode(unsigned long id, int layer, sf::Vector2f origo)
: Node(id), mLayer(layer), mOX(origo.x), mOY(origo.y)
{
}
DrawNode::~DrawNode()
{
Node::~Node();
}
void DrawNode::draw(Game* context, Angler::Graphics::GraphicsEngine* graphics, float time, float deltaTime)
{
if (mVisible)
{
graphics->draw(mLayer, mOX, mOY);
mDrawChildren(context, graphics, time, deltaTime);
}
}
void DrawNode::setOrigin(float x, float y)
{
mOX = x;
mOY = y;
}
void DrawNode::setOrigin(sf::Vector2f origin)
{
setOrigin(origin.x, origin.y);
}
sf::Vector2f DrawNode::getOrigin()
{
return sf::Vector2f(getOriginX(), getOriginY());
}
float DrawNode::getOriginX()
{
return mOX;
}
float DrawNode::getOriginY()
{
return mOY;
} | true |
9b24296d9203084bb6cf2f9c209d21e398f6d23b | C++ | allpasscool/leetcodes | /leetcode1177/leetcode1177_1.cpp | UTF-8 | 1,303 | 2.96875 | 3 | [] | no_license | class Solution {
public:
vector<bool> canMakePaliQueries(string s, vector<vector<int>>& queries) {
int n = queries.size();
vector<bool> output;
vector<vector<int>> alpha_count(s.size(), vector<int> (26, 0));
vector<int> tmp(26, 0);
for (int i = 0; i < s.size(); i++) {
int c = s[i] - 'a';
tmp[c]++;
alpha_count[i] = tmp;
}
for (int i = 0; i < n; i++) {
int left = queries[i][0], right = queries[i][1], replace = queries[i][2];
int count = 0;
for (int j = 0; j < 26; j++) {
count += left == 0 ? alpha_count[right][j] % 2: (alpha_count[right][j] - alpha_count[left - 1][j]) % 2;
}
if (count / 2 > replace) {
output.push_back(false);
}
else {
output.push_back(true);
}
}
return output;
}
};
// Runtime: 388 ms, faster than 29.93% of C++ online submissions for Can Make Palindrome from Substring.
// Memory Usage: 111.9 MB, less than 100.00% of C++ online submissions for Can Make Palindrome from Substring.
// time complexity: O(s.size() + queries.size())
// space complexity: O(26^n) | true |
8631237deb3d96eb5862b8f9446f3dc8a8caf163 | C++ | Ivanf1/learning-ATmega328P | /projects/blink-timer/main.cpp | UTF-8 | 434 | 2.53125 | 3 | [] | no_license | #include <Arduino.h>
// interrupt vector handler when timer overflows
ISR(TIMER1_OVF_vect) {
// toggle pin 2
PIND = (1 << PIND2);
}
void setup() {
// set pin 2 as output
DDRD = (1 << DDD2);
// not using anything from this register
TCCR1A = 0;
// count every 256 cycles
// roughly every 1 second
TCCR1B = (1 << CS12);
// generate an interrupt when the timer overflows
TIMSK1 = (1 << TOIE1);
}
void loop() {} | true |
062ee4bccbd0b22554652be16bb567437d508690 | C++ | kitech/mwget | /ksocket.h | WINDOWS-1252 | 4,170 | 2.59375 | 3 | [] | no_license | #ifndef _KSOCKET_H_
#define _KSOCKET_H_
/**
* created by icephoton drswinghead@163.com 2005-8-5
*/
#include <iostream>
#include <sys/socket.h>
class KSocket{
public:
//=
// Constructor
//=
KSocket(int pFamily = PF_INET, int pType = SOCK_STREAM , int pProtocal = 0);
//=
// Destructor
//=
~KSocket();
//=
// Sets the timeout value for Connect, Read and Send operations.
// Setting the timeout to 0 removes the timeout - making the Socket blocking.
//=
void setTimeout(int seconds, int microseconds);
//=
// Returns a description of the last known error
//=
const char *getError();
//=
// Connects to the specified server and port
// If proxies have been specified, the connection passes through tem first.
//=
bool Connect(const char *pServer, int pPort);
//=
// Connects to the specified server and port over a secure connection
// If proxies have been specified, the connection passes through them first.
//=
bool ConnectSSL(const char *pServer, int pPort);
//=
// Inserts a transparent tunnel into the connect chain
// A transparent Tunnel is a server that accepts a connection on a certain port,
// and always connects to a particular server:port address on the other side.
// Becomes the last server connected to in the chain before connecting to the destination server
//=
bool insertTunnel(const char *pServer, int pPort);
//=
// Inserts a Socks5 server into the connect chain
// Becomes the last server connected to in the chain before connecting to the destination server
//
//=
bool insertSocks5(const char *server, int port, const char *username, const char *password);
//=
// Inserts a Socks4 server into the connect chain
// Becomes the last server connected to in the chain before connecting to the destination server
//=
bool insertSocks4(const char *server, int port, const char *username);
//=
// Inserts a CONNECT-Enabled HTTP proxy into the connect chain
// Becomes the last server connected to in the chain before connecting to the destination server
//
//=
bool insertProxy(const char *server, int port);
//=
// Sends a buffer of data over the connection
// A connection must established before this method can be called
//=
int Write(const char *pData, int pLength);
//=
// Sends a buffer of data over the connection
// A connection must established before this method can be called
//=
int Writeline(const char *pData, int pLength);
//=
// Reads a buffer of data from the connection
// A connection must established before this method can be called
//=
int Read(char *pBuffer, int pLength);
//=
// Reads everything available from the connection
// A connection must established before this method can be called
//=
char *Reads(char * rbuf) ;
int Peek(char * rbuf, int pLength) ;
//=
// Reads a line from the connection
// A connection must established before this method can be called
//=
int Readline(char *pLine , int pLength );
//=
// Sends a null terminated string over the connection
// The string can contain its own newline characters.
// Returns false and sets the error message if it fails to send the line.
// A connection must established before this method can be called
//
//=
bool sends(const char *buffer);
//=
// Closes the connection
// A connection must established before this method can be called
//=
bool Close();
//=
// Sets an output stream to receive realtime messages about the socket
//=
void setMessageStream(std::ostream &o);
//add for test aim
int GetSocket();
bool SetSocket(KSocket * sock) ;
private:
bool init(int pFamily = PF_INET, int pType = SOCK_STREAM , int pProtocal = 0);
///socket
int mSockFD;
///
int mErrorNo ;
///Ϣ
int mErrorStr[128];
///
int mFamily;
///
int mType;
///
int mProtocol;
///
int mTimeOut ;
int mTimeOutUS ;
int mTORetry;
};
//int nanosleep(const timespec*, timespec*)
//unsigned int usleep(unsigned int)
#endif
| true |
e2382ebdc97d9e7cadabc75fa6d55fc5ccf6dc2b | C++ | tkubicz/ngengine | /source/include/NGE/Geometry/Basic/Floor.hpp | UTF-8 | 2,443 | 3.015625 | 3 | [] | no_license | /*
* File: Floor.hpp
* Author: tku
*
* Created on 7 maj 2013, 16:19
*/
#ifndef FLOOR_HPP
#define FLOOR_HPP
#include "NGE/Geometry/Basic/Basic.hpp"
#include "NGE/Media/Shaders/GLSLProgram.hpp"
namespace NGE {
namespace Geometry {
namespace Basic {
class Floor : public Basic {
public:
Floor();
virtual ~Floor();
virtual bool Initialize();
/**
* Initialise the floor. This method invokes geometry generation
* and initialise VBO and VBA.
* @param halfSize Half size of the floor. Default 100.f.
* @param step How dense the floor should be. Default 4.f.
* @param shader Shader program used to render the floor.
* @return true if everything was ok, otherwise false.
*/
bool Initialize(float halfSize = 100.f, float step = 4.f, Media::Shaders::GLSLProgram* shader = NULL);
/**
* Update the floor in time.
* @param dt Delta time.
*/
void Update(float dt);
/**
* Render the floor.
*/
void Render();
/**
* Set the floor color.
* @param color Color in RGBA.
*/
void SetColor(const Math::vec4f& color);
protected:
/**
* Delete all previously created vertex buffers.
*/
virtual void DeleteBuffers();
/**
* Delete all previously create vertex arrays.
*/
virtual void DeleteArrays();
/**
* Initialise geometry and store it in proper fields inherited from
* Mesh interface.
* @return true if everything was ok, otherwise false.
*/
virtual bool InitializeGeometry();
/**
* Initialise Vertex Buffer Objects.
* @return true if everything was ok, otherwise false.
*/
virtual bool InitializeVBO();
/**
* Initialise Vertex Buffer Arrays.
* @return true if everything was ok, otherwise false.
*/
virtual bool InitializeVBA();
protected:
/**
* Pointer to shader used to render the floor.
*/
Media::Shaders::GLSLProgram* shader;
/**
* Color in RGBA. This field is used in default rendering method
* to set the floor color. Please remeber, that if you use
* your own rendering routin, you have to implement it (or not)
* yourself.
*/
Math::vec4f color;
/**
* Half size of the floor in float.
*/
float halfSize;
/**
* How dense flor tiles should be.
*/
float step;
};
}
}
}
#endif /* FLOOR_HPP */
| true |
dd0ab76072d9e4f290984997a91a24eb8e84d2ca | C++ | mrdaa/tugasakhirlagi | /cal.ino | UTF-8 | 5,224 | 2.609375 | 3 | [] | no_license | #include <DHT.h>
#include <ESP8266WiFi.h>
#include <SocketIoClient.h>
#include <EEPROM.h>
#include <GravityTDS.h>
SocketIoClient socket;
//Setup Global Variable
String id = "1471984882";
bool IsConnect = false;
//define your sensors here
#define DHTTYPE DHT11
#define dhtPin D2
#define relay1 D3
#define relay2 D4
#define TdsSensorPin A0
GravityTDS gravityTds;
DHT dht(dhtPin, DHTTYPE);
const int trigPin = D6;
const int echoPin = D7;
long duration = 0;
float distance = 0;
float temperature = 25, tdsValue = 0;
// Setting WiFi
char ssid[] = "a";
char pass[] = "1234567890";
//Setting Server
char SocketServer[] = "139.180.189.208";
int port = 4000;
void setup()
{
//setup pins and sensor
pinMode(relay1, OUTPUT);
pinMode(relay1, HIGH);
pinMode(relay2, OUTPUT);
pinMode(relay2, HIGH);
gravityTds.setPin(TdsSensorPin);
gravityTds.setAref(5.0); //reference voltage on ADC, default 5.0V on Arduino UNO
gravityTds.setAdcRange(1024); //1024 for 10bit ADC;4096 for 12bit ADC
gravityTds.begin(); //initialization
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
dht.begin();
//setup tombol realtime aplikasi
SetupRelayAplikasi();
Serial.begin(115200);
//Setup WiFi
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
}
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("");
socket.begin(SocketServer, port);
//listener for socket io start
socket.on("connect", konek);
socket.on("rwl", RelayWl);
socket.on("rtds", RelayTds);
socket.on("rtemp", RelayTemp);
socket.on("rhum", RelayHum);
socket.on("disconnect", diskonek);
//listener for socket io end
}
void loop()
{
socket.loop();
// sensor suhu dan humidity
float t = dht.readTemperature();
float h = dht.readHumidity();
String temp = TangkapNilaiSensor(t);
String hum = TangkapNilaiSensor(h);
WlSensor(); //panggil function WaterLevel
String wlval = TangkapNilaiSensor(distance);
TdsSensor(); // panggil Function TDS
String tdsVal = TangkapNilaiSensor(tdsValue);
if (IsConnect)
{
// kirim Data Sensor Disini
KirimSocket("temp", temp);
KirimSocket("hum", hum);
KirimSocket("tds", tdsVal);
KirimSocket("wl", wlval);
}
delay(1000);
}
void WlSensor() // function water Level
{
// Sets the trigPin on HIGH state for 10
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
const float maxH = 10;
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = (duration * 0.034) / 2;
distance = maxH - distance;
distance = ((distance / maxH) * 100);
}
// end water level
void TdsSensor() // function tds sensor
{
gravityTds.setTemperature(temperature); // set the temperature and execute temperature compensation
gravityTds.update(); //sample and calculate
tdsValue = gravityTds.getTdsValue(); // then get the value
// Serial.print(tdsValue,0);
// Serial.println("ppm");
}
// end tds sensor
//Function Function Penting Di Bawah
void konek(const char *payload, size_t length)
{
socket.emit("new user", "\"P1471984882\"");
Serial.println("Made Socket Connection");
digitalWrite(relay1, HIGH);
digitalWrite(relay2, HIGH);
IsConnect = true;
SetupRelayAplikasi();
}
void JalankanRelay(const char *payload, String NamaSocket, uint8_t pin)
{
String value = String(payload);
if (value == "true")
{
digitalWrite(pin, LOW);
KirimSocket(NamaSocket, "true");
Serial.println("its true");
}
else
{
digitalWrite(pin, HIGH);
KirimSocket(NamaSocket, "false");
Serial.println("its false");
}
}
void RelayWl(const char *payload, size_t length)
{
Serial.println(payload);
JalankanRelay(payload, "resWl", relay1);
}
void RelayTemp(const char *payload, size_t length)
{
Serial.println(payload);
JalankanRelay(payload, "resTemp", relay2);
}
void RelayHum(const char *payload, size_t length)
{
Serial.println(payload);
JalankanRelay(payload, "resHum", relay1);
}
void diskonek(const char *payload, size_t length)
{
digitalWrite(relay1, HIGH);
digitalWrite(relay2, HIGH);
IsConnect = false;
}
void RelayTds(const char *payload, size_t length)
{
JalankanRelay(payload, "resTds", relay1);
}
void KirimSocket(String nama, String val)
{
String Data = "{\"_id\":\"" + id + "\",\"_val\":\"" + val + "\"}";
socket.emit(nama.c_str(), Data.c_str());
}
String TangkapNilaiSensor(float sensor)
{
char Var[20];
dtostrf(sensor, 1, 2, Var);
String hasil = String(Var);
return hasil;
}
void SetupRelayAplikasi()
{
KirimSocket("resTemp", "false");
KirimSocket("resHum", "false");
KirimSocket("resTds", "false");
KirimSocket("resWl", "false");
KirimSocket("Mode", "true");
// KirimSocket("Mode","false");
}
| true |
0d1aef8141e9043ed5d057332a27b0f815cd2e7c | C++ | inf-eth/i02-0491-projects | /example-code/examples/VLI/VLI.cpp | UTF-8 | 11,863 | 3.1875 | 3 | [] | no_license | #include "VLI.h"
#include <string>
using std::string;
CVLI::CVLI (): Sign(0)
{
}
CVLI::CVLI (bool pSign, vector<short> &pNumber): Sign(pSign), Number(pNumber)
{
Format ();
}
void CVLI::Format ()
{
// Remove any preceding zeros.
for (int i=Number.size()-1; i > 0; i--)
{
if (Number[i] == 0)
Number.pop_back();
else
break;
}
// Zero should have a positive sign.
if (Number.size() == 1 && Number[0] == 0)
Sign = 0;
}
bool CVLI::IsZero () const
{
if (Sign == 0 && Number.size () == 1 && Number[0] == 0)
return true;
else
return false;
}
CVLI CVLI::Abs () const
{
CVLI rAbs = (*this);
rAbs.Sign = 0;
return rAbs;
}
CVLI CVLI::Power10 (int n)
{
CVLI temp;
temp.Number.insert (temp.Number.begin(), (short)1);
for (int i=0; i<n; i++)
temp.Number.insert (temp.Number.begin(), (short)0);
return temp;
}
// Using twice of rough estimation as break-point
// http://en.wikipedia.org/wiki/Methods_of_computing_square_roots
bool CVLI::CheckPrime (bool CheckBaseCase)
{
// Base case conditions upto 11.
if (CheckBaseCase == true)
{
if (Number.size() == 1)
{
if (Number[0] == 1 || Number[0] == 2 || Number[0] == 3 || Number[0] == 5 || Number[0] == 7)
return true;
}
else if (Number.size() == 2 && Number[0] == 1 && Number[1] == 1)
return true;
}
// Division by 2 and 3.
CVLI two, three;
two.Number.push_back (2);
three.Number.push_back (3);
if ( ((*this) % two).IsZero() == true || ((*this) % three).IsZero() == true )
return false;
CVLI UpperBound;
CVLI temp;
CVLI i;
CVLI one;
CVLI six;
CVLI Check;
bool odd = false;
i.Number.push_back (1);
one.Number.push_back (1);
six.Number.push_back (6);
Check.Number.push_back (5);
UpperBound = ++(Sqrt ((*this)));
while (Check < UpperBound)
{
if (((*this) % Check).IsZero() == true)
return false;
odd == false ? Check = (six * (i++))+one : Check = (six * i)-one;
odd = !odd;
}
return true;
}
CVLI CVLI::Sqrt (CVLI& VLI, int Iterations)
{
int n;
int D = VLI.Number.size();
CVLI x;
CVLI two;
CVLI six;
two.Number.push_back (2);
six.Number.push_back (6);
// Determine guess.
if (D % 2 == 1)
{
n = (D-1)/2;
x = two * Power10 (n);
}
else
{
n = (D-2)/2;
x = six * Power10 (n);
}
for (int i=0; i<Iterations; i++)
{
x = (x+(VLI/x))/two;
}
return x;
}
// Comparison operators.
bool CVLI::operator== (const CVLI& pVLI)
{
if (Sign == pVLI.Sign && Number == pVLI.Number)
return true;
else
return false;
}
bool CVLI::operator!= (const CVLI& pVLI)
{
if ((*this) == pVLI)
return false;
else
return true;
}
bool CVLI::operator< (const CVLI& pVLI)
{
// Equality check.
if ((*this) == pVLI)
return false;
// Zero check.
if ((*this).IsZero() || pVLI.IsZero())
{
if ((*this).IsZero())
return !pVLI.Sign;
else
return Sign;
}
// Sign check.
if (Sign != pVLI.Sign)
return Sign;
// Both positive.
if (Sign == 0)
{
// Check length.
if (Number.size() != pVLI.Number.size())
{
return (Number.size() < pVLI.Number.size());
}
else
{
for (int i=0; i < (int)Number.size(); i++)
{
if (Number[Number.size()-1-i] == pVLI.Number[pVLI.Number.size()-1-i])
continue;
else
return (Number[Number.size()-1-i] < pVLI.Number[pVLI.Number.size()-1-i]);
}
}
}
// Else if both negative.
else
{
// Check length.
if (Number.size() != pVLI.Number.size())
{
return !(Number.size() < pVLI.Number.size());
}
else
{
for (int i=0; i < (int)Number.size(); i++)
{
if (Number[Number.size()-1-i] == pVLI.Number[pVLI.Number.size()-1-i])
continue;
else
return !(Number[Number.size()-1-i] < pVLI.Number[pVLI.Number.size()-1-i]);
}
}
}
return false;
}
bool CVLI::operator> (const CVLI& pVLI)
{
// Equality check.
if ((*this) == pVLI)
return false;
// Zero check.
if ((*this).IsZero() || pVLI.IsZero())
{
if ((*this).IsZero())
return pVLI.Sign;
else
return !Sign;
}
// Sign check.
if (Sign != pVLI.Sign)
return !Sign;
// Both positive.
if (Sign == 0)
{
// Check length.
if (Number.size() != pVLI.Number.size())
{
return (Number.size() > pVLI.Number.size());
}
else
{
for (int i=0; i < (int)Number.size(); i++)
{
if (Number[Number.size()-1-i] == pVLI.Number[pVLI.Number.size()-1-i])
continue;
else
return (Number[Number.size()-1-i] > pVLI.Number[pVLI.Number.size()-1-i]);
}
}
}
// Else if both negative.
else
{
// Check length.
if (Number.size() != pVLI.Number.size())
{
return !(Number.size() > pVLI.Number.size());
}
else
{
for (int i=0; i < (int)Number.size(); i++)
{
if (Number[Number.size()-1-i] == pVLI.Number[pVLI.Number.size()-1-i])
continue;
else
return !(Number[Number.size()-1-i] > pVLI.Number[pVLI.Number.size()-1-i]);
}
}
}
return false;
}
bool CVLI::operator<= (const CVLI& pVLI)
{
if ((*this) < pVLI || (*this) == pVLI)
return true;
else
return false;
}
bool CVLI::operator>= (const CVLI& pVLI)
{
if ((*this) > pVLI || (*this) == pVLI)
return true;
else
return false;
}
// Pre-post increment.
CVLI CVLI::operator++ ()
{
Number[0]++;
// Carry Pass.
short Carry = 0;
for (int i=0; i < (int)Number.size(); i++)
{
Number[i] += Carry;
if (Number[i] > 9)
{
Carry = 1;
Number[i] -= 10;
}
else
Carry = 0;
}
if (Carry == 1)
Number.push_back (1);
return (*this);
}
// Pre-post increment.
CVLI CVLI::operator++ (int dummy)
{
CVLI temp = (*this);
++(*this);
return temp;
}
// Addition and subtraction
CVLI CVLI::operator+ (const CVLI& pVLI)
{
CVLI Sum;
// Same signs, simple addition.
if (Sign == pVLI.Sign)
{
Sum.Sign = Sign;
Number.size()<pVLI.Number.size() ? Sum.Number = pVLI.Number : Sum.Number = Number;
// First Pass.
for (int i=0; i < (int)(Number.size()<pVLI.Number.size() ? Number.size() : pVLI.Number.size()); i++)
Sum.Number[i] = Number.size()<pVLI.Number.size() ? Number[i] + Sum.Number[i]: pVLI.Number[i] + Sum.Number[i];
// Carry Pass.
short Carry = 0;
for (int i=0; i < (int)(Number.size()<pVLI.Number.size() ? pVLI.Number.size() : Number.size()); i++)
{
Sum.Number[i] += Carry;
if (Sum.Number[i] > 9)
{
Carry = 1;
Sum.Number[i] -= 10;
}
else
Carry = 0;
}
if (Carry == 1)
Sum.Number.push_back (1);
return Sum;
}
// Subtraction in case of different signs.
else
{
Sum.Sign = (*this).Abs() > pVLI.Abs() ? (*this).Sign : pVLI.Sign;
(*this).Abs() < pVLI.Abs() ? Sum.Number = pVLI.Number : Sum.Number = Number;
// First Pass.
for (int i=0; i < (int)((*this).Abs() < pVLI.Abs() ? Number.size() : pVLI.Number.size()); i++)
Sum.Number[i] = (*this).Abs() < pVLI.Abs() ? Sum.Number[i] - Number[i]: Sum.Number[i] - pVLI.Number[i];
// Carry Pass.
short Carry = 0;
for (int i=0; i < (int)((*this).Abs() < pVLI.Abs() ? pVLI.Number.size() : Number.size()); i++)
{
Sum.Number[i] += Carry;
if (Sum.Number[i] < 0)
{
Carry = -1;
Sum.Number[i] += 10;
}
else
Carry = 0;
}
Sum.Format();
return Sum;
}
}
CVLI CVLI::operator- (const CVLI& pVLI)
{
CVLI temp;
temp.Sign = !pVLI.Sign;
temp.Number = pVLI.Number;
return ((*this)+temp);
}
// Multiplication
CVLI CVLI::operator* (const CVLI& pVLI)
{
CVLI Product, temp;
int z;
Product.Number.push_back (0);
// this
//x pVLI
//-------
//Product
//-------
for (int i=0; i < (int)pVLI.Number.size(); i++)
{
temp.Number.clear();
for (z=0; z<i; z++)
temp.Number.push_back (0);
// Raw multiplication
for (int j=0; j < (int)Number.size(); j++)
{
temp.Number.push_back (Number[j] * pVLI.Number[i]);
}
// Carry manipulation.
short Carry = 0;
for (int k=0; k < (int)temp.Number.size(); k++)
{
temp.Number[k] += Carry;
if (temp.Number[k] > 9)
{
Carry = temp.Number[k] / 10;
temp.Number[k] %= 10;
}
else
Carry = 0;
}
if (Carry != 0)
temp.Number.push_back (Carry);
temp.Format();
Product = Product + temp;
}
Product.Sign = Sign ^ pVLI.Sign;
return Product;
}
// Division
CVLI CVLI::operator/ (const CVLI& pVLI)
{
CVLI Quotient;
CVLI Dividend;
CVLI Remainder;
CVLI Product;
CVLI Divisor = pVLI;
Divisor.Sign = 0;
bool ZeroFlag = false;
bool InsertedFlag = false;
for (int i=0; i<(int)Number.size(); i++)
{
if (ZeroFlag == true && Number[Number.size()-1-i] == (short)0)
{
Quotient.Number.insert (Quotient.Number.begin(), (short)0);
continue;
}
else
{
Dividend.Number.insert (Dividend.Number.begin(), 1, Number[Number.size()-1-i]);
ZeroFlag = false;
}
if (Dividend < Divisor)
{
if (InsertedFlag == true)
Quotient.Number.insert (Quotient.Number.begin(), (short)0);
continue;
}
else
{
int j = 1;
Product = Divisor;
for (; j<10; j++)
{
if (Product == Dividend)
break;
if ((Product+Divisor) > Dividend)
break;
Product = Product + Divisor;
}
Remainder = Dividend - Product;
Quotient.Number.insert (Quotient.Number.begin(), 1, (short)j);
InsertedFlag = true;
if (Remainder.IsZero() == true)
{
ZeroFlag = true;
Dividend.Number.clear();
}
else
Dividend = Remainder;
}
}
Quotient.Sign = Sign ^ pVLI.Sign;
return Quotient;
}
// modulus
CVLI CVLI::operator% (const CVLI& pVLI)
{
CVLI Quotient;
CVLI Dividend;
CVLI Remainder;
CVLI Product;
CVLI Divisor = pVLI;
Divisor.Sign = 0;
bool ZeroFlag = false;
bool InsertedFlag = false;
for (int i=0; i<(int)Number.size(); i++)
{
if (ZeroFlag == true && Number[Number.size()-1-i] == (short)0)
{
Quotient.Number.insert (Quotient.Number.begin(), (short)0);
continue;
}
else
{
Dividend.Number.insert (Dividend.Number.begin(), 1, Number[Number.size()-1-i]);
ZeroFlag = false;
}
if (Dividend < Divisor)
{
if (InsertedFlag == true)
Quotient.Number.insert (Quotient.Number.begin(), (short)0);
continue;
}
else
{
int j = 1;
Product = Divisor;
for (; j<10; j++)
{
if (Product == Dividend)
break;
if ((Product+Divisor) > Dividend)
break;
Product = Product + Divisor;
}
Remainder = Dividend - Product;
Quotient.Number.insert (Quotient.Number.begin(), 1, (short)j);
InsertedFlag = true;
if (Remainder.IsZero() == true)
{
ZeroFlag = true;
Dividend.Number.clear();
}
else
Dividend = Remainder;
}
}
if (Dividend.Number.empty() == false)
Remainder = Dividend;
return Remainder;
}
// << and >> operators.
ostream& operator<<(ostream& out, const CVLI& pVLI)
{
out << (pVLI.Sign?"-":"");
for(int i= pVLI.Number.size()-1; i >= 0; i--)
out << pVLI.Number[i];
return out;
}
istream& operator >> (istream& in, CVLI& pVLI)
{
pVLI.Number.clear();
string input;
in >> input;
// Sign check.
if (input.size() > 0 && input[0]=='-')
{
pVLI.Sign = 1;
input.replace (0, 1, "");
}
else
pVLI.Sign = 0;
// Remove any preceding zeros.
for (int i=pVLI.Sign; i < (int)input.size(); i++)
{
if (input[0] == '0')
input.replace (0, 1, "");
else
break;
}
for (int i=input.size()-1; i >= 0; i--)
{
if ((unsigned short)(input.c_str()[i]-48) <= 9U)
pVLI.Number.push_back ((unsigned short)(input.c_str()[i]-48));
else
continue;
}
// If zero string.
if (input.size() == 0)
{
pVLI.Number.push_back ((unsigned short)(0));
pVLI.Sign = 0;
}
return in;
}
| true |
b71d37736f19c509b55d0a621b36ac6fb67fa703 | C++ | MoriokaReimen/PreyPredator | /Test/test_Utility.cpp | UTF-8 | 2,561 | 2.96875 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <eigen3/Eigen/Geometry>
#include "Utility.hpp"
TEST(Utility, test_calcAngle)
{
{
Eigen::Vector2d self{1.0, 1.0};
Eigen::Vector2d other(1.0, 2.0);
double angle = calcAngle(self, other);
EXPECT_NEAR(angle, 0.0, 1E-6);
}
{
Eigen::Vector2d self{1.0, 1.0};
Eigen::Vector2d other(2.0, 1.0);
double angle = calcAngle(self, other);
EXPECT_NEAR(angle, 90.0, 1E-6);
}
{
Eigen::Vector2d self{1.0, 1.0};
Eigen::Vector2d other(1.0, 0.0);
double angle = calcAngle(self, other);
EXPECT_NEAR(angle, 180.0, 1E-6);
}
{
Eigen::Vector2d self{1.0, 1.0};
Eigen::Vector2d other(0.0, 1.0);
double angle = calcAngle(self, other);
EXPECT_NEAR(angle, -90.0, 1E-6);
}
{
Eigen::Vector2d self{1.0, 1.0};
Eigen::Vector2d other(2.0, 2.0);
double angle = calcAngle(self, other);
EXPECT_NEAR(angle, 45.0, 1E-6);
}
{
Eigen::Vector2d self{1.0, 1.0};
Eigen::Vector2d other(2.0, 0.0);
double angle = calcAngle(self, other);
EXPECT_NEAR(angle, 135.0, 1E-6);
}
{
Eigen::Vector2d self{1.0, 1.0};
Eigen::Vector2d other(0.0, 0.0);
double angle = calcAngle(self, other);
EXPECT_NEAR(angle, -135.0, 1E-6);
}
{
Eigen::Vector2d self{1.0, 1.0};
Eigen::Vector2d other(0.0, 2.0);
double angle = calcAngle(self, other);
EXPECT_NEAR(angle, -45.0, 1E-6);
}
}
TEST(Utility, test_wrap_deg_180)
{
{
double angle = wrap_deg_180(360);
EXPECT_NEAR(angle, 0.0, 1E-6);
}
{
double angle = wrap_deg_180(405);
EXPECT_NEAR(angle, 45.0, 1E-6);
}
{
double angle = wrap_deg_180(315);
EXPECT_NEAR(angle, -45.0, 1E-6);
}
{
double angle = wrap_deg_180(495);
EXPECT_NEAR(angle, 135.0, 1E-6);
}
{
double angle = wrap_deg_180(225);
EXPECT_NEAR(angle, -135.0, 1E-6);
}
}
TEST(Utility, test_angle_diff)
{
{
double diff = diff_deg(0, 45);
EXPECT_NEAR(diff, 45, 1E-6);
}
{
double diff = diff_deg(0, -45);
EXPECT_NEAR(diff, -45, 1E-6);
}
{
double diff = diff_deg(-45, -90);
EXPECT_NEAR(diff, -45, 1E-6);
}
{
double diff = diff_deg(-90, -45);
EXPECT_NEAR(diff, 45, 1E-6);
}
{
double diff = diff_deg(-90, -145);
EXPECT_NEAR(diff, -55, 1E-6);
}
} | true |
6eec619c56d6b2af3386588d676cb2d5b9e2c889 | C++ | wangshaohua/py2cpp | /lib/iter.hpp | UTF-8 | 131 | 2.546875 | 3 | [] | no_license | #ifndef _ITER_HPP_
#define _ITER_HPP_
template<class BaseType>
class Iter{
public:
virtual BaseType next() = 0;
};
#endif
| true |
f649527b7aa51009faa5cb376fefe72954caf2b8 | C++ | adityanjr/code-DS-ALGO | /CodeForces/Complete/1100-1199/1157E-MinimumArray.cpp | UTF-8 | 556 | 2.578125 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <vector>
#include <set>
#include <algorithm>
int main(){
long n; scanf("%ld", &n);
std::vector<long> a(n); for(long p = 0; p < n; p++){scanf("%ld", &a[p]);}
std::multiset<long> s; for(long p = 0; p < n; p++){long x; scanf("%ld", &x); s.insert(x);}
for(long p = 0; p < n; p++){
const long x = (2 * n - a[p]) % n;
std::multiset<long>::iterator it = s.lower_bound(x);
if(it == s.end()){it = s.begin();}
printf("%ld ", (a[p] + *it) % n);
s.erase(it);
}
return 0;
}
| true |
a6f9efecda72903d9814cff2b0c1b49d1fdc0fed | C++ | Seoui/Algorithm | /백준/1233_주사위.cpp | UTF-8 | 449 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
vector<int> sumSet(81);
int a, b, c;
cin >> a >> b >> c;
for (int i = 1; i <= a; ++i)
for (int j = 1; j <= b; ++j)
for (int k = 1; k <= c; ++k)
++sumSet[i + j + k];
int result = max_element(begin(sumSet), end(sumSet)) - begin(sumSet);
cout << result;
return 0;
} | true |
8d610a2e99cc893af0f7f98140b7a3caaa1275d3 | C++ | FeiCoding/Coursera_Cpp | /C++ Programming Design/week10/part9.cpp | UTF-8 | 1,063 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <set>
#include <iterator>
#include <algorithm>
using namespace std;
// 在此处补充你的代码
class A{
public:
char type;
int age;
A(int a):age(a){
type = 'A';
}
};
class B: public A{
public:
B(int a):A(a){
type = 'B';
}
};
struct Comp{
bool operator ()(A* t1, A* t2){
return t1->age < t2->age;
}
};
void Print(A *a){
cout << a->type << " " << a->age << endl;
}
int main()
{
int t;
cin >> t;
set<A*,Comp> ct;
while( t -- ) {
int n;
cin >> n;
ct.clear();
for( int i = 0;i < n; ++i) {
char c; int k;
cin >> c >> k;
if( c == 'A')
ct.insert(new A(k));
else
ct.insert(new B(k));
}
for_each(ct.begin(),ct.end(),Print);
cout << "****" << endl;
}
} | true |
ed595ae0595733ec78c3dcd25d6971b879b78b65 | C++ | ZackBleus/ByondHook | /ByondHook/extools/socket/socket.h | UTF-8 | 2,198 | 2.625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "../core.h"
#include "../../third_party/json.hpp"
#include <string>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#pragma comment (lib, "Ws2_32")
#else
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netdb.h> /* Needed for getaddrinfo() and freeaddrinfo() */
#include <unistd.h> /* Needed for close() */
#define SOCKET int
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#endif
const char* const DBG_DEFAULT_PORT = "2448";
class Socket
{
Socket(const Socket&) = delete;
Socket& operator=(const Socket&) = delete;
SOCKET raw_socket = INVALID_SOCKET;
static Socket from_raw(int raw_socket);
friend class JsonListener;
friend class TcpListener;
public:
Socket() {}
Socket(Socket&& other);
Socket& operator=(Socket&& other);
virtual ~Socket();
bool create(int family = AF_INET, int socktype = SOCK_STREAM, int protocol = IPPROTO_TCP);
void close();
SOCKET raw() { return raw_socket; }
};
class JsonStream
{
Socket socket;
std::string recv_buffer;
public:
JsonStream() {}
explicit JsonStream(Socket&& socket) : socket(std::move(socket)) {}
bool connect(const char* port = DBG_DEFAULT_PORT, const char* remote = "127.0.0.1");
bool send(const char* type, nlohmann::json content);
bool send(nlohmann::json j);
nlohmann::json recv_message();
void close() { socket.close(); }
};
class JsonListener
{
Socket socket;
public:
JsonListener() {}
bool listen(const char* port = DBG_DEFAULT_PORT, const char* iface = "127.0.0.1");
JsonStream accept();
void close() { socket.close(); }
};
class TcpStream
{
Socket socket;
public:
TcpStream() {}
explicit TcpStream(Socket&& socket) : socket(std::move(socket)) {}
bool connect(const char* port, const char* remote); //augh, why port first?! damn it spaceman
bool send(std::string data);
std::string recv();
void close() { socket.close(); }
bool valid() { return socket.raw() != INVALID_SOCKET; }
};
class TcpListener
{
Socket socket;
public:
TcpListener() {}
bool listen(const char* port, const char* iface);
TcpStream accept();
void close() { socket.close(); }
bool valid() { return socket.raw() != INVALID_SOCKET; }
};
| true |
8bbe5ffcb5d5c912c70ee1a71587d5092abbdf78 | C++ | birgersp/df-jobsounds | /src/Arg_parser.h | UTF-8 | 768 | 2.796875 | 3 | [] | no_license | /**
* @author birgersp
* https://github.com/birgersp
*/
#pragma once
#include <functional>
#include <cpputil/core.hpp>
#include <cpputil/Map.hpp>
using Command_callback = std::function<void() >;
using Setting_callback = std::function<void(String_ref) >;
class Arg_parser
{
public:
struct Command
{
Command_callback callback;
String description;
};
struct Setting
{
Setting_callback callback;
String description;
};
void add_command(String command, Command_callback callback, String description = "");
void add_setting(String keyword, Setting_callback callback, String description = "");
void parse_as_command(String_ref string);
void parse_as_setting(String_ref string);
Map<String, Command> commands;
Map<String, Setting> settings;
};
| true |
0b4f66c84738f084a1c653c68a1d2b5e36a60f54 | C++ | ebinsaad/CS60_254 | /code/stacks/stacks_with_lists/stack.cpp | UTF-8 | 1,320 | 3.421875 | 3 | [] | no_license | //
// Created by ebinsaad on 20/09/17.
//
#include "stack.h"
#include <stdlib.h>
void InitiateStack(Stack *ptrStack){
ptrStack->top = nullptr;
}
void Push(StackElement e, Stack *ptrStack){
StackNode * node = (StackNode*)malloc(sizeof(StackNode));
node->element =e;
node->next = ptrStack->top;
ptrStack->top = node;
}
void Pop(StackElement *ptre, Stack *ptrStack){
*ptre = ptrStack->top->element;
StackNode * temp = ptrStack->top;
ptrStack->top = ptrStack->top->next;
free(temp);
}
void StackTop(StackElement *ptre, Stack *ptrStack) {
*ptre = ptrStack->top->element;
}
int IsFullStack(Stack *ptrStack){
return 0;
}
int IsEmptyStack(Stack *ptrStack){
return ptrStack->top == nullptr;
}
int StackSize(Stack *ptrStack){
StackNode *crr = ptrStack->top;
int size =0;
while(crr!= nullptr){
crr = crr->next;
size++;
}
return size;
}
void DeleteStack(Stack *ptrStack){
StackNode *crr = ptrStack->top;
while(crr!= nullptr){
crr = crr->next;
free(ptrStack->top);
ptrStack->top = crr;
}
}
void TraverseStack(Stack *ptrStack, void (*ptrFun)(StackElement)){
StackNode *crr = ptrStack->top;
while(crr!= nullptr){
(*ptrFun)(crr->element);
crr = crr->next;
}
}
| true |
475f7754ffe928fe8a1ff6694a7271a6c5f6f680 | C++ | dongdong97/TIL | /C++ ESPRESSO/CH 05/CH 05/car3.cpp | UTF-8 | 1,109 | 3.296875 | 3 | [
"MIT"
] | permissive | ////
//// car3.cpp
//// CH 05
////
//// Created by 동균 on 2018. 5. 24..
//// Copyright © 2018년 동균. All rights reserved.
////
//
//#include <iostream>
//#include <string>
//using namespace std;
//
//class Car{
//private:
// int speed;
// int gear;
// string color;
//public:
// //접근자 선언
// int getSpeed() {
// return speed;
// }
// //설정자 선언
// void setSpeed(int s){
// speed =s;
// }
// //접근자 선언
// int getGear() {
// return gear;
// }
// //설정자 선언
// void setGear(int g){
// gear = g;
// }
// //접근자 선언
// string getColor() {
// return color;
// }
// //설정자 선언
// void setColor(string c) {
// color =c;
// }
//};
//
//int main() {
// Car myCar;
//
// myCar.setSpeed(100);
// myCar.setGear(3);
// myCar.setColor("red");
//
// cout <<"차의 속도 " << myCar.getSpeed() <<endl;
// cout <<"차의 기어 " << myCar.getGear() <<endl;
// cout <<"차의 색상 " << myCar.getSpeed() <<endl;
//
// return 0;
//
//}
| true |
2f943e764b74c5d8c7aa71e5f8c8df01ed5e6241 | C++ | lijianmin01/CplusplusStudy | /1~5单元/vectorClass/StackOfIntegers.h | UTF-8 | 191 | 3.046875 | 3 | [] | no_license | #pragma once
class StackOfIntegers {
private:
int elements[100];
int size{ 0 };
public:
StackOfIntegers();
bool empty();
int peek();
void push(int value);
int pop();
int getSize();
}; | true |
3dabd6f585713fb94a9129c38e5d17eac7801910 | C++ | khoihd/dcop_generator_pdcdcop | /include/Kernel/variable.hpp | UTF-8 | 1,602 | 3.328125 | 3 | [] | no_license | #ifndef DCOP_GENERATOR_KERNEL_VARIABLE_HPP
#define DCOP_GENERATOR_KERNEL_VARIABLE_HPP
#include <string>
#include <memory>
namespace dcop_generator {
class variable {
public:
typedef std::shared_ptr<variable> ptr;
variable(int id, std::string name, std::string domain, std::string agent)
: m_id(id), m_name(name), m_domain(domain), m_agent(agent) { }
int get_id() const {
return m_id;
}
std::string get_name() const {
return m_name;
}
std::string get_domain() const {
return m_domain;
}
std::string get_agent() const {
return m_agent;
}
std::string to_string() const {
return std::to_string(m_id) + " " + m_name + " (domain: " + m_domain + ") owned by: " + m_agent;
}
friend bool operator==(const variable &lhs, const variable &rhs) {
// return (lhs.m_id == rhs.m_id) && (lhs.m_name == rhs.m_name) && (lhs.m_domain == rhs.m_domain) && (lhs.m_agent == rhs.m_agent);
return lhs.m_name == rhs.m_name;
}
friend bool operator!=(const variable &lhs, const variable &rhs) {
return lhs.m_name != rhs.m_name;
}
private:
// The variable id
int m_id;
// The Variable name.
std::string m_name;
// The domain name associated to this variable.
std::string m_domain;
// The name of the agent which ownes this variable,
std::string m_agent;
};
}
#endif // DCOP_GENERATOR_KERNEL_VARIABLE_HPP
| true |
25279e0553855e24bc9a9abdbf8f822292553fc3 | C++ | zha0ming1e/3D_Point_Cloud_Processing | /ch1/src/voxelgridfilter.cpp | UTF-8 | 4,741 | 2.890625 | 3 | [] | no_license | #include "voxelgridfilter.h"
VoxelGridFilter::VoxelGridFilter(const PointCloud::Ptr &origin_pointcloud_ptr,
Vec3 voxel_grid_size,
VoxelGridFilter::ALGO algorithm)
: origin_pointcloud_ptr_(origin_pointcloud_ptr),
voxel_grid_size_(std::move(voxel_grid_size)),
algorithm_(algorithm) {
// initialization
std::cout << "\n[ VoxelGridFilter Initializing... ]" << std::endl;
PointCloud::Ptr ptr(new PointCloud());
filtered_pointcloud_ptr_ = ptr;
// voxel grid filtering
voxel_grid_filter();
std::cout << "[ VoxelGridFilter Initialization Finished. ]" << std::endl;
}
VecVector3d VoxelGridFilter::minmaxVertex(const PointCloud::Ptr &point_cloud_ptr) {
// each point
VecVector3d all_points_coor;
auto all_points = point_cloud_ptr->GetAllPoints();
for (auto &pt : all_points) {
auto pt_coor = pt->GetPos();
all_points_coor.push_back(pt_coor);
}
// x, y, z
VecVector3d minmaxVertexVec(2);
for (int i = 0; i < 3; ++i) {
std::sort(all_points_coor.begin(), all_points_coor.end(),
[i](const Vec3 &coor1, const Vec3 &coor2) -> bool {
return coor1[i] < coor2[i];
});
minmaxVertexVec[0].row(i) = all_points_coor[0].row(i);
minmaxVertexVec[1].row(i) = all_points_coor.back().row(i);
}
return minmaxVertexVec;
}
void VoxelGridFilter::filter_algorithm(const std::map<long long, int> &index_and_id) {
// filter algorithm: CENTROID or RANDOM
if (algorithm_ == ALGO::CENTROID) {
auto iter0 = index_and_id.begin();
for (auto iter = index_and_id.begin(); iter != index_and_id.end(); ++iter) {
int count = 1;
Vec3 centroid = Vec3::Zero(3, 1);
centroid += origin_pointcloud_ptr_->GetAllPoints()[iter->second]->GetPos();
// iter0 = iter;
while (++iter0 != index_and_id.end() && iter0->first == iter->first) {
++iter;
++count;
centroid += origin_pointcloud_ptr_->GetAllPoints()[iter->second]->GetPos();
}
centroid /= count;
Point::Ptr pt_ptr(new Point(centroid));
filtered_pointcloud_ptr_->InsertPoint(pt_ptr);
}
} else if (algorithm_ == ALGO::RANDOM) {
std::default_random_engine rng(time(nullptr));
auto iter0 = index_and_id.begin();
for (auto iter = index_and_id.begin(); iter != index_and_id.end(); ++iter) {
std::vector<int> sameId;
sameId.push_back(iter->second);
// iter0 = iter;
while (++iter0 != index_and_id.end() && iter0->first == iter->first) {
++iter;
sameId.push_back(iter->second);
}
std::uniform_int_distribution<int> dist(0, sameId.size()-1);
int randomId = sameId[dist(rng)];
Vec3 randPos = origin_pointcloud_ptr_->GetAllPoints()[randomId]->GetPos();
Point::Ptr pt_ptr(new Point(randPos));
filtered_pointcloud_ptr_->InsertPoint(pt_ptr);
}
}
}
void VoxelGridFilter::voxel_grid_filter() {
// voxel dimension
auto minmaxVertexCoor = minmaxVertex(origin_pointcloud_ptr_);
Vec3 minVertex = minmaxVertexCoor[0];
Vec3 maxVertex = minmaxVertexCoor[1];
long long nx, ny, nz;
nx = static_cast<long long>((maxVertex.x()-minVertex.x()) / voxel_grid_size_.x());
ny = static_cast<long long>((maxVertex.y()-minVertex.y()) / voxel_grid_size_.y());
nz = static_cast<long long>((maxVertex.z()-minVertex.z()) / voxel_grid_size_.z());
// check data type overflow
if (nx < 0 || ny < 0 || nz < 0 || (nx*ny*nz) > static_cast<long long>(std::numeric_limits<int>::max())) {
std::cerr << "Error: data type overflow. " << std::endl;
return;
}
// each point's index and id
// std::map -> automatic sorting
std::map<long long, int> index_and_id;
auto all_points = origin_pointcloud_ptr_->GetAllPoints();
auto all_points_num = all_points.size();
for (int i = 0; i < all_points_num; ++i) {
auto pos = all_points[i]->GetPos();
long long hx = std::floor(1.0 * (pos.x()-minVertex.x()) / voxel_grid_size_.x());
long long hy = std::floor(1.0 * (pos.y()-minVertex.y()) / voxel_grid_size_.y());
long long hz = std::floor(1.0 * (pos.z()-minVertex.z()) / voxel_grid_size_.z());
long long index = hx + hy*nx + hz*nx*ny;
index_and_id.insert(std::make_pair(index, i));
}
// filtering
filter_algorithm(index_and_id);
}
| true |
12a11abf4f5b0607f53f9f3f700b129346ae7cf7 | C++ | onww1/Problem-Solving | /BOJ/Stack/boj1406_에디터.cpp | UTF-8 | 1,453 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
struct list {
char c;
list *prev, *next;
list(): c(0), prev(nullptr), next(nullptr){}
list(char _c): c(_c), prev(nullptr), next(nullptr){}
};
void printList(list *head) {
list *ptr = head;
while (ptr->c != 0) {
cout << ptr->c;
ptr = ptr->next;
}
cout <<'\n';
}
void addNode(char c, list *cur) {
list* newNode = new list(c);
newNode->next = cur;
newNode->prev = cur->prev;
cur->prev->next = newNode;
cur->prev = newNode;
}
void deleteNode(list *cur) {
if (cur->prev->c == 0) return;
list *deletedNode = cur->prev;
cur->prev->prev->next = cur;
cur->prev = cur->prev->prev;
delete deletedNode;
}
int main(int argc, char const *argv[])
{
cin.tie(NULL);
ios_base::sync_with_stdio(false);
string input;
cin >> input;
list *head = new list;
list *tail = new list;
head->next = tail;
tail->prev = head;
int len = input.size();
for (int i=0; i<len; i++) {
addNode(input[i], tail);
}
int N;
cin >> N;
char op, c;
list *ptr = tail;
for (int i=0; i<N; i++) {
cin >> op;
if (op == 'L') {
if (ptr->prev->c != 0)
ptr = ptr->prev;
}
else if (op == 'D') {
if (ptr->next != nullptr)
ptr = ptr->next;
}
else if (op == 'B') {
deleteNode(ptr);
}
else if (op == 'P') {
cin >> c;
addNode(c, ptr);
}
}
printList(head->next);
ptr = tail;
while (ptr->prev != head)
deleteNode(ptr);
delete head;
delete tail;
return 0;
} | true |
8be4af5cc028ac0f238a40edf35fd2b52b43b4dc | C++ | zerkaner/ALU | /Code/Agents/Agent.h | UTF-8 | 1,275 | 2.734375 | 3 | [] | no_license | #pragma once
class IAgentLogic;
class PerceptionUnit;
class World;
/** The abstract agent. This is the most generic agent form, it specifies the main execution
* cycle (SRA) and several extension points available for specialized agent implementations. */
class Agent {
private:
World* _world; // Execution reference for add and remove queries.
protected:
long ID; // Unique identifier.
long Ticks; // Tick counter.
bool IsAlive; // Alive flag for execution and deletion checks.
PerceptionUnit* PU; // Sensor container and input gathering.
IAgentLogic* RL; // The agent's reasoning logic.
/** Constructor for an abstract agent. It serves as a base class that is extended with
* domain specific sensors, actions and reasoning, optionally containing a knowledge base. */
Agent(World* world);
/** The removal method stops external triggering of the agent. */
virtual void Remove();
public:
/** This is the main function of the agent program. It executes all three steps,
* calling the concrete functions of the domain-specific agent, respectively.
* The execution is triggered by the 'World' this agent is living in. */
void Tick();
};
| true |
90dbaf69827e6a33446c09d0885d9ff2509c2350 | C++ | sunshinenny/Data-structure-study | /数据结构/C++与C的区别/练习2.cpp | UTF-8 | 174 | 2.96875 | 3 | [] | no_license | #include<iostream>
using namespace std;
void Input(int &x)
{
cin>>x;
}
int main()
{
int x;
cout<<"Input x:";
Input(x);
cout<<"x="<<x<<endl;
return 0;
}
| true |
162c76e48169703fe2d9ad15f10d3167325c4ffe | C++ | BoyanHou/Threading-and-Work-Distribution-Strategies-Server-Performance-and-Scalability-Study | /Client/client_main.cpp | UTF-8 | 3,136 | 3.171875 | 3 | [] | no_license | #include <assert.h>
#include <string>
#include "../Tools/String_Tools_Exceptions.h"
#include "Client.h"
void run_client_single(Client & client) {
//Read request from cmd line
std::string request;
std::getline(std::cin, request);
// //Split the request
// std::vector<std::string> to_send = String_Tools::split_str(request, ",");
// //Ensure the second string doesn't include '\n'
// assert(to_send[1].find("\n") == std::string::npos);
//Run client,send the 2 arguments
client.run_single(request);
return;
}
void run_client_multiple(Client & client, const std::vector<std::string> & requests) {
client.run_multi_thread(requests);
return;
}
void run_client_multiple(Client & client,
unsigned int thread_num,
unsigned int bucket_num,
unsigned int delay_min,
unsigned int delay_max) {
client.run_multi_thread(thread_num,
bucket_num,
delay_min,
delay_max);
return;
}
int main(int argc, char ** argv) {
if (argc != 3 && argc != 4 && argc != 7) {
std::string usage = "Usage:./client <server_ip> <server_port>\n";
usage += " ./client <server_ip> <server_port> <test_file_path>\n";
usage += " ./client <server_ip> <server_port> <thread_num> <bucket_num> <delay_min> <delay_max>\n";
std::cerr << usage << std::endl;
return -1;
}
// create client
std::string server_ip(argv[1]);
std::string server_port(argv[2]);
Client client(server_ip, server_port);
if (argc == 4) {
std::vector<std::string> requests;
try {
requests = String_Tools::read_vec_from_file(argv[3]);
// de-escape the "\\"s back to "\"s
for (unsigned int i = 0; i < requests.size(); i++) {
std::string::size_type len = requests[i].length();
if (len >= 2 && requests[i].substr(len-2).compare("\\n") == 0) {
requests[i] = requests[i].substr(0, len-2);
requests[i] += "\n";
}
}
}
catch (file_not_found_exception * e) {
std::cout << e->what() << std::endl;
return EXIT_FAILURE;
}
// for (unsigned int i = 0; i < requests.size(); i++) {
// std::cout << requests[i] << std::endl;
// }
run_client_multiple(client, requests);
}
else if (argc == 7) {
unsigned int thread_num = 0;
unsigned int bucket_num = 0;
unsigned int delay_min = 0;
unsigned int delay_max = 0;
try {
thread_num = String_Tools::str_to_unsigned_int(argv[3]);
bucket_num = String_Tools::str_to_unsigned_int(argv[4]);
delay_min = String_Tools::str_to_unsigned_int(argv[5]);
delay_max = String_Tools::str_to_unsigned_int(argv[6]);
}
catch (parse_unsigned_int_exception * e) {
std::cout << e->what() << std::endl;
return EXIT_FAILURE;
}
run_client_multiple(client,
thread_num,
bucket_num,
delay_min,
delay_max);
}
else {
run_client_single(client);
}
return 0;
}
| true |
40ef24b1f9ccbec07d57da1d0ae406aa609369f0 | C++ | hugues-vincent/uva | /893-Y3K_problem/main.cpp | UTF-8 | 993 | 2.875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int day[] = {31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int year_length(int y) { return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) ? 366 : 365; }
int month_length(int m, int y) {
if (m == 1) return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) ? 29 : 28;
return day[m];
}
int add_day(int &d, int &m, int &y){
d = (d + 1) % month_length(m, y);
if (d == 0) {
m = (m + 1) % 12;
if (m == 0) y++;
}
return 1;
}
int main() {
int N, d, m, y;
int m_len, y_len;
while(scanf("%d %d %d %d", &N, &d, &m, &y) != EOF && N != 0 && d != 0 && m != 0 && y != 0) {
d--; m--;
while( N > 0 && (m != 0 || d != 0)) N -= add_day(d, m, y);
y_len = year_length(y);
while(N >= y_len) {
y++;
N -= y_len;
y_len = year_length(y);
}
while(N > 0) N -= add_day(d, m, y);
printf("%d %d %d\n", d + 1, m + 1, y);
}
return 0;
} | true |
4b01b4e2eea81aa784beb8d2e8540377e3f37446 | C++ | vastamat/BGE | /bge/include/events/Event.h | UTF-8 | 1,991 | 3.203125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include "core/Common.h"
#include <functional>
namespace bge
{
/**
* All existing event types
*/
enum class EventType
{
None = 0,
WindowClose,
WindowResize,
WindowFocus,
WindowLostFocus,
WindowMoved,
KeyPressed,
KeyReleased,
KeyTyped,
MouseButtonPressed,
MouseButtonReleased,
MouseMoved,
MouseScrolled,
ComponentAdded,
ComponentRemoved,
EntitiesDestroyed,
CollidedBodies
};
#define EVENT_CLASS_TYPE(type) \
static EventType GetStaticType() { return EventType::type; } \
virtual EventType GetEventType() const override { return GetStaticType(); }
/**
* Base class for all events.
* Derived classes must override the GetEventType function,
* and implement a "static EventType GetStaticType() {}"
* which is needed to query the type of the event in the dispatcher.
* The macro above can be used for an easy way to do that.
*/
class Event
{
public:
bool m_Handled = false; /**< flag whether the event has been handled */
virtual EventType GetEventType() const = 0;
};
/**
* The event dispatcher handles the dispatching of events by
* invoking the passed handler function only of the event types match
*/
class EventDispatcher
{
template <typename T> using EventFn = std::function<bool(T&)>;
public:
explicit EventDispatcher(Event& event)
: m_Event(event)
{
}
/**
* The dispatch function is used to call event handler function safely
* by ignoring ones which do not match the event type
* @param func the event handler function of a specific event type
* @return flag whether the event has been dispatched successfully
*/
template <typename T> bool Dispatch(EventFn<T> func)
{
if (m_Event.GetEventType() == T::GetStaticType())
{
m_Event.m_Handled = func(*(T*)&m_Event);
return true;
}
return false;
}
private:
Event& m_Event; /**< Event which is being dispatched */
};
} // namespace bge | true |
47c4c2301cbe6c9cecce28559b27d70dc1209e9e | C++ | ro9n/lc | /162.find.peak.elem.cpp | UTF-8 | 456 | 3.09375 | 3 | [] | no_license | /**
* @file 162.find.peak.elem
* @author Touhid Alam <taz.touhid@gmail.com>
*
* @date Sunday September 06 CURRENT_YEAR
*
* @brief
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findPeakElement(vector<int>& v) {
int n = v.size(), l = 0, r = n - 1;
while(l < r) {
int m = l + (r - l) >> 1;
if (v[m - 1] > v[m]) l = m - 1;
else r = m + 1;
}
return l;
}
};
| true |
0a477e621c5690959b440c772eeb4690dac3ab9b | C++ | mguc/arts | /test/TestWallEstimator.cpp | UTF-8 | 1,926 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | #include "arts/estimator/LocationEstimator.hpp"
#include "arts/Path.hpp"
#include "arts/Simulation.hpp"
#include "catch2/catch.hpp"
#include <math.h>
using namespace arts;
using namespace std;
#define REFERENCE_ROOM "rsc/environment/4x5x3room.obj"
#define SIMULATION_TIME_S 0.1
#define DISTANCE_M 0.1
double EstimateAngle(double t1, double t2)
{
double c = 340;
return acos(c*(t1-t2)/DISTANCE_M) * 180.0 / M_PI;
}
double EstimateDistance(double t1, double t2)
{
double c = 340;
double t = (t1+t2)/2;
return c*t/2;
}
TEST_CASE("TestWallEstimator", "[estimator]")
{
Environment env;
env.Parse(REFERENCE_ROOM);
uint32_t order = 1;
double d = DISTANCE_M;
vector<Source> sources;
sources.push_back(Source(Point(d/2,0,0)));
vector<Receiver> receivers;
receivers.push_back(Receiver(Point(0,0,0)));
receivers.push_back(Receiver(Point(d,0,0)));
Simulation sim(env, receivers, sources);
vector<vector<vector<Path>>> paths(receivers.size(), vector<vector<Path>>(sources.size()));
vector<vector<AudioFile<double>>> audioFiles(receivers.size(), vector<AudioFile<double>>(sources.size()));
vector<vector<double>> rx_times(receivers.size());
sim.Run(SIMULATION_TIME_S, order, paths, audioFiles);
for (uint32_t rx = 0; rx < receivers.size(); ++rx)
{
for(uint32_t sample = 0; sample < audioFiles[rx][0].getNumSamplesPerChannel(); ++sample)
{
if(audioFiles[rx][0].samples[0][sample] > 0)
{
cout << "rx" << rx << ": " << sample << endl;
rx_times[rx].push_back((double)sample/receivers[rx].GetSamplingFrequency());
}
}
}
for(uint32_t i = 0; i < rx_times[0].size(); ++i) {
cout << "Angle: " << EstimateAngle(rx_times[0][i], rx_times[1][i]) << "°, Distance: " << EstimateDistance(rx_times[0][i], rx_times[1][i]) << endl;
}
}
| true |