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
ae0501e6bdd16b20326bacf4ccac66caa576e710
C++
NHERI-SimCenter/smelt
/src/beta_dist.cc
UTF-8
911
2.625
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
#include <vector> #include <boost/math/distributions/beta.hpp> #include "beta_dist.h" stochastic::BetaDistribution::BetaDistribution(double alpha, double beta) : Distribution(), alpha_{alpha}, beta_{beta}, distribution_{alpha, beta_} {} std::vector<double> stochastic::BetaDistribution::cumulative_dist_func( const std::vector<double>& locations) const { std::vector<double> evaluations(locations.size()); for (unsigned int i = 0; i < locations.size(); ++i) { evaluations[i] = cdf(distribution_, locations[i]); } return evaluations; } std::vector<double> stochastic::BetaDistribution::inv_cumulative_dist_func( const std::vector<double>& probabilities) const { std::vector<double> evaluations(probabilities.size()); for (unsigned int i = 0; i < probabilities.size(); ++i) { evaluations[i] = quantile(distribution_, probabilities[i]); } return evaluations; }
true
b030261a235273d8c6e2c0a3530b68b4c5dce7c3
C++
SlawomirKwiatkowski/Arkanoid
/CMapEditorState.cpp
UTF-8
4,619
2.71875
3
[]
no_license
#include "CMapEditorState.h" CMapEditorState::CMapEditorState(RenderWindow* window, stack<CState*>* states) :CState(window,states) { background.setSize(Vector2f(window->getSize().x, window->getSize().y)); background.setFillColor(Color::Black); initBlock(); } CMapEditorState::~CMapEditorState() { saveToFile(); auto it = this->blocks.begin(); for (it = this->blocks.begin();it != this->blocks.end();++it) { delete* it; } auto it2 = this->gobjects.begin(); for (it2 = this->gobjects.begin();it2 != this->gobjects.end();++it2) { delete* it2; } delete this->blockToClick; cout << "koniec editorstate"; Sleep(500); } void CMapEditorState::endState() { } void CMapEditorState::update(const float& dt) { this->updateInput(dt); updateMousePosition(); mouseKlickMapCreator(); for (auto& object : this->gobjects) { object->updatePos(); } } void CMapEditorState::render(RenderTarget* target) { for (auto& object : this->gobjects) if (object->isDestroyed() == false) { object->render(*target); } } void CMapEditorState::renderButtons(RenderTarget* target) { } void CMapEditorState::initBlock() { fstream plik; plik.open("mapa.txt", ios::in); if (plik.good() == false) { exit; }; int n; plik >> n; for (int i = 0;i < n;i++) { float x; plik >> x; float y; plik >> y; blocks.emplace_back(new CBlock(x, y, 60, 20)); gobjects.push_back(new CGBlock(blocks.back())); }; plik.close(); this->blockToClick = new CBlock(400, 550, 80,30); gobjects.push_back(new CGBlock(blockToClick)); } void CMapEditorState::saveToFile() { { fstream plik; plik.open("mapa.txt", ios::out); if (plik.good() == true) { std::cout << "Uzyskano dostep do pliku!" << std::endl; plik << size(this->blocks) << endl; for (auto& block : this->blocks) { plik << (block->left() + block->right()) / 2 << endl; plik << (block->top() + block->bottom()) / 2 << endl; } } else std::cout << "Dostep do pliku zostal zabroniony!" << std::endl; plik.close(); } } void CMapEditorState::updateInput(const float& dt) { this->checkForQuit(); } void CMapEditorState::mouseKlickMapCreator() { { cout << mousePosView.x << " " << mousePosView.y << " "; cout << "1 "; if (this->blockToClick->isKlicked() == true) //sprawdza czy bloczek jest klikniêty { this->blockToClick->updatePosi(mousePosView.x, mousePosView.y);//jeœli tak to pod¹¿a za kursorem cout << "2 "; addBlock(); //sprawdza czy kliknales eby dodac if (Mouse::isButtonPressed(Mouse::Right)) //sprawdza czy odklikn¹³eœ { this->blockToClick->unklick(); this->blockToClick->updatePosi(400, 550); } } else { //jeœli bloczek dodaj¹cy nie jest klikniêty to sprawdza inne i czy klikn¹³eœ na dodaj¹cy editBlock(); cout << "lolo "; if (Mouse::isButtonPressed(Mouse::Left) && this->blockToClick->isKlicked() == false// sprawdza czy klikn¹³eœ w dodanie && mousePosView.x < this->blockToClick->right() && mousePosView.x > this->blockToClick->left() && mousePosView.y < this->blockToClick->bottom() && mousePosView.y > this->blockToClick->top()) { this->blockToClick->klick(); cout << "elo elooll "; } } } } void CMapEditorState::addBlock() { bool kol = false; if (Mouse::isButtonPressed(Mouse::Left)) { for (auto& block : blocks) { if (block->right() >= this->blockToClick->left() && block->left() <= this->blockToClick->right() && block->bottom() >= this->blockToClick->top() && block->top() <= this->blockToClick->bottom()) { kol = true; } } if (kol == false && mousePosView.y<350) { blocks.emplace_back(new CBlock(mousePosView.x, mousePosView.y, 60, 20)); gobjects.push_back(new CGBlock(blocks.back())); } }; } void CMapEditorState::editBlock() { int i = -1; for (auto& block : this->blocks) { if (block->isKlicked() == true) { block->updatePosi(mousePosView.x, mousePosView.y); cout << "to jest: " << i << " "; if (Mouse::isButtonPressed(Mouse::Right)) { block->unklick(); cout << "wololo"; } } i++; if (block->isKlicked() == true && Keyboard::isKeyPressed(Keyboard::Delete)) { block->destroy(); for (auto& object : this->gobjects) { object->updatePos(); } auto it = blocks.begin() + i; this->blocks.erase(it); } if ((Mouse::isButtonPressed(Mouse::Left) && block->isKlicked() == false// sprawdza czy klikn¹³eœ w dodanie && mousePosView.x < block->right() && mousePosView.x > block->left() && mousePosView.y < block->bottom() && mousePosView.y > block->top())) { block->klick(); } } }
true
94f87e6c25245c10f9e2cbadcc3e5f3b8717084b
C++
brandonRichardson/uml-acm-games
/game_engine/Player.h
UTF-8
865
3.015625
3
[]
no_license
/* * File: Player.h * Author: J. Madden * * Created on February 8, 2013, 12:16 PM */ #ifndef PLAYER_H #define PLAYER_H /* * TODO: A lot, most of which is not doable until * we decide where we're going with this project. */ #include <string> #include "stats.h" #include "Inventory.h" #include "Position.h" class Player{ std::string name; StatSheet stats; Position pos; Inventory inv; public: //Constructor Player(std::string theName){ name = theName; } //Getter functions std::string getName(){ return name; } StatSheet &getStats(){ return stats; } Position &getPosition(){ return pos; } Inventory &getInventory(){ return inv; } //Inventory related functions void pickUpItem(Item toPickUp); //Action related functions }; #endif /* PLAYER_H */
true
48dc441488f53b1a9ce2193170c37dd7fbc167e3
C++
minhazmiraz/Codeforces_AC_Submission
/900A[Find_Extra_One].cpp
UTF-8
285
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ int n,neg=0,pos=0; cin>>n; for(int i=1;i<=n;i++){ int a,b; cin>>a>>b; if(a<0) neg++; if(a>0) pos++; } if(neg<=1 || pos<=1) cout<<"Yes\n"; else cout<<"No\n"; return 0; } /* Powered by Buggy plugin */
true
f1cf218d1762e464ef333dbf40c472c9163f1fa6
C++
grtushar/LightOJ
/loj1374_BNUOJ_13220_confusion_in_the_problemset.cpp
UTF-8
837
2.625
3
[]
no_license
using namespace std; #include<iostream> #include<cstdio> #include<cstring> int count[1000010]; int main() { long long int arr[10010]; int T,n,Case=1,i,flag; scanf("%d",&T); while(T--) { memset(count,0,sizeof(count)); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%lld",&arr[i]); count[arr[i]]++; } flag=1; for(i=0;i<n;i++) { if(count[i]>0) { count[i]--; } else if(count[n-1-i]>0) { count[n-1-i]--; } else { flag=0; } } if(flag) printf("Case %d: yes\n",Case++); else printf("Case %d: no\n",Case++); } return 0; }
true
4ea2708811cd44926a0a7892170faea4349e6489
C++
cxwcfea/uva-code
/232.cpp
UTF-8
2,896
2.75
3
[]
no_license
/* * ===================================================================================== * * Filename: 232.cpp * * Description: * * Version: 1.0 * Created: 07/04/2014 19:54:49 * Revision: none * Compiler: g++ * * Author: cxwcfea(cxwcfea@163.com), * Organization: * * ===================================================================================== */ #include <cstdio> enum class NodeType { BLACK, ELIGIBLE, WHITE }; struct Node { NodeType type; char ch; int value; bool process_for_down; Node(NodeType t = NodeType::WHITE, char c = '*') : type{t}, ch{c}, value{0}, process_for_down{false} {} void reset() { type = NodeType::WHITE; ch = '*'; value = 0; process_for_down = false; } }; const int kMax = 12; Node matrix[kMax][kMax]; char input[kMax]; int main() { #ifdef Debug freopen("232.in", "r", stdin); #endif int r, c, cases = 0; while (1) { scanf("%d", &r); if (!r) { break; } scanf("%d", &c); getchar(); if (cases) printf("\n"); printf("puzzle #%d:\n", ++cases); printf("Across\n"); int word_num = 0, count = 0; bool processing = false; for (int i = 0; i < r; ++i) { fgets(input, kMax, stdin); for (int j = 0; j < c; ++j) { matrix[i][j].reset(); if (input[j] == '*') { if (processing) { printf("\n"); processing = false; } matrix[i][j].type = NodeType::BLACK; } else { if (j == 0 || i == 0 || matrix[i-1][j].type == NodeType::BLACK || matrix[i][j-1].type == NodeType::BLACK) { matrix[i][j].type = NodeType::ELIGIBLE; matrix[i][j].value = ++count; if (j == 0 && processing) { printf("\n"); processing = false; } if (!processing) { processing = true; printf("%3d.%c", count, input[j]); } else { printf("%c", input[j]); } } else { printf("%c", input[j]); } matrix[i][j].ch = input[j]; } } } if (processing) printf("\n"); printf("Down\n"); for (int i = 0; i < r; ++i) { for (int j = 0; j < c; ++j) { if (matrix[i][j].type == NodeType::ELIGIBLE && !matrix[i][j].process_for_down) { matrix[i][j].process_for_down = true; processing = true; printf("%3d.%c", matrix[i][j].value, matrix[i][j].ch); int x = i + 1; while (x < r && matrix[x][j].type != NodeType::BLACK) { matrix[x][j].process_for_down = true; printf("%c", matrix[x][j].ch); ++x; } printf("\n"); } } } /* int count = 0; for (int i = 0; i < r; ++i) { for (int j = 0; j < c; ++j) { if (matrix[i][j].type == NodeType::BLACK) { printf(" * "); } else if (matrix[i][j].type == NodeType::ELIGIBLE) { printf("%2d ", ++count); } else { printf("%2c ", matrix[i][j].ch); } } printf("\n"); } */ } return 0; }
true
492444df9b1a8cace6576504faebd93ac9228a93
C++
ruszkait/DefQuery
/test/ListTest.cpp
UTF-8
463
2.5625
3
[ "Apache-2.0" ]
permissive
#include "gtest/gtest.h" #include <DefQuery/from.h> #include <DefQuery/list.h> #include <array> #include <list> TEST(ListTest, SubCollectionTest) { std::vector<int> vector = {1, 2, 3, 4}; auto subVectorList = DefQuery::from(vector).list(); ASSERT_EQ(std::list<int>({1, 2, 3, 4}), subVectorList); } TEST(ListTest, EmptyCollectionTest) { std::vector<int> vector; auto subVectorList = DefQuery::from(vector).list(); ASSERT_TRUE(subVectorList.empty()); }
true
55e88bc71f0c3b8f2c7d788a7f6c8386eaf39b1c
C++
luisco96/accelerated_cpp
/chapter_3/exercise_3_5.cpp
UTF-8
1,256
3.265625
3
[]
no_license
#include <algorithm> #include <iomanip> #include <ios> #include <iostream> #include <string> #include <vector> using namespace std; int main() { vector<string> names; vector<double> grades; string name; double midterm, final, homework = 0, x; // ask for and read the student's name cout << "Please enter the student name, q to quit: "; while(cin >> name) { if(name == "q") break; names.push_back(name); // Ask for the mid and final grades cout << "Please enter your midterm and final grades: "; cin >> midterm >> final; cout << "Enter the 3 homework grades: "; for(int i= 0; i < 3; i++ ){ cin >> x; homework += x; } homework /= 3; final = 0.2 * midterm + 0.4 * final + 0.4 * homework; grades.push_back(final); cout << "Please enter the student name, q to quit: "; } if(names.size() == 0) { cout << "No names were given!" << endl; return 1; } streamsize prec = cout.precision(); for(vector<string>::size_type i = 0; i < names.size(); i++) { cout << names[i] << ": " << setprecision(3) << grades[i] << endl; } cout.precision(prec); return 0; }
true
1d4c7654ebb9fa7c6b054481f6b4891c885216e0
C++
FriendedCarrot4z/cs235
/w09/bnode.h
UTF-8
4,819
3.59375
4
[]
no_license
/******************************************************************************* * Header File * node * Summary: * BNode struct. * Author: * Maximiliano Correa, Esteban Cabrera and Tony Moraes. *******************************************************************************/ #include <stdlib.h> #ifndef BNODE_H #define BNODE_H /******************************************************************************* * NODE * Linked list node. *******************************************************************************/ template <class T> class BNode { public: T data; BNode * pParent; BNode * pLeft; BNode * pRight; //Default Constructor BNode() : data(0), pParent(NULL), pLeft(NULL), , pRight(NULL) {} //Non Default Constructor BNode(const T &t) : data(t), pParent(NULL), pLeft(NULL), , pRight(NULL) {} }; /******************************************************************************* * FREE DATA (DELETE) * Release all the memory contained in a given linked-list. * The one parameter is a pointer to the head of the list. *******************************************************************************/ template <class T> void freeData(BNode<T> * & pNode) { if (!pNode) return null; freeData(pNode->pLeft); freeData(pNode->pRight); delete pNode; pNode = NULL; } /******************************************************************************* * COPY * To copy a binary tree, it is necessary to traverse the entire tree. *******************************************************************************/ template <class T> BNode <T> * copy(BNode <T> * pSource) { BNode<T> * pDestination = new BNode<T> (pSource->data); //BNode<T> * pDest = pDestination; pDestination->pLeft = copy(pSource->pLeft); pDestination->pRight = copy(pSource->pRight); if (pDestination->pLeft) { pDestination->pLeft->pParent = pDestination; } if (pDestination->pRight) { pDestination->pRight->pParent = pDestination; } // return head of copy node return pDestination; } /******************************************************************************* * INSERT * Inserts a new BNode into the current linked-list. The first parameter is the * BNode after the new BNode inserted into the list. The second parameter is the * value to be placed in the new BNode. An optional third parameter is set to true * if the new element is to be at the head of the list. Returns a pointer to the * newly created BNode. *******************************************************************************/ template <class T> BNode <T> * insert(BNode <T> * pBNode, const T & data, bool after = false) throw (const char *) { BNode <T> *pNew = new BNode <T> (data); if (pBNode == NULL) { return pNew; } if (after) { pNew->pNext = pBNode->pNext; pNew->pPrev = pBNode; if (pBNode->pNext) { pBNode->pNext->pPrev = pNew; } pBNode->pNext = pNew; return pNew; } pNew->pNext = pBNode; pNew->pPrev = pBNode->pPrev; if (pBNode->pPrev) { pBNode->pPrev->pNext = pNew; } pBNode->pPrev = pNew; return pNew; } /************************************************ * find * Helps the user find things within the node ***********************************************/ template <class T> BNode<T> * find(BNode<T> * pHead, const T &t) { // iterate through list and compare value to data for (BNode<T> * p = pHead; p; p = p->pNext) { if (p->data == t) return p; } return NULL; } /************************************************ * remove * Removes a node from a list ***********************************************/ template <class T> BNode<T> * remove(BNode<T> * pBNode) { if (pBNode == NULL) { std::cout << "The list is empty"; } BNode <T> * pReturn; // Fix the pNext pointer from previos node if (pBNode->pPrev) { pBNode->pPrev->pNext = pBNode->pNext; } //fix the pPrev pointer from next node if (pBNode->pNext) { pBNode->pNext->pPrev = pBNode->pPrev; } //returns previous, next or null; pReturn = pBNode->pPrev ? pBNode->pPrev : pBNode->pNext; delete pBNode; //returns who take its place return pReturn; } /************************************************ * << Operator * Stream insertion operator ***********************************************/ template <class T> std::ostream & operator<<(std::ostream & out, const BNode<T> * pHead) { // operator overload to display the list for (const BNode<T> * p = pHead; p; p = p->pNext) { if(p->pNext != NULL) { out << p->data << ", "; } else { out << p->data; } } return out; } #endif // BNODE_H
true
4880ed8c354c088375c205f01875f23b82111c91
C++
TeoPaius/Projects
/c++/Contests/olimpiada/subiecte/oji2012/oji2012/Solutii9_12/Solutii9_12/OJI10/10_OJILIC/p1-compresie/Solutii/compresie_cristina_sichim.cpp
UTF-8
1,460
2.71875
3
[]
no_license
/* Solutie prof. Cristina Sichim */ # include <fstream> # include <cstring> using namespace std; char s[1000001], a[1001][1001]; int i,n,l,j,k,Nr; ifstream f("compresie.in"); ofstream g("compresie.out"); int dimensiune() { n=0; int i=0,nr; while(i<l){ if(s[i]=='*') Nr++,i++; else if(s[i]>='a' && s[i]<='z') n++,i++; else {nr=0; while(s[i]>='0' && s[i]<='9') {nr=nr*10+(s[i]-'0'); i++;} n=n+nr;i++; } } i=1; while(i*i<n) i++; return i; } void matrice(int i1,int j1, int i2, int j2) { int x,y,nr; if(i1<=i2 && j1<=j2) { if(s[i]=='*') { i++; x=(i1+i2)/2;y=(j1+j2)/2; matrice(i1,j1,x,y); matrice(i1,y+1,x,j2); matrice(x+1,j1,i2,y); matrice(x+1,y+1,i2,j2); } else if(s[i]>='a' && s[i]<='z') { a[i1][j1]=s[i];i++; matrice(i1,j1+1,i1,j2); //B matrice(i1+1,j1,i2,j1); //C matrice(i1+1,j1+1,i2,j2); //D } else{ while(s[i]>='0' && s[i]<='9') i++; for(x=i1;x<=i2;x++) for(y=j1;y<=j2;y++)a[x][y]=s[i]; i++; } }} int main() { f>>s; l=strlen(s); n=dimensiune(); g<<Nr<<'\n'; i=0; matrice(1,1,n,n); for(i=1;i<=n;i++) {for(j=1;j<=n;j++) g<<a[i][j]; g<<'\n'; } f.close();g.close(); return 0; }
true
245a2b7eb7c8b70d7d1281fa9150f614e4e12586
C++
thamurath/Variant
/Common/NonCopyable.hpp
UTF-8
591
3
3
[]
no_license
#ifndef __COMMON_BASE_POCILIES_NONCOPYABLE_HPP__ #define __COMMON_BASE_POCILIES_NONCOPYABLE_HPP__ namespace Base { namespace Polycies { /** * @brief Utility class to mark another one as non-copyable. * * Just use private inheritance to use it. * @class NonCopyable*/ class NonCopyable { protected: NonCopyable(void) { } ~NonCopyable(void) { } private: NonCopyable(const NonCopyable&); NonCopyable& operator=(const NonCopyable&); }; } } #endif // __COMMON_BASE_POCILIES_NONCOPYABLE_HPP__
true
42c0f520982b3ddaff7ffba157a8a336bb6ef0e9
C++
microsoft/CCF
/src/node/test/channel_stub.h
UTF-8
1,345
2.546875
3
[ "Apache-2.0" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. #pragma once #include "node/node_types.h" #include <vector> namespace ccf { class ChannelStubProxy { public: std::vector<std::vector<uint8_t>> sent_encrypted_messages; ChannelStubProxy() {} template <class T> bool send_encrypted( NodeId to, const NodeMsgType& msg_type, const std::vector<uint8_t>& data, const T& msg) { sent_encrypted_messages.push_back(data); return true; } template <class T> bool send_authenticated( NodeId to, const ccf::NodeMsgType& msg_type, const T& data) { return true; } template <class T> std::pair<T, std::vector<uint8_t>> recv_encrypted( const NodeId& from, const uint8_t* data, size_t size) { T msg; return std::make_pair(msg, std::vector<uint8_t>(data, data + size)); } std::vector<uint8_t> get_pop_back() { auto back = sent_encrypted_messages.back(); sent_encrypted_messages.pop_back(); return back; } void clear() { sent_encrypted_messages.clear(); } size_t size() const { return sent_encrypted_messages.size(); } bool is_empty() const { return sent_encrypted_messages.empty(); } }; }
true
a9de91bbf6b1fcdc01b9d98b489cf4bcb9338d9d
C++
ddjddd/Algorithm-Study
/Backjoon_Onlie_Judge/2000/2178.cpp
UTF-8
1,688
3.109375
3
[]
no_license
#include <iostream> #include <queue> using namespace std; typedef struct Node { int x; int y; int len; } node; int main() { int n, m; cin >> n >> m; int arr[n][m]; bool visited[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%1d", &arr[i][j]); visited[i][j] = false; } } queue<node> q; node k; k.x = 0; k.y = 0; k.len = 0; int mi = 10000000; q.push(k); while (!q.empty()) { node t = q.front(); q.pop(); if (t.x < n - 1 && arr[t.x + 1][t.y] && !visited[t.x + 1][t.y]) { node nn; nn.x = t.x + 1; nn.y = t.y; nn.len = t.len + 1; q.push(nn); visited[nn.x][nn.y] = true; } if (t.x > 0 && arr[t.x - 1][t.y] && !visited[t.x - 1][t.y]) { node nn; nn.x = t.x - 1; nn.y = t.y; nn.len = t.len + 1; q.push(nn); visited[nn.x][nn.y] = true; } if (t.y > 0 && arr[t.x][t.y - 1] && !visited[t.x][t.y - 1]) { node nn; nn.x = t.x; nn.y = t.y - 1; nn.len = t.len + 1; q.push(nn); visited[nn.x][nn.y] = true; } if (t.y < m - 1 && arr[t.x][t.y + 1] && !visited[t.x][t.y + 1]) { node nn; nn.x = t.x; nn.y = t.y + 1; nn.len = t.len + 1; q.push(nn); visited[nn.x][nn.y] = true; } if (t.x == n - 1 && t.y == m - 1) mi = min(mi, t.len); } cout << ++mi << endl; return 0; }
true
689dd75f3737bb3e36540cc6ee002eeb4efe7c32
C++
wusatteam/WUSATP1
/CubeSat_GPS/LED.ino
UTF-8
298
2.828125
3
[]
no_license
void LED_init() { pinMode(LED, OUTPUT); digitalWrite(LED,LOW); } void LED_on() { digitalWrite(LED,HIGH); } void LED_off() { digitalWrite(LED,LOW); } void LED_flash(int time) { LED_on(); delay(time); LED_off(); delay(time); } void Error() { while(true) LED_flash(100); }
true
d2f05176069fb7c2b90770825298c250d0b67b77
C++
defacto2k15/pwAsteroids
/src/Model/components/PositionComponent.cpp
UTF-8
915
2.78125
3
[]
no_license
// // Created by defacto on 24.10.15. // #include <Model/python/PythonModule.h> #include "PositionComponent.h" PositionComponent::PositionComponent( PythonModule &python) : position_(0.0, 0.0), rotation_(0.0), visibility_(python) { } Point PositionComponent::getPosition() { return position_; } Rotation PositionComponent::getRotation() { return rotation_; } void PositionComponent::setPosition( Point newPos) { position_ = newPos; } void PositionComponent::setX( double newX) { position_ = Point( newX, position_.getY() ); } void PositionComponent::setY(double newY ) { position_ = Point(position_.getX(), newY ); } void PositionComponent::moveBy( Point moveVector ) { position_.move(moveVector.getX(), moveVector.getY()); } void PositionComponent::setRotation( Rotation newRotation ) { rotation_ = newRotation; } void PositionComponent::rotateBy( double toRotate ) { rotation_+=toRotate; }
true
9d20b2ad1152478e09c2846181ec2c2ad677b440
C++
haka913/boj
/1764.cpp
UTF-8
562
2.859375
3
[]
no_license
/* * 1764.cpp * * Created on: 2018. 11. 13. * Author: paul */ #include <iostream> #include <set> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { int n, m; cin >> n >> m; set<string> s; vector<string> ans; string a; while(n--){ cin >> a; s.insert(a); } while(m--){ cin >> a; if(s.count(a)!=0){ ans.push_back(a); } } sort(ans.begin(),ans.end()); cout << ans.size() <<"\n"; for(vector<string>:: iterator it = ans.begin() ; it != ans.end();it++){ cout << *it <<"\n"; } return 0; }
true
c8785067aeff6087a4d424983a4e6818257a682b
C++
kanikapoor-dot/learn-DSA
/uniontry.cpp
UTF-8
332
3.21875
3
[]
no_license
#include<iostream> using namespace std; union uniontry { int a; int b; char c; float f; }; int main(){ union uniontry t; t.c = 'w'; t.f = 12.3; cout << t.f << " "; t.b = 5; cout << t.b << " "; t.a = 1; cout << t.a << " "; cout << t.f; //Garbage value return 0; }
true
a491f02d611b08ddee17e2764649fdf39f1def8d
C++
DimitriRocha/quickSortVisualization
/main.cpp
UTF-8
730
2.84375
3
[]
no_license
#include <SFML/Graphics.hpp> #include "QuickSort.h" #include <future> int main() { sf::RenderWindow window(sf::VideoMode(1200, 800), "Quick Sort Visualization SFML", sf::Style::Close); QuickSort* qSort = new QuickSort(1200, 800); auto future = std::async(&QuickSort::sortArray, qSort ,&qSort->arr, 0, (int)qSort->arr.size() - 1); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Resized) qSort->setViewSize(event.size.width, event.size.height); if (event.type == sf::Event::Closed) window.close(); } window.clear(sf::Color::Black); qSort->generateVisualSort(&window); window.display(); } return 0; }
true
6a204b7b7ab6b09b8d3c37366bffeb035f081aba
C++
KepAmun/BSplineSurfaceModeling
/Vertex3d.h
UTF-8
928
2.8125
3
[]
no_license
#ifndef VERTEX3D_H #define VERTEX3D_H #include <iostream> #include <cmath> using namespace std; class Vertex3d { private: double m_v[3]; public: Vertex3d(); Vertex3d(double*v); Vertex3d(double x, double y, double z); Vertex3d(Vertex3d* v); double* Get3dv(); double X() const; double Y() const; double Z() const; double* XRef(); double* YRef(); double* ZRef(); double length() const; void normalize(); Vertex3d& operator = (const Vertex3d& v); Vertex3d& operator = (double *d); Vertex3d operator + (const Vertex3d& v); Vertex3d& operator += (const Vertex3d& v); Vertex3d operator - (const Vertex3d& v); Vertex3d& operator -= (const Vertex3d& v); Vertex3d operator * (const double& d); Vertex3d& operator *= (const double& d); Vertex3d& operator *= (const Vertex3d& v); double& operator [] (int i); }; #endif // VERTEX3D_H
true
82c0383cfb5298d92d201932fcd1aab4f1e491cd
C++
fbi-octopus/biggles
/include/biggles/simulate.hpp
UTF-8
5,798
2.875
3
[ "Apache-2.0" ]
permissive
/// @file simulate.hpp Simulate the dynamic model to generate synthetic datasets #ifndef BIGGLES_SIMULATE_HPP__ #define BIGGLES_SIMULATE_HPP__ #include <boost/shared_ptr.hpp> #include "model.hpp" #include "point_2d.hpp" #include "track.hpp" namespace biggles { /// @brief Simulate ground truth data and synthetic input for the Biggles tracker namespace simulate { /// @brief Simulate a single track. /// /// Given the model parameters specified in \p parameters, simulate a single track with birth time \p first_time_stamp. The /// state evolution covariance matrix, \f$ Q \f$, is set to /// /// \f[ /// Q = \left[ /// \begin{array}{cccc} /// s_p^2 & 0 & 0 & 0 \\ 0 & s_v^2 & 0 & 0 \\ 0 & 0 & s_p^2 & 0 \\ 0 & 0 & 0 & s_v^2 /// \end{array} /// \right] /// \f] /// /// where \f$ s_p \f$ is the value of \p position_sigma and \f$ s_v \f$ is the value of \p velocity_sigma. /// /// @param parameters The model parameters to generate this track with. /// @param first_time_stamp The birth time of the new track. /// @param initial_position The initial position of the track. /// @param initial_velocity The initial velocity of the track. /// @param position_sigma The standard deviation of the position random walk. /// @param velocity_sigma The standard deviation of the velocity random walk. /// /// @return A shared pointer to the new track. boost::shared_ptr<track> generate_track(std::deque<state_t> &states, const model::parameters& parameters, const point_2d& initial_position = point_2d(), const point_2d& initial_velocity = point_2d(), time_stamp first_time_stamp = 0, float position_sigma = 0.25f, float velocity_sigma = 0.01f); boost::shared_ptr<track> generate_track(const model::parameters& parameters, const point_2d& initial_position = point_2d(), const point_2d& initial_velocity = point_2d(), time_stamp first_time_stamp = 0, float position_sigma = 0.25f, float velocity_sigma = 0.01f); /// @brief Simulate an entire partition configuration. /// /// @note All generated observations are included, even those outside of the bounds specified in the parameters. If you /// want observations bounded to a region, use biggles::crop_partition() after calling this function. /// /// @sa biggles::simulate_track() /// @sa biggles::crop_partition() /// /// @param[out] output_partition Write the generated partition to this reference. /// @param params The model parameters. /// @param start_time_stamp The first frame of data to generate. /// @param end_time_stamp The last frame of data to birth tracks on. This may not be the last time stamp generated, see /// the function documentation. /// @param image_width The width of the output image. Used for generating clutter and choosing track initial position. /// @param image_height The height of the output image. Used for generating clutter and choosing track initial position. /// @param position_sigma The standard deviation of the position random walk. /// @param velocity_sigma The standard deviation of the velocity random walk. /// @param initial_velocity_sigma The standard deviation of the initial velocity for the track. void generate_partition(partition_ptr_t& output_part_ptr, const model::parameters& params, time_stamp start_time_stamp = 0, time_stamp end_time_stamp = 128, float image_width = 128.f, float image_height = 128.f, float position_sigma = 0.25f, float velocity_sigma = 0.01f, float initial_velocity_sigma = 1.f); /// @brief Crop out observations from a partition within a spatio-temporal window. /// /// Remove observations from a partition whose x co-ordinate does not lie on [ \p first_x, \p last_x ) or whose y /// co-ordinate does not lie on [ \p first_y, \p last_y ) or whose time stamp does not lie on [ \p first_time_stamp, \p /// last_time_stamp ). /// /// Tracks which end up with no observations are removed from the partition. Track birth and death times are modified to /// be cropped to [ \p first_time_stamp, \p last_time_stamp ). /// /// It is safe for \p output_partition and \p input_partition to refer to the same partition. /// /// @param output_partition /// @param input_partition /// @param first_x /// @param last_x /// @param first_y /// @param last_y /// @param first_time_stamp /// @param last_time_stamp void crop_partition(partition_ptr_t& output_part_ptr, const partition_ptr_t& input_part_ptr, float first_x, float last_x, float first_y, float last_y, time_stamp first_time_stamp, time_stamp last_time_stamp); /// @brief Demote all tracks in a partition to the clutter. /// /// Take all the tracks in \p input_partition and demote all their observations to the clutter. This function is useful /// for generating synthetic input data sets from ground truths. /// /// It is safe for \p output_partition and \p input_partition to refer to the same partition. /// /// @param[out] output_partition overwritten with new partition /// @param input_partition void demote_all_tracks_from_partition(partition_ptr_t& output_part_ptr, const partition_ptr_t& input_part_ptr); } } #endif // BIGGLES_SIMULATE_HPP__
true
818730f07b73fb145fb295f4d17c01dbb023e587
C++
razvanw0w/university
/sda/SDA_SortedBag_BST/SortedBag.cpp
UTF-8
6,872
2.8125
3
[]
no_license
// // Created by razvan on 23.05.2019. // #include "SortedBag.h" SortedBag::SortedBag(Relation r): root{-1}, numberOfElements{0}, capacity{16}, firstFree{0}, r{r} { tree = new BSTNode[16]; } void SortedBag::add(TComp e) { if (mustBeResized()) { // daca trebuie sa redimensionam vectorul, o facem resize(); } // nodul nou adaugat o sa fie pe pozitia firstFree, asa ca-l adaugam de pe acuma tree[firstFree].setValue(e); tree[firstFree].setLeftSon(-1); tree[firstFree].setRightSon(-1); // caut pozitia pe care trebuie sa adaug nodul // la final o sa fie "parent" int current = root, parent = -1; while (current != -1) { parent = current; if (r(e, tree[current].getValue())) // daca relatia dintre elementu pe care trebe sa-l bag si valoarea in arbore se satisface // atunci trebuie sa ma duc pe fiul stang current = tree[current].getLeftSon(); else // altfel ma duc pe fiul drept current = tree[current].getRightSon(); } if (root == -1) // caz particular - nu avem radacina => radacina este firstFree root = firstFree; else if (r(e, tree[parent].getValue())) // daca trebuie sa pun elementul pe fiul stang, il pun pe fiul stang tree[parent].setLeftSon(firstFree); else // altfel, pe fiul drept tree[parent].setRightSon(firstFree); changeFirstFree(); // actualizam firstFree ++numberOfElements; // crestem nr. de elemente } void SortedBag::changeFirstFree() { ++firstFree; while (firstFree < capacity && !tree[firstFree].isNull()) ++firstFree; } bool SortedBag::remove(TComp e) { bool removed = false; // daca l-am sters sau nu, o sa se actualizeze in functia removeRecursively root = removeRecursively(root, e, removed); if (removed) --numberOfElements; return removed; } bool SortedBag::search(TComp e) const { int currentNode = root; // ma duc pe fiul stang sau drept in functie de cum se stabileste relatia while (currentNode != -1) { if (tree[currentNode].getValue() == e) return true; if (r(e, tree[currentNode].getValue())) { currentNode = tree[currentNode].getLeftSon(); } else { currentNode = tree[currentNode].getRightSon(); } } return false; } int SortedBag::nrOccurrences(TComp e) const { int currentNode = root; int counter = 0; // la fel ca la search, nu e foarte greu de urmarit while (currentNode != -1) { if (tree[currentNode].getValue() == e) ++counter; if (r(e, tree[currentNode].getValue())) { currentNode = tree[currentNode].getLeftSon(); } else { currentNode = tree[currentNode].getRightSon(); } } return counter; } int SortedBag::size() const { return numberOfElements; } SortedBagIterator SortedBag::iterator() const { return SortedBagIterator(*this); } bool SortedBag::isEmpty() const { return numberOfElements == 0; } SortedBag::~SortedBag() { delete[] tree; } bool SortedBag::mustBeResized() { return firstFree >= capacity; } void SortedBag::resize() { BSTNode *newTree = new BSTNode[capacity * 2]; for (int i = 0; i < capacity; ++i) { newTree[i].setValue(tree[i].getValue()); newTree[i].setLeftSon(tree[i].getLeftSon()); newTree[i].setRightSon(tree[i].getRightSon()); } delete[] tree; tree = newTree; firstFree = capacity; capacity *= 2; } TComp SortedBag::getMinimum(int startingRoot) { int currentNode = startingRoot, minNode = startingRoot; TComp minimum; // caut cel mai mic element din subarborele BSB cu radacina in startingRoot // asta inseamna cel mai din stanga nod, adica ma duc cat de tare pot in stanga // o sa se afle in minNode while (currentNode != -1) { minimum = tree[currentNode].getValue(); minNode = currentNode; currentNode = tree[currentNode].getLeftSon(); } return minNode; } TComp SortedBag::getMaximum(int startingRoot) { int currentNode = startingRoot, maxNode = startingRoot; TComp maximum; // caut cel mai mare element din subarborele BSB cu radacina in startingRoot // asta inseamna cel mai din dreapta nod, adica ma duc cat de tare pot in dreapta // o sa se afle in maxNode while (currentNode != -1) { maximum = tree[currentNode].getValue(); maxNode = currentNode; currentNode = tree[currentNode].getRightSon(); } return maxNode; } int SortedBag::removeRecursively(int node, TComp e, bool &removed) { if (node == -1) return node; if (e == tree[node].getValue()) { // am dat de elementul pe care-l caut, tre sa-l sterg removed = true; if (tree[node].getLeftSon() == -1) { // daca nu exista un fiu stang, inseamna ca mutam subarborele care incepe // in fiul drept peste subarborele determinat de "node" int rightSon = tree[node].getRightSon(); tree[node] = BSTNode{NULL_TCOMP, -1, -1}; return rightSon; } else if (tree[node].getRightSon() == -1) { // analog ca mai sus, doar ca pt fiul drept, mutam subarborele // care incepe in fiul stang int leftSon = tree[node].getLeftSon(); tree[node] = BSTNode{NULL_TCOMP, -1, -1}; return leftSon; } // altfel daca are ambii fii, punem valoarea celui mai mare element din subarborele stang // cu valoarea din nodul si stergem o aparitie a celui mai mare element (ca sa nu apara de 2 ori, ca e ca si // cum l-am muta pe ala in nodul curent int maxNode = getMaximum(tree[node].getLeftSon()); tree[node].setValue(tree[maxNode].getValue()); tree[node].setLeftSon(removeRecursively(tree[node].getLeftSon(), tree[maxNode].getValue(), removed)); } else if (r(e, tree[node].getValue())) { // daca nodul se afla in subarborele determinat de fiul stang, atunci // fiul stang va fi radacina subarborelui determinat de initialul fiu stang dupa ce elementul cautat // a fost sters tree[node].setLeftSon(removeRecursively(tree[node].getLeftSon(), e, removed)); } else { // la fel, doar ca pt fiul drept tree[node].setRightSon(removeRecursively(tree[node].getRightSon(), e, removed)); } return node; }
true
008c6dea85f8a32a9621066b2672e0ce20fd5478
C++
Daniel95/MuseEngine
/MuseEngine/Muse/src/Platform/OpenGL/Buffer/OpenGLFrameBuffer.cpp
UTF-8
2,978
2.515625
3
[]
no_license
#include "MusePCH.h" #include "OpenGLFrameBuffer.h" #include "glad/glad.h" #include "Core/Instrumentor.h" namespace Muse { static const uint32_t s_MaxFramebufferSize = 8192; OpenGLFrameBuffer::OpenGLFrameBuffer(const FrameBufferProperties& spec) : m_Properties(spec) { Invalidate(); } OpenGLFrameBuffer::~OpenGLFrameBuffer() { glDeleteFramebuffers(1, &m_RendererID); glDeleteTextures(1, &m_ColorAttachment); glDeleteTextures(1, &m_DepthAttachment); } void OpenGLFrameBuffer::Invalidate() { if (m_RendererID) { glDeleteFramebuffers(1, &m_RendererID); glDeleteTextures(1, &m_ColorAttachment); glDeleteTextures(1, &m_DepthAttachment); } glCreateFramebuffers(1, &m_RendererID); glBindFramebuffer(GL_FRAMEBUFFER, m_RendererID); glCreateTextures(GL_TEXTURE_2D, 1, &m_ColorAttachment); glBindTexture(GL_TEXTURE_2D, m_ColorAttachment); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Properties.Width, m_Properties.Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_ColorAttachment, 0); glCreateTextures(GL_TEXTURE_2D, 1, &m_DepthAttachment); glBindTexture(GL_TEXTURE_2D, m_DepthAttachment); glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH24_STENCIL8, m_Properties.Width, m_Properties.Height); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_DepthAttachment, 0); ASSERT_ENGINE(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Framebuffer is incomplete!"); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void OpenGLFrameBuffer::Bind() { glBindFramebuffer(GL_FRAMEBUFFER, m_RendererID); glViewport(0, 0, m_Properties.Width, m_Properties.Height); } void OpenGLFrameBuffer::Unbind() { glBindFramebuffer(GL_FRAMEBUFFER, 0); } void OpenGLFrameBuffer::Resize(uint32_t width, uint32_t height) { if (width == 0 || height == 0 || width > s_MaxFramebufferSize || height > s_MaxFramebufferSize) { LOG_ENGINE_WARN("Attempted to rezize framebuffer to {0}, {1}", width, height); return; } m_Properties.Width = width; m_Properties.Height = height; Invalidate(); } void OpenGLFrameBuffer::SetData(void* a_Data, uint32_t a_Size) const { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, m_Properties.Width, m_Properties.Height, 0, GL_RGBA, GL_FLOAT, a_Data); } void OpenGLFrameBuffer::BindTexture(uint32_t a_Slot) const { glActiveTexture(GL_TEXTURE0 + a_Slot); glBindTexture(GL_TEXTURE_2D, m_ColorAttachment); } }
true
8db6e25dc20a31c44ab939b55a9e776a2263bdae
C++
fatihkaan22/CSE241
/hw2/src/ioHandler.h
UTF-8
5,419
3.109375
3
[]
no_license
#ifndef UNTITLED_IOHANDLER_H #define UNTITLED_IOHANDLER_H #include <iostream> #include <string> #include <fstream> #include "gameStructures.h" using namespace std; string getDataFromLine(const string &line) { return line.substr(line.find(':') + 1); } // Overloaded load functions for different data types void loadData(ifstream &inStream, int &data) { string line; getline(inStream, line); string strData = getDataFromLine(line); data = stoi(strData); } void loadData(ifstream &inStream, CELL data[MAX_SIZE][MAX_SIZE], const int &size) { string line; getline(inStream, line); string strData = getDataFromLine(line); int strIndex = 0; for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { CELL c = static_cast<CELL>(strData[strIndex++]); data[j][i] = c; } } } void loadData(ifstream &inStream, MARK &data) { string line; getline(inStream, line); char charData = getDataFromLine(line)[0]; data = (charData == 'x') ? MARK::X : MARK::O; } void loadData(ifstream &inStream, STATUS &data) { string line; getline(inStream, line); char charData = getDataFromLine(line)[0]; data = (charData == '0') ? STATUS::defense : STATUS::attack; } void loadData(ifstream &inStream, bool &data) { string line; getline(inStream, line); char charData = getDataFromLine(line)[0]; data = (charData == '1') ? true : false; } void loadData(ifstream &inStream, pos data[], const int &size) { string line; getline(inStream, line); string strData = getDataFromLine(line); for (int i = 0; i < size; ++i) { int strIndex1 = strData.find(','); int strIndex2 = strData.find(' '); data[i].x = stoi(strData.substr(0, strIndex1)); data[i].y = stoi(strData.substr(strIndex1 + 1, strIndex2)); strData = strData.substr(strIndex2 + 1); } } // returns true if there is error on file opening bool loadFile(const string &fileName, CELL board[MAX_SIZE][MAX_SIZE], int &boardSize, bool &vsComputer, MARK &nextTurn, memory &computerMemory) { ifstream inStream; inStream.open(fileName); if (inStream.fail()) { cerr << "File open failed\n"; return true; } loadData(inStream, boardSize); loadData(inStream, board, boardSize); loadData(inStream, nextTurn); loadData(inStream, vsComputer); if (vsComputer) { loadData(inStream, computerMemory.opponentPos.top); loadData(inStream, computerMemory.opponentPos.array, computerMemory.opponentPos.top); loadData(inStream, computerMemory.computerLastMove.x); loadData(inStream, computerMemory.computerLastMove.y); loadData(inStream, computerMemory.nextMove.x); loadData(inStream, computerMemory.nextMove.y); loadData(inStream, computerMemory.status); } return false; } string boardToStr(const CELL board[MAX_SIZE][MAX_SIZE], const int &boardSize) { string s; for (int i = 0; i < boardSize; ++i) { for (int j = 0; j < boardSize; ++j) { s += static_cast<char>(board[j][i]); } } return s; } string arrToStr(const pos arr[], const int &size) { string s; for (int i = 0; i < size; ++i) { s += to_string(arr[i].x); s += ','; s += to_string(arr[i].y); s += ' '; } return s; } // Overloaded saving functions for different data types void saveData(const string &identifier, const int &data, ofstream &outStream) { outStream << identifier << ':' << data << endl; } void saveData(const string &identifier, const string &data, ofstream &outStream) { outStream << identifier << ':' << data << endl; } void saveData(const string &identifier, const bool &data, ofstream &outStream) { outStream << identifier << ':' << data << endl; } void saveData(const string &identifier, const char &data, ofstream &outStream) { outStream << identifier << ':' << data << endl; } // returns true if there is error on file opening bool saveFile(const string &fileName, const CELL board[MAX_SIZE][MAX_SIZE], const int &boardSize, const bool &vsComputer, const MARK &nextTurn, const memory &computerMemory) { ofstream outStream; outStream.open(fileName); if (outStream.fail()) { cerr << "File open failed\n"; return true; } saveData("boardSize", boardSize, outStream); saveData("board", boardToStr(board, boardSize), outStream); saveData("nextTurn", static_cast<char>(nextTurn), outStream); saveData("vsComputer", vsComputer, outStream); if (vsComputer) { saveData("computerMemory.opponentPos.top", computerMemory.opponentPos.top, outStream); saveData("computerMemory.opponentPos.array", arrToStr(computerMemory.opponentPos.array, computerMemory.opponentPos.top), outStream); saveData("computerMemory.computerLastMove.x", computerMemory.computerLastMove.x, outStream); saveData("computerMemory.computerLastMove.y", computerMemory.computerLastMove.y, outStream); saveData("computerMemory.nextMove.x", computerMemory.nextMove.x, outStream); saveData("computerMemory.nextMove.y", computerMemory.nextMove.y, outStream); saveData("computerMemory.status", computerMemory.status, outStream); } outStream.close(); return false; } #endif //UNTITLED_IOHANDLER_H
true
14c8a5cec276d255247ecc6f5685230f06ffabdb
C++
jaychao1973/smartHome
/及時資料庫/2touch_sensor/touchSensor/touchSensor.ino
UTF-8
1,958
3.03125
3
[]
no_license
// Firebase // 使用arduino nano 33 iot /* *連線Firebase realtimeDatabase *touch sensor 狀態改變,立即上傳至firebase */ //Example shows how to connect to Firebase RTDB and perform basic operation for set, get, push and update data to database //Required WiFiNINA Library for Arduino from https://github.com/arduino-libraries/WiFiNINA #include "Firebase_Arduino_WiFiNINA.h" #define FIREBASE_HOST "arduinofirebase-6d104.firebaseio.com" #define FIREBASE_AUTH "z5lPWwjZLZuNNcUEelbJdiNaIvnR2Zfq49BuQBAa" #define WIFI_SSID "robert_hsu_home" #define WIFI_PASSWORD "0926656000" #define led 13 #define touchSensor 12 //Define Firebase data object FirebaseData firebaseData; bool currentState; void setup() { pinMode(led,OUTPUT); pinMode(touchSensor, INPUT); Serial.begin(9600); delay(100); Serial.println(); Serial.print("Connecting to Wi-Fi"); int status = WL_IDLE_STATUS; while (status != WL_CONNECTED) { status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("."); delay(300); } Serial.println(); Serial.print("Connected with IP: "); Serial.println(WiFi.localIP()); Serial.println(); //Provide the autntication data Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH, WIFI_SSID, WIFI_PASSWORD); Firebase.reconnectWiFi(true); //得第一次的currentState currentState = digitalRead(touchSensor); } void loop() { bool state = digitalRead(touchSensor); String path = "touchSensor/touch"; Serial.println(state); if(state != currentState){ currentState = state; Serial.println("上傳"); if(Firebase.setBool(firebaseData, path, state)){ if(firebaseData.dataType() == "boolean"){ Serial.print("及時資料庫目前的狀態"); Serial.println(firebaseData.boolData()); digitalWrite(led,firebaseData.boolData()); } }else{ //設定失敗 Serial.println("Firbase設取失敗"); Serial.println(firebaseData.errorReason()); } } delay(10); }
true
e1fb7065fe2e329f86a5ebd19206050159354ae8
C++
tybenz/cerebro
/lib/LightGrid/LightGrid.cpp
UTF-8
2,133
2.984375
3
[]
no_license
#include <LightGrid.h> #define NUM_LEDS 9 int MODE_RED = A0; int MODE_GREEN = A1; int MODE_BLUE = A2; LightGrid::LightGrid(int serPin, int rClockPin, int srClockPin, int lastPin) { // Pin mode set by shifter lib _shifter = new Shifter(serPin, rClockPin, srClockPin, 1); _lastPin = lastPin; pinMode(_lastPin, OUTPUT); clearShifter(); } void LightGrid::writeShifter() { _shifter->write(); } void LightGrid::clearShifter() { _shifter->clear(); _shifter->write(); } void LightGrid::set(bool* leds, int red, int green, int blue) { setLeds(leds); setMode(red, green, blue); } void LightGrid::setLeds(bool* leds) { _shifter->clear(); for (int i = 0; i < NUM_LEDS; i++) { if (leds[i]) { turnOnLed(i); } else { turnOffLed(i); } } _shifter->write(); } void LightGrid::setMode(int red, int green, int blue) { if (red != -1) { analogWrite(MODE_RED, red); analogWrite(MODE_GREEN, green); analogWrite(MODE_BLUE, blue); } } void LightGrid::turnOffAll() { _shifter->clear(); for (int i = 0; i < NUM_LEDS; i++) { turnOffLed(i); } _shifter->write(); } void LightGrid::turnOnLed(int num) { if (num == 8) { digitalWrite(_lastPin, HIGH); } else { _shifter->setPin(num, HIGH); } } void LightGrid::turnOnLed(int num, int offset) { if (num == 8) { digitalWrite(_lastPin, HIGH); } else { _shifter->setPin(num + offset, HIGH); } } void LightGrid::turnOffLed(int num) { if (num == 8) { digitalWrite(_lastPin, LOW); } else { _shifter->setPin(num, LOW); } } void LightGrid::turnOffLed(int num, int offset) { if (num == 8) { digitalWrite(_lastPin, LOW); } else { _shifter->setPin(num + offset, LOW); } } void LightGrid::turnOnBankLed(int num) { turnOnLed(num, 5); } void LightGrid::turnOffBankLed(int num) { turnOffLed(num, 5); } void LightGrid::turnOnPatchLed(int num) { turnOnLed(num, 2); } void LightGrid::turnOffPatchLed(int num) { turnOffLed(num, 2); }
true
ec1dc4ea5f3922651c773e839179936f3944336e
C++
xCrypt0r/Baekjoon
/src/2/2693.cpp
UTF-8
570
2.96875
3
[ "MIT" ]
permissive
/** * 2693. N번째 큰 수 * * 작성자: xCrypt0r * 언어: C++14 * 사용 메모리: 1,984 KB * 소요 시간: 0 ms * 해결 날짜: 2020년 9월 10일 */ #include <iostream> #include <algorithm> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); const int size = 10; int T; cin >> T; while (T--) { int A[size]; for (int i = 0; i < size; ++i) { cin >> A[i]; } sort(A, A + size); cout << A[7] << "\n"; } }
true
42841126258278fd5b8b70e8c7686f9768fd16a7
C++
anthonycj04/bitReader-Writer
/bitReader.h
UTF-8
1,156
3.28125
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; class BitReader{ private: int fileLength; int currentPosition; int bitPosition; ifstream fileHandler; char buffer; public: BitReader(){ } void open(const char * fileName){ fileHandler.open(fileName, ios::in | ios::binary); fileHandler.seekg(0, fileHandler.end); fileLength = fileHandler.tellg(); fileHandler.seekg(0, fileHandler.beg); bitPosition = currentPosition = 0; if (fileLength > currentPosition){ currentPosition++; fileHandler.get(buffer); bitPosition = 7; } } BitReader(const char * fileName){ open(fileName); } int getRemainingBits(){ return (fileLength - currentPosition) * 8 + bitPosition + 1; } bool readBit(){ if (getRemainingBits() > 0){ bool result = (buffer >> bitPosition-- & 0x01)?true:false; if (bitPosition < 0 && fileLength - currentPosition){ currentPosition++; fileHandler.get(buffer); bitPosition = 7; } return result; } else cout << "check remaining bits before reading!!!"; return false; } void close(){ fileHandler.close(); } int getFileLength(){ return fileLength; } };
true
4bbbbe8b3b95b80a7829db5fe0e032eb34c9797b
C++
seb9465/inf1995
/tp4/pb2/pb2.cpp
UTF-8
3,711
2.9375
3
[]
no_license
/* * Equipe no71 * * WILLIAM LABERGE 1852751 * COLIN STEPHENNE 1852773 * SÉBASTIEN CADORETTE 1734603 * * 26 janvier 2017 * * TRAVAIL PRATIQUE 4 - INF1995 * Probleme 2 */ #define F_CPU 8000000UL #include <avr/io.h> #include <util/delay.h> #include <math.h> #define PORT_SORTIE 0xff #define F_1 60 #define F_2 400 #define ETEINT 0x00 #define AVANCE 0x01 void delai_us(uint32_t nombreUs, int freq); //Prototype de la fonction delai_us. void debug(){PORTD = 0x02; for(;;){}}; //Fonction utile pour debuguer. int main() { DDRD = PORT_SORTIE; //Port D en sortie. const uint32_t force_F_1[5] = {0, 33333, 66666, 99999 , 133332}; //Nombre de cycle d'horloge du "a" pour la frequence 1. const uint32_t force_F_2[5] = {0, 5000, 10000, 15000, 20000}; //Nombre de cycle d'horloge du "a" pour la frequence 2. uint32_t compteurDeB = 0; uint32_t a, b = 0; b = force_F_1[4]; //"b" correspond a ... a = 0; int frequence = F_1; PORTD = ETEINT; for(;;) { if(a > 0) { PORTD = AVANCE; delai_us(a, frequence); } PORTD = ETEINT; delai_us((b-a)+1, frequence); //Il ne faut jamais faire un delai de 0, meme quand a = b. compteurDeB++; if(frequence == F_1 && compteurDeB >= 120) { //120 b par deux secondes a une frequence de 60Hz. uint8_t varTemp = 0; for(uint16_t i = 0; i < 5; i++) { if(a == force_F_1[i]) varTemp = i; } if(varTemp >= 4){ a = force_F_2[0]; frequence = F_2; b = force_F_2[4]; } else a = force_F_1[++varTemp]; compteurDeB = 0; } else if(frequence == F_2 && compteurDeB >= 800) { //800 b par deux secondes a une frequence de 400 Hz. uint8_t varTemp = 0; for(uint16_t i = 0; i < 5; i++) { if(a == force_F_2[i]) varTemp = i; } if(varTemp >= 4) { a = force_F_1[0]; frequence = F_1; b = force_F_1[4]; } else a = force_F_2[++varTemp]; compteurDeB = 0; } } } /*************************************************************************** * Fonction : delai_us * Description : Nous avons créé une fonction afin de nous faciliter un peu * la tache pour gerer les delais. Nous avons utilisé * _delay_loop_2 pour créer un delai, mais nous devons modifié * la valeur du parametre pour pouvoir avoir un nombre de us * bien précis. Nous avons donc créé une fonction afin que cela * soit geré a part de notre main. * Parametres : - (unint16_t) nombreCycle : Contient le nombre de microsecondes * durant lesquels on veut un délai. * Retour : Aucun. ***************************************************************************/ void delai_us(uint32_t nombreCycle, int freq) { if(freq == F_1) { nombreCycle /= 3; double nombreIterations = floor(nombreCycle/255); //la fonction _delay_loop_1 prend 255 comme valeur maximale!!! for(int i=0; i<nombreIterations; i++) _delay_loop_1(255); _delay_loop_1(nombreCycle%255); } else { nombreCycle /= 4; _delay_loop_2(nombreCycle); } }
true
21d7d4d08bd277835129c36746a6a01c481c79c7
C++
cosensible/LeetCode
/LeetCode/283-MoveZeroes.h
WINDOWS-1252
1,322
4.03125
4
[]
no_license
#include <vector> #include <algorithm> #include <iostream> /* Given an array `nums`, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. */ class Solution_283 { public: void moveZeroes(std::vector<int>& nums) { //// stable_partition //std::stable_partition(nums.begin(), nums.end(), [](int i) {return i != 0; }); int lastNotZero = 0; for (int i = 0; i < nums.size(); ++i) { if (nums[i] != 0) { nums[lastNotZero++] = nums[i]; } } //for (int i = lastNotZero; i < nums.size(); ++i) { // nums[i] = 0; //} memset(nums.data() + lastNotZero, 0, (nums.size() - lastNotZero) * sizeof(int)); //// lastNotZero <= cur 0 ִн //for (int lastNotZero = 0, cur = 0; cur < nums.size(); ++cur) { // if (nums[cur] != 0) { // std::swap(nums[cur], nums[lastNotZero++]); // } //} } }; bool isVectorSame(const std::vector<int> &v1, const std::vector<int> &v2) { if (v1.size() != v2.size()) { return false; } for (int i = 0; i < v1.size(); ++i) { if (v1[i] != v2[i]) { return false; } } return true; } void test_283() { std::vector<int> iv1 = { 0,1,0,3,2 }; std::vector<int> iv2 = { 1,3,2,0,0 }; Solution_283().moveZeroes(iv1); std::cout << "test_283 : " << isVectorSame(iv1, iv2) << std::endl; }
true
1f54a1ffc560554910d1f7b05578ddf0410c0eaf
C++
risooonho/AStarPathFinding
/Source/Pathfinding/Path.h
UTF-8
2,286
2.578125
3
[]
no_license
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "Grid.h" #include "Path.generated.h" UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class PATHFINDING_API UPath : public UActorComponent { GENERATED_BODY() public: UPath(); //Reference to the grid where the algorithm will perform UPROPERTY(EditAnywhere, BlueprintReadWrite) AGrid* Grid; //List of Open Nodes UPROPERTY(VisibleAnywhere) TArray<AGridNode*> OpenNodes; //List of Closed/Explored Nodes UPROPERTY(VisibleAnywhere) TArray<AGridNode*> ClosedNodes; //Reference to the starting node UPROPERTY(EditAnywhere, BlueprintReadWrite) AGridNode* StartNode; //Reference to the goal node UPROPERTY(EditAnywhere, BlueprintReadWrite) AGridNode* GoalNode; //Amount of total different nodes added to the open nodes list UPROPERTY(EditAnywhere, BlueprintReadWrite) int TotalOpenNodes; //Total amount of different nodes added to the closed nodes list UPROPERTY(EditAnywhere, BlueprintReadWrite) int ExploredNodes; //Heuristic multiplier for the Euclidean Distance UPROPERTY(EditAnywhere, BlueprintReadWrite) int HeuristicMultiplier; protected: virtual void BeginPlay() override; //Calculates the cost between two given nodes int CostNodes(AGridNode* n1, AGridNode* n2); //Calculates the Euclidean distance based on an heuristic multiplier int Heuristic(AGridNode* n); public: virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; //Performs the pathfinding algorithm UFUNCTION(BlueprintCallable, Category = "Path Functions") void Solution(); //User Interface Functions UFUNCTION(BlueprintCallable, Category = "Path Functions") void SetStartNode(AGridNode* n); UFUNCTION(BlueprintCallable, Category = "Path Functions") void SetGoalNode(AGridNode* n); void SetOpenNode(AGridNode* n); void SetClosedNode(AGridNode* n); UFUNCTION(BlueprintCallable, Category = "Path Functions") void ShowSolution(); private: //Keeps the current explored node as a private variable to use later when calculating the both based on the current node's parent node AGridNode* CurrentNode; };
true
2e4cc05f5f3f0c7604b97d8362118edd61362f4f
C++
LenyKholodov/wood
/src/Tests/misc/test10.cpp
WINDOWS-1251
1,053
2.625
3
[]
no_license
#include <misc\tree.h> #include <kernel.h> void main () { K_FastInit ("test10.map"); int i = 0; try { BinTree<int> tree; for (i=0;i<100;i++) { int x = random (100); // int x = i; BinTree<int>::diter iter = tree.find (x); if (iter.valid ()) { dout<<":\t"<<iter<<endl; } tree.insert (x,x); } int old = tree.count (); for (i=0;i<80;i++) { int x = random (100); tree.erase (x); } dout<<"Deleted:\t"<<old - tree.count ()<<endl; // tree.insert (5,5); // tree.insert (7,7); // tree.insert (1,1); BinTree<int>::diter iter = tree.GetMin (); int count = tree.count (); dout<<"Count:\t"<<count<<endl; for (i=0;i<count;i++) { dout<<iter<<endl;; try { iter++; } catch (Exception& exc) { dout<<"!!!\t"<<exc<<endl; } } } catch (Exception& exc) { dout<<"Error:\t"<<i<<endl; dout<<exc<<endl; } }
true
6d0676d1b37149391d8230c209d638c996ff5a33
C++
matitr/Roguelike-Game
/CombatTextManager.cpp
UTF-8
1,772
2.6875
3
[]
no_license
#include "CombatTextManager.h" #include "CombatText.h" #include "Unit.h" #include "Settings.h" #include "DataBase.h" #include "PassivesManager.h" #include <sstream> #include <iomanip> void CombatTextManager::update() { std::vector<CombatText*>::iterator it_combatText = combatTexts.begin(); while (it_combatText != combatTexts.end()) { if (!(*it_combatText)->update()) { delete (*it_combatText); it_combatText = combatTexts.erase(it_combatText); } else it_combatText++; } } void CombatTextManager::draw(SDL_Point* startRender) { std::vector<CombatText*>::iterator it_combatText = combatTexts.begin(); while (it_combatText != combatTexts.end()) { (*it_combatText)->draw(startRender); it_combatText++; } } void CombatTextManager::addDamage(float value, DamageType damageType, Unit* unit) { if (unit->getUnitType() == UnitType::Player) { if (!Settings::get()->getSettingDisplay(SettingsDisplay::ShowEnemyDamage)) return; } else if (!Settings::get()->getSettingDisplay(SettingsDisplay::ShowDamage)) return; std::stringstream stream; stream << std::fixed << std::setprecision(2) << (value); CombatText* combatT = new CombatText(unit); SDL_Color color; if (damageType == DamageType::Physical) color = DataBase::colors[TextColor::CombatTextDamage]; else if (damageType == DamageType::Fire) color = DataBase::colors[TextColor::CombatTextFireDmg]; else if (damageType == DamageType::Heal) color = DataBase::colors[TextColor::CombatTextHeal]; combatT->setText(stream.str(), DataBase::fonts[FontPurpose::CombatTextDmg], color); combatTexts.push_back(combatT); } void CombatTextManager::addDebuff(float value, Unit* unit) { } CombatTextManager::CombatTextManager() { } CombatTextManager::~CombatTextManager() { }
true
6e5b1fb6ab3ac1d48b8f599072fbdf26663dc2fe
C++
Shahdee/firework
/Contrib/Engine/include/Distortion.h
UTF-8
1,578
2.5625
3
[]
no_license
#pragma once #include "Utils/IPoint.h" #include "Render/VertexBuffer.h" // Назначение: описывает поведение "искажающей сетки" enum RefPoint { REF_NODE, REF_CENTER, REF_TOPLEFT }; class Distortion { VertexBufferIndexed _drawBuffer; // Размер сетки int _nRows,_nCols; // Размер ячейки float _cellw,_cellh; IRect _rect; float _uStart,_uEnd,_vStart,_vEnd; // аплоад каждый ход bool _upload; Distortion(); public: Distortion(int cols, int rows, bool upload = true); Distortion(const Distortion& dist); Distortion(int cols, int rows, std::vector<int> &invis, bool upload = true); ~Distortion(); void Upload(); void Draw(); void DrawGrid(); void SetRenderRect(const IRect& rect, float uStart = 0.0f, float uEnd = 1.0f, float vStart = 0.0f, float vEnd = 1.0f); void SetRenderRect(const IRect& rect, const FRect &uv); const IRect& GetRenderRect() const { return _rect; } FRect GetTextureRect() const { return FRect(_uStart, _uEnd, _vStart, _vEnd); } void SetDisplacement(int col, int row, float dx, float dy,RefPoint ref); void SetColor(int col, int row, DWORD color); void SetColor(DWORD color); void Clear(DWORD color); int getColsCount() const {return _nCols;} int getRowsCount() const {return _nRows;} void SetTextureCoord(int col, int row, float u, float v); float getCellWidth() { return _cellw; } float getCellHeight() { return _cellh; } };
true
7539128febbda35dba7f399ccca7174c86bc969e
C++
MagicalGuy/CPP_ODebugger
/TangDebugger/TangDebugger/Expression.cpp
GB18030
11,324
2.71875
3
[]
no_license
#include "stdafx.h" #include "Expression.h" Expression::Expression(DbgObject* pDbgObj) : m_pDdbgObj(pDbgObj) { } Expression::~Expression() { } /* : BYTE/WORD/DWORD/QWORD [ ʱ,Ȼȡ[]ʽеֵ Ĵ,ȡĴֵ. ȼ: 0~9, ֵԽȼԽ. ÿκĵöᴫһȼֵ,ȼ߼֧ ܴȼIJ */ const char *skipspace(const char *p) { for (; *p == ' ' || *p == '\t'; p++); return p; } bool isReg(const char* pStr, const char** pEnd) { if (*pStr == 'e') { switch (*((WORD*)(pStr + 1))) { case 'xa'://eax case 'xc'://ecx case 'xd'://edx case 'xb'://ebx case 'is'://esi case 'id'://edi case 'ps'://esp case 'pb'://ebp case 'pi'://eip if (pEnd) *pEnd = pStr + 3; return true; } } else { switch (*((WORD*)(pStr + 1))) { case 'xa'://ax case 'cx'://cx case 'dx'://dx case 'bx'://bx case 'si'://si case 'di'://di case 'sp'://sp case 'bp'://bp case 'la'://al case 'ha'://ah case 'lc'://cl case 'hc'://ch case 'ld'://dl case 'hd'://dh case 'lb'://bl case 'hb'://bh if (pEnd) *pEnd = pStr + 2; return true; } } return false; } SSIZE_T Expression::readProcMem(LPVOID lpAddr, DWORD dwSize) { SSIZE_T nValue = 0; if (dwSize == m_pDdbgObj->ReadMemory((uaddr)lpAddr, (pbyte)&nValue, dwSize)) return nValue; return 0; } bool Expression::readRegValue(const char* pReg, const char** pEnd, SSIZE_T& uRegValue) { if (pReg == NULL) return false; CONTEXT ct = { 0 }; ct.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL; if (!m_pDdbgObj->GetRegInfo(ct)) return false; pReg = skipspace(pReg); if (*pReg == 'e') { *pEnd = pReg + 3; switch (*((WORD*)(pReg + 1))) { case 'xa'://eax uRegValue = ct.Eax; break; case 'xc'://ecx uRegValue = ct.Ecx; break; case 'xd'://edx uRegValue = ct.Edx; break; case 'xb'://ebx uRegValue = ct.Ebx; break; case 'is'://esi uRegValue = ct.Esi; break; case 'id'://edi uRegValue = ct.Edi; break; case 'ps'://esp uRegValue = ct.Esp; break; case 'pb'://ebp uRegValue = ct.Ebp; break; case 'pi':// eip uRegValue = ct.Eip; break; default: uRegValue = 0; return false; } } else { *pEnd = pReg + 2; switch (*((WORD*)(pReg + 1))) { case 'xa'://ax uRegValue = ct.Eax & 0xFFFF; break; case 'xc'://cx uRegValue = ct.Ecx & 0xFFFF; break; case 'xd'://dx uRegValue = ct.Edx & 0xFFFF; break; case 'xb'://bx uRegValue = ct.Ebx & 0xFFFF; break; case 'is'://si uRegValue = ct.Esi & 0xFFFF; break; case 'id'://di uRegValue = ct.Edi & 0xFFFF; break; case 'ps'://sp uRegValue = ct.Esp & 0xFFFF; break; case 'pb'://bp uRegValue = ct.Ebp & 0xFFFF; break; case 'la'://al uRegValue = ct.Eax & 0x0f; break; case 'ha'://ah uRegValue = ct.Eax & 0xf0; break; case 'lc'://cl uRegValue = ct.Ecx & 0x0f; break; case 'hc'://ch uRegValue = ct.Ecx & 0xf0; break; case 'ld'://dl uRegValue = ct.Edx & 0x0f; break; case 'hd'://dh uRegValue = ct.Edx & 0xf0; break; case 'lb'://bl uRegValue = ct.Ebx & 0x0f; break; case 'hb'://bh uRegValue = ct.Ebx & 0xf0; break; default: uRegValue = 0; return false; } } return true; } bool Expression::WriteRegValue(const char* pReg, const char** pEnd, SSIZE_T& uRegValue) { if (pReg == NULL) return false; CONTEXT ct = { 0 }; ct.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL; if (!m_pDdbgObj->GetRegInfo(ct)) return false; pReg = skipspace(pReg); if (*pReg == 'e') { *pEnd = pReg + 3; switch (*((WORD*)(pReg + 1))) { case 'xa'://eax ct.Eax = uRegValue; break; case 'xc'://ecx ct.Ecx = uRegValue; break; case 'xd'://edx ct.Edx = uRegValue; break; case 'xb'://ebx ct.Ebx = uRegValue; break; case 'is'://esi ct.Esi = uRegValue; break; case 'id'://edi ct.Edi = uRegValue; break; case 'ps'://esp ct.Esp = uRegValue; break; case 'pb'://ebp ct.Ebp = uRegValue; break; case 'pi':// eip ct.Eip = uRegValue; break; default: 0; return false; } } else { *pEnd = pReg + 2; switch (*((WORD*)(pReg + 1))) { case 'xa'://ax ct.Eax = uRegValue & 0xFFFF; break; case 'xc'://cx ct.Ecx = uRegValue & 0xFFFF; break; case 'xd'://dx ct.Edx = uRegValue & 0xFFFF; break; case 'xb'://bx ct.Ebx = uRegValue & 0xFFFF; break; case 'is'://si ct.Esi = uRegValue & 0xFFFF; break; case 'id'://di ct.Edi = uRegValue & 0xFFFF; break; case 'ps'://sp ct.Esp = uRegValue & 0xFFFF; break; case 'pb'://bp ct.Ebp = uRegValue & 0xFFFF; break; case 'la'://al ct.Eax = uRegValue & 0x0f; break; case 'ha'://ah ct.Eax = uRegValue & 0xf0; break; case 'lc'://cl ct.Ecx = uRegValue & 0x0f; break; case 'hc'://ch ct.Ecx = uRegValue & 0xf0; break; case 'ld'://dl ct.Edx = uRegValue & 0x0f; break; case 'hd'://dh ct.Edx = uRegValue & 0xf0; break; case 'lb'://bl ct.Ebx = uRegValue & 0x0f; break; case 'hb'://bh ct.Ebx = uRegValue & 0xf0; break; default: 0; return false; } } if (!m_pDdbgObj->SetRegInfo(ct)) return false; return true; } bool Expression::getValue(SSIZE_T& uValue, const char* pStr, const char** pEnd, int nPriorty) { // жϱʽڴַıʽֵͨʽ bool bFalg = true; pStr = skipspace(pStr); if (*pStr == 0) return 0; // жϱʽǷڴѰַ // ڴѰַ, ڴѰַıʽΪӱʽ,ӱʽҪֵ if (*pStr == '[') { // õӱʽֵ if (!getValue(uValue, pStr + 1, &pStr, 9)) { bFalg = false; } } else if (_strnicmp(pStr, "BYTE", 4) == 0) { // õӱʽֵ pStr = skipspace(pStr + 4); getValue(uValue, pStr, &pStr, 9); if (*pStr == ']') { ++pStr; // uValue ڴַ,ȡڴֵַ uValue = readProcMem((LPVOID)uValue, sizeof(BYTE)); } else { bFalg = false; } } else if (_strnicmp(pStr, "WORD", 4) == 0) { pStr = skipspace(pStr + 4); // õӱʽֵ getValue(uValue, pStr, &pStr, 9); // uValue ڴַ,ȡڴֵַ if (*pStr == ']') { ++pStr; // uValue ڴַ,ȡڴֵַ uValue = readProcMem((LPVOID)uValue, sizeof(WORD)); } else { bFalg = false; } } else if (_strnicmp(pStr, "DWORD", 5) == 0) { pStr = skipspace(pStr + 5); // õӱʽֵ getValue(uValue, pStr, &pStr, 9); // uValue ڴַ,ȡڴֵַ if (*pStr == ']') { ++pStr; // uValue ڴַ,ȡڴֵַ uValue = readProcMem((LPVOID)uValue, sizeof(DWORD)); } else { bFalg = false; } } else if (_strnicmp(pStr, "QWORD", 5) == 0) { pStr = skipspace(pStr + 5); // õӱʽֵ getValue(uValue, pStr, &pStr, 9); // uValue ڴַ,ȡڴֵַ if (*pStr == ']') { ++pStr; // uValue ڴַ,ȡڴֵַ uValue = readProcMem((LPVOID)uValue, sizeof(__int64)); } else { bFalg = false; } } else if (*pStr == '0'&&pStr[1] == 'x') { uValue = strtol(pStr, (char**)&pStr, 16); } else if (isReg(pStr, NULL)) // ǸĴֵ { const char *pReg = pStr; isReg(pStr, &pReg); pReg = skipspace(pReg); if (*pReg == '=' && *(pReg + 1) != '=') // Ĵֵ { // ȡ SSIZE_T nlValue = 0; if (getValue(nlValue, pReg + 1, &pReg, 9)) { uValue = nlValue; WriteRegValue(pStr, &pStr, nlValue); pStr = pReg; } else bFalg = false; } else { if (!readRegValue(pStr, &pStr, uValue)) bFalg = false; } } else if ('0' <= *pStr && *pStr <= '9') { uValue = strtol(pStr, (char**)&pStr, 10); } else if (*pStr == '+') { pStr = skipspace(pStr + 1); uValue = getValue(uValue, pStr, &pStr, 0); } else if (*pStr == '-') { pStr = skipspace(pStr + 1); if (getValue(uValue, pStr, &pStr, 0)) { uValue = -uValue; } } else if (*pStr == '(') /*ŵȼ*/ { pStr = skipspace(pStr + 1); getValue(uValue, pStr, &pStr, 9); pStr = skipspace(pStr); if (*pStr == ')') pStr = skipspace(pStr + 1); else bFalg = false; } else { bFalg = false; } pStr = skipspace(pStr); /* õ */ if (bFalg == false) return false; if (*pStr == '+' && nPriorty > 3) { // ȡڶ SSIZE_T right = 0; if (!getValue(right, pStr + 1, &pStr, 3)) return false; uValue += right; } else if (*pStr == '-' && nPriorty > 3) { // ȡڶ SSIZE_T right = 0; if (!getValue(right, pStr + 1, &pStr, 3)) return false; uValue -= right; } else if (*pStr == '*' && nPriorty > 2) { // ȡڶ SSIZE_T right = 0; if (!getValue(right, pStr + 1, &pStr, 2)) return false; uValue *= right; } else if (*pStr == '/' && nPriorty > 2) { // ȡڶ SSIZE_T right = 0; if (!getValue(right, pStr + 1, &pStr, 2)) return false; uValue /= right; } else if (*pStr == '%' && nPriorty > 2) { // ȡڶ SSIZE_T right = 0; if (!getValue(right, pStr + 1, &pStr, 2)) return false; uValue %= right; } else if (*pStr == '<' && nPriorty>9) { // ȡڶ SSIZE_T right = 0; if (!getValue(right, pStr + 1, &pStr, 9)) return false; uValue = uValue < right; } else if (*pStr == '>'&& nPriorty>9) { // ȡڶ SSIZE_T right = 0; if (!getValue(right, pStr + 1, &pStr, 9)) return false; uValue = uValue > right; } else if (*pStr == '='&&pStr[1] == '='&& nPriorty >= 9) { // ȡڶ SSIZE_T right = 0; if (!getValue(right, pStr + 2, &pStr, 9)) return false; uValue = uValue == right; } else if (*pStr == '&'&&pStr[1] == '&' && nPriorty >= 9) { // ȡڶ SSIZE_T right = 0; if (!getValue(right, pStr + 2, &pStr, 9)) return false; uValue = uValue && right; } else if (*pStr == '|'&&pStr[1] == '|'&& nPriorty >= 9) { // ȡڶ SSIZE_T right = 0; if (!getValue(right, pStr + 2, &pStr, 9)) return false; uValue = uValue || right; } else if (*pStr == '<'&&pStr[1] == '='&& nPriorty >= 9) { // ȡڶ SSIZE_T right = 0; if (!getValue(right, pStr + 2, &pStr, 9)) return false; uValue = uValue <= right; } else if (*pStr == '>'&&pStr[1] == '='&& nPriorty >= 9) { // ȡڶ SSIZE_T right = 0; if (!getValue(right, pStr + 2, &pStr, 9)) return false; uValue = uValue >= right; } else if (*pStr == '!'&&pStr[1] == '='&& nPriorty >= 9) { // ȡڶ SSIZE_T right = 0; if (!getValue(right, pStr + 2, &pStr, 9)) return false; uValue = uValue != right; } *pEnd = pStr; return bFalg; } SSIZE_T Expression::getValue(const char* pStr) { if (pStr == nullptr) return 0; const char* pEnd = pStr; SSIZE_T uValue = 0; if (getValue(uValue, pStr, &pEnd, 9)) return uValue; return 0; }
true
545bb814085203e05dd7212d6f5e13f5db3c8c31
C++
kmc7468/lowi
/src/lowi/instructions/nop.cc
UTF-8
730
3.15625
3
[ "MIT" ]
permissive
#include <lowi/instructions/nop.hh> namespace lowi { namespace instructions { nop::nop() : instruction_type("nop", 0) {} bool nop::operator==(const nop& nop) const noexcept { return equal(nop); } bool nop::operator!=(const nop& nop) const noexcept { return !equal(nop); } nop& nop::assign(const nop&) { return *this; } nop& nop::assign(nop&&) noexcept { return *this; } bool nop::equal(const instruction_type& instruction_type) const { if (this == &instruction_type) return true; return name() == instruction_type.name() && number_of_operands() == instruction_type.number_of_operands(); } bool nop::equal(const nop&) const noexcept { return true; } } }
true
4a0e389b621e88fe0d45850f066d6359d0f4e4cc
C++
simion-iulian/wavelamp
/_3ServoSweep.ino
UTF-8
1,391
3.28125
3
[ "CC0-1.0" ]
permissive
/* Sweep by BARRAGAN <http://barraganstudio.com> This example code is in the public domain. modified 8 Nov 2013 by Scott Fitzgerald http://www.arduino.cc/en/Tutorial/Sweep */ #include <Servo.h> Servo servo1; Servo servo2;// create servo object to control a servo Servo servo3; const int NUM_SERVOS = 3;// twelve servo objects can be created on most boards Servo servos[NUM_SERVOS]; int pos = 0; // variable to store the servo position void setup() { delay(3000); servo1.attach(3); // attaches the servo on pin 9 to the servo object servo2.attach(5); servo3.attach(6); servos[0] = servo1; servos[1] = servo2; servos[2] = servo3; } void loop() { int p = 75; int s = 60; int e = 160; int increment = 1; for(pos = s; pos <= e; pos += increment) // goes from 0 degrees to 180 degrees { // in steps of 1 degree for(int i = 0; i<NUM_SERVOS;i++){ servos[i].write(pos); }// tell servo to go to position in variable 'pos' delay(p); // waits 15ms for the servo to reach the position } for(pos = e; pos>=s; pos-=increment) // goes from 180 degrees to 0 degrees { for(int i = 0; i<NUM_SERVOS;i++){ servos[i].write(pos); } delay(p); // waits 15ms for the servo to reach the position } }
true
2f61d4bf49c84e3c3bf386bbe898f47934ce7dcd
C++
goodann/AlgorithmsStudy
/JHS/01 - Algorithm/02 - Implementation/53 - Fair Rations.cpp
UHC
1,301
3.15625
3
[]
no_license
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; /* - N 迭 Է¹޴´. پִ 1 ִ. - ¦ ִ° - ϴٸ ּҰ ض Ұϴٸ NO ϴ */ int main() { //Է== int N; cin >> N; vector<int> B(N); for (int B_i = 0; B_i < N; B_i++) { cin >> B[B_i]; } //== int count = 0; // for (int B_i = 0; B_i<N; B_i++) { if (B[B_i] % 2 != 0) { //ù ʴ Žϸ Ȧ 1 Ѵ. if (B_i + 1 == N) { //Ȧ ϰ NO Ѵ. cout << "NO"; return 0; } B[B_i]++; B[B_i + 1]++; count += 2; } } //== cout << count; return 0; }
true
aef6e21f906cc320e48224229c06884156cfe536
C++
AdityaKarn/cp-cpp
/codeforces/1397/C.cpp
UTF-8
2,105
2.578125
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <climits> #define REP(i, n) for (int i = 1; i <= n; i++) #define mod 1000000007 #define pb push_back #define ff first #define ss second #define ii pair<int, int> #define vi vector<int> #define vii vector<ii> #define lli long long int #define INF 1000000000 using namespace std; int arr[100001]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; cin >> n; for (int i = 0; i < n; i++) { cin >> arr[i]; } int bar1 = 1, bar2 = n - 1; int len1 = 1, len3 = 1; int len2 = n - len1 - len3; bool possible = false; for (int i = 1; i < n - 1; i++) { //to check whether we can take a[i] for (int j = 0; j <= bar1; j++) { // cout << len2 << " " << len1 << " " << arr[j] << "\n"; if ((len2 + len1 - arr[j]) % len2 != 0 && (len2 + len1 - arr[j]) % len1 != 0) { break; } bar1++; len1++; } } for (int i = n - 1; i > len1; i--) { for (int j = n - 1; j >= bar2; j--) { if ((len2 + len3 - arr[j]) % len2 != 0 && (len2 + len3 - arr[j]) % len3 != 0) { break; } } bar2--; len2++; } cout << 0 << " " << len1 - 1 << "\n"; if (len1 == 1) { cout << 1 << " " << 1 << "\n"; cout << -arr[0] << "\n"; } else { cout << 1 << " " << len1 << "\n"; for (int i = 0; i < len1 - 1; i++) { cout << arr[i] % len1 << "\n"; } cout << "\n"; } if (len1 == 1) { } for (int i = 0; i < len1; i++) { cout << (len2 + len1 - arr[i]) << " "; arr[i] += arr[i] % len2; } cout << "\n"; cout << 0 << " " << len2 << "\n"; for (int i = 0; i < n - 1; i++) { cout << -1 * arr[i] << " "; } cout << "\n"; cout << len3 << " " << len3 << "\n"; cout << -1 * arr[n - 1]; // cout << bar1; return 0; }
true
1be5b1c8e915a735b877554688ba29d0917f90ea
C++
Argasz/CPROGLib
/EventLoop.h
UTF-8
2,171
2.625
3
[]
no_license
// // Created by Aron on 2018-11-23. // #ifndef CPROGLIB_EVENTLOOP_H #define CPROGLIB_EVENTLOOP_H #include <vector> #include <SDL.h> #include "Sprite.h" #include "Entity.h" #include "Window.h" #include "Background.h" #include "Map.h" #include "DebugInfo.h" #include "PhysicsObject.h" #include "MemPtrCommand.h" #include "Scene.h" namespace CPROGLib{ class EventLoop { private: SDL_Event event; int fps; std::vector<Entity*> entities,added,removed; std::vector<KeyCommand*> commands; bool running; int mainLoop(); SDL_Rect camera; Background* bg; void adjustCamera(Entity& e); void readKeyCommands(SDL_Event& ev); Map* map; bool debug = false; DebugInfo* debugInfo; PhysicsObject* physicsObject; void clearRemoved(); void addAdded(); Scene* currentScene; bool paused = false; public: EventLoop(int fps, const std::string& bgImgPath, Map* map); EventLoop(int fps, Scene* s); ~EventLoop(); void addEntity(Entity* e); void removeEntity(Entity* e); void clearEntities(); void start(); void stop(); void pause(){ paused = true;}; void unpause(){paused = false;}; void attachCameraToEntity(Entity& ent); void addDebugInfo(DebugInfo& debugInfo){ this->debugInfo = &debugInfo; }; void addPhysicsObject(PhysicsObject& p){ this->physicsObject = &p; }; void toggleDebug() { debug = !debug; }; void addKeyCommand(KeyCommand& kc){ commands.push_back(&kc); } Map& getMap(){ return *map; } SDL_Rect& getCamera(){ return camera; } PhysicsObject& getPhys(){ return *physicsObject; } std::vector<Entity*> getEntities(){ return entities; } std::vector<Entity*> getSceneEntities(){ return currentScene->entities; } void loadScene(Scene* s); }; } #endif //CPROGLIB_EVENTLOOP_H
true
b77f00fb3e48d8fd6e637df8b092deb9feafdfd1
C++
HenryLoo/cozybirdFX
/cozybirdFX/Texture.cpp
UTF-8
683
2.65625
3
[ "BSD-3-Clause" ]
permissive
#include "Texture.h" #include <glad/glad.h> #include <iostream> namespace { const std::string ASSET_PATH{ "assets/" }; const std::string TEXTURE_PATH{ "texture/" }; } Texture::Texture(unsigned int textureId, int width, int height, int numChannels) : m_textureId(textureId), m_width(width), m_height(height), m_numChannels(numChannels) { } Texture::~Texture() { glDeleteTextures(1, &m_textureId); } void Texture::bind() const { glBindTexture(GL_TEXTURE_2D, m_textureId); } int Texture::getWidth() const { return m_width; } int Texture::getHeight() const { return m_height; } int Texture::getNumChannels() const { return m_numChannels; }
true
4410e8d1b3989d237ca796f55ad470957d88780a
C++
wis-niowy/Programming-2---Object-Oriented
/lab2/lab2_2016/lamana.h
UTF-8
529
2.578125
3
[]
no_license
#pragma once #include <iostream> using namespace std; #include "punkt.h" const int num = 5; class Lamana { Odcinek ol[num]; int number; public: Lamana() { }; Lamana(int number); Lamana(Odcinek*, int number); friend Lamana operator+(const Lamana&, const Lamana&); friend ostream& operator<<(ostream&, const Lamana&); Odcinek getol(int indeks) const { return ol[indeks]; }; void setol(Odcinek p, int i); int getnumber() const { return number; }; void setnumber(int a) { number = a; }; };
true
b7263f6149f3e31ae69a0f742678dd1c72be663c
C++
nursyazaathirah/smartshirt
/bit_test/bit_test.ino
UTF-8
888
2.875
3
[]
no_license
#include <binary.h> byte data = 0; boolean step_taken; int body_temp; //needs to be between 0 and 32 int BPM; boolean danger_location; boolean danger_hit; boolean byte_flag = true; void setup() { Serial.begin(9600); step_taken = true; body_temp = 15; BPM = 100/10; danger_hit = true; danger_location = 0; } void loop() { data = 0; // Transfer the byte with BPM information if (byte_flag) { data = data | step_taken | (body_temp << 1) | (danger_hit << 6) | (danger_location << 7); } else { // Transfer the byte with temperature information data = data | step_taken | (BPM << 1) | (danger_hit << 6) | (danger_location << 7); } // Flip byte flag byte_flag = !byte_flag; // Print to console for (int i = 7; i >= 0; i--) { Serial.print(bitRead(data, i)); } Serial.println(); // Alternate byte every half second delay(500); }
true
d997690b2ddde318bcd38e3be0aecff773de76d4
C++
dmironov1993/acmp
/acmp/0340.cpp
UTF-8
1,114
3.203125
3
[]
no_license
//https://acmp.ru/asp/do/index.asp?main=task&id_course=1&id_section=2&id_topic=31&id_problem=1216 #include <bits/stdc++.h> using namespace std; bool firstCan(vector<int> v1, vector<int> v2) { for (int i = 0; i < 3; i++) { if (v1[i] > v2[i]) { return false; } } return true; } bool secondCan(vector<int> v1, vector<int> v2) { for (int i = 0; i < 3; i++) { if (v2[i] > v1[i]) { return false; } } return true; } int main() { int a1,b1,c1; cin >> a1 >> b1 >> c1; vector<int> a(3); a[0] = a1; a[1] = b1; a[2] = c1; sort(a.begin(), a.end()); int a2,b2,c2; cin >> a2 >> b2 >> c2; vector<int> b(3); b[0] = a2; b[1] = b2; b[2] = c2; sort(b.begin(), b.end()); if (a == b) { cout << "Boxes are equal"; } else if (firstCan(a,b)) { cout << "The first box is smaller than the second one"; } else if (secondCan(a,b)) { cout << "The first box is larger than the second one"; } else { cout << "Boxes are incomparable"; } return 0; }
true
5e4a5a20f0e1a8431b3ea7cc778d1de0e004319b
C++
diwujiahao/leetcode
/220. Contains Duplicate III/solution1.cpp
UTF-8
959
3.359375
3
[]
no_license
// 利用集合的红黑树查找功能--实现候选数字的快速确定 class Solution { // |x - nums[i]| <= t ==> -t <= x - nums[i] <= t; public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { set<double> window; // set is ordered automatically for (int i = 0; i < nums.size(); i++) { // 保证集合窗口大小 if (i > k) window.erase(double(nums[i-k-1])); // keep the set contains nums i j at most k // 保证 x-nums[i] >= -t ==> x >= nums[i]-t 限制 auto pos_left = window.lower_bound(double(nums[i]) - double(t)); // 保证 x - nums[i] <= t ==> x <= nums[i]+t 限制 if (pos_left != window.end() && *pos_left <= double(nums[i]) + double(t)) return true; // 保证集合窗口大小 window.insert(double(nums[i])); } return false; } };
true
1bc112d720da401813bf53d72b3b01905b918434
C++
adrianohrl/alliance
/alliance/src/utilities/has_name.cpp
UTF-8
698
2.53125
3
[]
no_license
/** * This source file implements the HasName class. * * Author: Adriano Henrique Rossette Leite (adrianohrl@unifei.edu.br) * Maintainer: Expertinos UNIFEI (expertinos.unifei@gmail.com) */ #include "utilities/has_name.h" namespace utilities { HasName::HasName(const std::string& name, const std::string& id) : HasId<std::string>::HasId(id.empty() ? name : id), name_(name) { if (id.empty()) { throw utilities::Exception("Id must not be empty."); } if (name.empty()) { throw utilities::Exception("Name must not be empty."); } } HasName::HasName(const HasName& has_name) : HasId<std::string>::HasId(has_name), name_(has_name.name_) { } HasName::~HasName() {} const std::string HasName::getName() const { return name_; } }
true
88c4ede3a993a30d8c2dfb630caadd4610573b56
C++
mementum/codeeval
/01-easy/0230-football/0230-football.cpp
UTF-8
3,297
2.796875
3
[]
no_license
/* Copyright (C) 2016 Daniel Rodriguez This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // Headers for test case input/output #include <fstream> #include <iostream> // Headers for the implementation #include <algorithm> #include <iterator> #include <tuple> #include <vector> struct SeparatorReader: std::ctype<char> { template<typename T> SeparatorReader(const T &seps): std::ctype<char>(get_table(seps), true) {} template<typename T> std::ctype_base::mask const *get_table(const T &seps) { auto &&rc = new std::ctype_base::mask[std::ctype<char>::table_size](); for(auto &&sep: seps) rc[static_cast<unsigned char>(sep)] = std::ctype_base::space; return &rc[0]; } }; /////////////////////////////////////////////////////////////////////////////// // Main /////////////////////////////////////////////////////////////////////////////// // Use a vector of tuples approach to avoid having a map<int, vector> which is // a lot more expensive, given prealloc is not possible, whereas a single // vector of tuples can be preallocated and reused by copying/transforming each // time from the beginning (since we get the last item as result) int main(int argc, char *argv[]) { std::ifstream stream(argv[1]); // Ensure '\n' is not ws and breaks reading ints as '|' does stream.imbue(std::locale(stream.getloc(), new SeparatorReader(" "))); auto in2 = std::istream_iterator<int>{}; auto teamfans = std::vector<std::tuple<int, int>>(100); auto tffirst = teamfans.begin(); while(stream) { // run over the "fans" and keep a (team, fan) reference // transform instead of copy to create the pair // fans are 1 based auto tflast = tffirst; // make sure we copy at the beginning auto sep = '\0'; for(auto f=1; stream and sep != '\n'; f++, stream.clear(), stream >> sep) { auto in1 = std::istream_iterator<int>{stream}; tflast = std::transform( in1, in2, tflast, [f](const int t) { return std::make_tuple(t, f); }); } // now tflast points to the last element added to the vector std::sort(tffirst, tflast); // the output is sorted team/fan auto lastteam = -1, iteam = 0, ifan = 0; for(auto tf=tffirst; tf != tflast; tf++) { std::tie(iteam, ifan) = *tf; // unpack the tuple if(iteam != lastteam) { lastteam = iteam; std::cout << (tf != tffirst ? "; " : "") << iteam << ':' << ifan; } else std::cout << ',' << ifan; } std::cout << ';' << std::endl; // complete the output } return 0; }
true
4eb785cb982ea7329b2474a775c9d2e02bede06b
C++
harp07/HumberPhysicsGame
/Classes/AudioManager.h
UTF-8
798
2.859375
3
[]
no_license
/* AudioManager.h ** Manages all the sound effects and music for the game. ** use .wav files since they are supported by all platforms */ #include <SimpleAudioEngine.h> #include <string> class AudioManager { private: //The Audio Engine SimpleAudioEngine *audioEngine; //Sounds. These will all be strings of the filepath to the sound. string shoot; string splash; string hit; // etc ... //Music string song1; string song2; string song3; // etc ... public: AudioManager(SimpleAudioEngine); void playSound(string sound); void playMusic(string song, bool loop); void stopSound(); void stopAllSounds(); void pauseMusic(); void resumeMusic(); void stopMusic(); void setSoundVolume(float); void setMusicVolume(float); ~AudioManager(); }
true
d0ca409dcf6c6bf2007f70e712e102605deb33bd
C++
TallanGroberg/EECS183
/testing/testing/coinCounter.cpp
UTF-8
2,724
2.9375
3
[]
no_license
// // // //// //// coinCounter.cpp //// testing //// //// Created by Tallan Groberg on 1/26/21. //// // //#include <iostream> //#include<string> //#include<cmath> //#include<cassert> //using namespace std; // //string pluralize(string singluar, string plural, double amount) { // if(amount > 1 || amount == 0){ // return plural; // } else { // return singluar; // } // // // //} // ////change to string //string changeBack(double change){ // // int dollars = change * 100; // int dollar = 100; // // // int ones = 0; // int quarter = 0; // int quarts = 0; // int dime = 0; // int nickel = 0; // int penney = 0; // int coin = dollar; // // while (dollars > 0){ // if(dollars > 100) // { // ones++; // } // if(dollars <= 100 && dollars > 25) // { // quarter++; // coin = 25; // } // if(dollars <= 25 && dollars > 10) // { // dime++; // coin = 10; // } // if(dollars <= 10 && dollars > 5) // { // nickel++; // coin = 5; // } // if(dollars < 5) // { // penney++; // coin = 1; // } // dollars = dollars - coin; // }; // // // // // // // // // // // // // // // string moneys = to_string(ones) + " " + // pluralize("dollar", "dollars", ones) + ", " + // to_string(quarter) + " " + // pluralize("quarter", "quarters", quarter) + ", " + // to_string(dime) + " " + // pluralize("dime", "dimes", dime) + ", " + // to_string(nickel) + " " + // pluralize("nickel", "nickels", nickel) + ", " + // to_string(penney) + " " + // pluralize("penney", "pennies", penney); // // return moneys; //} // //void test_change_back(){ // // // // // assert(changeBack(1.34) == "1 dollar, 1 quarter, 0 dimes, 1 nickel, 4 pennies"); // assert(changeBack(2.34) == "2 dollars, 1 quarter, 0 dimes, 1 nickel, 4 pennies"); // assert(changeBack(2.64) == "2 dollars, 2 quarters, 1 dime, 0 nickels, 4 pennies"); // assert(changeBack(2.61) == "2 dollars, 2 quarters, 1 dime, 0 nickels, 1 penney"); // assert(changeBack(2.71) == "2 dollars, 2 quarters, 2 dimes, 0 nickels, 1 penney"); // assert(changeBack(37.99) == "37 dollars, 3 quarters, 2 dimes, 0 nickels, 4 pennies"); // // //} // // // //int main(int argc, const char * argv[]) { // // // changeBack(13.45); // // // return 0; //} //
true
874fc84e94727181147761683efd4413b41cd92f
C++
libocca/occa
/tests/src/internal/lang/parser/scope.cpp
UTF-8
4,451
2.765625
3
[ "MIT" ]
permissive
#include "utils.hpp" void testScopeUp(); void testScopeKeywords(); void testScopeErrors(); int main(const int argc, const char **argv) { setupParser(); testScopeUp(); testScopeKeywords(); testScopeErrors(); return 0; } const std::string scopeTestSource = ( // root[0] "int x;\n" // root[1] "typedef int myInt;\n" // root[2] "void foo() {\n" " int x;\n" " {\n" " int x;\n" " }\n" " typedef int myInt;\n" "}\n" // root[3] "int main(const int argc, const char **argv) {\n" " int x = argc;\n" " int a;\n" " if (true) {\n" " int x = 0;\n" " int b;\n" " if (true) {\n" " int x = 1;\n" " int c;\n" " if (true) {\n" " int x = 2;\n" " int d;\n" " }\n" " }\n" " }\n" "}\n" // root[4] "struct struct1_t {\n" " int x1;\n" "};\n" // root[5] "typedef struct {\n" " int x2;\n" "} struct2_t;\n" // root[6] "typedef struct struct3_t {\n" " int x3, x4;\n" "} struct4_t;\n" // root[7] "struct struct1_t struct1;\n" // root[8] "struct struct2_t struct2;\n" // root[9] "struct struct3_t struct3;\n" // root[10] "struct struct4_t struct4;\n" ); void testScopeUp() { parseSource(scopeTestSource); blockStatement &root = parser.root; statement_t *x = root[0]; blockStatement &foo = root[2]->to<blockStatement>(); blockStatement &main = root[3]->to<blockStatement>(); blockStatement &fooBlock = foo[1]->to<blockStatement>(); ASSERT_EQ(&root, x->up); ASSERT_EQ(&root, foo.up); ASSERT_EQ(&root, main.up); ASSERT_EQ(&foo, fooBlock.up); } void testScopeKeywords() { parseSource(scopeTestSource); blockStatement &root = parser.root; blockStatement &foo = root[2]->to<blockStatement>(); blockStatement &fooBlock = foo[1]->to<blockStatement>(); ASSERT_TRUE(root[7]->is<declarationStatement>()); ASSERT_TRUE(root[8]->is<declarationStatement>()); ASSERT_TRUE(root[9]->is<declarationStatement>()); ASSERT_TRUE(root[10]->is<declarationStatement>()); // Make sure we can find variables 'x' ASSERT_TRUE(root.hasInScope("x")); ASSERT_TRUE(foo.hasInScope("x")); ASSERT_TRUE(fooBlock.hasInScope("x")); // Make sure variables 'x' exist ASSERT_EQ_BINARY(keywordType::variable, root.getScopeKeyword("x").type()); ASSERT_EQ_BINARY(keywordType::variable, foo.getScopeKeyword("x").type()); ASSERT_EQ_BINARY(keywordType::variable, fooBlock.getScopeKeyword("x").type()); // Make sure all instances are different ASSERT_NEQ(&root.getScopeKeyword("x").to<variableKeyword>().variable, &foo.getScopeKeyword("x").to<variableKeyword>().variable); ASSERT_NEQ(&root.getScopeKeyword("x").to<variableKeyword>().variable, &fooBlock.getScopeKeyword("x").to<variableKeyword>().variable); ASSERT_NEQ(&foo.getScopeKeyword("x").to<variableKeyword>().variable, &fooBlock.getScopeKeyword("x").to<variableKeyword>().variable); // Test function ASSERT_EQ_BINARY(keywordType::function, root.getScopeKeyword("foo").type()); ASSERT_EQ_BINARY(keywordType::function, root.getScopeKeyword("main").type()); // Test types ASSERT_EQ_BINARY(keywordType::type, root.getScopeKeyword("myInt").type()); ASSERT_EQ_BINARY(keywordType::type, foo.getScopeKeyword("myInt").type()); // Test structs ASSERT_EQ_BINARY(keywordType::type, root.getScopeKeyword("struct1_t").type()); ASSERT_EQ_BINARY(keywordType::type, root.getScopeKeyword("struct2_t").type()); ASSERT_EQ_BINARY(keywordType::type, root.getScopeKeyword("struct3_t").type()); ASSERT_EQ_BINARY(keywordType::type, root.getScopeKeyword("struct4_t").type()); } void testScopeErrors() { std::cerr << "\n---[ Testing scope errors ]---------------------\n\n"; const std::string var = "int x;\n"; const std::string type = "typedef int x;\n"; const std::string func = "void x() {}\n"; std::string sources[3] = { var, type, func }; for (int j = 0; j < 3; ++j) { for (int i = 0; i < 3; ++i) { parseBadSource(sources[j] + sources[i]); std::cout << '\n'; } } parseBadSource("int x, x;\n"); std::cerr << "==============================================\n\n"; }
true
9717d277bf1a46c4e500b2f1414f97d0df594f93
C++
Thugday/BOJ
/11725.cpp
UTF-8
903
2.953125
3
[]
no_license
#include <iostream> #include <algorithm> #include <queue> #include <vector> #define MAX 100001 using namespace std; int depth[MAX], d[MAX], parent[MAX]; bool check[MAX]; vector<int> a[MAX]; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; for (int i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; a[u].push_back(v); a[v].push_back(u); } queue<int> q; depth[1] = 0; // 루트 1. check[1] = true; // 1은 방문 한 상태. parent[1] = 0; // 1의 루트는 없으니 0. q.push(1); // bfs 구현. while (!q.empty()) { int x = q.front(); q.pop(); for (int y : a[x]) { if (!check[y]) { depth[y] = depth[x] + 1; // depth 1 증가. check[y] = true; // 방문 표시. parent[y] = x; // 다음 y 가 현재 x가 된다. q.push(y); } } } for (int i = 2; i <= n; i++) { cout << parent[i] << '\n'; } return 0; }
true
7e157bb12e047666c219375f15d861afc486d396
C++
HaoLIU94/Heat_diffusion
/2dimension/square.cpp
UTF-8
5,335
2.75
3
[]
no_license
# include <cstdlib> # include <iostream> # include <iomanip> # include <cmath> /* [x] = read("/home/hao/ensiieS3/PAP/project/2dimension/square/square_u0001.txt",1000,1000) set(gcf(),"color_map",[jetcolormap(64);hotcolormap(64)]) zm = min(x); zM = max(x); colorbar(zm,zM,[1,64]) Sgrayplot(1:1000,1:1000,x,strf="041",rect=[0,0,1000,1000],colminmax=[1,64]) */ using namespace std; double *dirichlet_condition ( int node_num, double node_xy[], double time ); double *initial_condition ( int node_num, double node_xy[], double time ); double k_coef ( int node_num, double node_xy[], double time ); double rhs ( int node_num, double node_xy[], double time ); //****************************************************************************80 double *dirichlet_condition ( int node_num, double node_xy[], double time ) //****************************************************************************80 // // Purpose: // // DIRICHLET_CONDITION sets the value of a Dirichlet boundary condition. // // Discussion: // // The input points (X,Y) are assumed to lie on the boundary of the // region. // // This routine is set for the unit square. // // We assume that the equation to be solved is // // dUdT - Laplacian U + K * U = F // // with K = 0, and F = (2*pi*pi-1)*sin(pi*x)*sin(pi*y)*exp(-t). // // The exact solution is: // // U = sin(pi*x) * sin(pi*y) * exp(-t) // // Modified: // // 04 December 2013 // // Author: // // John Burkardt // // Parameters: // // Input, int NODE_NUM, the number of points. // // Input, double NODE_XY[2*NODE_NUM], the coordinates of the points. // // Input, double TIME, the current time. // // Output, double DIRICHLET_CONDITION[NODE_NUM], the value of // the solution at the the point. // { int node; double *u; u = new double[node_num]; for ( node = 0; node < node_num; node++ ) { u[node] = 250.15; } return u; } //****************************************************************************80 double *initial_condition ( int node_num, double node_xy[], double time ) //****************************************************************************80 // // Purpose: // // INITIAL_CONDITION sets the initial condition. // // Discussion: // // The input value TIME is assumed to be the initial time. // // We assume that the equation to be solved is // // dUdT - Laplacian U + K * U = F // // with K = 0, and F = (2*pi*pi-1)*sin(pi*x)*sin(pi*y)*exp(-t). // // The exact solution is: // // U = sin(pi*x) * sin(pi*y) * exp(-t) // // Modified: // // 08 January 2007 // // Author: // // John Burkardt // // Parameters: // // Input, int NODE_NUM, the number of points. // // Input, double NODE_XY[2*NODE_NUM], the coordinates of the points. // // Input, double TIME, the current time. // // Output, double INITIAL_CONDITION[NODE_NUM], the value of the // solution at the the initial time. // { int node; double *u; u = new double[node_num]; for ( node = 0; node < node_num; node++ ) { u[node] = 250.15; } return u; } //****************************************************************************80 double k_coef ( int node_num, double node_xy[], double time ) //****************************************************************************80 // // Purpose: // // K_COEF evaluates the coefficient K(X,Y,T) function. // // Discussion: // // Right now, we are assuming that NODE_NUM is always 1! // // We assume that the equation to be solved is // // dUdT - Laplacian U + K * U = F // // with K = 0, and F = (2*pi*pi-1)*sin(pi*x)*sin(pi*y)*exp(-t). // // The exact solution is: // // U = sin(pi*x) * sin(pi*y) * exp(-t) // // Modified: // // 08 January 2007 // // Author: // // John Burkardt // // Parameters: // // Input, int NODE_NUM, the number of points. // // Input, double NODE_XY[2*NODE_NUM], the coordinates of the points. // // Input, double TIME, the current time. // // Output, double K_COEF, the value of the coefficient. // { double k; //fer={80.2, 7874.0, 440.0} k = 80.2/(7874*440); return k; } //****************************************************************************80 double rhs ( int node_num, double node_xy[], double time ) //****************************************************************************80 // // Purpose: // // RHS gives the right-hand side of the differential equation. // // Discussion: // // Right now, we are assuming that NODE_NUM is always 1! // // We assume that the equation to be solved is // // dUdT - Laplacian U + K * U = F // // with // // K = 0, // // and // // F = (2*pi*pi-1)*sin(pi*x)*sin(pi*y)*exp(-t). // // The exact solution is: // // U = sin(pi*x) * sin(pi*y) * exp(-t) // // Modified: // // 08 January 2007 // // Author: // // John Burkardt // // Parameters: // // Input, int NODE_NUM, the number of points. // // Input, double NODE_XY[2*NODE_NUM], the coordinates of the points. // // Input, double TIME, the current time. // // Output, double RHS, the value of the right hand side. // { int node; double f; f = 250.15; for ( node = 0; node < node_num; node++ ) { u[node] = sin ( pi * node_xy[0+node*2] ) * sin ( pi * node_xy[1+node*2] ) * exp ( - time ); } return f; }
true
3713ffeab105d19fe986fd199920b90d97c97ac9
C++
taichuai/cpp_practice
/code/逻辑运算符.cpp
UTF-8
390
3.578125
4
[ "Apache-2.0" ]
permissive
#include<iostream> #include<cstdio> #include<string> using namespace std; int main() { //逻辑运算符 // 非 ! int a = 10; // 在c++中,除了0都为真 cout << !a << endl; // 与 &,同真为真,其余为假 int b = 0; cout << (a && b) << endl; //或 || cout << (a || b) << endl; // 提示: | & 与 | &有所区别 return 0; }
true
80a82079822a4119862f58503f580b18cdba7bf2
C++
binghe2001021/leetcode
/leetcode#71.cpp
UTF-8
1,113
2.875
3
[]
no_license
#include<cstdio> #include<iostream> #include<vector> #include<string> #include<map> #include<queue> #include<stack> #define maxn 1111 using namespace std; class Solution { public: string simplifyPath(string path) { size_t found = path.find('/'); string ans; stack<int> q; path.push_back('/'); while (found != string::npos){ if (path[found + 1] != '/'){ if (path[found + 1] == '.' && (path[found + 2] == '/' || path[found + 2] == '.' && path[found + 3] == '/')){ if (path[found + 2] == '.' && path[found + 3] == '/' && !q.empty()){ ans.resize(ans.size() - q.top()); q.pop(); } } else{ int cnt = 0; for (int i = found; path[i] != 0 && (path[i] != '/' || i == found); i++){ ans.push_back(path[i]); cnt++; } q.push(cnt); } } found = path.find('/', found + 1); } while (ans.size()>1 && ans[ans.size() - 1] == '/') ans.resize(ans.size() - 1); if (ans.size() == 0) ans.push_back('/'); return ans; } }; int main(){ Solution sol; cout << sol.simplifyPath("/..//"); }
true
9ca7e27bf69defa4aea0eca9f6dcbd70f11ddebf
C++
sahilahmed7707/Basic-C-Calculator
/next_permutation.cpp
UTF-8
486
2.8125
3
[]
no_license
#include "bits/stdc++.h" using namespace std; class Solution { public: void nextPermutation(vector<int>& nums) { vector<int> a = nums; int idx = -1; int n = a.size(); if (n == 1) { return; } int i = n - 2; while (i >= 0 and a[i] >= a[i + 1])i--; if (i >= 0) { int j = n - 1; while (a[j] <= a[i])j--; swap(a[i] , a[j]); } int l = i + 1 , r = n - 1; while (l < r)swap(a[l] , a[r]) , l++ , r--; nums = a; } }; int main() { return 0 ; }
true
8632aee90f0d6cb72f00a2fb908288bad9c578e7
C++
d01000100/tank_game
/ProtocolManager/ProtocolManager.cpp
UTF-8
5,961
2.609375
3
[]
no_license
#include "ProtocolManager.h" int getGameStateSize(GameStateMessage* message); int getSMessageTank_size(sMessageTank smTank); int getSMessageBullet_size(sMessageBullet smBullet); SendBuffer writeMessage(OliMessage* message) { // int int // [theLength][message_type] SendBuffer buffer; buffer.writeInt(8); buffer.writeInt(OLI); return buffer; } SendBuffer writeMessage(NameMessage* message) { // int int int string // [theLength][message_type][length][tank_name] unsigned int name_length = message->tank_name.length(); SendBuffer buffer; buffer.writeInt(12+name_length); buffer.writeInt(NAME); buffer.writeInt(name_length); buffer.writeString(message->tank_name); return buffer; } SendBuffer writeMessage(UserInputMessage* message) { // int int int int int int int // [theLength][message_type][W] [A] [S] [D] [Space] SendBuffer buffer; buffer.writeInt(7*4); buffer.writeInt(USER_INPUT); buffer.writeInt(message->W); buffer.writeInt(message->A); buffer.writeInt(message->S); buffer.writeInt(message->D); buffer.writeInt(message->Space); return buffer; } SendBuffer writeMessage(GameStateMessage* message) { // int int int Object int Object // [theLength][message_type][nTanks] [tanks] [nBullets] [bullets] SendBuffer buffer; buffer.writeInt(16+getGameStateSize(message)); buffer.writeInt(GAME_STATE); buffer.writeInt(message->tanks.size()); for (int t = 0; t < message->tanks.size(); t++) { sMessageTank* tank = message->tanks[t]; // int string int int //[name_length][name][fire_cooldown][is_alive] buffer.writeInt(tank->name.size()); buffer.writeString(tank->name); buffer.writeInt(tank->fireCooldown); buffer.writeInt(tank->isAlive); buffer.writeInt(tank->xV); buffer.writeInt(tank->yV); buffer.writeInt(tank->zV); buffer.writeInt(tank->xP); buffer.writeInt(tank->yP); buffer.writeInt(tank->zP); buffer.writeInt(tank->degrees); } buffer.writeInt(message->bullets.size()); for (int t = 0; t < message->bullets.size(); t++) { sMessageBullet* bullet = message->bullets[t]; // int string int string //[name_length][name][shooter_lenght][shooter] buffer.writeInt(bullet->name.size()); buffer.writeString(bullet->name); buffer.writeInt(bullet->shooter.size()); buffer.writeString(bullet->shooter); buffer.writeInt(bullet->xV); buffer.writeInt(bullet->yV); buffer.writeInt(bullet->zV); buffer.writeInt(bullet->xP); buffer.writeInt(bullet->yP); buffer.writeInt(bullet->zP); buffer.writeInt(bullet->lifetime); } return buffer; } Message* readMessage(RecieveBuffer buffer) { // ====== Header ======== // int //[message_type] int theLength = buffer.readInt(); MessageType message_type = (MessageType)buffer.readInt(); switch (message_type) { case OLI: { OliMessage* message = new OliMessage(); message->theLength = theLength; return message; break; } case NAME: { // int string //[length][tank_name] NameMessage* message = new NameMessage(); message->theLength = theLength; int name_length = buffer.readInt(); message->tank_name = buffer.readString(name_length); return message; break; } case USER_INPUT: { //int int int int int //[W] [A] [S] [D] [Space] UserInputMessage* message = new UserInputMessage(); message->theLength = theLength; message->W = buffer.readInt(); message->A = buffer.readInt(); message->S = buffer.readInt(); message->D = buffer.readInt(); message->Space = buffer.readInt(); return message; break; } case GAME_STATE: { // int Object int Object //[nTanks] [tanks] [nBullets] [bullets] GameStateMessage* message = new GameStateMessage(); int nTanks = buffer.readInt(); message->theLength = theLength; for (int t = 0; t < nTanks; t++) { sMessageTank* tank = new sMessageTank(); // int string int int //[name_length][name][fire_cooldown][is_alive] int name_length = buffer.readInt(); tank->name = buffer.readString(name_length); tank->fireCooldown = buffer.readInt(); tank->isAlive = buffer.readInt(); tank->xV = buffer.readInt(); tank->yV = buffer.readInt(); tank->zV = buffer.readInt(); tank->xP = buffer.readInt(); tank->yP = buffer.readInt(); tank->zP = buffer.readInt(); tank->degrees = buffer.readInt(); message->tanks.push_back(tank); } int nBullets = buffer.readInt(); for (int t = 0; t < nBullets; t++) { sMessageBullet* Bullet = new sMessageBullet(); // int string int string //[name_length][name][shooter_length][shooter] int name_length = buffer.readInt(); Bullet->name = buffer.readString(name_length); int shooter_length = buffer.readInt(); Bullet->shooter = buffer.readString(shooter_length); Bullet->xV = buffer.readInt(); Bullet->yV = buffer.readInt(); Bullet->zV = buffer.readInt(); Bullet->xP = buffer.readInt(); Bullet->yP = buffer.readInt(); Bullet->zP = buffer.readInt(); Bullet->lifetime = buffer.readInt(); message->bullets.push_back(Bullet); } return message; break; } default: Message *m = new Message(); m->type = UNOWN; return m; break; } } int getGameStateSize(GameStateMessage* message) { int theSize = 0; for (int index = 0; index < message->tanks.size(); index++) { sMessageTank* smT = message->tanks[index]; theSize += getSMessageTank_size(*smT); } for (int index = 0; index < message->bullets.size(); index++) { sMessageBullet* smB = message->bullets[index]; theSize += getSMessageBullet_size(*smB); } return theSize; } int getSMessageTank_size(sMessageTank smTank) { int theSize = 4*9; theSize += smTank.name.size(); return theSize; } int getSMessageBullet_size(sMessageBullet smBullet) { int theSize = 4*6; theSize += smBullet.name.size(); theSize += smBullet.shooter.size(); return theSize; }
true
f03c5a7d1d507671f4a6a00093e667603e0ed64e
C++
arjunbhatt670/CodeForces
/1118C - Palindromic Matrix.cpp
UTF-8
2,300
2.90625
3
[]
no_license
/* * User: Isanchez_Aguilar * Problem: CodeForces 1118C - Palindromic Matrix */ #include <bits/stdc++.h> using namespace std; using Long = long long; int main(void) { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; map<int, int> freq; for (int i = 0; i < n * n; ++i) { int val; cin >> val; ++freq[val]; } set< pair<int, int>, greater< pair<int, int> > > vals; for (map<int, int>::iterator i = begin(freq); i != end(freq); ++i) vals.insert(make_pair(i->second, i->first)); bool isPossible = true; vector< vector<int> > ans(n, vector<int>(n)); int middle = n / 2; for (int i = 0; i < middle and isPossible; ++i) { for (int j = 0; j < middle; ++j) { set< pair<int, int> >::iterator k = begin(vals); if (k->first < 4) { isPossible = false; break; } ans[i][j] = k->second; ans[i][n - j - 1] = k->second; ans[n - i - 1][j] = k->second; ans[n - i - 1][n - j - 1] = k->second; pair<int, int> aux(*k); vals.erase(k); if (aux.first - 4 > 0) { aux.first -= 4; vals.insert(aux); } } } if (isPossible and n % 2 != 0) { for (int i = 0; i < middle; ++i) { set< pair<int, int> >::iterator k = begin(vals); if (k->first < 2) { isPossible = false; break; } ans[i][middle] = k->second; ans[n - i - 1][middle] = k->second; pair<int, int> aux(*k); vals.erase(k); if (aux.first - 2 > 0) { aux.first -= 2; vals.insert(aux); } } if (isPossible) { for (int i = 0; i < middle; ++i) { set< pair<int, int> >::iterator k = begin(vals); if (k ->first < 2) { isPossible = false; break; } ans[middle][i] = k->second; ans[middle][n - i - 1] = k->second; pair<int, int> aux(*k); vals.erase(k); if (aux.first - 2 > 0) { aux.first -= 2; vals.insert(aux); } } ans[middle][middle] = begin(vals)->second; } } if (isPossible) { cout << "YES\n"; for (const vector<int>& r : ans) { cout << r[0]; for (int i = 1; i < n; ++i) cout << " " << r[i]; cout << "\n"; } } else cout << "NO\n"; return 0; }
true
1ce52e1bc1a3cc34bd884ee35bc1ad3bcd4193f2
C++
itomomoti/Basics
/test/StepCode_Test.cpp
UTF-8
7,648
2.8125
3
[]
no_license
#include "StepCode.hpp" #include <gtest/gtest.h> #include <stdint.h> namespace itmmti { class StepCode_Test : public ::testing::Test { }; TEST_F(StepCode_Test, Constructor) { const size_t num = 32; // { // Compare with different SizeT // StepCode<16, uint64_t> code1; // code1.printStatistics(); // StepCode<16, uint32_t> code2; // code2.printStatistics(); // StepCode<16, uint16_t> code3; // code3.printStatistics(); // } using SC = StepCode<num, uint16_t>; SC code1(64); for (uint64_t j = 0; j < num; ++j) { const auto val = UINT64_C(1) << (j % 64); const auto newBvSize = code1.bitSize() + StepCodeUtil::calcSteppedW(val); if (newBvSize > code1.bitCapacity()) { code1.changeBitCapacity(static_cast<size_t>(newBvSize * 1.25)); } code1.append(val); } // code1.printStatistics(true); { SC code2(code1); ASSERT_EQ(code1.size(), code2.size()); ASSERT_EQ(code1.bitSize(), code2.bitSize()); for (uint64_t j = 0; j < num; ++j) { ASSERT_EQ(code1.read(j), code2.read(j)); } } { SC code2(num/2); code2 = code1; ASSERT_EQ(code1.size(), code2.size()); ASSERT_EQ(code1.bitSize(), code2.bitSize()); for (uint64_t j = 0; j < num; ++j) { ASSERT_EQ(code1.read(j), code2.read(j)); } } { SC code_copy(code1); SC code2(std::move(code_copy)); ASSERT_EQ(0, code_copy.size()); ASSERT_EQ(0, code_copy.bitCapacity()); ASSERT_EQ(code1.size(), code2.size()); ASSERT_EQ(code1.bitSize(), code2.bitSize()); for (uint64_t j = 0; j < num; ++j) { ASSERT_EQ(code1.read(j), code2.read(j)); } } { SC code_copy(code1); SC code2(num/2); code2 = std::move(code_copy); ASSERT_EQ(0, code_copy.size()); ASSERT_EQ(0, code_copy.bitCapacity()); ASSERT_EQ(code1.size(), code2.size()); ASSERT_EQ(code1.bitSize(), code2.bitSize()); for (uint64_t j = 0; j < num; ++j) { ASSERT_EQ(code1.read(j), code2.read(j)); } } } TEST_F(StepCode_Test, AppendRead) { const size_t num = 128; using SC = StepCode<num, uint16_t>; SC code(64); for (uint64_t j = 0; j < num; ++j) { const auto val = UINT64_C(1) << (j % 64); const auto newBvSize = code.bitSize() + StepCodeUtil::calcSteppedW(val); if (newBvSize > code.bitCapacity()) { code.changeBitCapacity(static_cast<size_t>(newBvSize * 1.25)); } code.append(val); } // code.printStatistics(true); uint64_t pos = 0; for (uint64_t j = 0; j < num; ++j) { const auto w = code.readW(j); ASSERT_EQ(UINT64_C(1) << (j % 64), code.readWBits(pos, w)); pos += w; } // code.changeBitCapacity(); // code.printStatistics(true); } TEST_F(StepCode_Test, ChangeWCodes) { const size_t num = 32; using SC = StepCode<num, uint16_t>; SC code(64); for (uint64_t j = 0; j < num - 16; ++j) { const auto val = UINT64_C(1) << (j % 64); const auto newBvSize = code.bitSize() + StepCodeUtil::calcSteppedW(val); if (newBvSize > code.bitCapacity()) { code.changeBitCapacity(static_cast<size_t>(newBvSize * 1.25)); } code.append(val); } code.printStatistics(true); uint64_t wCodeSrc = 0; for (uint8_t j = 0; j < 16; ++j) { StepCodeUtil::writeWCode(j, &wCodeSrc, j); } { SC cc(code); const uint64_t srcIdxBeg = 0; const uint64_t srcIdxLen = 5; const uint64_t tgtIdxBeg = 0; const uint64_t tgtIdxLen = 0; const uint64_t bitPos = cc.calcBitPos(tgtIdxBeg); const auto insBitLen = StepCodeUtil::sumW(&wCodeSrc, srcIdxBeg, srcIdxBeg + srcIdxLen); const auto delBitLen = StepCodeUtil::sumW(cc.getConstPtr_wCodes(), tgtIdxBeg, tgtIdxBeg + tgtIdxLen); const auto newBvSize = cc.bitSize() + insBitLen - delBitLen; if (insBitLen > delBitLen && newBvSize > cc.bitCapacity()) { cc.changeBitCapacity(newBvSize); } std::cout << "srcIdxBeg = " << srcIdxBeg << ", srcIdxLen = " << srcIdxLen << ", tgtIdxBeg = " << tgtIdxBeg << ", tgtIdxLen = " << tgtIdxLen << ", bitPos = " << bitPos << ", insBitLen = " << insBitLen << ", delBitLen = " << delBitLen << std::endl; cc.changeWCodesAndValPos(&wCodeSrc, srcIdxBeg, srcIdxLen, tgtIdxBeg, tgtIdxLen, bitPos, insBitLen, delBitLen); cc.printStatistics(true); } { SC cc(code); const uint64_t srcIdxBeg = 0; const uint64_t srcIdxLen = 16; const uint64_t tgtIdxBeg = 0; const uint64_t tgtIdxLen = 3; const uint64_t bitPos = cc.calcBitPos(tgtIdxBeg); const auto insBitLen = StepCodeUtil::sumW(&wCodeSrc, srcIdxBeg, srcIdxBeg + srcIdxLen); const auto delBitLen = StepCodeUtil::sumW(cc.getConstPtr_wCodes(), tgtIdxBeg, tgtIdxBeg + tgtIdxLen); const auto newBvSize = cc.bitSize() + insBitLen - delBitLen; if (insBitLen > delBitLen && newBvSize > cc.bitCapacity()) { cc.changeBitCapacity(newBvSize); } std::cout << "srcIdxBeg = " << srcIdxBeg << ", srcIdxLen = " << srcIdxLen << ", tgtIdxBeg = " << tgtIdxBeg << ", tgtIdxLen = " << tgtIdxLen << ", bitPos = " << bitPos << ", insBitLen = " << insBitLen << ", delBitLen = " << delBitLen << std::endl; cc.changeWCodesAndValPos(&wCodeSrc, srcIdxBeg, srcIdxLen, tgtIdxBeg, tgtIdxLen, bitPos, insBitLen, delBitLen); cc.printStatistics(true); } { SC cc(code); const uint64_t srcIdxBeg = 0; const uint64_t srcIdxLen = 8; const uint64_t tgtIdxBeg = 8; const uint64_t tgtIdxLen = 1; const uint64_t bitPos = cc.calcBitPos(tgtIdxBeg); const auto insBitLen = StepCodeUtil::sumW(&wCodeSrc, srcIdxBeg, srcIdxBeg + srcIdxLen); const auto delBitLen = StepCodeUtil::sumW(cc.getConstPtr_wCodes(), tgtIdxBeg, tgtIdxBeg + tgtIdxLen); const auto newBvSize = cc.bitSize() + insBitLen - delBitLen; if (insBitLen > delBitLen && newBvSize > cc.bitCapacity()) { cc.changeBitCapacity(newBvSize); } std::cout << "srcIdxBeg = " << srcIdxBeg << ", srcIdxLen = " << srcIdxLen << ", tgtIdxBeg = " << tgtIdxBeg << ", tgtIdxLen = " << tgtIdxLen << ", bitPos = " << bitPos << ", insBitLen = " << insBitLen << ", delBitLen = " << delBitLen << std::endl; cc.changeWCodesAndValPos(&wCodeSrc, srcIdxBeg, srcIdxLen, tgtIdxBeg, tgtIdxLen, bitPos, insBitLen, delBitLen); cc.printStatistics(true); } { // delete SC cc(code); const uint64_t srcIdxBeg = 0; const uint64_t srcIdxLen = 0; const uint64_t tgtIdxBeg = 7; const uint64_t tgtIdxLen = 4; const uint64_t bitPos = cc.calcBitPos(tgtIdxBeg); const auto insBitLen = StepCodeUtil::sumW(&wCodeSrc, srcIdxBeg, srcIdxBeg + srcIdxLen); const auto delBitLen = StepCodeUtil::sumW(cc.getConstPtr_wCodes(), tgtIdxBeg, tgtIdxBeg + tgtIdxLen); const auto newBvSize = cc.bitSize() + insBitLen - delBitLen; if (insBitLen > delBitLen && newBvSize > cc.bitCapacity()) { cc.changeBitCapacity(newBvSize); } std::cout << "srcIdxBeg = " << srcIdxBeg << ", srcIdxLen = " << srcIdxLen << ", tgtIdxBeg = " << tgtIdxBeg << ", tgtIdxLen = " << tgtIdxLen << ", bitPos = " << bitPos << ", insBitLen = " << insBitLen << ", delBitLen = " << delBitLen << std::endl; cc.changeWCodesAndValPos(&wCodeSrc, srcIdxBeg, srcIdxLen, tgtIdxBeg, tgtIdxLen, bitPos, insBitLen, delBitLen); cc.printStatistics(true); } } } // namespace
true
2224fd3c79547d9c97b8e2496c0cfabdbdb9ad31
C++
masiko/humanoid
/12pwmTest/12pwm.cpp
UTF-8
1,065
2.5625
3
[]
no_license
#include "mbed.h" #include "ServoControl.h" /* class Softpwm{ public: Softpwm(PinName pin) : _pin(pin) { _pin = 0; } void setf(){ _pin = 1; wait_us(1500); _pin = 0; } private: DigitalOut _pin; }; class Servo{ public: Servo(PinName pin) : _softpwm(pin) { ser.attach(&_softpwm, &Softpwm::setf, 0.2); } private: Ticker ser; Softpwm _softpwm; }; class ServoC{ public: ServoC(PinName pin): _pin(pin) { ser.attach(this, &ServoC::setf, 0.02); } void setf(){ _pin = 1; wait_us(1500); _pin = 0; } private: Ticker ser; DigitalOut _pin; }; */ int main(){ ServoControl s5(p5); ServoControl s7(p7); ServoControl s9(p9); ServoControl s11(p11); ServoControl s13(p13); ServoControl s15(p15); ServoControl s17(p17); ServoControl s19(p19); ServoControl s21(p21); ServoControl s23(p23); ServoControl s25(p25); ServoControl s27(p27); /* s5.setPulseWidth(21); s5.setPos(1200); s9.setPulseWidth(21); s9.setPos(1200); */ while(1){ wait(1); } return 0; }
true
d2da1f380c2389a2fb9251e5d1ce4d923367ad05
C++
moguchev/KKM
/src/Исходники DLL модели ФН/FP/uart.cpp
UTF-8
1,131
2.828125
3
[]
no_license
// Leonid Moguchev (c) 2020 #include "pch.h" #include "uart.h" Uart::Uart() { reset(); } void Uart::reset() { rxCompleted = false; rxData = 0x0; rxState = 0; txCompleted = true; txData = 0x0; txState = 0; } void Uart::txDat(uint8_t data) { txData = data; txState = 1; } bool Uart::txBit() { if (!txCompleted) { // передача данных if (txState == 0) { // start bit txState++; return false; // start bit = 0 } if (txState <= 8) { // data bit // получение нужного бита байта return 0 != (txData & (1 << (txState++ - 1))); } else { // stop bit txCompleted = true; txState = 0; return true; } } else { // высокий уровень сигнала (передачи нет) return true; } } void Uart::rxBit(bool bit) { if (rxState > 0) { // мы читаем if (rxState <= 8) { rxData |= (bit << (rxState - 1)); rxState++; } else { // закончили чтение rxState = 0; rxCompleted = true; } } else { if (!bit) { // получили старт бит rxState = 1; // режим чтения rxData = 0x0; } } }
true
1bdb7197ec4738a878255c223b106593befbbfa4
C++
rbock/hana
/include/boost/hana/ext/std/integer_sequence.hpp
UTF-8
2,272
2.71875
3
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
/*! @file Adapts `std::integer_sequence`. @copyright Louis Dionne 2014 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_EXT_STD_INTEGER_SEQUENCE_HPP #define BOOST_HANA_EXT_STD_INTEGER_SEQUENCE_HPP #include <boost/hana/bool.hpp> #include <boost/hana/comparable/equal_mcd.hpp> #include <boost/hana/core/datatype.hpp> #include <boost/hana/ext/std/integral_constant.hpp> #include <boost/hana/iterable/mcd.hpp> #include <type_traits> #include <utility> namespace boost { namespace hana { struct StdIntegerSequence; template <typename T, T ...v> struct datatype<std::integer_sequence<T, v...>> { using type = StdIntegerSequence; }; template <> struct Iterable::instance<StdIntegerSequence> : Iterable::mcd { template <typename T, T x, T ...xs> static constexpr auto head_impl(std::integer_sequence<T, x, xs...>) { return std::integral_constant<T, x>{}; } template <typename T, T x, T ...xs> static constexpr auto tail_impl(std::integer_sequence<T, x, xs...>) { return std::integer_sequence<T, xs...>{}; } template <typename T, T ...xs> static constexpr auto is_empty_impl(std::integer_sequence<T, xs...>) { return bool_<sizeof...(xs) == 0>; } }; template <> struct Comparable::instance<StdIntegerSequence, StdIntegerSequence> : Comparable::equal_mcd { template <typename X, X ...xs, typename Y, Y ...ys> static constexpr auto equal_impl( std::integer_sequence<X, xs...>, std::integer_sequence<Y, ys...>, // this dummy parameter disables this specialization if // sizeof...(xs) != sizeof...(ys) char(*)[sizeof...(xs) == sizeof...(ys)] = 0) { return bool_<std::is_same< std::integer_sequence<bool, (xs == ys)...>, std::integer_sequence<bool, (xs, true)...> >::value>; } template <typename Xs, typename Ys> static constexpr auto equal_impl(Xs, Ys, ...) { return false_; } }; }} // end namespace boost::hana #endif // !BOOST_HANA_EXT_STD_INTEGER_SEQUENCE_HPP
true
47bb23fc9a94c74bcc195557536fa4ee70f83c76
C++
ChoiWooHyuk2/Dicon
/Entity.cpp
UTF-8
1,353
2.78125
3
[]
no_license
#include "DXUT.h" #include "Entity.h" Entity::Entity() :pos(0, 0), scale(1, 1), scaleCenter(0, 0), rotation(0), rotationCenter(0, 0), rect(0, 0, 0, 0), visibleRect(0, 0, 0, 0), visible(true), updateEnabled(true), renderChildrenEnabled(true), parent(nullptr), removing(false), deleting(false), tag("") { } Entity::~Entity() { for (auto child : children) SAFE_DELETE(child); } void Entity::addChild(Entity* child) { children.push_back(child); child->parent = this; } void Entity::removeChild(Entity* child) { child->removing = true; } void Entity::update(float dt) { if(!updateEnabled) return; children.erase(remove_if(children.begin(), children.end(), [&](auto iter) { bool removing = iter->removing; if (removing){ SAFE_DELETE(iter); } return removing; }), children.end()); for (auto child : children) { child->update(dt); } } void Entity::render() { if(!visible) return; D3DXMatrixTransformation2D(&matrix, &scaleCenter, 0, &scale, &rotationCenter, rotation, &pos); if (parent) { matrix *= parent->matrix; } if(!renderChildrenEnabled) return; for (auto child : children) { child->render(); } } Vec2 Entity::center() { return pos + rect.center(); } Rect Entity::rectWithPos() { return rect.offset(pos); } void Entity::setCenter(Vec2 pos) { this->pos = pos - rect.center(); }
true
ec98f1a8045fd5824211c52069e8b3cc13e7a38f
C++
MariusHerget/LMU-SS18-cpppc
/Assignments/06/solution/list_base.h
UTF-8
4,948
3.296875
3
[]
no_license
#include <iterator> namespace cpppc { template <typename ValueT, ValueT default_value = ValueT()> class list { typedef list<ValueT, default_value> self_t; typedef typename std::size_t size_type; public: struct list_node { list_node *next; ValueT value; }; using list_node_t = list_node; template <class Derived> class ForwardIteratorBase { private: using derived_t = Derived; using self_t = ForwardIteratorBase<Derived>; derived_t &derived() { return static_cast<derived_t &>(*this); } constexpr const derived_t &derived() const { return static_cast<const derived_t &>(*this); } public: using iterator_category = std::forward_iterator_tag; using value_type = ValueT; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; protected: // evtl protected ForwardIteratorBase() = default; public: self_t &operator+(int index) { auto it = self_t(*this); for (int i = 0; i <= index; it++) { if (index == i) break; i++; } return *this; } self_t &operator++() { derived().increment(1); return *this; } self_t operator++(int) { auto old = *this; derived().increment(1); return old; } const ValueT &operator*() const { return derived().dereference(); } ValueT &operator*() { return derived().dereference(); } bool operator!=(const self_t rhs) const { return !(*this == rhs); } bool operator==(const self_t &rhs) const { return (this == &rhs); } }; // template <class T> class ListIterator : public ForwardIteratorBase<ListIterator> { using list_t = typename list::self_t; using list_node_t = list::list_node_t; using self_t = ListIterator; using base_t = ForwardIteratorBase<ListIterator>; using value_type = ValueT; public: ListIterator() = delete; ListIterator(list_node_t *node) : _node(node) // , ForwardIteratorBase(0) {} ~ListIterator() = default; // Copy ListIterator(self_t &rhs) = default; // // Move ListIterator(self_t &&rhs) = default; // Assignment self_t &operator=(const self_t &rhs) = default; // Move-Assignment self_t &operator=(self_t &&rhs) = default; value_type &dereference() { return _node->value; } void increment(int offset) { for (int i = 0; i < offset; i++) _node = _node->next; } bool operator==(const self_t &rhs) const { return (base_t::operator==(rhs) || (_node == rhs._node)); } // void decrement(int offset) { increment(-offset); } private: list_node_t *_node = nullptr; }; public: typedef ValueT value_type; typedef ListIterator iterator; typedef const ListIterator const_iterator; typedef value_type &reference; typedef const value_type &const_reference; list() { // printf("\n!!!DEBUG called default constructor\n"); } // copy list(const self_t &other) = default; // assignment self_t &operator=(const self_t &other) { // printf("\n!!!DEBUG called assign operator\n"); if (this != &other) { // Free the existing resource. while (!empty()) { pop_front(); } // Copy all nodes // _head = nullptr; int size = other.size(); for (int i = size; i > 0; i--) { push_front(other[i - 1]); } } return *this; }; self_t &operator=(self_t &&other) { // printf("\n!!!DEBUG called Move-Assignment operator %lu\n",other._size); if (this != &other) { // Clean up own list while (!empty()) { pop_front(); } // Steal others data _head = other._head; _size = other._size; // Prepare Other for destructor other._head = nullptr; other._size = 0; } return *this; }; // destructor ~list() = default; // MOVE list(self_t &&other) : _head(other._head), _size(other._size) { // printf("\n!!!DEBUG called Move constructor %lu\n\n", other._size); other._head = NULL; other._size = 0; } public: iterator begin() { return iterator{_head}; } iterator end() { return iterator{nullptr}; } const_iterator begin() const { return iterator{_head}; } const_iterator end() const { return iterator{nullptr}; } size_type size() const { return _size; } bool empty() const { return (size() == 0); } bool operator==(self_t &rhs); ValueT &operator[](const int index); const ValueT &operator[](const int index) const; // Since I do not know how to implement push_back I will implemented // push_front. void push_front(ValueT value); ValueT pop_front(); const ValueT &front() const { return _head->value; } // Like std::list<T>::insert void insert(iterator &position, ValueT value); private: list_node_t *_head = NULL; // = &_tail; size_t _size = 0; }; // END CLASS list #include "list_impl_base.h" } // namespace cpppc
true
0c0780274c5029315bb6b56167cd883b5afb924a
C++
UZerbinati/Suite
/LA/iteractive.cpp
UTF-8
2,997
2.859375
3
[]
no_license
#include "../suite.hpp" #include "iteractive.hpp" #include <iostream> #include <string> #include <algorithm> #include <omp.h> int ResidualStop(spmat &A,vec b,vec x,double eps){ vec r(b.getLen()); r = b-A*x; if (r.norm(2) < eps){ return 1; }else{ return 0; } } vec Jacobi(spmat &A,vec b,vec guess,int JacobiIT,double eps){ /* |JACOBI METHOD| * x_{k+1} = D^{-1}[b-(L+U)x_{k}] * where D=diag(A), L is the lower triangular part of A * and U is the upper triangular of A. */ vec x0(guess.getLen()); x0 = guess; assert(A.getWidth() == A.getHeight() && "Matrix must be square, for the Jacobi Method."); int k = 0; double S = 0; vec x(b.getLen()); while(k < JacobiIT){ for(int i=1; i < A.getWidth()+1;i++){ S = 0; for(int j=1; j < A.getHeight()+1;j++){ if (j != i){ //Element-wise y_k =(L+U)x_k S = S + A.getData(i,j)*x0.getData(j-1); } } //Update the solution iteration //Element-wise x_{k+1} = D^{-1}(b-y_k); x.setData((1/A.getData(i,i))*(b.getData(i-1)-S),i-1); } k = k+1; x0 = x; if( ResidualStop(A,b,x,eps) == 1){ break; } } return x; } vec GauBSeidel(spmat &A,vec b,vec guess,int itmax,double eps){ /* |GAUSS-SIEDEL METHOD| * L^{*}x_{k+1} = Ux_{k}] * where D=diag(A), L is the lower triangular part of A, * U is the upper triangular of A, and L^{*} = D+L; */ assert(A.getWidth() == A.getHeight() && "Matrix must be square, for the Jacobi Method."); vec x(guess.getLen()); int k = 0; double S = 0; x = guess; while(k < itmax){ for (int i=1;i < A.getWidth()+1; i++){ S=0; for (int j=1; j < A.getHeight()+1; j++){ if(j!=i){ //Element-wise yk = U * x_k S = S + A.getData(i,j)*x.getData(j-1); } } //Element-wise x_k = L^{-1} y_k x.setData((b.getData(i-1)-S)/A.getData(i,i),i-1); } k++; if( ResidualStop(A,b,x,eps) == 1){ break; } } return x; } vec SOR(spmat &A,vec b,vec guess,double omega,int itmax,double eps){ assert(omega <= 2 && "Relaxation parameters must be smaller then 2."); assert(0<= omega && "Relaxation parameters must be greater then 1."); vec x(guess.getLen()); int k = 0; double S = 0; x = guess; while(k < itmax){ for (int i=1;i < A.getWidth()+1; i++){ S=0; for (int j=1; j < A.getHeight()+1; j++){ if(j!=i){ S = S + A.getData(i,j)*x.getData(j-1); } } //Element-wise convex combination of Gauss-Siedel iteraction x.setData((1-omega)*x.getData(i-1)+(b.getData(i-1)-S)*(omega/A.getData(i,i)),i-1); } k++; if( ResidualStop(A,b,x,eps) == 1){ break; } } return x; } vec ConjugateGradient(spmat &A,vec b,vec x0,int itmax,double eps){ vec x(x0.getLen()); vec r(x0.getLen()); vec p(x0.getLen()); vec q(x0.getLen()); double alpha; double beta; double rold; r = b - A*x0; p = r; x = x0; for (int k=0; k < itmax; k++){ q = A*p; alpha = (r*r)/(p*q); x = x + p*alpha; rold = r*r; r = r - q*alpha; if( ResidualStop(A,b,x,eps) == 1){ break; } beta = (r*r)/rold; p = r + p*beta; } return x; }
true
945d086877eb128cccc0988288f82e73a0e67ea7
C++
ellynhan/challenge100-codingtest-study
/hall_of_fame/gusah009/[PGS]_weekly6.cpp
UTF-8
1,336
2.71875
3
[]
no_license
#include <string> #include <vector> #include <algorithm> #define FOR(i, j) for(int i = 0; i < j; i++) using namespace std; int matches[1001] = {0}; int win[1001] = {0}; int heavyWin[1001] = {0}; vector<int> solution(vector<int> weights, vector<string> head2head) { vector<int> answer; FOR(i, head2head.size()) { FOR(j, head2head[i].size()) { if (head2head[i][j] == 'W') { win[i]++; matches[i]++; if (weights[i] < weights[j]) { heavyWin[i]++; } } else if (head2head[i][j] == 'L') { matches[i]++; } } } // 승률, 무거운복서 횟수, 자기 몸무게, 내 번호 vector<pair<pair<pair<double, int>, int>, int> > players; FOR(i, weights.size()) { pair<pair<pair<double, int>, int>, int> player; if (matches[i] == 0) player.first.first.first = 0; else player.first.first.first = -(double)win[i] / matches[i]; player.first.first.second = -heavyWin[i]; player.first.second = -weights[i]; player.second = i + 1; players.push_back(player); } sort(players.begin(), players.end()); FOR(i, players.size()) { answer.push_back(players[i].second); } return answer; }
true
52486fae48a9d364d94d4f026149e91d81eb99ed
C++
suyashagno3/Beginner_Codeforces_Problems
/Solutions(cpp)/ColorfulField(79)working.cpp
UTF-8
818
2.578125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int n, m, k, t, a, b, i, j, t0; cin >> n >> m >> k >> t; int w[k]; for (int in = 0; in < k; in++) { cin >> a >> b; w[in] = ((a - 1) * m) + b - 1; } sort(w, w + k); for (int in = 0; in < t; in++) { int f = 0; int count = 0; cin >> i >> j; t0 = ((i - 1) * m) + j - 1; for (int z = 0; z < k; z++) { if (w[z] == t0) { cout << "Waste" << endl; f = 1; break; } else { if (t0 > w[z]) count++; } } if ((t0 - count) % 3 == 0 && f == 0) cout << "Carrots" << endl; else if ((t0 - count) % 3 == 1 && f == 0) cout << "Kiwis" << endl; else if (f == 0) cout << "Grapes" << endl; } }
true
c888342ec8e29d5ddd3a65fe4b3967504be1f6e5
C++
George8327/rail-canyon
/src/util/config.cc
UTF-8
2,989
3.1875
3
[ "Zlib" ]
permissive
#include "common.hh" struct ConfigEntry { std::string key; std::string value; }; static bool isConfigLoaded = false; static std::vector<ConfigEntry> config; static void config_load() { if (!isConfigLoaded) { isConfigLoaded = true; FILE* f = fopen("config.ini", "r"); if (!f) return; fseek(f, 0, SEEK_END); auto len = ftell(f); fseek(f, 0, SEEK_SET); char* buffer = new char[len + 1]; fread(buffer, len, 1, f); fclose(f); buffer[len] = '\0'; char* p = buffer; while (*p) { char* lineBegin = p; char* colonPoint = 0; while (*p && *p != '\n') { if (!colonPoint && (*p == ':' || *p == '=')) colonPoint = p; p++; } char* lineEnd = p; if (*p == '\n') p++; if (!colonPoint) continue; config.emplace_back(); auto& entry = config.back(); // read key while (*lineBegin == ' ' || *lineBegin == '\t') lineBegin++; char* keyEnd = colonPoint - 1; while (*keyEnd == ' ' || *keyEnd == '\t') keyEnd--; keyEnd++; // put key if (keyEnd - lineBegin <= 0) { entry.key = ""; } else { entry.key = std::string(lineBegin, keyEnd - lineBegin); } // read value colonPoint++; while (*colonPoint == ' ' || *colonPoint == '\t') colonPoint++; lineEnd--; while (*lineEnd == ' ' || *lineEnd == '\t') lineEnd--; lineEnd++; // put value if (lineEnd - colonPoint <= 0) { entry.value = ""; } else { entry.value = std::string(colonPoint, lineEnd - colonPoint); } log_info("READ '%s': '%s'", entry.key.c_str(), entry.value.c_str()); } delete[] buffer; } } static void config_save() { FILE* f = fopen("config.ini", "w"); if (!f) { log_error("Could not write config.ini"); return; } for (auto& entry : config) { fprintf(f, "%s : %s\n", entry.key.c_str(), entry.value.c_str()); } fclose(f); log_info("Wrote config.ini"); } const char* config_get(const char* key, const char* def) { config_load(); std::string s_key(key); for (auto& entry : config) { if (entry.key == s_key) return entry.value.c_str(); } return def; } int config_geti(const char* key, int def) { const char* result = config_get(key, 0); if (result) { int x; sscanf(result, "%d", &x); return x; } return def; } float config_getf(const char* key, float def) { const char* result = config_get(key, 0); if (result) { float x; sscanf(result, "%f", &x); return x; } return def; } void config_set(const char* key, const char* value) { config_load(); std::string s_key(key); for (auto& entry : config) { if (entry.key == s_key) { entry.value = value; config_save(); return; } } config.emplace_back(); auto& entry = config.back(); entry.key = key; entry.value = value; config_save(); } void config_seti(const char* key, int value) { char buffer[64]; snprintf(buffer, 64, "%d", value); config_set(key, buffer); } void config_setf(const char* key, float value) { char buffer[64]; snprintf(buffer, 64, "%g", value); config_set(key, buffer); }
true
75618a462beb4ad135859c77425ff68ba91b21ba
C++
renbou/personal-cpp-lib
/utility.hpp
UTF-8
1,085
3.578125
4
[ "GPL-3.0-only" ]
permissive
// Artem Mikheev 2019 // GNU GPLv3 License #ifndef UTILITY_HPP #define UTILITY_HPP // Various utility classes for use in code and other structures // Template structure for creating linked-list based structures template<typename T> struct listNode { T * elem; listNode * next = nullptr; listNode(T t_val): elem(new T(t_val)) {} listNode (const listNode & other) { elem = other.elem; next = other.next; } listNode& operator=(const listNode & other) { elem = other.elem; next = other.next; } }; // Simple helper classes for pairs and triples of various element types template<typename T1, typename T2> class Pair { public: T1 first; T2 second; Pair() : first(T1()), second(T2()) {} Pair(T1 t_first, T2 t_second) : first (t_first), second(t_second) {} }; template<typename T1, typename T2, typename T3> class Triple { public: T1 first; T2 second; T3 third; Triple() : first(T1()), second(T2()), third(T3()) {} Triple(T1 t_first, T2 t_second, T3 t_third) : first (t_first), second(t_second), third(t_third) {} }; #endif //UTILITY_HPP
true
2f6dfa77b9e1e2bdb73e82c867a09324e81216cb
C++
Andydiaz12/Estructura-de-Datos-con-Muratalla
/Ejercicios de parciales/2 parcial/CH02_3_230216_24500468.cpp
ISO-8859-1
1,052
3.625
4
[]
no_license
/* Jos Andrs Daz Escobar 23 de Febrero del 2016 Ingrese N nmeros, cree un programa que identifique los nmeros pares e impares ya ingresados. FUNCIN 1: funcin sin parmetros que solicite el nmero a analizar y lo regrese al main. FUNCIN 3: funcin que le pasarn como parmetro el nmero e imprimir si se trata de un nmero par o impar. No regresa nada.*/ #include <stdio.h> #include <cstdlib> int numero(){ int numero; printf("Ingrese el numero a evaluar:\t"); scanf("%d", &numero); return numero; } void operacion(int b){ int a; if(b%2 == 0) printf("El numero es par\n"); else printf("El numero es impar\n"); } char OPCION (){ char OP; printf("\n\t\nSi desea evaluar otro numero\nHacer click en la letra 'R'\nSi desea salir hacer click en alguna otra letra\n\t"); getchar(); scanf("%c", &OP); return OP; } int main(){ char op; int num, opcion; do{ num=numero(); operacion(num); op = OPCION(); system("CLS"); }while(op == 'r' || op == 'R'); system("PAUSE"); return 0; }
true
e0294d7ff0be2b44f4b02a987ddf73686b369dd5
C++
mattmcmenamin/Lab8
/BinaryTree.h
UTF-8
5,993
3.328125
3
[]
no_license
#pragma once #ifndef _BIN_TREE_H #define _BIN_TREE_H #include "RandomUtilities.h" #include<iostream> #include<string> #include<vector> #include<queue> //***Binary Tree class ***// class BinaryTree { protected: class BinaryNode { public: short entry_; BinaryNode * left_; BinaryNode *right_; BinaryNode(short entry = 0, BinaryNode * left = NULL, BinaryNode * right = NULL ) : entry_(entry), left_(left), right_(right) {} BinaryNode() {} private: BinaryNode(const BinaryNode&); const BinaryNode & operator=(const BinaryNode&); }; public: BinaryTree(); ~BinaryTree(); void build(long size); void display(std::ostream& outfile) const; long size() const; long height() const; long leaves() const; short leftmost() const; std::vector<short> preorder() const; std::vector<short> postorder() const; private: BinaryNode * tree_; static int btEntry_; BinaryTree& operator=(BinaryTree&); BinaryTree(const BinaryTree &); static void destroy(BinaryNode* &subtree); static void buildRandom(long size, BinaryNode* & subtree); static void displayLeft(std::ostream &outfile, BinaryNode *subtree, std::string prefix); static void displayRight(std::ostream &outfile, BinaryNode *subtree, std::string prefix); static long size(const BinaryNode*subtree); static long height(const BinaryNode*subtree); static long leaves(const BinaryNode*subtree); static short leftmost(const BinaryNode*subtree); static void preorder(std::vector<short> & traversal, const BinaryNode*subtree); static void postorder(std::vector<short> & traversal, const BinaryNode*subtree); }; int BinaryTree::btEntry_ = 1; BinaryTree::BinaryTree() : tree_(NULL) {} BinaryTree::~BinaryTree() { destroy(tree_); } void BinaryTree::build(long size) { destroy(tree_); buildRandom(size, tree_); } inline void BinaryTree::display(std::ostream & outfile) const { std::string prefix; if (tree_ == NULL) { outfile << "-" << std::endl; } else { displayLeft(outfile, tree_->left_, " "); outfile << "---" << tree_->entry_ << std::endl; displayRight(outfile, tree_->right_, " "); } } long BinaryTree::size() const { return size(tree_); } long BinaryTree::height() const { return height(tree_); } long BinaryTree::leaves() const { return leaves(tree_); } short BinaryTree::leftmost() const { return leftmost(tree_); } std::vector<short> BinaryTree::preorder() const { std::vector<short> traversal; preorder(traversal, tree_); return traversal; } std::vector<short> BinaryTree::postorder() const { std::vector<short> traversal; postorder(traversal, tree_); return traversal; } inline BinaryTree & BinaryTree::operator=(BinaryTree &) { // TODO: insert return statement here } void BinaryTree::destroy(BinaryNode* & subtree) { if (subtree != NULL) { destroy(subtree->left_); destroy(subtree->right_); delete subtree; subtree = NULL; } } inline void BinaryTree::buildRandom(long size, BinaryNode *& subtree) { if (size == 0) { subtree = NULL; } else { subtree = new BinaryNode(btEntry_); btEntry_++; long leftSize = randInt(0, size); buildRandom(leftSize, subtree->left_); long rightSize = size - 1 - leftSize; buildRandom(rightSize, subtree->right_); } } inline void BinaryTree::displayLeft(std::ostream & outfile, BinaryNode * subtree, std::string prefix) { if (subtree == NULL) { outfile << prefix + "/" << std::endl; } else { displayLeft(outfile, subtree->left_, prefix + " "); outfile << prefix + "/---" << subtree->entry_ << std::endl; displayRight(outfile, subtree->right_, prefix + "| "); } } void BinaryTree::displayRight(std::ostream & outfile, BinaryNode * subtree, std::string prefix) { if (subtree == NULL) { outfile << prefix + "\\" << std::endl; } else { displayLeft(outfile, subtree->left_, prefix + "| "); outfile << prefix + "\\---" << subtree->entry_ << std::endl; displayRight(outfile, subtree->right_, prefix + " "); } } long BinaryTree::size(const BinaryNode * subtree) { if (subtree == NULL) return 0; else return (size(subtree->left_) + 1 + size(subtree->right_)); } inline long BinaryTree::height(const BinaryNode * subtree) { if (subtree == NULL) return 0; else { /* compute the depth of each subtree */ int lHeight = height(subtree->left_); int rlHeight = height(subtree->right_); /* use the larger one */ if (lHeight > rlHeight) return(lHeight + 1); else return(rlHeight + 1); } } inline long BinaryTree::leaves(const BinaryNode * subtree) { if (subtree == NULL) return 0; else if (subtree->left_ == NULL && subtree->right_ == NULL) return 1; else { return leaves(subtree->left_) + leaves(subtree->right_); } } short BinaryTree::leftmost(const BinaryNode * subtree) { const BinaryNode* current = subtree; while (current->left_ != NULL) { current = current->left_; } return (current->entry_); } void BinaryTree::preorder(std::vector<short>& traversal, const BinaryNode * subtree) { if (subtree != NULL) { traversal.push_back(subtree->entry_); preorder(traversal, subtree->left_); preorder(traversal, subtree->right_); } } void BinaryTree::postorder(std::vector<short>& traversal, const BinaryNode * subtree) { if (subtree != NULL) { postorder(traversal, subtree->left_); postorder(traversal, subtree->right_); traversal.push_back(subtree->entry_); } } #endif
true
bc13eab24a521590abd1f90e98556e0be496f1c1
C++
extramaster/2DLevelGenerator
/src/main.cpp
UTF-8
1,047
3.015625
3
[ "MIT" ]
permissive
#include <cstdlib> #include <ctime> #include <SFML/Graphics.hpp> #include "Level.hpp" #include "LevelGenerationAlgorithm.hpp" #include "ModifiedKruskalsMazeGen.hpp" int main() { std::srand(std::time(0)); sf::RenderWindow app(sf::VideoMode(15*32, 15*32), "Level"); ModifiedKruskalsMazeGen generator; Level level(&generator); while(app.isOpen()) { sf::Event event; while(app.pollEvent(event)) { if(event.type == sf::Event::Closed) { app.close(); } else if(event.type == sf::Event::KeyPressed) { if(event.key.code == sf::Keyboard::Escape) { app.close(); } else if(event.key.code == sf::Keyboard::Down) { level.movePlayer(0); } else if(event.key.code == sf::Keyboard::Right) { level.movePlayer(1); } else if(event.key.code == sf::Keyboard::Up) { level.movePlayer(2); } else if(event.key.code == sf::Keyboard::Left) { level.movePlayer(3); } } } app.clear(sf::Color(0, 0, 0)); app.draw(level); app.display(); } return 0; }
true
2ab5216711bef33311f5096edfe2541a8c49bd25
C++
CARDSflow/cardsflow_gazebo
/include/cardsflow_gazebo/muscle/ISee.hpp
UTF-8
2,868
2.609375
3
[ "BSD-3-Clause" ]
permissive
#pragma once #include <vector> #include <boost/numeric/odeint.hpp> #include <cmath> #include <ros/ros.h> # define M_PI 3.14159265358979323846 /* pi */ #define toRadian( x ) ( (x) / 180 * M_PI ) #define toDegree( x ) ( (x) / M_PI * 180 ) namespace cardsflow_gazebo { using namespace std; using namespace boost::numeric::odeint; //using namespace gazebo; /* struct tendonType { vector<ignition::math::Vector3> MidPoint; vector<ignition::math::Vector3> Vector; //might need it to calculate length vector<ignition::math::Vector3> Orientation; vector<double> Pitch; vector<double> Roll; }; */ struct SEE { double stiffness = 30680.0; // N/m double length = 0.056; //m double expansion = 0.0; //m double force = 0.0; // double length0 = 0; //m }; class ISee { // c1-c3 are constand values, c4 is x0. documentation can be found at ____________________ double c1 = 0.012, c2 = 0.008, c3 = 0.018, c4 = 0.039; //m // the angles alpha_* describe the angle the tendons attach to the see.element double alpha_1 = std::atan( c1 / c4 ), alpha_2 = std::atan( c2 / (c3+c4) ); // radian // the angles beta_* describe the third angles of the corresponding triangles double beta_1 = M_PI / 4 - alpha_1, beta_2 = M_PI / 4 - alpha_2; // radian // length_* is the tendonlength from the two triangles inside the motor double length_1 = sqrt( c1*c1 + c4*c4 ), length_2 = sqrt( c2*c2 + (c3+c4)*(c3+c4) ); //m // length_c* are constand tendonlengths inside the motor double length_c1 = 0.04, length_c2 = 0.013; //m // Tendon stiffness (this is a random high number. A real number still has to be set) double tendonStiffness = 1e6; // N/m double tendonForce = 0; public: //deltaX is the displacement of the spring inside the motor double deltaX = 0.0; //m // the Length of the tendon inside the motor. the internal length changes depending on the displacement of the spring. double internalLength = length_c1 + length_1 + length_2 + length_c2; //m SEE see; ISee(); /////////////////////////////////////// /// \brief Calculate elastic force of the series elastic element /// \param[in] The tandonLength represents the length of the entire tendon.from the motor to the last viapoint. /// \param[in] The muscleLength representes the length of the tendon forn the outside of the motor to the last viapoint. void ElasticElementModel(const double &tendonLength, const double &muscleLength); /////////////////////////////////////// /// \brief apply the springForce onto the tendons going to motor and out the muscle. The force depends on the angle the tendons have towards the spring /// \parm[in] the force going out the muscle /// \parm[in] the force going toward the motor void applyTendonForce( double &_muscleForce , double &_actuatorForce ); }; }
true
2f10cfb801b79c1157df5fce35b8989f091a3334
C++
AlexisLeveque/Piscine_CPP
/day04/ex03/Ice.cpp
UTF-8
498
2.953125
3
[]
no_license
// // Created by Alexis LEVEQUE on 6/1/18. // #include "Ice.hpp" Ice::Ice(void) : AMateria("ice") {} Ice::Ice(Ice const &src) : AMateria("ice") { this->_xp = src.getXP(); } Ice &Ice::operator=(Ice const &rhs) { this->_xp = rhs.getXP(); } Ice::~Ice(void) {} void Ice::use(ICharacter &target) { std::cout << "* shoots an ice bolt at " << targe.getName() << " *" << std::endl; this->increase_xp(); } AMateria* Ice::clone() const { AMateria *newIce(Ice(*this)); return &newIce; }
true
3913b9adb25325ced701c3792a166e1d83d3293b
C++
nickgreenquist/GraphicsProgrammingProject
/DirectX11_Starter/BoundingBox.cpp
UTF-8
2,904
3.125
3
[]
no_license
#include "BoundingBox.h" BoundingBox::BoundingBox() { } BoundingBox::BoundingBox(std::vector<Vertex>& verts) { startMin = XMFLOAT3(999.0f, 999.0f, 999.0f); startMax = XMFLOAT3(-999.0f, -999.0f, -999.0f); // loop through the vector of verts provided by the mesh // and apply to set up the original min/max values for (int i = 0; i < verts.size(); i++) { if (verts[i].Position.x < startMin.x) startMin.x = verts[i].Position.x; if (verts[i].Position.x > startMax.x) startMax.x = verts[i].Position.x; if (verts[i].Position.y < startMin.y) startMin.y = verts[i].Position.y; if (verts[i].Position.y > startMax.y) startMax.y = verts[i].Position.y; if (verts[i].Position.z < startMin.z) startMin.z = verts[i].Position.z; if (verts[i].Position.z > startMax.z) startMax.z = verts[i].Position.z; } } // Accessors XMFLOAT3 BoundingBox::GetAABBMin() { return AABBMin; } XMFLOAT3 BoundingBox::GetAABBMax() { return AABBMax; } BoundingBox::~BoundingBox() { } // Pass in the GameEntity's worldMatrix to update the bounding box void BoundingBox::Update(XMFLOAT4X4 world) { XMMATRIX tempWorld = XMMatrixTranspose(XMLoadFloat4x4(&world)); XMVECTOR tempMin = XMLoadFloat3(&startMin); XMVECTOR tempMax = XMLoadFloat3(&startMax); tempMin = XMVector3Transform(tempMin, tempWorld); tempMax = XMVector3Transform(tempMax, tempWorld); XMFLOAT3 min; XMFLOAT3 max; XMStoreFloat3(&min, tempMin); XMStoreFloat3(&max, tempMax); CalculateOBBVerts(min, max); CalculateAABBVerts(); } // Check if two bounding boxes are colliding (this one and other) bool BoundingBox::IsColliding(BoundingBox& other) { // AABB collision detection if ((AABBMin.x < other.GetAABBMax().x && AABBMax.x > other.GetAABBMin().x) && // test x-axis (AABBMin.y < other.GetAABBMax().y && AABBMax.y > other.GetAABBMin().y) && // test y-axis (AABBMin.z < other.GetAABBMax().z && AABBMax.z > other.GetAABBMin().z))// test z-axis return true; return false; } void BoundingBox::CalculateOBBVerts(XMFLOAT3 min, XMFLOAT3 max) { OBBVerts[0] = max; OBBVerts[1] = XMFLOAT3(max.x, max.y, min.z); OBBVerts[2] = XMFLOAT3(min.x, max.y, max.z); OBBVerts[3] = XMFLOAT3(min.x, max.y, min.z); OBBVerts[4] = XMFLOAT3(max.x, min.y, min.z); OBBVerts[5] = XMFLOAT3(min.x, min.y, max.z); OBBVerts[6] = XMFLOAT3(max.x, min.y, max.z); OBBVerts[7] = min; } void BoundingBox::CalculateAABBVerts() { AABBMin = XMFLOAT3(999.0f, 999.0f, 999.0f); AABBMax = XMFLOAT3(-999.0f, -999.0f, -999.0f); for (int i = 0; i < 8; i++) { if (OBBVerts[i].x < AABBMin.x) AABBMin.x = OBBVerts[i].x; if (OBBVerts[i].x > AABBMax.x) AABBMax.x = OBBVerts[i].x; if (OBBVerts[i].y < AABBMin.y) AABBMin.y = OBBVerts[i].y; if (OBBVerts[i].y > AABBMax.y) AABBMax.y = OBBVerts[i].y; if (OBBVerts[i].z < AABBMin.z) AABBMin.z = OBBVerts[i].z; if (OBBVerts[i].z > AABBMax.z) AABBMax.z = OBBVerts[i].z; } }
true
e8088dbaa92f2c9c6b4cc50c9eb56a6957bac952
C++
sayuree/leetcode-problems
/stack/1047.RemoveAllAdjacentDuplicatesInString.cpp
UTF-8
706
3.609375
4
[]
no_license
//My NOT very efficient solution //O(n+m) time and O(n) space //Pushing into stack and checking whether it matches with upcoming element //Then concatenating final elements of a stack into new string //Then reverse it (due to FIFO nature of Stack DS) class Solution { public: string removeDuplicates(string S) { stack<char> temp; string res=""; for(char c:S){ if(temp.size()>0&&c==temp.top()){ temp.pop(); }else{ temp.push(c); } } while(!temp.empty()){ res+=temp.top(); temp.pop(); } reverse(res.begin(),res.end()); return res; } };
true
48b8301b8c5a1ff4c6a78998a883a151ac1541bc
C++
khadijaAssem/Compiler
/src/Parser.cpp
UTF-8
8,147
2.984375
3
[]
no_license
// // Created by hp on 06/05/2021. // #include "../include/Parser.h" using namespace std; vector<string> RULES_SET; set<char> puncs; map<string ,string> REs; map<string ,string> RDs; vector<string> RDKeys; set<string> keyWords; void Parser:: read_file(){ freopen(RULES_FILE, "r", stdin); string input; while (getline(std::cin,input)){ RULES_SET.push_back(input); } } void Parser:: save_keyWords(string line){ line.erase(remove(line.begin(), line.end(), '{'), line.end()); line.erase(remove(line.begin(), line.end(), '}'), line.end()); stringstream ss(line); while (ss >> line) keyWords.insert(line); } void Parser:: save_puncs(const string& line){ for (auto sym : MAIN_PUNCS){ if (line.find(sym) != string::npos){ puncs.insert(sym); } } } void Parser:: save_RE (const string& line , int sep_indx){ string name = line.substr(0, sep_indx); string expr = line.substr(sep_indx + 1, string::npos); name.erase(remove(name.begin(), name.end(), ' '), name.end()); expr.erase(remove(expr.begin(), expr.end(), ' '), expr.end()); REs[name] = expr; } void Parser:: save_RD (const string& line , int sep_indx){ string name = line.substr(0, sep_indx); string expr = line.substr(sep_indx + 1, string::npos); name.erase(remove(name.begin(), name.end(), ' '), name.end()); expr.erase(remove(expr.begin(), expr.end(), ' '), expr.end()); replace( expr.begin(), expr.end(), '-', '^' ); RDKeys.push_back(name); RDs[name] = expr; } void Parser:: parse_Line(string line){ if (line[0] == '[') { // cout << "Punctuations" << nLINE; save_puncs(line); global->puncs = puncs; return; } if (line[0] == '{') { // cout << "KeyWord" << nLINE; save_keyWords(line); global->keyWords = keyWords; return; } int indx = 0; while ( indx < line.size() && ((line[indx] >= 'a' && line[indx] <= 'z') || (line[indx] >= 'A' && line[indx] <= 'Z')) ) indx ++; while (indx < line.size() && line[indx] == ' ') indx++; if (indx < line.size() && line[indx] == ':'){ // cout << "Regular Expression" << nLINE; save_RE (line, indx); return; } if (indx < line.size() && line[indx] == '='){ // cout << "Regular Definition" << nLINE; save_RD(line, indx); return; } cout << "NON-VALID RULE" << nLINE; } map<string, vector<string>> Parser:: parse() { read_file(); for (const auto &line : RULES_SET) { // cout << line << nLINE; parse_Line(line); // cout << nLINE; } /* cout << "READ DONE AND MAIN PARSING DONE" << nLINE; cout << "Regular Definitions\n" << SEPARATOR; for (const auto& pr : RDs) cout << pr.fp << SPACE << SPACE << pr.sp << nLINE;*/ sort(RDKeys.begin(), RDKeys.end(), sort_by_length); // Sorting for dividing NOTE : (DIGIT VS DIGITS) /*cout << SEPARATOR; cout << "Regular Expressions\n" << SEPARATOR; for (const auto& pr : REs) cout << pr.fp << SPACE << SPACE << pr.sp << nLINE; cout << SEPARATOR; cout << "Keywords\n" << SEPARATOR; for (auto keyWord : keyWords) cout << keyWord << SPACE; cout << SEPARATOR; cout << "\nSymbols\n" << SEPARATOR; for (auto punc : puncs) cout << punc << SPACE; cout << nLINE << SEPARATOR; cout << SEPARATOR; cout << SEPARATOR; cout << SEPARATOR;*/ for(auto i:RDs){ cout<<"converting old is"<<nLINE; cout<<i.second<<nLINE; RDs[i.first] = convertRegularDefinition(i.second); cout<<"new is"<<nLINE; cout<<i.second<<nLINE; } cout << "FOR EXPRESSIONS" << nLINE; for (const auto& regExpr : REs) { vector<string> h = divide_RE(regExpr.sp); cout << regExpr.fp << nLINE; h = to_postfix(h); for (const auto& hh : h) { cout << hh << SPACE; } cout << nLINE; postfixREs[regExpr.fp] = h; } cout << SEPARATOR << nLINE; cout << "input Symbols \n"; global->inputSymbols = set<string>(tokns); for (const auto& g : global->inputSymbols) cout << g << nLINE; cout << nLINE; tokns.clear(); cout << "FOR DEFINITIONS" << nLINE; for (const auto& regDef : RDs) { vector<string> h = divide_RE(regDef.sp); cout << regDef.fp << nLINE; h = to_postfix(h); for (const auto& hh : h) { cout << hh << SPACE; } cout << nLINE; postfixRDs[regDef.fp] = h; } global->RDs = postfixRDs; global->RDinputSymbols = set<string>(tokns); cout << "input Symbols \n"; for (const auto& g : global->RDinputSymbols) cout << g << nLINE; cout << nLINE; cout << SEPARATOR; return postfixREs; } bool Parser:: sort_by_length(const string& s1, const string& s2){ return s1.length() > s2.length(); } vector<string> Parser:: divide_RE (string re){ vector<string> expressionTokens; vector<string> expression(re.size()); for(const auto& def : RDKeys){ std::size_t found = re.find(def); while (found != string::npos){ expression[found] = def; re[found] = '$'; found = re.find(def); } } for (int i = 0; i < re.size(); ++i) { string s; if (!expression[i].empty()){ s = expression[i]; i += (int)expression[i].length() - 1; } else { if (re[i] == '\\') { s = re[i]; s += re[++i]; } else { s += re[i]; } } if (!expressionTokens.empty() && expressionTokens[expressionTokens.size()-1] != "|" && expressionTokens[expressionTokens.size()-1] != "^" && expressionTokens[expressionTokens.size()-1] != ")" && expressionTokens[expressionTokens.size()-1] != "(" && RE_SYMPOLS.find(s) == RE_SYMPOLS.end()) expressionTokens.emplace_back("$"); if (RE_SYMPOLS.find(s) == RE_SYMPOLS.end()) tokns.insert(s); expressionTokens.push_back(s); } return expressionTokens; } vector<string> Parser:: to_postfix(const vector<string>& exprVec){ stack <string> stk; stk.push("#"); vector<string> postfix; for(const auto& it : exprVec) { if(RE_SYMPOLS.find(it) == RE_SYMPOLS.end()) postfix.push_back(it); else if (it == "(") stk.push(it); else if(it == ")"){ while(stk.top() != "#" && stk.top() != "(") { postfix.push_back(stk.top()); stk.pop(); } stk.pop(); //remove the '(' from stack } else { if(PRECEDENCE[it] > PRECEDENCE[stk.top()]) stk.push(it); else { while(stk.top() != "#" && PRECEDENCE[it] <= PRECEDENCE[stk.top()]) { postfix.push_back(stk.top()); stk.pop(); } stk.push(it); } } } while(stk.top() != "#") { postfix.push_back(stk.top()); stk.pop(); } for (auto it = postfix.begin(); it < postfix.end(); ++it) { cout << *it << nLINE; if (*it == "^") { it--; string s = *it; tokns.erase(*it); it--; s += "-"; s += (*it); tokns.erase(*it); reverse(s.begin(), s.end()); tokns.insert(s); it += 2; } } return postfix; } string Parser:: convertRegularDefinition(const string str) { map<string, string>::iterator it; string rd; string ans; for (auto i : str){ if (!ans.empty() && (i == '|' || i == '+' || i == '*' || i == '(' || i == ')')){ it = RDs.find(ans); if(it != RDs.end()){ ans='('+it->second+')'; } ans+=i; } else { ans += i; } } return ans; }
true
2f2ed440b7ac1263af9e2874c1ab4877a1e57247
C++
BGCX067/ezgame-svn-to-git
/EzGame-1.0.0/CoreLibs/EzAnimation3D/EzInterpolator.cpp
UTF-8
2,480
2.5625
3
[]
no_license
#include "EzInterpolator.h" EzImplementRTTI(EzInterpolator, EzObject); InterpFunction EzInterpolator::InterpFunctions[NUMKEYCONTENTS*MAX_ANI_KEYFREAMTYPE]; void EzInterpolator::RegisterLoader() { static bool bRegistered = false; if(bRegistered) return; bRegistered = true; setInterpFunctions(POSKEY, LINEAR_KEY, Interpolate_pos1); setInterpFunctions(ROTKEY, LINEAR_KEY, Interpolate_rot1); setInterpFunctions(FLOATKEY, LINEAR_KEY, interpolate_Scale_Linear); } EzInterpolator::EzInterpolator(void) { RegisterLoader(); } EzInterpolator::~EzInterpolator(void) { } bool EzInterpolator::update(f32 fTime, EzTransform &Value) { return false; } void EzInterpolator::setInterpFunctions(EANI_KEYCONTENT content, EANI_KEYFREAMTYPE keyFreamType, InterpFunction fInterp) { InterpFunctions[content * NUMKEYCONTENTS + keyFreamType] = fInterp; } InterpFunction EzInterpolator::getInterpFunctions(EANI_KEYCONTENT content, EANI_KEYFREAMTYPE keyFreamType) { return InterpFunctions[content * NUMKEYCONTENTS + keyFreamType]; } void Interpolate_pos1(f32 fTime, const void* pKey0, const void* pKey1, void* pResult) { EzPoint3* pPosKey0 = (EzPoint3*)pKey0; EzPoint3* pPosKey1 = (EzPoint3*)pKey1; // interpolate positions *(EzPoint3*)pResult = fTime*(*pPosKey1) + (1.0f-fTime)*(*pPosKey0); } void Interpolate_rot1(f32 fTime, const void* pKey0, const void* pKey1, void* pResult) { EzQuaternion* pQutKey0 = (EzQuaternion*)pKey0; EzQuaternion* pQutKey1 = (EzQuaternion*)pKey1; EzQuaternion Quttemp; *(EzQuaternion*)pResult = Quttemp.slerp( *pQutKey0, *pQutKey1, fTime); } void interpolate_Scale_Linear(f32 fTime, const void* pKey0, const void* pKey1, void* pResult) { f32* pOutKey0 = (f32*)pKey0; f32* pOutKey1 = (f32*)pKey1; *(f32*)pResult = (*pOutKey0) * (1-fTime) + (*pOutKey1) *fTime; } void interpolate_floatKey_Bezier(f32 fTime, const void* pKey0, const void* pKey1, void* pResult) { f32* pOutKey0 = (f32*)pKey0; f32* pOutKey1 = (f32*)pKey1; *(f32*)pResult = (*pOutKey0) * (1-fTime) + (*pOutKey1) *fTime; } //const NiBezFloatKey* pBez0 = (const NiBezFloatKey*) pKey0; //const NiBezFloatKey* pBez1 = (const NiBezFloatKey*) pKey1; // //// interpolate between this key and pQ //*(float*)pResult = NiInterpScalar::Bezier(fTime,pBez0->GetValue(), // pBez0->GetOutTan(),pBez1->GetValue(),pBez1->GetInTan());
true
4985433a84b97550d42992b2c98f4007ebf27636
C++
Showrin/codeforces-catagory-A-
/A - String Task.cpp
UTF-8
984
3
3
[]
no_license
#include <iostream> using namespace std; int main() { int n; string input_word; string output_word; string word; cin >> input_word; for (int i=0; i<input_word.length(); i++) { if (input_word.at(i) == 'A' || input_word.at(i) == 'E' || input_word.at(i) == 'I' || input_word.at(i) == 'O' || input_word.at(i) == 'U' || input_word.at(i) == 'Y' || input_word.at(i) == 'a' || input_word.at(i) == 'e' || input_word.at(i) == 'i' || input_word.at(i) == 'o' || input_word.at(i) == 'u' || input_word.at(i) == 'y') { } else { output_word.append("."); if (input_word.at(i) >= 'A' && input_word.at(i) <= 'Z') { word=input_word.at(i)+32; output_word.append(word); } else { word=input_word.at(i); output_word.append(word); } } } cout << output_word << endl; return 0; }
true
5ef623e1a1cb4e7e4e3dc66ec150c8679b3f36a3
C++
AnantaYudica/basic
/include/type/trait/rem/Pointer.h
UTF-8
842
2.59375
3
[ "MIT" ]
permissive
#ifndef BASIC_TYPE_TRAIT_REM_POINTER_H_ #define BASIC_TYPE_TRAIT_REM_POINTER_H_ namespace basic { namespace type { namespace trait { namespace rem { template<typename T> struct Pointer { typedef T type; typedef typename Pointer<T>::type Type; }; template<typename T> struct Pointer<T*> { typedef T type; typedef typename Pointer<T*>::type Type; }; template<typename T> struct Pointer<T*const> { typedef T type; typedef typename Pointer<T*const>::type Type; }; template<typename T> struct Pointer<T*volatile> { typedef T type; typedef typename Pointer<T*volatile>::type Type; }; template<typename T> struct Pointer<T*const volatile> { typedef T type; typedef typename Pointer<T*const volatile>::type Type; }; } //!rem } //!trait } //!type } //!basic #endif //!BASIC_TYPE_TRAIT_REM_POINTER_H_
true
5ed186158c7a26545654c5a5e1bdcddad8bd52a1
C++
takumhonde9/Cpp-Projects
/Data Structures/Queues/Queue/tests.cpp
UTF-8
1,151
3.0625
3
[]
no_license
/* * tests.cpp * * Created on: May 4, 2018 * Author: takudzwamhonde */ #include "tests.hpp" void test1(){ Queue<std::string> CoffeeShopList; CoffeeShopList.enqueue("Jonathan Burt - Frapaccino (XL) & Apple Crumble"); CoffeeShopList.enqueue("Melissa Funck - Cafe Americano (M) & Chocolate Chip Cookie"); CoffeeShopList.enqueue("Tafadzwa Nhema - French Vanilla Latte (L)"); CoffeeShopList.enqueue("Frank Kunzwa - BC Kicker Special (R)"); CoffeeShopList.enqueue("Dav Example - Roiboos Tea Latte w Honey (XXL) & Carrot Muffin"); std::cout << "------------ Coffee Shop -----------" << std::endl; while(!CoffeeShopList.empty()) { std::cout << "Customers Left: " << CoffeeShopList.size() << std::endl; std::cout << "Now serving : " << CoffeeShopList.front() << std::endl; CoffeeShopList.dequeue(); usleep(2000000); } } void test2(){ Queue<std::string> CoffeeShopList; try{ CoffeeShopList.dequeue(); }catch(QueueEmpty& qe) { std::cout << qe.getmsg() << std::endl; } // obtaining front on an empty queue try{ CoffeeShopList.front(); }catch(QueueEmpty& qe) { std::cout << qe.getmsg() << std::endl; } }
true
51e04e9806f8b0e50246972d0335d9b596ba283d
C++
loerac/BB-usr-led
/main.cpp
UTF-8
2,851
3.71875
4
[]
no_license
/* * Simple BBB on-board LED flashing program * This program uses all USR LED's and can be executed in three ways * - on * - off * - flash * - status * * Author: Christian Loera */ #include<iostream> #include<fstream> #include<string> using namespace std; // The path to the four LED's #define PATH "/sys/class/leds/beaglebone:green:usr" // Functions for LED's void writeLED(char* file, char* value, int led); void commands(int cmd, int led); void removeTrigger(int led); int main(int argc, char* argv[]) { int bw, cmd; // bw = bitwise; cmd = command cout << "\n====================================\n"; cout << "Starting the LED Program\n"; cout << "USER LED: usr0 [1], usr1 [2], usr2 [4], usr3 [8]\n"; cout << "Commands: ON [1], OFF [2], FLASH [3], STATUS [4]\n"; cout << "Exit: 0\n"; cout << "====================================\n"; cout << "Enter USER LED then command >> "; cin >> bw; // Loop until the user wants to exit (0) while(bw != 0) { cin >> cmd; cout << endl; // Checking which LED the user wants to be used if((bw & 1) == 1) { commands(cmd, 0); } if((bw & 2) == 2) { commands(cmd, 1); } if((bw & 4) == 4) { commands(cmd, 2); } if((bw & 8) == 8) { commands(cmd, 3); } cout << "\nEnter USER LED then command >> "; cin >> bw; } // Turning OFF all the LED's cout << endl; for(int i = 0; i < 4; i++) { removeTrigger(i); commands(2, i); } cout << "\nFinished the LED Program\n"; return 0; } void writeLED(char* file, char* value, int led) { FILE *fp; char fn[255]; snprintf(fn, sizeof(fn), PATH "%i%s", led, file); fp = fopen(fn, "w+"); fprintf(fp, "%s", value); fclose(fp); } void commands(int cmd, int led) { /* * cmd: 1 --> on * cmd: 2 --> off * cmd: 3 --> flash * cmd: 4 --> status */ if(cmd == 1) { removeTrigger(led); cout << "Turning LED " << led << " ON\n"; writeLED("/brightness", "1", led); } else if(cmd == 2) { removeTrigger(led); cout << "Turning LED " << led << " OFF\n"; writeLED("/brightness", "0", led); } else if(cmd == 3) { cout << "Flashing LED " << led << "\n"; writeLED("/trigger", "timer", led); writeLED("/delay_on", "500", led); writeLED("/delay_off", "500", led); } else if(cmd == 4) { char name[100]; std::fstream fs; sprintf(name, PATH "%i%s", led, "/trigger"); fs.open(name, std::fstream::in); string line; while(getline(fs, line)) { cout << line; } fs.close(); cout << endl; } else { cout << "\nInvalid Command\n"; } } void removeTrigger(int led) { // Remove the trigger from the LED writeLED("/trigger", "none", led); }
true
cfef2e87c38bc23e03b38727ab499529144ba5c7
C++
itu-robotics/intro-to-cpp
/week3/src/week3.cpp
UTF-8
3,521
4.28125
4
[]
no_license
//============================================================================ // Name : week3.cpp // Author : // Version : // Copyright : // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <vector> using namespace std; int main() { // Funtion Prototypes int sum(int firstNumber, int secondNumber); void printVector(vector<int> vectorToPrint, int size); int countToZero(int number); int factorial(int number); // Defines an empty array with 5 integer size int myArray[100]; // Defines an array with 10,20,30 elements int numberArray[] = { 10, 20, 30 }; // We can also define arrays as pointers, which I will cover in 4th week int *anotherArray = new int[5]; // prints the first element of the array cout << numberArray[0] << endl; // we can insert a new element into an array like this numberArray[3] = 40; cout << numberArray[3] << endl; // Let's fill an array to play with for(int i=0;i<100;i++) { myArray[i] = i; } // Getting the size of array int arraySize = (sizeof(myArray)/sizeof(*myArray)); for(int i=0;i<arraySize;i++) { cout << myArray[i] << endl; } cout << "-------------------------" << endl; // Removing an element from an array int arrayCursor = 0; int toRemove = 98; int removeCounter = 0; for(int i=0; i<arraySize; i++ ) { if( myArray[i] != toRemove ) { myArray[arrayCursor++] = myArray[i]; } else { removeCounter++; } } arraySize -= removeCounter; for(int i=0;i<arraySize;i++) { cout << myArray[i] << endl; } // Arrays are can be a little bit frustrating to deal with, in C++ we can use vectors instead std::vector<int> intVector(20); // Getting the size of vector int vectorSize = intVector.size(); // Place some values in vector for(int i=0;i<vectorSize;i++) { intVector.at(i) = i; } cout << "-------------------------" << endl; for(int i=0;i<vectorSize;i++) { cout << intVector.at(i) << endl; } cout << "-------------------------" << endl; // Delete the second element intVector.erase(intVector.begin() + 1); vectorSize = intVector.size(); for(int i=0;i<vectorSize;i++) { cout << intVector.at(i) << endl; } cout << "-------------------------" << endl; // Delete between second and 6th element intVector.erase(intVector.begin() + 1, intVector.begin() + 5); vectorSize = intVector.size(); for(int i=0;i<vectorSize;i++) { cout << intVector.at(i) << endl; } // Let's use some functions int number1, number2; cout << "Enter number 1: " << endl; cin >> number1; cout << "Enter number 2: " << endl; cin >> number2; cout << "Sum of " << number1 << " and " << number2 << " is " << sum(number1, number2) << endl; printVector(intVector, vectorSize); countToZero(200); cout << factorial(10) << endl; return 0; } // Functions int sum(int firstNumber, int secondNumber) { return firstNumber+secondNumber; } void printVector(vector<int> vectorToPrint, int size) { cout << "--- PRINTING VECTOR ---" << endl; for(int i=0;i<size;i++) { cout << vectorToPrint.at(i) << endl; } cout << "-----------------------" << endl; } // We can call the function in itself int countToZero(int number) { if (number == 0) { return 0; } else { cout << number-1 << endl; return (countToZero(number-1)); } } int factorial(int number) { if(number == 0 || number == 1) { return 1; } else { return number*factorial(number-1); } }
true
97fbd4bbb20e28094cf048787a8e02e9ca1374c3
C++
OfficineSistemiche/Double-Click
/double_click_arduino_2014_04_22_BLACKnWHITE/double_click_arduino_2014_04_22_BLACKnWHITE.ino
UTF-8
1,930
2.984375
3
[]
no_license
// doubleCLICK - by OfficineSISTEMICHE - april 2014 #include <Servo.h> Servo servoPen, servoRadar; // create servo objects // a maximum of eight servo objects can be created int brighRead; int posPen = 171; int touchPen = 3; boolean downPen = false; boolean downPPen = false; boolean invertRadar = false; int posRadar = 0; int shiftRadar = 1; int moveRadar; int slowRadar = 0; void setup() { Serial.begin(9600); servoPen.attach(10); // attaches the servo on pin 10 to the servo object servoRadar.attach(9); // attaches the servo on pin 9 to the servo object servoPen.write(160); servoRadar.write(0); establishContact(); } void loop() { if (Serial.available() > 0) { //read serial: it will be a number between 1 (black) and 9 (white) brighRead = Serial.read(); //--------------------- only BlackandWhite value if (brighRead < 9){ servoPen.write(posPen + touchPen); downPen = true; } if (brighRead == 9){ servoPen.write(posPen); downPen = false; } // when pen has to draw, slow a little the brush servo if (downPen != downPPen){ slowRadar = 30; downPPen = downPen; } else { slowRadar = 0; } //--------------------- for GREY scale values //brighRead *= 0.5; //servoPen.write(posPen + (sqrt(brighRead)*3)); //------------------------------brush----- 20° if (posRadar > 19){ invertRadar = true; } if (posRadar < 1){ invertRadar = false; } if (invertRadar == true){ moveRadar = - shiftRadar; } if (invertRadar == false){ moveRadar = + shiftRadar; } posRadar += moveRadar; servoRadar.write(posRadar); delay(15 + slowRadar); Serial.write(posRadar); } } void establishContact() { while (Serial.available() <= 0) { Serial.print('A'); // send a capital A delay(300); } }
true
0a86c3b9af8ae14d6a6c56e9355dc178645112c5
C++
vayush/coding-in-c
/DIFFICULT/ALL SUBARRAY WITH SUM ZERO/ALL SUBARRAY WITH SUM ZERO.cpp
UTF-8
493
2.921875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; void print(int a[],int start,int end){ for(int i=start;i<=end;i++){ cout<<a[i]<<" "; } cout<<endl; } void printAll(int a[],int n){ map<int,int>m; int sum =0; for(int i=0;i<n;i++){ sum = sum+a[i]; if(sum == 0) print(a,0,i); if(m.find(sum)!=m.end()){ print(a,m[sum]+1,i); } else m[sum] = i; } } int main(){ int a[] = {3,4,-7,3,1,3,1,-4,-2,-2}; int n = sizeof(a)/sizeof(a[0]); printAll(a,n); return 0; }
true
b3d74dbeb933b8e7b3d8031d259c76a259e22d07
C++
EvanMcGorty/expression-evaluator
/include/expression-evaluator/features/stl_optional_utilities.h
UTF-8
1,565
2.640625
3
[]
no_license
#include"../../../implementation/function_sets.h" namespace expr { namespace impl { template <typename t> struct type_operation_info<std::optional<t>> : public wrapper_type_operation_trait { static std::string print(std::optional<t> const& tar) { if (tar) { return "?" + type_operation_info<t const&>::print(*tar); } else { return "nullopt"; } } template<typename name_generator = compiler_name_generator> static std::string type_name(name_generator instance) { return instance.template retrieve<t>() + "-optional"; } static std::optional<std::optional<t>> parse(std::string::const_iterator& start, std::string::const_iterator stop) { if (start == stop) { //invalid input return std::optional<std::optional<t>>(std::nullopt); } static char const none[] = "nullopt"; auto m = std::mismatch(start, stop, std::begin(none), std::end(none) - 1); if (m.second == std::end(none) - 1) { //valid input indicating an empty optional of t. start = m.first; return std::optional<std::optional<t>>(std::optional<t>(std::nullopt)); } else if (*start == '?') { ++start; std::optional<t>&& g = type_operation_info<t>::parse(start, stop); if (g) { return std::optional<std::optional<t>>(std::move(g)); } else { return std::nullopt; } } else { return std::nullopt; } } }; } }
true
7229215ac3d260a77ff76641ef588c60dbaeba4c
C++
SauravPati08/FacePrep-CPP
/1D Array/Array insertion.cpp
UTF-8
580
3.359375
3
[ "MIT" ]
permissive
#include<iostream> using namespace std; int main() { int n,loc,val,i,temp; cin>>n; int a[n+1]; for(i=0;i<n;i++) cin>>a[i]; cout<<"Enter the number of elements in the array\nEnter the elements in the array\nEnter the location where you wish to insert an element\n"; cin>>loc>>val; if(loc>n || loc<=0) { std::cout<<"Invalid Input"; exit(0); } cout<<"Enter the value to insert\n"; for(int i=n-1; i>=loc-1; i--) a[i+1] = a[i]; a[loc-1] = val; cout<<"Array after insertion is\n"; for(int i=0; i<=n; i++) cout<<a[i]<<"\n"; }
true
c8bd1e36a8bfc2a9eed1947d4116d96439272755
C++
hebinbing/rover_navigation
/nodes/convert_pcl_node.cpp
UTF-8
2,348
2.515625
3
[ "BSD-3-Clause" ]
permissive
// rover_navigation #include "rover_navigation/GridMap.hpp" // ROS #include <ros/ros.h> // grid_map #include <grid_map_ros/grid_map_ros.hpp> #include <grid_map_core/iterators/GridMapIterator.hpp> // pcl #include <pcl/io/pcd_io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl_ros/point_cloud.h> using namespace grid_map; using namespace rover; int main(int argc, char** argv) { // Get point cloud std::string pcdFile = argv[1]; std::cout << "pcdFile:" << pcdFile << "\n"; pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>); if (pcl::io::loadPCDFile<pcl::PointXYZ> (pcdFile, *cloud) == -1) // load the file { PCL_ERROR ("Couldn't read file %s\n", pcdFile); return -1; } std::cout << "Loaded " << cloud->width * cloud->height << " data points from " << pcdFile << std::endl; // Initialize node and publisher ros::init(argc, argv, "grid_map_simple_demo_x"); ros::NodeHandle nh("~"); // namespace = home ros::Publisher publisher = nh.advertise<grid_map_msgs::GridMap>("grid_map", 1, true); // Point cloud publisher ros::Publisher pclPublisher = nh.advertise<pcl::PointCloud<pcl::PointXYZ>> ("points2", 1); // set cloud frame id cloud->header.frame_id = "map"; // Get grid map from point cloud rover::GridMap map; map.setGeometry(Length(10, 10), 0.02); map.setFrameId("map"); std::cout << "Initializing...\n"; // initialize with zeros // for (grid_map::GridMapIterator it(map); !it.isPastEnd(); ++it) { // map.at("elevation", *it) = 0; // } map.addPointCloud(cloud); ROS_INFO("Created map with size %f x %f m (%i x %i cells).\n The center of the map is located at (%f, %f) in the %s frame.", map.getLength().x(), map.getLength().y(), map.getSize()(0), map.getSize()(1), map.getPosition().x(), map.getPosition().y(), map.getFrameId().c_str()); ros::Rate rate(1); // rate in Hz while(nh.ok()) { ros::Time time = ros::Time::now(); // Publish grid map map.setTimestamp(time.toNSec()); grid_map_msgs::GridMap message; GridMapRosConverter::toMessage(map, message); publisher.publish(message); ROS_INFO_THROTTLE(1.0, "Grid map (timestamp %f) published.", message.info.header.stamp.toSec()); pclPublisher.publish(cloud); rate.sleep(); } return 0; }
true
390a97605e9f7221fe5c13d569f96689dab2173f
C++
alexandraback/datacollection
/solutions_5640146288377856_0/C++/sankettotala/cj_1c_q1.cpp
UTF-8
246
2.796875
3
[]
no_license
#include<iostream> using namespace std; int main(){ int t; cin>>t; for(int iiii=1; iiii<=t; iiii++){ int r, c, w; cin>>r>>c>>w; int min = c/w; min *= r; min += w; if(c%w == 0) min--; cout<<"Case #"<<iiii<<": "<<min<<endl; } }
true
221bdb8b24e6260ac432429028611e7eea667795
C++
jsharf/plasticity
/symbolic/numeric_value.h
UTF-8
1,683
2.890625
3
[ "MIT" ]
permissive
#ifndef NUMERIC_VALUE_H #define NUMERIC_VALUE_H #include "symbolic/expression_node.h" #include <experimental/optional> #include <iostream> #include <set> #include <string> #include <unordered_map> namespace symbolic { class NumericValue : public ExpressionNode { public: NumericValue(double a) : is_bound_(true), a_(a), b_(0) {} NumericValue(double a, double b) : is_bound_(true), a_(a), b_(b) {} NumericValue(std::string name) : is_bound_(false), name_(name) {} NumericValue() : is_bound_(true), a_(0), b_(0) {} NumericValue(const NumericValue& rhs) : is_bound_(rhs.is_bound_), name_(rhs.name_), a_(rhs.a_), b_(rhs.b_) {} virtual double& real() { return a_; } virtual double& imag() { return b_; } virtual double real() const { return a_; } virtual double imag() const { return b_; } std::shared_ptr<const ExpressionNode> Bind( const std::unordered_map<std::string, std::unique_ptr<NumericValue>>& env) const override; std::set<std::string> variables() const override; std::unique_ptr<NumericValue> TryEvaluate() const override; // Returns the symbolic partial derivative of this expression. std::shared_ptr<const ExpressionNode> Derive( const std::string& x) const override; std::string to_string() const override; virtual std::unique_ptr<NumericValue> CloneValue() const; std::unique_ptr<const ExpressionNode> Clone() const override; static const NumericValue pi; static const NumericValue e; protected: bool is_bound_; // For unbound variables. std::string name_; // For bound variables with actual values. double a_; double b_; }; } // namespace symbolic #endif /* NUMERIC_VALUE_H */
true
3ec2a2bbf430d2f8b8c604cd440ad64b2c78bc8d
C++
PVDVliet/EDS-Assignment-5
/Inc/Timer.h
UTF-8
511
3.21875
3
[]
no_license
#ifndef TIMER_H #define TIMER_H #include "ITimer.h" #include <inttypes.h> class Timer : public ITimer { public: Timer() : Timer(0) { } Timer(uint64_t time) : m_time(time) { } ~Timer() { } // ITimer uint64_t GetTime() const { return m_time; } void SetTime(const uint64_t time) { m_time = time; } void Increment(const uint64_t time) { m_time += time; } void Reset() { m_time = 0; } private: uint64_t m_time; }; #endif //TIMER_H
true
bd2d786a2ebb4d133ee46b9abaebc70d18bedd2e
C++
strifey/2804hw4
/src/processor.h
UTF-8
662
2.75
3
[]
no_license
#ifndef processor_h #define processor_h #include <iostream> #include <fstream> #include <sstream> #include <string> #include "storage.h" #include "instruction.h" class Processor { private: StorageFile registers; StorageFile memory; Storage PC; Instruction *curr_instr; bool halted; unsigned int instr_run; public: Processor(int reg_size, int mem_size, int max_size): registers(reg_size, max_size), memory(mem_size, max_size), PC(mem_size, max_size), halted(false), instr_run(0){} void next_step(); void fetch(); int run(); void dump(){std::cout<<registers.to_string()<<std::endl;} void load(std::ifstream& fr); }; #endif
true
8d998c39837e94395a8b43d55969d77ee81c98c6
C++
jaskaranbhatia/Interview-Prep
/Basics/DereferenceOperator.cpp
UTF-8
485
3.828125
4
[]
no_license
#include<iostream> using namespace std; // * is used for multiplication, creating pointer and dereferencing // In dereferencing, we derefer a pointer // & of a variable -> address // * of a addrress -> variable int main(){ int x = 10; int *ptr; ptr = &x; cout<<*ptr<<endl; //variable cout<<*&x<<endl; //variable cout<<*ptr + 1<<endl; //variable + 1 cout<<ptr<<endl; cout<<ptr+1<<endl; //next address //Double pointer - Pointer to a Pointer int **xptr = &ptr; cout<<xptr; }
true
38139bf527d20243d831cdd5904d0007d924f547
C++
TheRoD2k/Algorithm_OOP_DIHT
/SEM_2/MODULE_2/C/source.cpp
UTF-8
6,687
3.25
3
[]
no_license
/*Задача A. Восьминашки Имя входного файла: puzzle.in Имя выходного файла: puzzle.out Ограничение по времени: 1 секунда Ограничение по памяти: 256 мегабайт «Восьминашки» – упрощенный вариант известной головоломки «Пятнашки». Восемь костяшек, пронумерованных от 1 до 8, расставлены по ячейкам игровой доски 3 на 3, одна ячейка при этом остается пустой. За один ход разрешается передвинуть одну из костяшек, расположенных рядом с пустой ячейкой, на свободное место. Цель игры – для заданной начальной конфигурации игровой доски за минимальное число ходов получить выигрышную конфигурацию (пустая ячейка обозначена нулем): 1 2 3 4 5 6 7 8 0 Формат входного файла Во входном файле содержится начальная конфигурация головоломки – 3 строки по 3 числа в каждой. Формат выходного файла Если решение существует, то в первой строке выходного файла выведите минимальное число перемещений костяшек, которое нужно сделать, чтобы достичь выигрышной конфигурации, а во второй строке выведите соответствующую последовательность ходов: L означает, что в результате перемещения костяшки пустая ячейка сдвинулась влево, R – вправо, U – вверх, D – вниз. Если таких последовательностей несколько, то выведите любую из них. Если же выигрышная конфигурация недостижима, то выведите в выходной файл одно число −1. INPUT: 0 1 6 4 3 2 7 5 8 OUTPUT: 8 RDRULDDR */ #include <iostream> #include <fstream> #include <vector> #include <queue> #include <map> #include <string> #include <algorithm> std::vector<int> tens{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; class State { public: State() : _status(8765321) {}; State(int stat) : _status(stat) {} bool operator==(const State &other) { return _status == other._status; } bool IsNeeded() { return _status == 87654321; } std::vector<std::pair<State, char>> GetNextStates() const; private: int _status; State _MoveUp() const; State _MoveDown() const; State _MoveLeft() const; State _MoveRight() const; int _MoveZero(int number_to_replace) const; int _GetZeroPosition() const; State _ReversedMove(char c) const; friend std::string GetAnswer(std::map<State, char> &known); friend bool operator<(const State &left, const State &right); }; bool operator<(const State &left, const State &right) { return left._status < right._status; } int State::_MoveZero(int number_to_replace) const { int new_status = 0, temp_status = _status; for (int i = 0; i < 9; i++) { int new_number = temp_status % 10; if (new_number == 0) new_number = number_to_replace; else if (new_number == number_to_replace) new_number = 0; new_status += tens[i] * new_number; temp_status /= 10; } return new_status; } int State::_GetZeroPosition() const { int temp_status = _status, zero_position = 0; for (int i = 0; i < 9; i++) { if (temp_status % 10 == 0) break; temp_status /= 10; ++zero_position; } return zero_position; } std::vector<std::pair<State, char>> State::GetNextStates() const { int zero_position = _GetZeroPosition(); std::vector<std::pair<State, char>> next; if ((zero_position + 1) % 3 != 0) next.push_back({ _MoveRight(), 'R' }); if (zero_position % 3 != 0) next.push_back({ _MoveLeft(), 'L' }); if (zero_position >= 3) next.push_back({ _MoveUp(), 'U' }); if (zero_position <= 5) next.push_back({ _MoveDown(), 'D' }); return next; } State State::_MoveUp() const { int zero_position = _GetZeroPosition(); int number_to_replace = (_status / tens[zero_position - 3]) % 10; int new_status = _MoveZero(number_to_replace); return State(new_status); } State State::_MoveDown() const { int zero_position = _GetZeroPosition(); int number_to_replace = (_status / tens[zero_position + 3]) % 10; int new_status = _MoveZero(number_to_replace); return State(new_status); } State State::_MoveLeft() const { int zero_position = _GetZeroPosition(); int number_to_replace = (_status / tens[zero_position - 1]) % 10; int new_status = _MoveZero(number_to_replace); return State(new_status); } State State::_MoveRight() const { int zero_position = _GetZeroPosition(); int number_to_replace = (_status / tens[zero_position + 1]) % 10; int new_status = _MoveZero(number_to_replace); return State(new_status); } State State::_ReversedMove(char c) const { if (c == 'L') return _MoveRight(); if (c == 'R') return _MoveLeft(); if (c == 'U') return _MoveDown(); if (c == 'D') return _MoveUp(); } std::string GetAnswer(std::map<State, char> &known) { State curState(87654321); std::string answer; while (known[curState] != '-') { char step = known[curState]; answer += step; curState = curState._ReversedMove(step); } std::reverse(answer.begin(), answer.end()); return answer; } std::string FindWay(const State &startState) { std::queue<State> q; std::map<State, char> known; known[startState] = '-'; q.push(startState); State curState; std::pair<State, char> final; while (!q.empty()) { curState = q.front(); if (curState.IsNeeded()) break; q.pop(); auto next = curState.GetNextStates(); for (int i = 0; i < next.size(); i++) { if (known.find(next[i].first) == known.end()) { known[next[i].first] = next[i].second; q.push(next[i].first); } } } if (q.empty()) return "NOANSWER"; return GetAnswer(known); } int main() { std::ifstream T("puzzle.in"); std::ofstream To("puzzle.out"); int input, suminp = 0; for (int i = 0; i < 9; i++) { T >> input; suminp += tens[i] * input; } std::string way = FindWay(State(suminp)); if (way == "NOANSWER") To << -1 << std::endl; else { To << way.size() << std::endl; To << way << std::endl; } return 0; }
true
f188e015a16c1aaee39c30c2636ed9bdd531a302
C++
vineet21tiwari/Algorithm
/BST_Insertion_Searching.cpp
UTF-8
1,371
3.359375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; class Node{ public: int data; Node* left; Node* right; Node(int x){ data = x; left = NULL; right = NULL; } }; class BST{ public: Node* root; BST(){ root = NULL; } void inorder(Node* root){ if(root!=NULL){ inorder(root->left); cout<<root->data<<" "; inorder(root->right); } } Node* searchkey(Node* node,int key){ if(node==NULL ||node->data==key) return node; if(key < node->data) return searchkey(node->left,key); else return searchkey(node->right,key); } void search(int key){ Node* node = searchkey(this->root,key); if(node!=NULL) cout<<"Key found"<<"\n"; else cout<<"Key mot found"<<"\n"; } Node* insert(Node* temp, int key){ if(temp==NULL){ temp = new Node(key); return temp; } if(key<temp->data){ temp->left = insert(temp->left,key); } else temp->right = insert(temp->right,key); return temp; } void addkey(int key){ root = insert(root,key); } }; int main(){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif BST bt; int n,x; cin>>n; for(int i=0;i<n;i++){ cin>>x; bt.addkey(x); } bt.inorder(bt.root); cout<<"\n"; bt.search(11); return 0; }
true
1b90af9eeb1558bdbe5afa4f25d446ea5f914c26
C++
halmer/oop
/lab08/Paint/Model.h
UTF-8
1,186
2.578125
3
[]
no_license
#pragma once #include "Shape.h" class CModel { public: using AddShapeSignal = boost::signals2::signal<void(std::shared_ptr<CShape> const & shape, boost::optional<size_t> position)>; using DeleteShapeSignal = boost::signals2::signal<void(boost::optional<size_t> position)>; using DeleteAllShapesSignal = boost::signals2::signal<void()>; using OffsetShapeSignal = boost::signals2::signal<void(std::shared_ptr<CShape> const & shape, size_t position)>; void AddShape(std::shared_ptr<CShape> const & shape, boost::optional<size_t> position); void DeleteShape(boost::optional<size_t> position); void DeleteAllShapes(); void OffsetShape(std::shared_ptr<CShape> const & shape, CPoint const & delta, OffsetType type); void DoOnAddShape(AddShapeSignal::slot_type const & slot); void DoOnDeleteShape(DeleteShapeSignal::slot_type const & slot); void DoOnDeleteAllShapes(DeleteAllShapesSignal::slot_type const & slot); void DoOnOffsetShape(OffsetShapeSignal::slot_type const & slot); private: std::vector<std::shared_ptr<CShape>> m_shapes; AddShapeSignal m_addShape; DeleteShapeSignal m_deleteShape; DeleteAllShapesSignal m_deleteAllShapes; OffsetShapeSignal m_offsetShape; };
true
2a40bc1542bc6f8911d46c6bfecf3ca453d7eae9
C++
linneox/NCC_CIS17C
/HW_5a/main5a.cpp
UTF-8
1,649
3.953125
4
[ "MIT" ]
permissive
// ======================================================================== // Attached: HW_5ab // ======================================================================== // Project: HW_5a // ======================================================================== // Programmer: Johnny Valles // Class: CIS 17C // ======================================================================== #include <iostream> #include <list> using namespace std; void getNumbers(list<int>&); int addNumbers(list<int>&); void displaySum(list<int>&,int); int main() { list<int> aList; getNumbers(aList); int sum = addNumbers(aList); displaySum(aList, sum); } void getNumbers(list<int> & aList) { int entry; cout << "Enter 5 integer values." << endl; for (int i = 0; i < 5; i++) { cout << "Enter a value: "; cin >> entry; aList.push_back(entry); } } int addNumbers(list<int> & aList) { int sum = 0; for (list<int>::iterator it = aList.begin(); it != aList.end(); it++) { sum += *it; } return sum; } void displaySum(list<int> & aList, int sum) { cout << "Here is the list: "; for (list<int>::iterator it = aList.begin(); it != aList.end(); it++) { cout << *it << "\t"; } cout << endl; cout << "The sum equals: " << sum << endl; } // ======================================================================== /* OUTPUT: Enter 5 integer values. Enter a value: 5 Enter a value: 7 Enter a value: 3 Enter a value: 4 Enter a value: 2 Here is the list: 5 7 3 4 2 The sum equals: 21 */ // ========================================================================
true
de3aa1646b32620b1cf80e61cd31c0c275494837
C++
kasuuuu4423/taruhi
/main-alt-reverse-3leds/sketch_jan06a.ino
UTF-8
599
2.8125
3
[]
no_license
#include <FastLED.h> #define PIN 0 #define NUM_LED 600 #define BRIGHTNESS 64 CRGB leds[NUM_LED]; void setup() { Serial.begin(115200); delay(100); FastLED.addLeds<WS2812B, PIN, GRB>(leds, NUM_LED); FastLED.setBrightness(BRIGHTNESS); FastLED.showColor(CRGB::Black); Serial.println("init"); } void loop() { setall(); FastLED.show(); delay(5); } void setall(){ for(int i = 0; i < NUM_LED; i++) { setPix(i, leds, 0, 0, 255); } } void setPix(int num, CRGB rin[], int r, int g, int b) { rin[num].r = r; rin[num].g = g; rin[num].b = b; }
true
b0f3b97e07004b8eea03f3a635f5193c7965b31e
C++
jimlinntu/gym
/leetcode/191/main-divide-bits.cc
UTF-8
546
2.875
3
[]
no_license
class Solution { public: const int n = 1 << 8; const int mask = n-1; // 11111111 int count[1 << 8]; void precompute(){ for(int i = 0; i < n; i++){ int num = i; int c = 0; for(; num > 0; num = num & (num-1)){ c++; } count[i] = c; } } int hammingWeight(uint32_t num) { precompute(); return count[num & mask] + count[(num >> 8) & mask] + count[(num >> 16) & mask] + count[(num >> 24) & mask]; } };
true
babad96fa01ef869cac31fcf86780f853268e1fe
C++
DariusL/invaders2
/invaders v2/Texture.h
UTF-8
883
2.5625
3
[]
no_license
#pragma once #include "includes.h" #include "Globals.h" enum TEXTURE_VIEW { TEXTURE_VIEW_RENDER_TARGET = 1 << 0, TEXTURE_VIEW_SHADER_RESOURCE = 1 << 1, TEXTURE_VIEW_UNORDERED_ACCESS = 1 << 2 }; class Texture { e::ComPtr<ID3D11Texture2D> texture; e::ComPtr<ID3D11ShaderResourceView> shaderResourceView; e::ComPtr<ID3D11UnorderedAccessView> unorderedAccessView; e::ComPtr<ID3D11RenderTargetView> renderTargetView; uint view; uint width, height; public: Texture(ID3D11Device *device, uint width, uint height, uint view); Texture(Texture&) = delete; Texture(Texture&&); ~Texture(){} ID3D11ShaderResourceView *GetSRV(){ return shaderResourceView.Get(); } ID3D11UnorderedAccessView *GetUAV(){ return unorderedAccessView.Get(); } ID3D11RenderTargetView *GetRTV(){ return renderTargetView.Get(); } uint GetWidth(){ return width; } uint Getheight(){ return height; } };
true
16cf8e0e7d1df7bb59b16b677f5a43333e9fff33
C++
yasir18/ncrwork
/Ds Assignment/Sorting/QuickSort.cpp
UTF-8
961
3.828125
4
[]
no_license
#include<iostream> using namespace std; int partition(int *,int,int); void QuickSort(int *,int,int ); void swap(int &x,int &y){ int temp; temp=x; x=y; y=temp; } int main(){ int num; cout<<"Enter the count of numbers"; cin>>num; int *arr=new int [num]; cout<<"Enter the numbers: "; for(int i=0;i<num;i++){ cin>>arr[i]; } //sorting logic int low=0,high=num-1; QuickSort(arr,low,high); cout<<"The sorted list is: \n"; for(int i=0;i<num;i++){ cout<<arr[i]<<" "; } delete (arr); return 0; } void QuickSort(int *arr,int low,int high){ if(low>=high) return; int pivot=partition(arr,low,high); QuickSort(arr,low,pivot-1); QuickSort(arr,pivot+1,high); } int partition(int *arr,int low,int high){ int pivot=arr[high]; int low_idx=low-1; for(int i=low;i<high;i++){ if(arr[i]<pivot){ //swapping arr[i] and arr[low_idx] low_idx++; swap(arr[i],arr[low_idx]); } } low_idx++; swap(arr[high],arr[low_idx]); return low_idx; }
true
7a7bdea7b51333480f4e5004ec083c04d4799e9b
C++
VasuGoel/leetcode
/challenge/2020/september-leetcoding-challenge/largest-time-for-given-digits.cpp
UTF-8
492
3.03125
3
[]
no_license
// O(24) time. Checking all 4! = 24 permutations class Solution { public: string largestTimeFromDigits(vector<int>& arr) { sort(arr.begin(), arr.end(), greater<int>()); do { if((arr[0] < 2 or (arr[0] == 2 and arr[1] < 4)) and arr[2] < 6) return to_string(arr[0]) + to_string(arr[1]) + ":" + to_string(arr[2]) + to_string(arr[3]); } while(prev_permutation(arr.begin(), arr.end())); return ""; } };
true