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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
203931fde26b38f75e404849632a4a0533876139 | C++ | piratebreizh/DockAuto | /noeud.h | UTF-8 | 792 | 2.90625 | 3 | [] | no_license | #ifndef NODE_H
#define NODE_H
#include <math.h>
class Noeud
{
int xPos;
int yPos;
int distanceParcourue; // distance totale déjà parcourue jusqu'à ce noeud
// priorite= distanceParcourue + Distance Restante Estimee
int priorite; // smaller: higher priorite
public:
Noeud(int, int, int, int);
int getxPos() const ;
int getyPos() const;
int getDistanceParcourue() const;
int getPriorite() const ;
void majPriorite(const int &, const int &);
void prochaineDistance();
const int & getDistanceRestanteEstimee(const int &, const int &) const;
friend bool operator<(const Noeud & a, const Noeud & b)
{
return a.getPriorite() > b.getPriorite();
}
};
#endif // NODE_H
| true |
8e5463223a61fbcedd9d556b2db2e77539cbc278 | C++ | venkatesh551/CodeChef | /2015/Jan/Lunchtime/Piece_of_cake.cpp | UTF-8 | 455 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main(void)
{
int t;
cin >> t;
while (t-- > 0)
{
string s;
cin >> s;
int cnt[26] = {0};
for (auto c: s)
{
++cnt[c-'a'];
}
int sum = 0, max_cnt = 0;
for (int i = 0; i < 26; ++i)
{
sum += cnt[i];
max_cnt = max(max_cnt, cnt[i]);
}
sum -= max_cnt;
if (sum == max_cnt)
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
}
return 0;
}
| true |
b6cc628220b22a75ddf3fdd19ad723f8a169e008 | C++ | 1iuyzh/exercise | /data_structures_and_algorithm_analysis/5/HashTable_quatratic/HashTable.cpp | UTF-8 | 434 | 3.125 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<vector>
#include"HashTable.h"
using namespace std;
int main() {
HashTable<string> hashTable(101);
vector<string> vecs{"struggle", "indignant", "sophisticated", "staggering", "gaze"};
for (auto &s : vecs)
hashTable.insert(s);
cout << hashTable.contains("gaze") << endl;
hashTable.remove("gaze");
cout << hashTable.contains("gaze") << endl;
return 0;
} | true |
d068f38f1c130d2235fb79986a62bd33613be4e7 | C++ | Ujjwal120/MyC- | /__GEOXD__rns5.cpp | UTF-8 | 2,218 | 2.625 | 3 | [] | no_license |
// 1.87 second sec
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int X1, X2, Y1, Y2, a, b, c;
ll d;
const ll inf = 1e18;
const int mod = 1e9 + 7;
ll gcd(ll a, ll b, ll &x, ll &y) {
if (!b) {
x = 1, y = 0; return a;
}
ll rlt = gcd(b, a % b, y, x);
y -= a / b * x;
return rlt;
}
ll presolve(ll A, ll B, ll C) {
if (C < 0) return 0;
if (A > B) swap(A, B);
if (!A) {
assert(0);
return inf;
}
ll p = C / B;
ll k = B / A;
ll d = (C - p * B) / A;
return presolve(B - k * A, A, C - A * (k * p + d + 1)) + (p + 1) * (d + 1) + k * p * (p + 1) / 2;
}
ll calc(ll x, ll y, ll a, ll b) {
if (x >= b || y >= b) {
ll rx = x / b, ry = y / b;
return (rx * (y + 1) + ry * (x + 1) - b * rx * ry + calc(x % b, y % b, a, b)) % mod;
}
if (a * x <= y) return x + 1;
ll rlt = presolve(a, b, a * x) - presolve(a, b, a * x - y - 1);
rlt %= mod;
if (rlt < 0) rlt += mod;
return rlt;
}
void solve() {
cin>>X1>>X2>>Y1>>Y2>>a>>b>>c>>d;
X2 -= X1, Y2 -= Y1;
if (X2 < 0 || Y2 < 0) {
cout<<0<<endl;
return;
}
d = (d - 1ll * a * X1 - 1ll * b * Y1) % c;
int dbc = __gcd(b, c);
if (dbc > 1) {
ll x, y;
ll dall = gcd(a, dbc, x, y);
if (d % dall != 0) {
cout<<0<<endl;
return;
}
d /= dall, a /= dall, b /= dall, c /= dall, dbc /= dall;
x = x * d % dbc;
if (x < 0) x += dbc;
if (X2 < x) {
cout<<0<<endl;
return;
}
X2 -= x, d = (d - 1ll * a * x) % c;
assert(d % dbc == 0);
b /= dbc, d /= dbc, c /= dbc, X2 /= dbc;
}
int dac = __gcd(a, c);
if (dac > 1) {
ll x, y;
assert(gcd(b, dac, x, y) == 1);
x = x * d % dac; if (x < 0) x += dac;
if (Y2 < x) {
cout<<0<<endl;
return;
}
Y2 -= x, d = (d - 1ll * b * x) % c;
assert(d % dac == 0);
a /= dac, d /= dac, c /= dac, Y2 /= dac;
}
ll x, y;
assert(gcd(b, c, x, y) == 1);
a = 1ll * a * x % c, d = 1ll * d * x % c;
if (a < 0) a += c;
if (d < 0) d += c;
ll p = Y2 / c * c + c;
ll rlt = calc(X2, d + p, a, c) - calc(X2, d + p - Y2 - 1, a, c);
rlt = (rlt % mod + mod) % mod;
cout<<rlt<<endl;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int T;
cin>>T;
while (T --) solve();
}
| true |
afc8aa02b7872182779de5f10fd12d0645172c7f | C++ | duanxianze/lab7 | /Graph.h | GB18030 | 8,925 | 3.40625 | 3 | [] | no_license | #ifndef GRAPH_H
#define GRAPH_H
#include "SeqQueue.h"
#include <fstream>
const int maxWeight = 100000;
// ͼijඨ#Ȩͼ
// TΪͣEΪȨֵͣһӦΪijһ͡
template <class T, class E>
class Graph{
public:
Graph(int sz){
maxVertices = sz;
numVertices = 0;
numEdges = 0;
}
virtual ~Graph(){};
bool GraphEmpty() const{ //ͼշ
return (numEdges == 0);
}
bool GraphFull() const{ //ͼ
return (numVertices == maxVertices ||
numEdges == maxVertices*(maxVertices-1)/2);//ͼͼ2
}
int NumberOfVertices(){ //صǰ
return numVertices;
}
int NumberOfEdges(){ //صǰ
return numEdges;
}
void DFS(); //ȱͼеͨ
void BFS(); //ȱͼеͨ
void Components(); //ͨͼͨ㷨
friend istream& operator>> (istream &in, Graph<T,E> &G){
int i, j, k, n, m;
T e1, e2;
E weight;
in >> n >> m; //붥
for (i = 0; i < n; i++){ //붥ֵ
in >> e1;
G.insertVertex(e1);
}
i = 0;
while (i < m){
assert(in >> e1 >> e2 >> weight); //ߵֵȨֵ
j = G.getVertexPos(e1); //ȡӦ±
k = G.getVertexPos(e2);
if (j == -1 || k == -1){ //ȡӦ㲻
cout << "Input error!\n";
}
else{
G.insertEdge(j, k, weight); //ɶ±Ȩֵ
i++;
}
}
return in;
}friend ifstream& operator >> (ifstream &in, Graph<T, E> &G) {
int i, j, k, n, m;
T e1, e2;
E weight;
in >> n >> m; //붥
for (i = 0; i < n; i++) { //붥ֵ
in >> e1;
G.insertVertex(e1);
}
i = 0;
while (i < m) {
assert(in >> e1 >> e2 >> weight); //ߵֵȨֵ
j = G.getVertexPos(e1); //ȡӦ±
k = G.getVertexPos(e2);
if (j == -1 || k == -1) { //ȡӦ㲻
cout << "Input error!\n";
}
else {
G.insertEdge(j, k, weight); //ɶ±Ȩֵ
i++;
}
}
return in;
}
friend ostream& operator<< (ostream &out, Graph<T,E> &G){
int i, j, n, m;
T e1, e2;
E weight;
n = G.NumberOfVertices(); //
m = G.NumberOfEdges();
out << "Number of Vertices: " << n << endl;
out << "Number of Edges: " << m << endl;
out << "The edges in the graph are:\n";
for (i = 0; i < n; i++){
for (j = i + 1; j < n; j++){
weight = G.getWeight(i, j);
if (weight > 0 && weight < maxWeight){
e1 = G.getValue(i); //±ȡöֵ
e2 = G.getValue(j);
out << "(" << e1 << "," << e2 << "," << weight << ")" << endl;
}
}
}
return out;
}
// ͼʵֵһЩӿ
virtual T getValue(int i) = 0; //ȡλΪiĶеֵ
virtual E getWeight(int v1, int v2) = 0; //ر(v1,v2)ϵȨֵ
virtual bool insertVertex(const T &vertex) = 0; //ͼвһvertex
virtual bool removeVertex(int v) = 0; //ͼɾһv
virtual bool insertEdge(int v1, int v2, E weight) = 0; //ȨֵΪweightı(v1,v2)
virtual bool removeEdge(int v1, int v2) = 0; //ɾ(v1,v2)
virtual int getFirstNeighbor(int v) = 0; //ȡvĵһڽӶ
virtual int getNextNeighbor(int v, int w) = 0; //ȡvڽӶwһڽӶ
virtual int getVertexPos(const T &vertex) = 0; //vertexͼеλ
protected:
int maxVertices; //ͼ
int numEdges; //ǰ
int numVertices; //ǰ
void DFS(int v, bool visited[]); //ȱͼӹ
void BFS(int v, bool visited[]);
};
//ȱͼ,ͨͼнڵ
template<class T, class E>
void Graph<T,E>::DFS(){
int i, n = NumberOfVertices(); //ȡͼж
bool *visited = new bool[n]; //
for (i = 0; i < n; i++){ //visitedʼ
visited[i] = false;
}
//DFS(0,visited); //ͨͼ
for(i=0;i<n;i++){ //#ͨͼÿ㿪ʼһα
if(!visited[i]){ //#飬һ˱ѷʹĸ㲻Ϊ㡣ͨظ
DFS(i, visited); //Ӷ0ʼ
cout<<endl;
}
}
delete [] visited; //ͷvisited
}
//Ӷλv, ȵĴпɶδʹĶ㡣
//㷨õһvisited, ѷʹĶʱǡ
template<class T, class E>
void Graph<T,E>::DFS(int v, bool visited[]){
/*д*/
}
//ȱͼеͨ
template <class T, class E>void Graph<T,E>::BFS(){
int i, n = NumberOfVertices(); //ͼж
bool *visited = new bool[n];
for (i = 0; i < n; i++){
visited[i] = false;
}
for (i = 0; i < n; i++){ //#ÿ㿪ʼһα
//if (visited[i] == true){//#飬һ˱ѷʹĸ㲻Ϊ㡣ͨظ
// continue;
//}
if(!visited[i])
{
BFS(i,visited);
}
}
delete [] visited;
}
template <class T, class E>
void Graph<T,E>::BFS(int i, bool visited[]){/*д*/
}
//ͨͼͨ㷨
template<class T, class E> void Graph<T,E>::Components(){
int i, n = NumberOfVertices(); //ȡͼж
bool *visited = new bool[n]; //
for (i = 0; i < n; i++){ //visitedʼ
visited[i] = false;
}
int j=1;
for(i=0;i<n;i++){
if(!visited[i]){
cout << "Component " << j << ":" << endl;
DFS(i, visited); //Ӷ0ʼ
j++;
cout << endl;
}
}
delete [] visited; //ͷvisited
}
//////////////////////////////////////////////////////////////////
//Ȩͼ·
template <class T, class E>
void BFS_shortestpath(Graph<T,E> &G, T vertex, E dist[], int path[])
{
SeqQueue<int> Q;
int n=G.NumberOfVertices();
T w;
int v=G.getVertexPos(vertex);
for(int i=0;i<n;i++)
dist[i]=maxValue;
dist[v]=0;
// cout << getValue(i) << ' '; //ʶv
// visited[v] = true; //ѷʱ
Q.EnQueue(v);
//, ʵֲַ
while (!Q.IsEmpty()){ //ѭ, н
Q.DeQueue(v); //ıƱi
w =G.getFirstNeighbor(v); //һڽӶ
while (w != -1){ //ڽӶw
if (dist[w]==maxValue){ //δʹ
dist[w]=dist[v]+1;
path[w]=v;
Q.EnQueue(w); //w
}
w = G.getNextNeighbor(v, w); //ҶvһڽӶ
}
}//ѭжпշ
cout << endl;
//delete [] visited;
}
// path
template <class T,class E>
void printpath(Graph<T,E> &g, int v, int path[])
{//int i=g.getvertexPos();
if(path[v]!=-1)
printpath(g,path[v],path);
cout<<g.getValue(v)<< " ";
}
//Dijkstra
//GraphһȨͼ
//dist[j], 0j<n, ǵǰĴӶvj·,
//path[j], 0j<n, ·
template <class T, class E>
void ShortestPath(Graph<T,E> &G, T v, E dist[], int path[]){
int n = G.NumberOfVertices();
bool *S = new bool[n]; //·㼯
int i, j, k; E w, min;
for (i = 0; i < n; i++) {
dist[i] = G.getWeight(v, i);
S[i] = false;
if (i != v && dist[i] < maxValue) path[i] = v;
else path[i] = -1;
}
S[v] = true; dist[v] = 0; //v붥㼯
/**/
}
//a[i][j]Ƕij֮·ȡ
//path[i][j]Ӧ·϶jǰһĶš
template <class T, class E>
void Floyd(Graph<T,E> &G, E **a, int **path){
int i, j, k, n = G.NumberOfVertices();
for (i = 0; i < n; i++){ //apathʼ
for (j = 0; j < n; j++){
a[i][j] = G.getWeight (i,j);
if (i != j && a[i][j] < maxValue){
path[i][j] = i;
}
else{
path[i][j] = 0;
}
}
}
for (k = 0; k < n; k++){ //ÿһk, a(k)path(k)
for (i = 0; i < n; i++){
for (j = 0; j < n; j++){
if (a[i][k] + a[k][j] < a[i][j]){
a[i][j] = a[i][k] + a[k][j];
path[i][j] = path[k][j];
//·, ƹ k j
}
}
}
}
}
// ͨpath·ĺ
#endif
| true |
7fba3b8cbd082a4bfb00a76e51e0a3c970030b7f | C++ | lcp102/ButtonManager | /src/mdw/button/buttonstatesm.cpp | UTF-8 | 3,338 | 2.875 | 3 | [] | no_license | /*
* buttonstatesm.cpp
*
* Created on: 29 mars 2019
* Author: Yan Michellod
*/
#include <buttonstatesm.h>
#include "event/evbuttonpressed.h"
#include "event/evbuttonreleased.h"
#include "event/events.h"
#include "buttonEventsHandler.h"
/**
* @brief Constructor of ButtonStateSM
*/
ButtonStateSM::ButtonStateSM() {
_currentState = STATE_INITIAL;
}
/**
* @brief Destructor of ButtonStateSM
*/
ButtonStateSM::~ButtonStateSM() {
}
/**
* @brief Set the object to notify
*/
void ButtonStateSM::setNotified(ButtonEventsHandler* notified) {
_notified = notified;
}
/**
* @brief Set the index of the button
*/
void ButtonStateSM::setButtonIndex(ButtonIndex index) {
_buttonIndex = index;
}
/**
* @brief launch a event evButtonPressed in the state machine
*/
void ButtonStateSM::buttonPressed() {
GEN(evButtonPressed());
}
/**
* @brief launch a event evButtonReleased in the state machine
*/
void ButtonStateSM::buttonReleased() {
GEN(evButtonReleased);
}
/**
* @brief processing state machine
*/
XFEventStatus ButtonStateSM::processEvent() {
XFEventStatus status = XFEventStatus::Unknown;
handlerState _oldState = _currentState;
switch(_currentState){// BEGIN STATE CHANGE
case STATE_INITIAL:
{
if(getCurrentEvent()->getEventType() == XFEvent::Initial){
_currentState = STATE_WAIT_BUTTON_PRESSED;
status = XFEventStatus::Consumed;
}
break;
}
case STATE_WAIT_BUTTON_PRESSED:
{
if( getCurrentEvent()->getEventType() == XFEvent::Event && getCurrentEvent()->getId() == EventIds::evButtonPressedId){
_currentState = STATE_BUTTON_PRESSED;
status = XFEventStatus::Consumed;
}
break;
}
case STATE_BUTTON_PRESSED:
{
if(getCurrentEvent()->getEventType() == XFEvent::Event && getCurrentEvent()->getId() == EventIds::evButtonReleasedId){
GEN(XFNullTransition());
_currentState = STATE_BUTTON_SHORT_PRESSED;
status = XFEventStatus::Consumed;
}
else if(getCurrentEvent()->getEventType() == XFEvent::Timeout){
GEN(XFNullTransition());
_currentState = STATE_BUTTON_LONG_PRESSED;
status = XFEventStatus::Consumed;
}
break;
}
case STATE_BUTTON_SHORT_PRESSED:
{
if(getCurrentEvent()->getEventType() == XFEvent::NullTransition){
GEN(XFNullTransition());
_currentState = STATE_WAIT_BUTTON_PRESSED;
status = XFEventStatus::Consumed;
}
break;
}
case STATE_BUTTON_LONG_PRESSED:
{
if(getCurrentEvent()->getEventType() == XFEvent::NullTransition){
GEN(XFNullTransition());
_currentState = STATE_WAIT_BUTTON_PRESSED;
status = XFEventStatus::Consumed;
}
break;
}
default:
break;
}
// END STATE CHANGE
// BEGIN ACTION ON ENTRY
if(_oldState != _currentState){
switch(_currentState){
case STATE_BUTTON_PRESSED:
{
// start timer to detect a long pressed
scheduleTimeout(EventIds::evButtonPressedId,1000);
break;
}
case STATE_BUTTON_SHORT_PRESSED:
{
// unschedule timeout because short pressed
unscheduleTimeout(EventIds::evButtonPressedId);
// notify the handler that the button was short pressed
_notified->notifyButtonShortPressed(_buttonIndex);
break;
}
case STATE_BUTTON_LONG_PRESSED:
{
// notify the handler that the button is long pressed
_notified->notifyButtonLongPressed(_buttonIndex);
break;
}
default:
break;
}
}
// END ACTION ON ENTRY
return status;
}
| true |
fbcd8b0f57380a7da2babb895db32d7f9fd14195 | C++ | JsKim4/BOJ-BaekJoon-Online-judge- | /cpp/1000/1600/P1600.cpp | UTF-8 | 1,523 | 2.609375 | 3 | [] | no_license | #include<iostream>
#include<tuple>
#include<queue>
#pragma warning (disable:4996)
#define MAX 210000000
using namespace std;
// 1600 말이 되고픈 원숭이
int k, h, w;
int zoo[31][200][200];
int way[][3] = { {0,1,0},{0,-1,0}, {1,0,0},{-1,0,0},
{-1,-2,1},{-2,-1,1},{1,-2,1},{2,-1,1},
{1,2,1},{2,1,1},{-1,2,1},{-2,1,1} };
bool avail(int i,int j,int m) {
if (i >= 0 && i < h && j >= 0 && j < w&&m<=k)
return true;
return false;
}
void print(){
for (int i = 0; i < h; i++) {
for (int l = 0; l <= k; l++) {
for (int j = 0; j < w; j++) {
cout << zoo[l][i][j];
}
cout << " ";
}
cout << endl;
}
cout << endl;
}
int main() {
queue<tuple<int, int, int>>q;
cin >> k >> w >> h;
for (int i = 0; i < h;i++) {
for (int j = 0; j < w;j++) {
cin >> zoo[0][i][j];
for (int l = 0; l <= k;l++) {
zoo[l][i][j] = zoo[0][i][j];
}
}
}
if (h == 1 && w == 1) {
cout << 0;
return 0;
}
int count = 1;
q.push(make_tuple(0,0,0));
while (!q.empty()) {
int len = q.size();
for (int i = 0; i < len;i++) {
int l = get<0>(q.front()), y = get<1>(q.front()), x = get<2>(q.front()); q.pop();
for (int w = 0; w < 12;w++) {
int wy = y + way[w][0], wx = x + way[w][1],wl=l+way[w][2];
if (avail(wy,wx,wl)) {
if (zoo[wl][wy][wx] == 0) {
zoo[wl][wy][wx] = count;
q.push(make_tuple(wl,wy, wx));
}
}
}
}
//print();
for (int j = 0; j <= k; j++) {
if (zoo[j][h - 1][w - 1] != 0) {
cout << count;
return 0;
}
}
count++;
}
cout << -1;
} | true |
0d9b2180037176103d74ad16b055f9d0bc10839c | C++ | zhanghouxin07/communication-protocol-yinnuo | /path_generate/ref/main_ref.cpp | UTF-8 | 739 | 2.78125 | 3 | [] | no_license | #include "Agent.h"
#include <fstream>
#include <iostream>
using namespace std;
void InitializeAgent(AgentController*& _agents);
int main(int _argc, char** _argv){
srand(static_cast<unsigned int>(time(NULL)));
char next = 'Y';
AgentController* agent = NULL;
InitializeAgent(agent);
//main render loop
while(true){
//update AgentStates
while(agent->Update());
cout << "Continue? (Y/N)" << endl;
cin >> next;
if (next != 'Y' && next != 'y')
break;
agent->SetGoal(RandomQuery());
}
delete agent;
agent = NULL;
return 0;
}//end main
void InitializeAgent(AgentController*& _agent){
_agent = new AgentController;
_agent->SetState(RandomQuery());
_agent->SetGoal(RandomQuery());
}
| true |
c60aece6d6fe2f6284f0ab1f609f87102f5ad90b | C++ | chrisbex/tic-tac-toe-sfml | /brick.h | UTF-8 | 1,336 | 2.9375 | 3 | [] | no_license | class Brick
{
public:
Brick();
Brick(sf::Vector2f x);
void SetCoordinates(sf::Vector2f x);
void draw(sf::RenderWindow &wind);
sf::Vector2f GetCoordinates();
void update();
void SetState(int x) { state = x; };
int GetState() { return state; };
private:
int state;
bool isClicked;
sf::Vector2f coords;
sf::Texture BrickTex;
sf::Sprite BrickSpr;
};
Brick::Brick()
{
state = 0;
coords = sf::Vector2f(0, 0);
isClicked = false;
BrickTex.loadFromFile(".\\bin\\Debug\\nope.png");
BrickSpr.setTexture(BrickTex);
BrickSpr.setPosition(coords);
}
Brick::Brick(sf::Vector2f x)
{
state = 0;
coords = x;
isClicked = false;
}
void Brick::SetCoordinates(sf::Vector2f x)
{
coords = x;
}
sf::Vector2f Brick::GetCoordinates()
{
return coords;
}
void Brick::draw(sf::RenderWindow &wind)
{
wind.draw(BrickSpr);
}
void Brick::update()
{
BrickSpr.setPosition(coords);
if (this->state > 2) this->state = 0;
if (state == 0) BrickTex.loadFromFile(".\\bin\\Debug\\nope.png");
if (state == 1) BrickTex.loadFromFile(".\\bin\\Debug\\cross.png");
if (state == 2) BrickTex.loadFromFile(".\\bin\\Debug\\circle.png");
}
| true |
0978ed57792d6ece5e2844fdc48593c207af879f | C++ | ahbarif/Online-Judge-Solutions | /LightOJ/1182 - Parity.cpp | UTF-8 | 500 | 3 | 3 | [] | no_license | #include<iostream>
#include<iomanip>
#include<math.h>
using namespace std;
int main()
{
long long int num, mod, count, i, test;
cin >> test;
for (i = 1; i <= test; i++)
{
count = 0;
cin >> num;
while (num > 0)
{
mod = num % 2;
num = num / 2;
if (mod % 2 == 1)
{
count++;
}
}
if (count % 2 == 0)
{
cout << "Case " << i << ": even" << endl;
}
else
{
cout << "Case " << i << ": odd" << endl;
}
}
return 0;
} | true |
92dc5aada5ac7f2126b00fa4020876f350d17b37 | C++ | Abigail-Verhelle/CS120 | /onlyLetters.cpp | UTF-8 | 411 | 3.5 | 4 | [] | no_license | #include <iostream>
using namespace std;
string justletters(string r)
{
int i = 0;
while (r[i] != 0)
{
i++;
}
for (int x =0; x < i; x++)
{
string l = alpha(r[x]);
}
return string l;
}
int main()
{
string r = "";
cout < "Enter string: ";
cin >> r;
string answer = justletters(w);
cout << "The letters are " << answer << endl;
}
| true |
64255fe48023701aabc398317ab69dd8c2cb5835 | C++ | ntustison/Utilities | /src/GetJointSamples.cxx | UTF-8 | 2,391 | 2.78125 | 3 | [] | no_license | #include "itkArray.h"
#include "itkImageDuplicator.h"
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageFileWriter.h"
#include <string>
#include <vector>
#include <fstream>
template <unsigned int ImageDimension>
int GetJointSamples( int argc, char * argv[] )
{
typedef float PixelType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::ImageFileReader<ImageType> ReaderType;
typedef unsigned int LabelType;
typedef itk::Image<LabelType, ImageDimension> LabelImageType;
typedef itk::ImageFileReader<LabelImageType> LabelReaderType;
typename LabelImageType::Pointer maskImage = ITK_NULLPTR;
try
{
typename LabelReaderType::Pointer maskReader = LabelReaderType::New();
maskReader->SetFileName( argv[3] );
maskReader->Update();
maskImage = maskReader->GetOutput();
}
catch(...)
{
}
/**
* list the files
*/
std::vector<typename ImageType::Pointer> images;
std::cout << "Using the following files: " << std::endl;
for( unsigned int n = 4; n < static_cast<unsigned int>( argc ); n++ )
{
std::cout << " " << n-3 << ": " << argv[n] << std::endl;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[n] );
reader->Update();
images.push_back( reader->GetOutput() );
}
std::ofstream os( argv[2] );
itk::ImageRegionIteratorWithIndex<ImageType> It( images[0],
images[0]->GetLargestPossibleRegion() );
for( It.GoToBegin(); !It.IsAtEnd(); ++It )
{
if( !maskImage || maskImage->GetPixel( It.GetIndex() ) != 0 )
{
for( unsigned int n = 0; n < images.size(); n++ )
{
os << images[n]->GetPixel( It.GetIndex() ) << ' ';
}
os << std::endl;
}
}
os.close();
return EXIT_SUCCESS;
}
int main( int argc, char *argv[] )
{
if( argc < 5 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " imageDimension outputFile "
<< "maskImage imageList" << std::endl;
return EXIT_FAILURE;
}
switch( atoi( argv[1] ) )
{
case 2:
GetJointSamples<2>( argc, argv );
break;
case 3:
GetJointSamples<3>( argc, argv );
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
exit( EXIT_FAILURE );
}
}
| true |
84ee7048ba3656b1cdd1e8a8065ce50802bdd8c0 | C++ | Yur4ikMarchenko/GameOfHeroes | /Source.cpp | UTF-8 | 9,582 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string comeback;
string path = "history.txt";
fstream fs;
//меню
menu:
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << "~~~~~~~~~~~~ Game of Heroes ~~~~~~~~~~~~~~" << endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << "\t\tStart" << endl;
cout << "\t\tHistory" << endl;
cout << "\t\tAbout" << endl;
cout << "\t\tExit" << endl;
cout << "What do you want? : ";
string choose_menu;
cin >> choose_menu;
//починаєм грати
if (choose_menu == "Start")
{
srand(time(NULL));
vector<string> NamePlayer = { "Yura","Maks","Igor","Anton","Alex","Vlad","Turar","Boris","Nastya","Volodya" }; //можливі гравці
vector<string> NameHero = { "Sven","Zeus","Kunkka","Pangolier","Lycan","Underlord","Pudge","Huskar","Sniper","Tiny" }; //можливі герої
vector<string> NamePlayerTeamOne; //для формування команд
vector<string> NamePlayerTeamTwo;
vector<int> Rank_after_game_TeamOne; //для обрахунку рейтингу після гри
vector<int> Rank_after_game_TeamTwo;
int Rank[10] = { 100,200,150,250,175,225,75,125,200,300 }; //рейтинг гравців
int Damage[10] = { 100,200,250,150,175,235,400,500,550,450 }; //характеристики героїв
int HP[10] = { 500,700,800,950,600,900,550,700,800,990 };
int random; //змінна для випадкового отримання гравця та героя
int TeamOneHP = 0; //змінні для загальних НР та Damage команди (№1)
int TeamTwoHP = 0;
int TeamOneDamage = 0; //змінні для загальних НР та Damage команди (№2)
int TeamTwoDamage = 0;
int rezult_hp_one, rezult_hp_two;
string Winner = ""; //змінна для зберігання назви команди, що перемогла
cout << "------------Team Natus Vincere-------------" << endl << "Players: " << endl;
bool check_players[10] = { false }; //масиви для усунення повторень гравців
bool check_heroes[10] = { false }; //масиви для усунення повторень героїв
int n; //змінна для перевірки зайнятості позиції у масивах усунення повторень
for (int i = 0; i < 5; ++i)
{
while (check_players[n = rand() % 10]); //перевірка повторень гравців
check_players[n] = true;
random = n;
NamePlayerTeamOne.push_back(NamePlayer[random]); //додавання в команду гравців
Rank_after_game_TeamOne.push_back(Rank[random]); //додавання в команду рейтингу гравців
cout << "\tName: " << NamePlayer[random] << "\t" << "Rank: " << Rank[random] << endl;
}
cout << "Heroes: " << endl;
for (int i = 0; i < 5; ++i)
{
while (check_heroes[n = rand() % 10]); //перевірка повторень героїв
check_heroes[n] = true;
random = n;
TeamOneDamage += Damage[random]; //формування загальних характеристик команди
TeamOneHP += HP[random];
cout << "\tName: " << NameHero[random] << "\t" << "HP: " << HP[random] << "\t" << "Damage: " << Damage[random] << endl;
}
cout << "-------------------------------------------" << endl;
cout << "----------------Team Liquid----------------" << endl << "Players: " << endl;
for (int j = 0; j < 5; ++j)
{
while (check_players[n = rand() % 10]); //перевірка повторень гравців
check_players[n] = true;
random = n;
NamePlayerTeamTwo.push_back(NamePlayer[random]); //додавання в команду гравців
Rank_after_game_TeamTwo.push_back(Rank[random]); //додавання в команду рейтингу гравців
cout << "\tName: " << NamePlayer[random] << "\t" << "Rank: " << Rank[random] << endl;
}
cout << "Heroes: " << endl;
for (int j = 0; j < 5; ++j)
{
while (check_heroes[n = rand() % 10]); //перевірка повторень героїв
check_heroes[n] = true;
random = n;
TeamTwoDamage += Damage[random]; //формування загальних характеристик команди
TeamTwoHP += HP[random];
cout << "\tName: " << NameHero[random] << "\t" << "HP: " << HP[random] << "\t" << "Damage: " << Damage[random] << endl;
}
cout << "-------------------------------------------" << endl;
cout << "Natus Vincere " << "\tAll Hp: " << TeamOneHP << "\tAll Damage: " << TeamOneDamage << endl; //підрахнок загальної кількості НР та Damage команд
cout << "Liquid " << "\t\tAll Hp: " << TeamTwoHP << "\tAll Damage: " << TeamTwoDamage << endl;
cout << endl;
rezult_hp_one = TeamOneHP - TeamTwoDamage; //обрахунок кількості НР після атак команд
rezult_hp_two = TeamTwoHP - TeamOneDamage;
(rezult_hp_one > rezult_hp_two) ? Winner = "Natus Vincere" : Winner = "Luquid"; //перевірка переможця
cout << "-------------------------------------------" << endl;
cout << "*-*-*-*-*-* Team winner: " << Winner << " *-*-*-*-*-*" << endl; //вивід переможця
cout << "-------------------------------------------" << endl;
//розподіл рейтингу (+-25)
if (Winner == "Natus Vincere")
{
for (int i = 0; i < 5; i++) //якщо перемогла команда №1,
{ //то гравцям цієї команди до рейтингу + 25
Rank_after_game_TeamOne[i] = Rank_after_game_TeamOne[i] + 25;
}
for (int j = 0; j < 5; j++) // а гравцям іншої команди -25 від рейтингу
{
Rank_after_game_TeamTwo[j] = Rank_after_game_TeamTwo[j] - 25;
}
}
else
{ //аналогічно, якщо перемогла команда №2
for (int i = 0; i < 5; i++)
{
Rank_after_game_TeamTwo[i] = Rank_after_game_TeamTwo[i] + 25;
}
for (int j = 0; j < 5; j++)
{
Rank_after_game_TeamOne[j] = Rank_after_game_TeamOne[j] - 25;
}
}
//вивід команд та рейтингу після
cout << "___________ Teams after the game __________" << endl;
cout << "-------------- Natus Vincere --------------" << endl << "Players: " << endl;
for (int i = 0; i < 5; i++)
{
cout << "\tName: " << NamePlayerTeamOne[i] << "\tRank: " << Rank_after_game_TeamOne[i] << endl;
}
cout << "-------------- Team Liquid ----------------" << endl << "Players: " << endl;
for (int i = 0; i < 5; i++)
{
cout << "\tName: " << NamePlayerTeamTwo[i] << "\tRank: " << Rank_after_game_TeamTwo[i] << endl;
}
cout << "___________________________________________" << endl;
//продовження гри або кінець
string choose;
cout << "Continue the game? (y/n): ";
cin >> choose;
if (choose == "y")
{
fs.open(path, fstream::in | fstream::out | fstream::app);
if (!fs.is_open())
{
cout << "Error!!! The session was not recorded!!" << endl;
}
fs << "-------------- Natus Vincere --------------" << endl;
for (int i = 0; i < 5; i++)
{
fs << "\tName: " << NamePlayerTeamOne[i] << "\tRank: " << Rank_after_game_TeamOne[i] << endl;
}
fs << "-------------- Team Liquid ----------------" << endl;
for (int i = 0; i < 5; i++)
{
fs << "\tName: " << NamePlayerTeamTwo[i] << "\tRank: " << Rank_after_game_TeamTwo[i] << endl;
}
fs << "*******************************************" << endl;
fs << "\t\tWinner: " << Winner << endl;
fs << "*******************************************" << endl;
fs.close();
system("cls");
goto menu;
}
else if (choose == "n")
{
system("cls");
cout << "Goodbye!!!" << endl;
system("pause");
return 0;
}
}
//інформація про гру
if (choose_menu == "About")
{
cout << "Two teams are created, in which 5 players are randomly selected." << endl;
cout << "Each player is randomly assigned one of the available characters.HP and" << endl;
cout << "Damage per team is calculated by summing the corresponding scores of the" << endl;
cout << "team heroes. The total number of HP and Damage per team is calculated by" << endl;
cout << "summing the corresponding scores of the team heroes. The winning team is" << endl;
cout << "determined: The Damage of the opposing team is subtracted from the HP team," << endl;
cout << "after which the team with the most HP left is considered the winner." << endl << endl;
cout << "Go back? (y)";
cin >> comeback;
while (comeback != "y")
{
cout << "Error!!!" << endl;
cin >> comeback;
}
if (comeback == "y")
{
system("cls");
goto menu;
}
}
//історія ігор
if (choose_menu == "History")
{
fs.open(path, fstream::in);
while (!fs.eof())
{
string msg = "";
getline(fs, msg);
cout << msg << endl;
}
fs.close();
cout << "Go back? (y|n)";
cin >> comeback;
if (comeback == "y")
{
system("cls");
goto menu;
}
else if (comeback == "n")
{
return 0;
}
}
//вихід з гри
if (choose_menu == "Exit")
{
cout << "Goodbye, my friend!";
return 0;
}
} | true |
83ace6d3de09ade2c92cdd30452b2ae1429f0d8a | C++ | Bappy38/Light-OJ-solved-Problem | /Beginner/LOJ-1107.cpp | UTF-8 | 453 | 2.703125 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int T,i,m,j,x,y,x1,y1,x2,y2;
scanf("%d",&T);
for(i=1;i<=T;i++)
{
scanf("%d %d %d %d",&x1,&y1,&x2,&y2);
scanf("%d",&m);
printf("Case %d:\n",i);
for(j=1;j<=m;j++)
{
scanf("%d %d",&x,&y);
if((x>=x1 && x<=x2) && (y>=y1 && y<=y2))
printf("Yes\n");
else
printf("No\n");
}
}
return 0;
}
| true |
793fa95fc179b44a4384b7ed39b38adcd5b4c210 | C++ | Apostoln/tree | /BinaryTreeNode.h | UTF-8 | 5,059 | 3.375 | 3 | [] | no_license | #ifndef TREE_BINARYTREENODE_H
#define TREE_BINARYTREENODE_H
#include <iostream>
#include <memory>
#include <cassert>
#include <queue>
#include <experimental/memory>
#include "Order.h"
template <class T>
class Node : public INode<T> {
protected:
using typename INode<T>::UniqNode;
using typename INode<T>::ObserveNode;
protected:
T mValue;
ObserveNode mParent = nullptr;
UniqNode mLeft = nullptr;
UniqNode mRight = nullptr;
UniqNode& getChild(const T &other) {
return other < mValue ? mLeft : mRight;
}
UniqNode& getNullChild() {
static UniqNode nullUniqNode;
if (nullptr == mLeft ) {
return mLeft;
}
if (nullptr == mRight) {
return mRight;
}
return nullUniqNode;
}
UniqNode& getChildOfParent() {
static UniqNode nullUniqNode;
if (nullptr == mParent) {
return nullUniqNode;
}
return mParent->mLeft.get() == this? mParent->mLeft : mParent->mRight;
}
public:
Node() = delete;
Node(const T& val) : mValue(val) {}
Node(const T& val, Node* parentNode): mValue(val), mParent(parentNode) {}
Node* getMin() {
Node* node = this;
while(true) {
if(nullptr == node->mLeft) {
return node;
}
node = node->mLeft.get();
}
}
Node* getMax() {
Node* node = this;
while(true) {
if(nullptr == node->mRight) {
return node;
}
node = node->mRight;
}
}
Node* find(const T& element) {
Node* node = this;
while (true) {
if (element == node->mValue) {
return node;
}
if (element < node->mValue) {
if (nullptr == node->mLeft ) {
return nullptr;
}
node = node->mLeft.get();
} else {
if (nullptr == node->mRight) {
return nullptr;
}
node = node->mRight.get();
}
}
}
virtual UniqNode add(const T& value) {
Node* node = this;
if (UniqNode& child = node->getChild(value); nullptr == child) { // Указатель на указатель на нужного потомка
child.reset(new Node{value, node});
return {this};
} else {
child->add(value);
}
return {this};
}
bool remove(const T& value) {
Node* node = this;
Node* el = node->find(value);
if (nullptr == el) {
return false;
}
if (nullptr == el->mRight &&
nullptr == el->mLeft ) {
UniqNode& childOfParent = el->getChildOfParent();
childOfParent.reset();
}
else if (nullptr == el->mRight ) {
UniqNode& childOfParent = el->getChildOfParent();
childOfParent = std::move(el->mLeft);
childOfParent->mParent = el->mParent;
}
else if (nullptr == el->mLeft ) {
UniqNode& childOfParent = el->getChildOfParent();
childOfParent = std::move(el->mRight);
childOfParent->mParent = el->mParent;
}
else {
Node* minNodeInRightSubtree = el->mRight->getMin();
el->mValue = minNodeInRightSubtree->mValue;
el->mRight->remove(minNodeInRightSubtree->mValue);
}
}
template <class F>
void bfs(F visit) {
std::queue<Node*> q;
q.push(this);
while (!q.empty()) {
Node* node = q.front();
q.pop();
visit(node);
if (nullptr != node->mLeft) {
q.push(node->mLeft.get());
}
if (nullptr != node->mRight) {
q.push(node->mRight.get());
}
}
}
template <class F>
void dfs(F visit, Order order) {
Node* node = this;
switch (order) {
case Order::PRE: {
visit(node);
dfs(visit, node->mLeft, order);
dfs(visit, node->mRight, order);
return;
}
case Order::POST: {
dfs(visit, node->mLeft, order);
dfs(visit, node->mRight, order);
visit(node);
return;
}
case Order::IN: {
dfs(visit, node->mLeft, order);
visit(node);
dfs(visit, node->mRight, order);
return;
}
default: {
assert(false);
}
}
}
friend std::ostream& operator << (std::ostream& out, const Node& node) {
out << &node << " "
<< node.mValue << " "
<< node.mParent.get() << " "
<< node.mLeft.get() << " "
<< node.mRight.get() << std::endl;
return out;
}
};
#endif //TREE_BINARYTREENODE_H
| true |
efc584a898db4e5114090fee5eebe54011f6516a | C++ | Raffaello/sdl2-vga-terminal | /sdl2-vga-terminal/src/VgaTerminal.hpp | UTF-8 | 7,112 | 2.875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Window.hpp"
#include <memory>
#include <string>
#include <bitset>
#include <atomic>
#include <mutex>
#include <utility>
class VgaTerminal : public Window
{
public:
typedef struct
{
uint8_t mode; // video mode (only mode 3 available at the moment)
uint8_t tw; // terminal width
uint8_t th; // height
uint8_t cw; // char width
uint8_t ch; // height | font size
uint16_t numColors; // 65K max (16 bit) otherwse 24|32 bits if 0 (?)
uint8_t* font;
uint8_t* palette; // RGB palette
uint8_t* cursors;
} videoMode_t;
typedef struct
{
uint8_t c;
uint8_t col;
uint8_t bgCol;
} terminalChar_t;
// TODO major version refactor to a struct
// BODY instead of having first and second
// BODY have a struct with x, y.
typedef std::pair<uint8_t, uint8_t> position_t;
enum class CURSOR_MODE : uint8_t {
CURSOR_MODE_NORMAL = 0,
CURSOR_MODE_FAT = 1,
CURSOR_MODE_BLOCK = 2,
CURSOR_MODE_VERTICAL = 3,
};
static constexpr uint8_t NUM_CURSOR_MODES = 4;
CURSOR_MODE cursor_mode = CURSOR_MODE::CURSOR_MODE_NORMAL;
enum class CURSOR_SPEED : uint16_t {
CURSOR_SPEED_NORMAL = 500,
CURSOR_SPEED_FAST = 250,
CURSOR_SPEED_SLOW = 750
};
static constexpr uint8_t NUM_CURSOR_SPEEDS = 3;
static const std::string getVersion();
VgaTerminal() = delete;
VgaTerminal(const VgaTerminal&) = delete;
VgaTerminal(const VgaTerminal&&) = delete;
VgaTerminal& operator=(const VgaTerminal&) = delete;
VgaTerminal& operator=(const VgaTerminal&&) = delete;
explicit VgaTerminal(const std::string& title);
VgaTerminal(const std::string& title, const int winFlags, const int drvIndex, const int renFlags);
VgaTerminal(const std::string& title, const int width, const int height, const int winFlags, const int drvIndex, const int renFlags);
VgaTerminal(const std::string& title, const int x, const int y, const int width, const int height, const int winFlags, const int drvIndex, const int renFlags);
virtual ~VgaTerminal();
void gotoXY(const uint8_t x, const uint8_t y) noexcept;
void gotoXY(const position_t &position) noexcept;
position_t getXY() const noexcept;
uint8_t getX() const noexcept;
uint8_t getY() const noexcept;
void write(const uint8_t c, const uint8_t col, const uint8_t bgCol) noexcept;
void write(const terminalChar_t& tc) noexcept;
void write(const std::string &str, const uint8_t col, const uint8_t bgCol) noexcept;
void writeLine(const std::string& str, const uint8_t col, const uint8_t bgCol) noexcept;
void writeXY(const uint8_t x, const uint8_t y, const uint8_t c, const uint8_t col, const uint8_t bgCol) noexcept;
void writeXY(const position_t& pos, const uint8_t c, const uint8_t col, const uint8_t bgCol) noexcept;
void writeXY(const uint8_t x, const uint8_t y, const std::string &str, const uint8_t col, const uint8_t bgCol) noexcept;
void writeXY(const position_t& pos, const std::string &str, const uint8_t col, const uint8_t bgCol) noexcept;
void writeXY(const uint8_t x, const uint8_t y, const terminalChar_t& tc) noexcept;
void writeXY(const position_t& pos, const terminalChar_t& tc) noexcept;
terminalChar_t at(const uint8_t x, const uint8_t y) noexcept;
void render(const bool force = false);
void clear() noexcept;
void clearLine(const uint8_t y, const uint8_t bgCol = 0) noexcept;
void fill(const uint8_t c, const uint8_t col, const uint8_t bgCol) noexcept;
void moveCursorLeft() noexcept;
void moveCursorRight() noexcept;
void moveCursorUp() noexcept;
void moveCursorDown() noexcept;
void newLine() noexcept;
bool setViewPort(const position_t& viewport, const uint8_t width, const uint8_t height) noexcept;
bool setViewPort(const uint8_t x, const uint8_t y, const uint8_t width, const uint8_t height) noexcept;
bool setViewPort(const SDL_Rect& r) noexcept;
SDL_Rect getViewport() const noexcept;
void resetViewport() noexcept;
const videoMode_t getMode() const noexcept;
bool isIdle() const noexcept;
// NOTE: if you are using the methods do not use cursor_time field.
void setCursorSpeed(const CURSOR_SPEED speed) noexcept;
CURSOR_SPEED getCursorSpeed() const noexcept;
// TODO not really sure what is this for anymore...
uint8_t cursorDefaultCol = 7;
// @deprecated to be removed in 1
std::atomic<uint16_t> cursor_time = static_cast<uint16_t>(CURSOR_SPEED::CURSOR_SPEED_NORMAL); /// ms
bool showCursor = true;
bool blinkCursor = true;
bool autoScroll = true;
protected:
private:
typedef struct _terminalChar_t : terminalChar_t
{
bool rendered;
bool operator==(const _terminalChar_t& o) const;
} _terminalChar_t;
static const videoMode_t mode3;
std::unique_ptr<SDL_Color[]> pCol;
SDL_Palette _pal;
// potentially candidate for atomic, when setMode would be available
// at the moment is like a const, so defined as a const...
const videoMode_t mode;
std::unique_ptr<_terminalChar_t[]> _pGrid;
std::mutex _pGridMutex;
const _terminalChar_t _defaultNullChar = _terminalChar_t({ 0, 0, 0, false });
std::mutex _renderMutex;
std::atomic<uint8_t> _curX = 0;
std::atomic<uint8_t> _curY = 0;
std::atomic<uint8_t> _viewPortX;
std::atomic<uint8_t> _viewPortWidth;
std::atomic<uint8_t> _viewPortY;
std::atomic<uint8_t> _viewPortHeight;
std::atomic<uint8_t> _viewPortX2; /// _viewportX + _viewportWidth derived value
std::atomic<uint8_t> _viewPortY2; /// _viewportY + _viewportHeight derived value
CURSOR_SPEED _cursor_speed = CURSOR_SPEED::CURSOR_SPEED_NORMAL;
//std::atomic<uint16_t> _cursor_time = static_cast<uint16_t>(_cursor_speed); /// ms
std::atomic<bool> _drawCursor = true;
SDL_TimerID _cursorTimerId = 0;
std::atomic<bool> _onIdle = true;
void _setBusy() noexcept;
static uint32_t _timerCallBackWrapper(uint32_t interval, void* param);
uint32_t _timerCallBack(uint32_t interval);
void _incrementCursorPosition(const bool increment = true) noexcept;
void _scrollDownGrid() noexcept;
void _renderFontChar(const SDL_Point& dst, _terminalChar_t& tc);
void _renderCharLine(const std::bitset<8>& line, const int dstx, const int dsty, const uint8_t col, const uint8_t bgCol);
void _renderCursor(const SDL_Point&dst, const _terminalChar_t& tc);
void _renderGridPartialY(const uint8_t y1, const uint8_t y2, const bool force);
void _renderGridLinePartialX(const uint8_t x1, const uint8_t x2, const int yw, const int ych, const bool force);
_terminalChar_t _getCharAt(const size_t pos) noexcept;
const int _getCursorPosition() const noexcept;
_terminalChar_t _getCursorChar() noexcept;
void _setCharAtCursorPosition(const _terminalChar_t& tc) noexcept;
void _setCursorNotRendered() noexcept;
};
| true |
1bd225c54ebae54be393d08d55462a0b0f6fb67c | C++ | Jamil132/DSA-COMPLETE-SERIES | /Practise Code 1/Multiply Inheritance.cpp | UTF-8 | 938 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
class Base1
{
public:
void setdata(int r){
base1 = r;
}
protected:
int base1;
private:
};
class Base2
{
public:
void setdata1(int r){
base2 = r;
}
protected:
int base2;
private:
};
class Base3
{
public:
void setdata2(int r){
base3 = r;
}
protected:
int base3;
private:
};
class Derived : public Base1, public Base2, public Base3
{
public:
void display()
{
cout<<"The value of base1 is: "<<base1<<endl;
cout<<"The value of base2 is: "<<base2<<endl;
cout<<"The value of base3 is: "<<base3<<endl;
cout<<"The value of base1 + base2 + base3 is: "<<base1 + base2 + base3<<endl;
}
protected:
private:
};
int main()
{
Derived v;
v.setdata(7);
v.setdata1(3);
v.setdata2(10);
v.display();
return 0;
}
| true |
dfd0515072312963829bf24e2df63532a80a7695 | C++ | danmur14/DataStructures560 | /Murga_Lab6/test.cpp | UTF-8 | 3,785 | 3.28125 | 3 | [] | no_license | /*
* @file: test.cpp
* @author: Daniel Murga
* @date: 2017.3.5
* @brief: Timing between BST and MinHeap
*/
#include <iostream>
#include <fstream>
#include "Timer.cpp"
#include "MinHeap.h"
#include "BinarySearchTree.h"
int main()
{
double duration;
Timer T;
std::cout << " | BST | Heap" << std::endl;
for (int n = 50000; n <= 400000; n = n * 2)
{
int random[n]; //store random numbers
std::cout << n;
double bst[5], hp[5], bstDI[5], hpDI[5]; //hold times
for (int i = 1; i < 6; i++)
{
srand(i); //set seed
for (int j = 0; j < n; j++)
{
random[j] = rand() % (4 * n) + 1; //fill with random numbers
}
//time building BST
BinarySearchTree BST;
T.start();
for (int c = 0; c < n; c++)
{
BST.insert(random[c]);
}
bst[i - 1] = T.stop();
std::cout << " |" << bst[i - 1];
//time building MinHeap
MinHeap MH (2 * n);
T.start();
MH.build(random, n);
hp[i - 1] = T.stop();
std::cout << " |" << hp[i - 1];
//time deletion and insertion
//create x operation array
int op_size = .10 * n;
int op[op_size];
int op_y[op_size];
for (int d = 0; d < op_size; d++)
{
op[d] = rand() % 100;
op_y[d] = rand() % (4 * n) + 1;
}
std::cout << " | Ops ";
//time BST operations
T.start();
for (int e = 0; e < op_size; e++)
{
int x = op[e];
if ((0 <= x) && (x < 10))
{
BST.deleteMin();
}
else if ((10 <= x) && (x < 20))
{
BST.deleteMax();
}
else if ((20 <= x) && (x < 50))
{
int y = op_y[e];
BST.remove(y);
}
else if ((50 <= x) && (x < 100))
{
int y = op_y[e];
BST.insert(y);
}
}
bstDI[i - 1] = T.stop();
std::cout << " |" << bstDI[i - 1];
//time MinHeap operations
T.start();
for (int f = 0; f < op_size; f++)
{
int x = op[f];
if ((0 <= x) && (x < 10))
{
MH.deleteMin();
}
else if ((10 <= x) && (x < 20))
{
MH.deleteMax();
}
else if ((20 <= x) && (x < 50))
{
int y = op_y[f];
MH.remove(y);
}
else if ((50 <= x) && (x < 100))
{
int y = op_y[f];
MH.insert(y);
}
}
hpDI[i - 1] = T.stop();
std::cout << " |" << hpDI[i - 1] << std::endl;
}
//calculate average
double ABST = 0;
double AMH = 0;
double ABSTDI = 0;
double AMHDI = 0;
for (int a = 0; a < 5; a++)
{
ABST += bst[a];
AMH += hp[a];
ABSTDI += bstDI[a];
AMHDI += hpDI[a];
}
ABST = ABST / 5.0;
AMH = AMH / 5.0;
ABSTDI = ABSTDI / 5.0;
AMHDI = AMHDI / 5.0;
std::cout << "AVG|" << ABST << " |" << AMH << " ";
std::cout << "OPAVG|" << ABSTDI << " |" << AMHDI << std::endl;
}
return (0);
}
| true |
f1a8eb57edb6b764bd09d8c1f9277ad4b29fea8c | C++ | itsboazlevy/Portfolio | /advCPP/catalog/include/Publisher.h | UTF-8 | 665 | 2.9375 | 3 | [] | no_license | #ifndef PUBLISHER_H
#define PUBLISHER_H
#include <string>
class Publisher
{
public:
Publisher(const std::string& _publisher);
const std::string& GetPublisher() const;
private:
const std::string m_publisher;
};
////////////////////////////////////////////////
bool operator == (const Publisher& _a, const Publisher& _b)
{
return _a.GetPublisher() == _b.GetPublisher();
}
class HashPublisher
{
public:
size_t operator()(const Publisher& _publisher) const
{
size_t hash = 5381;
int temp;
int i = 0;
while (( temp = _publisher.GetPublisher()[i]) != 0)
{
hash = ( hash << 5) + hash +temp;
++i;
}
return hash;
}
};
#endif //PUBLISHER_H
| true |
0e5bb8a49c3b35b9da5eca51529c7844b68e3b18 | C++ | quanghona/Caro2 | /Caro.cpp | UTF-8 | 2,122 | 3.171875 | 3 | [
"MIT"
] | permissive | /*
* Caro - A simple game writing in C++ console programming.
* This game operate state by state. Every state has specific functions
* 1. Menu: At this state, there are 3 option: Start new game, information
* and Quit.
* 1.1 Start new game: players start a new game.
* 1.2 information : print the introduction and some informations of the
* game.
* 1.3 Quit: Quit the game.
* 2. Information: print the introduction, the rules and some other features.
* After this, the player will return to main menu.
* 3. Game Config: Setup the board before playing the game.
* 4. Game Play : 2 players playing turn by turn.
* 5. Quit : Quit the game.
*
* Feature:
* - Undo move
* - Control using cursor
* - Graphics, Color
* - Save history
* - Config using external file
*
* Date: April 2016
* Rev: 1.2
* Author: Team 8
* Group: TNMT - Fundamental of C++ Programming
* Ho Chi Minh University of Technology
*
* Revision History:
* - 1.0: First release
* - 1.1: fixed main()
* - 1.2: little fix
* - 1.3: add one more state: BeforeQuit
*/
#include "Game.h"
#include "Board.h"
#include <iostream>
#include <stdint.h>
#include <Windows.h>
#include <conio.h>
using namespace std;
State GameState = Menu;
CaroBoard board_c;
void main()
{
//The program running according to the current state of the game
while (GameState != Quit)
{
system("cls");
switch (GameState)
{
case Menu:
GameState = Game_Menu();
break;
case GamePlay_Config:
GameState = board_c.ConfigBoard() ? GamePlay_Playing : (system("pause"), BeforeQuit);
break;
case GamePlay_Playing:
GameState = Game_Playing();
break;
case Information:
Game_Information();
cout << "Press any key to back to Main menu." << endl;
_getch();
GameState = Menu;
break;
case BeforeQuit:
cout << endl << "Thanks for playing this game!!" << endl;
GameState = Quit;
break;
case Error: //This case should never happen
cout << "Unexpected Error occurred!" << endl;
break;
}
}
Sleep(1000);
}
/* End of Caro.cpp */
| true |
1fec0c5728cd5dd35ec1fefb269402d90005846a | C++ | mstemen0010/CC | /,mstring.h | UTF-8 | 2,930 | 2.859375 | 3 | [] | no_license | #ifndef _MSTRING_H
#define _MSTRING_H
#include <iostream.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#ifndef TRUE
#define TRUE 1
#define FALSE !TRUE
#endif
#define ERROR_INDEX_OUT_OF_BOUNDS "index out of range"
#define OPERATE_FIRST 0
#define OPERATE_ALL 1
class mstring {
public:
mstring();
mstring(const char* );
mstring(char *);
mstring(char);
mstring(const mstring& );
mstring(mstring*);
mstring& operator=(const char *);
mstring& operator=(const mstring &);
mstring& operator=(const int);
// user defined type conversion
operator char *() { return p->s;}
operator const char*() { return p->s;}
operator const char() { return *p->s;}
operator const int() { return atoi(p->s); }
operator int() { return atoi(p->s); }
~mstring();
const char* operator[] (int i ) const;
char operator [] (int i);
friend int operator==(const mstring &x, char *s)
{return strcmp(x.p->s, s) == 0; }
friend int operator==(const mstring &x, const char *s)
{return strcmp(x.p->s, s) == 0; }
friend int operator==(const mstring &x, const mstring &y)
{return strcmp(x.p->s, y.p->s) == 0; }
friend int operator!=(const mstring &x, const char *s)
{return strcmp(x.p->s, s) != 0; }
friend int operator!=(const mstring &x, const mstring &y)
{return strcmp(x.p->s, y.p->s) != 0; }
friend ostream& operator<<(ostream& s, const mstring& x)
{ return s << x.p->s;}
mstring& operator+=(const mstring &x);
mstring& operator+=(const char *x);
mstring& operator+=(const int x);
mstring& operator-=(const mstring &x);
mstring& operator-=(const char *x);
mstring operator+ (const int y);
int sndLike(const mstring &x);
mstring& mstring::cutn(int wordToDrop, char *delimiter);
mstring& mstring::clipn(int posToDrop);
char* operator()() const { return p->s;}
mstring* parse(const char *s);
mstring* sub(const int s);
mstring* sub(const char *s);
mstring* sub(const mstring x);
void clear(){ p->pcount=0;}
void delimiter(char *d);
char *delimiter();
int ccount(char *s);
int len() const { return p->_lenStr;}
int wcount(){ return p->_numWords;}
int cPos(char s);
int wPos(char *s);
int index();
char* charAtIndex();
char* charAtIndex(int index);
int mstring::find(const mstring &x, int index);
// mstring wordAtIndex();
mstring *wordAtIndex(int index);
mstring *wPos(int wordToGet, char *delimiter);
mstring upper();
mstring lower();
mstring deSpace();
mstring deXSpaces();
void swap(const char* t, const char* r, int howMany);
int isBlank();
private:
struct srep
{
char* s;
char* d;
int n;
int pcount; // counter for the parser
int _lenStr;
int _numWords;
int _index;
srep() {n = 1;}
};
srep *p;
void len(int newLen){ p->_lenStr = newLen;}
void wcount(int newWCount){p->_numWords = newWCount;}
mstring* sndxCalc() const;
};
#endif
| true |
65735170bb3615391779b1c05485c96446607286 | C++ | linoyisr/RoboticaFinal | /RoboticaProject/behaviors/GoForward.cpp | UTF-8 | 1,994 | 2.59375 | 3 | [] | no_license | /*
* GoForward.cpp
*/
#include "GoForward.h"
bool GoForward::startCond() {
/*return (_robot.checkRange(_robot.getLaserSpec() / 2 - LASER_SPEC,
_robot.getLaserSpec() / 2 + LASER_SPEC));*/
bool result = (_robot->isRangeClear(_robot->getLaserSpec() / 2 - 111, _robot->getLaserSpec() / 2 + 111));
cout << endl << "GoForward startCond: " <<result << endl;
return result;
}
bool GoForward::stopCond() {
_robot->Read();
double xLoc = _robot->getEstimateLocation().GetPoint().GetX();
double yLoc = _robot->getEstimateLocation().GetPoint().GetY();
Point wpoint(99999,99999);
double waypointX = (_waypointsManager->currentWayPoint.GetX());
double waypointY = (_waypointsManager->currentWayPoint.GetY());
cout << "waypointX " << waypointX;
cout << " waypointY " <<waypointY << endl;
cout << "x sum " << waypointX - xLoc << " y sum " <<waypointY - yLoc <<endl;
cout << "x abs " << abs(waypointX - xLoc) << " y abs " << abs(waypointY - yLoc) << endl;
double powX = (pow(waypointX - xLoc, 2));
double powY = (pow(waypointY - yLoc, 2));
cout << "powX " << powX << " powY " << powY << endl;
double distance = sqrt(powX + powY);
cout << "distance " << distance << endl;
if (distance < sqrt(1.6))
{
cout << "Is Innnn" << endl;
wpoint = _waypointsManager->currentWayPoint;
}
bool isRangeClear = startCond();
bool locationInWaypoints = (wpoint.GetX() != 99999 || wpoint.GetY() != 99999);
cout << "GoForward::stopCond , isRangeClear: " << isRangeClear << " location In Waypoints: " << locationInWaypoints << endl;
cout << "GoForward::stopCond , robotLoc: " << endl;
_robot->getEstimateLocation().Print();
return (!isRangeClear || locationInWaypoints);
}
void GoForward::action() {
cout << endl << "GoForward start run" << endl;
_robot->setSpeed(0.2, 0.0);
}
GoForward::GoForward(Robot* robot, WaypointsManager* waypointsManager) :
Behavior(robot) {
_waypointsManager = waypointsManager;
}
GoForward::~GoForward() {
// TODO Auto-generated destructor stub
}
| true |
ce3c1089e202d92e64065518ee479f530b4e2539 | C++ | adekwal/lab4 | /main.cpp | WINDOWS-1250 | 1,815 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <math.h>
#include "rk4.h"
//zagadnienie pocztkowe: {1} y'(t)=f(t,y);
//warunek pocztkowy: {2} y(t0)=y0;
double t0 = 0, tk = 2;//t nalezy do takiego przedzialu
double y_0 = 1;
double lambda = 10;
double f(double t, double y);//f(t,y);
double y_an(double t);
int main()
{
double t = t0, y = y_0;
double h = 0.01, eps_euler = 0, eps_rk4 = 0;
FILE* dane_do_zadania;
errno_t err = fopen_s(&dane_do_zadania, "dane_do_zadania.txt", "a+");
FILE* wyniki_euler;
errno_t err2 = fopen_s(&wyniki_euler, "wyniki_metoda_eulera.txt", "a+");
FILE* wyniki_rk4;
errno_t err3 = fopen_s(&wyniki_rk4, "wyniki_metoda_rk4.txt", "a+");
for (int i = 0; i < 7; i++)//wszystkie h zamienione na tk/n - nowy krok calkowania
{
double N = pow(2, i);//n - liczba krokow jakie nalezy wykonac
t = t0, y = y_0; fprintf(wyniki_euler, "N = %lf\n", N);
for (int j = 0; j < N; j++)//metoda eulera
{
t += (tk / N);//czyli t[i+1] = t[i] + h;
y += (tk / N) * f(t, y);//czyli y[i+1] = y[i] + h * f(t[i], y[i]);
eps_euler = fabs(y - y_an(t)) / fabs(y_an(t));
fprintf(wyniki_euler, "%lf\t%lf\t%lf\n", t, y, eps_euler);
}
t = t0, y = y_0; fprintf(wyniki_rk4, "N = %lf\n", N);
for (int j = 0; j < N; j++)//metoda rungego-kuty
{
t += (tk / N);
y = rk4(t, y, (tk / N), f);
eps_rk4 = fabs(y - y_an(t)) / fabs(y_an(t));
fprintf(wyniki_rk4, "%lf\t%lf\t%lf\n", t, y, eps_rk4);
}
fprintf(dane_do_zadania, "%lf\t%lf\t%lf\t%lf\n", N, (tk / N), eps_euler, eps_rk4);//dla ostatniego przedzialu czasowego
}
fclose(dane_do_zadania);
fclose(wyniki_euler);
fclose(wyniki_rk4);
printf("wszystkie wyniki mozna znalezc w plikach\n");
}
double f(double t, double y)
{
return lambda * y;
}
double y_an(double t)
{
return y_0 * exp(lambda * (t - t0));
} | true |
e9e55b68bdf6ff5d4f779804e7838265b9ce73c5 | C++ | sid6602/curated-resources | /STL Code/Deque.cpp | UTF-8 | 417 | 3.171875 | 3 | [] | no_license | #include<iostream>
#include<deque>
using namespace std;
int main()
{
deque<int> d;
cout<<"size"<<d.size()<<endl;
d.push_back(70);
d.push_front(50);
cout<<"size"<<d.size()<<endl;
cout<<"index element is->"<<d.at(1)<<endl;
cout<<"is deque empty?->"<<d.empty()<<endl;
d.pop_front();
cout<<"size"<<d.size()<<endl;
cout<<"index element is->"<<d.at(0)<<endl;
} | true |
61709036ce63fbae3af89b9fb8c07ae189bc32e4 | C++ | dmeneses/ask-me | /src/structs/trienode.cpp | UTF-8 | 693 | 3.171875 | 3 | [] | no_license | #include "trienode.h"
TrieNode::TrieNode() : content_(' '), marker_(false)
{
}
char TrieNode::content()
{
return content_;
}
void TrieNode::setContent(char c)
{
content_ = c;
}
bool TrieNode::wordMarker()
{
return marker_;
}
void TrieNode::setWordMarker()
{
marker_ = true;
}
TrieNode* TrieNode::findChild(char c)
{
for (unsigned int i = 0; i < chidren_.size(); i++)
{
TrieNode* tmp = chidren_.at(i);
if (tmp->content() == c)
{
return tmp;
}
}
return NULL;
}
void TrieNode::appendChild(TrieNode* child)
{
chidren_.push_back(child);
}
std::vector<TrieNode*> TrieNode::children()
{
return chidren_;
}
| true |
8464cd13e926e11a692e24b535191d3e8dfe193d | C++ | neoJINXD/Concordia-Projects | /COMP 371/Assignment 2/VS2017/src/Texture.cpp | UTF-8 | 1,124 | 2.75 | 3 | [] | no_license | #define STB_IMAGE_IMPLEMENTATION
#include "Texture.h"
#include <iostream>
Texture::Texture(std::string file, unsigned int _type)
{
//type = _type;
unsigned char* data = stbi_load(file.c_str(), &width, &height, &colorChannels, 0);
if (!data)
{
std::cout << "Failed to load texture @ " + file << std::endl;
exit(-1);
}
init(data);
}
Texture::~Texture()
{
glDeleteTextures(1, &id);
}
void Texture::Bind()
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, id);
}
void Texture::Unbind()
{
glActiveTexture(0);
glBindTexture(GL_TEXTURE_2D, 0);
}
void Texture::init(unsigned char* data)
{
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(data);
glBindTexture(GL_TEXTURE_2D, 0);
} | true |
69f69758e341bb267c4fa5651c4d49345e1f0bdd | C++ | BGCX261/zk-tool-svn-to-git | /trunk/zk_tool/ZkAdaptor.h | UTF-8 | 12,462 | 2.59375 | 3 | [] | no_license | #ifndef __ZK_ADAPTOR_H__
#define __ZK_ADAPTOR_H__
/**
*@file ZkAdaptor.h
*@brief Zookeeper的c++接口,采用Zookeeper的多线程模式
*@author cwinux@gmail.com
*@version 1.0
*@date 2011-11-10
*@warning 无
*@bug
*/
#include <string>
#include <vector>
#include <list>
#include <map>
#include <inttypes.h>
using namespace std;
extern "C" {
#include "zookeeper.h"
}
class ZkAdaptor
{
public:
enum{
ZK_DEF_RECV_TIMEOUT_MILISECOND = 5000 ///<通信超时时间,5s
};
enum{///<add auth状态
AUTH_STATE_WAITING = 0, ///<正在add auth
AUTH_STATE_FAIL = 1, ///<add auth失败
AUTH_STATE_SUCCESS = 2 ///<add auth成功
};
public:
///构造函数
ZkAdaptor(string const& strHost, ///<zookeeper连接,为host:port结构
uint32_t uiRecvTimeout=ZK_DEF_RECV_TIMEOUT_MILISECOND);
///析构函数
virtual ~ZkAdaptor();
/**
*@brief 对象初始化.
*@param [in] level 错误日志级别,可以为
ZOO_LOG_LEVEL_ERROR,ZOO_LOG_LEVEL_WARN,ZOO_LOG_LEVEL_INFO,ZOO_LOG_LEVEL_DEBUG
*@return 0:success; -1:failure.
*/
int init(ZooLogLevel level=ZOO_LOG_LEVEL_WARN);
/**
*@brief 建立连接,连接建立后会触发onConnect()。底层调用zookeeper_init()
也可以通过isConnected()去轮询连接是否建立。
*@param [in] clientid_t 连接的session
*@param [in] flags zookeeper_init的flags参数,当前为0.
*@param [in] watch zk的事件watch函数,若不指定则采用系统默认的watch,需要重载on的函数处理事件。
*@param [in] context 若设定了watch,则需要指定watch的context。
*@return 0:success; -1:failure.
*/
virtual int connect(const clientid_t *clientid=NULL, int flags=0, watcher_fn watch=NULL, void *context=NULL);
///关闭连接
void disconnect();
///检测连接是否建立。true:建立;false:未建立。
bool isConnected()
{
if (m_zkHandle){
int state = zoo_state (m_zkHandle);
if (state == ZOO_CONNECTED_STATE) return true;
}
return false;
}
/**
*@brief 对连接授权,底层调用zoo_add_auth()。
*@param [in] scheme auth的scheme,当前只支持digest类型的授权
*@param [in] cert auth的证书。对于digest模式,为user:passwd的格式
*@param [in] certLen cert的长度。
*@param [in] timeout 授权超时的时间,单位为ms。若为0则不等待,需要主动调用getAuthState()获取授权的结果。
*@return true:授权成功;false:授权失败.
*/
bool addAuth(const char* scheme, const char* cert, int certLen, uint32_t timeout=0, void_completion_t completion=NULL, const void *data=NULL);
///获取赋权状态,为AUTH_STATE_WAITING,AUTH_STATE_FAIL,AUTH_STATE_SUCCESS之一
int getAuthState() const { return m_iAuthState;}
/**
*@brief 创建node,底层调用zoo_create()。
*@param [in] path 节点路径
*@param [in] data 节点的数据
*@param [in] dataLen 数据的长度。
*@param [in] acl 节点的访问权限。
*@param [in] flags 节点的flag,0表示正常节点,或者为ZOO_SEQUENCE与ZOO_EPHEMERAL的组合。
*@param [in] recursive 是否递归创建所有节点。
*@param [out] pathBuf 若为ZOO_SEQUENCE类型的节点,返回真正的节点名字。
*@param [in] pathBufLen pathBuf的buf空间。
*@return 1:成功;0:节点存在;-1:失败
*/
int createNode(const string &path,
char const* data,
uint32_t dataLen,
const struct ACL_vector *acl=&ZOO_OPEN_ACL_UNSAFE,
int flags=0,
bool recursive=false,
char* pathBuf=NULL,
uint32_t pathBufLen=0);
/**
*@brief 删除节点及其child节点。
*@param [in] path 节点路径
*@param [in] recursive 是否删除child node。
*@param [in] version 数据版本,-1表示不验证版本号。
*@return 1:成功;0:节点不存在;-1:失败.
*/
int deleteNode(const string &path,
bool recursive = false,
int version = -1);
/**
*@brief 获取一个node的孩子。
*@param [in] path 节点路径
*@param [out] childs 节点的孩子列表
*@param [in] watch 是否watch节点的变化。
*@return 1:成功;0:节点不存在;-1:失败.
*/
int getNodeChildren( const string &path, list<string>& childs, int watch=0);
/**
*@brief 检测一个节点是否存在。
*@param [in] path 节点路径
*@param [out] stat 节点的信息
*@param [in] watch 是否watch节点的变化。
*@return 1:存在;0:节点不存在;-1:失败.
*/
int nodeExists(const string &path, struct Stat& stat, int watch=0);
/**
*@brief 获取一个节点的数据及信息。
*@param [in] path 节点路径
*@param [out] data 数据空间。
*@param [in out] dataLen 传入数据空间大小,传出data的真实大小。
*@param [out] stat 节点信息。
*@param [in] watch 是否watch节点的变化。
*@return 1:成功;0:节点不存在;-1:失败.
*/
int getNodeData(const string &path, char* data, uint32_t& dataLen, struct Stat& stat, int watch=0);
/**
*@brief 获取一个node的孩子,并注册事件函数。
*@param [in] path 节点路径
*@param [out] childs 节点的孩子列表
*@param [in] watcher watch函数,若不指定则不watch。
*@param [in] watcherCtx watch函数的context。
*@return 1:成功;0:节点不存在;-1:失败.
*/
int wgetNodeChildren( const string &path, list<string>& childs, watcher_fn watcher=NULL, void* watcherCtx=NULL);
/**
*@brief 检测一个节点是否存在。
*@param [in] path 节点路径
*@param [out] stat 节点的信息
*@param [in] watcher watch函数,若不指定则不watch。
*@param [in] watcherCtx watch函数的context。
*@return 1:存在;0:节点不存在;-1:失败.
*/
int wnodeExists(const string &path, struct Stat& stat, watcher_fn watcher=NULL, void* watcherCtx=NULL);
/**
*@brief 获取一个节点的数据及信息。
*@param [in] path 节点路径
*@param [out] data 数据空间。
*@param [in out] dataLen 传入数据空间大小,传出data的真实大小。
*@param [out] stat 节点信息。
*@param [in] watcher watch函数,若不指定则不watch。
*@param [in] watcherCtx watch函数的context。
*@return 1:成功;0:节点不存在;-1:失败.
*/
int wgetNodeData(const string &path, char* data, uint32_t& dataLen, struct Stat& stat, watcher_fn watcher=NULL, void* watcherCtx=NULL);
/**
*@brief 获取一个节点的数据及信息。
*@param [in] path 节点路径
*@param [in] data 数据。
*@param [in] dataLen 数据大小。
*@param [in] version 数据版本,若为-1表示不限定。
*@return 1:成功;0:节点不存在;-1:失败.
*/
int setNodeData(const string &path, char const* data, uint32_t dataLen, int version = -1);
/**
*@brief 获取一个节点的ACL信息。
*@param [in] path 节点路径
*@param [out] acl 节点的acl信息。
*@param [out] stat 节点的统计信息。
*@return 1:成功;0:节点不存在;-1:失败.
*/
int getAcl(const char *path, struct ACL_vector& acl, struct Stat& stat);
/**
*@brief 设置一个节点的ACL信息。
*@param [in] path 节点路径
*@param [int] acl 节点的acl信息。
*@param [in] version 数据版本,若为-1表示不限定。
*@return 1:成功;0:节点不存在;-1:失败.
*/
int setAcl(const char *path, const struct ACL_vector *acl=&ZOO_OPEN_ACL_UNSAFE, bool recursive=false, int version=-1);
///获取zookeeper的主机
string const& getHost() const { return m_strHost;}
///获取zookeeper的连接handle
zhandle_t* getZkHandle() { return m_zkHandle;}
///获取zookeeper连接的client session
const clientid_t * getClientId() { return isConnected()?zoo_client_id(m_zkHandle):NULL;}
///获取出错的错误代码
int getErrCode() const { return m_iErrCode;}
///获取错误消息
char const* getErrMsg() const { return m_szErr2K;}
public:
///sleep miliSecond毫秒
static void sleep(uint32_t miliSecond);
///split the src
static int split(string const& src, list<string>& value, char ch);
/**
*@brief 对input的字符串进行base64的签名,用户需要释放返回的字符空间。
*@param [in] input 要base64签名的字符串
*@param [in] length input的长度。
*@return NULL:失败;否则为input的base64签名
*/
static char* base64(const unsigned char *input, int length);
/**
*@brief 对input的字符串进行sha1的签名。
*@param [in] input 要sha1签名的字符串
*@param [in] length input的长度。
*@param [out] output 20byte的sha1签名值。
*@return void
*/
static void sha1(char const* input, int length, unsigned char *output);
/**
*@brief 对input的字符串进行sha1签名后,再进行base64变换。用户需要释放返回的空间
*@param [in] input 要签名的字符串
*@param [in] length input的长度。
*@return NULL:失败;否则为input的base64签名
*/
static char* digest(char const* input, int length);
/**
*@brief 根据priv形成acl。priv可以为all,self,read或者user:passwd:acrwd
*@param [in] priv 要签名的字符串,可以为all,self,read或者user:passwd:acrwd
*@param [in] acl 权限
*@return false:失败;true:成功
*/
static bool fillAcl(char const* priv, struct ACL& acl);
///输出权限信息,一个权限一个list的元素
static void dumpAcl(ACL_vector const& acl, list<string>& info);
///输出节点的信息,一行一个信息项
static void dumpStat(struct Stat const& stat, string& info);
public:
///事件通知,此时所有事件的根api
virtual void onEvent(zhandle_t *t, int type, int state, const char *path);
///连接建立的回调函数,有底层的zk线程调用
virtual void onConnect(){}
///正在建立联系的回调函数,有底层的zk线程调用
virtual void onAssociating(){}
///正在建立连接的回调函数,有底层的zk线程调用
virtual void onConnecting(){}
///鉴权失败的回调函数,有底层的zk线程调用
virtual void onFailAuth(){}
///Session失效的回调函数,有底层的zk线程调用
virtual void onExpired(){}
/**
*@brief watch的node创建事件的回调函数,有底层的zk线程调用。应用于zoo_exists的watch。
*@param [in] zk的watcher的state
*@param [in] path watch的path.
*@return void.
*/
virtual void onNodeCreated(int state, char const* path);
/**
*@brief watch的node删除事件的回调函数,有底层的zk线程调用。应用于 zoo_exists与zoo_get的watch。
*@param [in] zk的watcher的state
*@param [in] path watch的path.
*@return void.
*/
virtual void onNodeDeleted(int state, char const* path);
/**
*@brief watch的node修改事件的回调函数,有底层的zk线程调用。应用于 zoo_exists与zoo_get的watch。
*@param [in] zk的watcher的state
*@param [in] path watch的path.
*@return void.
*/
virtual void onNodeChanged(int state, char const* path);
/**
*@brief watch的node孩子变更事件的回调函数,有底层的zk线程调用。应用于zoo_get_children的watch。
*@param [in] zk的watcher的state
*@param [in] path watch的path.
*@return void.
*/
virtual void onNodeChildChanged(int state, char const* path);
/**
*@brief zk取消某个wathc的通知事件的回调函数,有底层的zk线程调用。
*@param [in] zk的watcher的state
*@param [in] path watch的path.
*@return void.
*/
virtual void onNoWatching(int state, char const* path);
/**
*@brief 其他zookeeper的事件通知回调函数,有底层的zk线程调用。
*@param [in] type的watcher的事件type
*@param [in] zk的watcher的state
*@param [in] path watch的path.
*@return void.
*/
virtual void onOtherEvent(int type, int state, const char *path);
private:
///内部的wacher function
static void watcher(zhandle_t *zzh, int type, int state, const char *path,
void* context);
///内部add auth的function
static void authCompletion(int rc, const void *data);
private:
string m_strHost; ///<The host addresses of ZK nodes.
uint32_t m_uiRecvTimeout; ///<消息接收超时
int m_iAuthState; ///<add auth的完成状态
zhandle_t* m_zkHandle; ///<The current ZK session.
int m_iErrCode; ///<Err code
char m_szErr2K[2048]; ///<Err msg
};
#endif /* __ZK_ADAPTER_H__ */
| true |
248c21c7568ca439b9c80d7895923ec8ecd059cd | C++ | BitRapture/Fite | /TopdownBeatemup/EventManager.h | UTF-8 | 1,035 | 2.78125 | 3 | [] | no_license | #ifndef _EVENTMANAGER_H_
#define _EVENTMANAGER_H_
#include <SDL.h>
class EventManager
{
// Private variables
private:
// Change in x and y movement
int mDeltaX{ 0 }, mDeltaY{ 0 };
// Mouse x and y position
int mMouseX{ 0 }, mMouseY{ 0 };
// Mouse left and right buttons
bool mMouseL{ false }, mMouseR{ false };
// Private methods
private:
// Poll window events
bool PollWindowEv(SDL_Event& _ev);
// Poll input down events
void PollInputDownEv(SDL_Event& _ev);
// Poll input up events
void PollInputUpEv(SDL_Event& _ev);
// Poll mouse motion event
void PollMouseMotionEv(SDL_Event& _ev);
// Poll mouse button down events
void PollMouseButtonDownEv(SDL_Event& _ev);
// Poll mouse button up events
void PollMouseButtonUpEv(SDL_Event& _ev);
// Public methods
public:
// Poll all events
bool Poll();
// Get delta movements
int GetDeltaX();
int GetDeltaY();
// Get mouse positions
int GetMouseX();
int GetMouseY();
// Get mouse buttons
bool GetMouseL();
bool GetMouseR();
// Default CTOR & DTOR
};
#endif | true |
fa0f6500cb1d693492c1c428a8244d29efd9ede0 | C++ | DiegoBanegas/programacion2 | /cicloanidado3/main.cpp | UTF-8 | 1,593 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
/*
ingresar el nombre del alumno,luego debemos de pedir
las tres notas parciales usando un ciclo,presentar el promedio,la nota mayor
de los tres parciales.
Preguntar si desea continuar,al final presentar el nombre del alumnocon la mejor nota.
*/
int main()
{ char nombre[30];
char resp;
int nota,promedio,notamax,suma,alumnomax;
char nombremayor[30];
alumnomax=0;
do
{
cout<<"Nombre del alumno....:";
cin.getline(nombre,30);
suma=0;
notamax=0;
for (int i=1;i<=3;i++)
{
cout<<"Ingresar el parcial "<<i<<"..:";
cin>>nota;
suma+=nota;
if (nota>notamax)
notamax=nota;
}
promedio=suma/3;
cout<<"Presentar Promedio.....:"<<promedio<<"\n";
cout<<"Nota maxima es....:"<<notamax<<"\n";
_flushall();
if (alumnomax<promedio)
{
alumnomax=promedio;
strcpy(nombremayor,nombre);
}
_flushall();
do
{
cout<<"Desea Continuar...:";
cin.get(resp);
_flushall();
}
while ((resp!='N') and (resp!='S'));
}
while (resp!='N');
cout<<"Nombre del alumno con la mejor nota.....:"<<nombremayor;
cout<<" Con la nota"<<alumnomax<<"\n";
return 0;
}
| true |
09665e8e33b867f79fd664013abfa41eccb6496d | C++ | uvbs/gameengine | /Development/Src/LibCommon/ExpressionNode.h | UTF-8 | 2,482 | 2.703125 | 3 | [] | no_license | #ifndef __ZION_EXPRESSION_NODE__
#define __ZION_EXPRESSION_NODE__
namespace Zion
{
namespace Expression
{
class BaseNode;
class Node;
class BaseNode
{
public:
BaseNode(_U32 level);
virtual ~BaseNode();
bool SetParent(Node* pParent, _U32 Index);
virtual _U32 GetChildrenCount();
virtual BaseNode* GetChild(_U32 index);
_U32 GetLevel();
private:
_U32 m_Level;
Node* m_pParent;
_U32 m_Index;
};
class Node : public BaseNode
{
friend class BaseNode;
public:
Node(_U32 level);
virtual ~Node();
virtual _U32 GetChildrenCount();
virtual BaseNode* GetChild(_U32 index);
protected:
bool SetChild(BaseNode* node, _U32& index);
private:
Array<BaseNode*> m_Children;
};
// level 0
class ConstantNode : public BaseNode
{
public:
ConstantNode(const JsonValue& value);
const JsonValue& GetValue();
private:
JsonValue m_Value;
};
class VariantNode : public BaseNode
{
public:
VariantNode(const String& name);
const String& GetName();
private:
String m_Name;
};
class FunctionNode : public Node
{
public:
FunctionNode(const String& name) : Node(0) {}
private:
String m_Name;
};
class NotNode : public Node
{
public:
NotNode();
};
class BracketNode : public Node
{
public:
BracketNode();
};
class ArrayNode : public Node
{
public:
ArrayNode(const String& name);
private:
String m_Name;
};
// level 1
class MultiplyNode : public Node
{
public:
MultiplyNode();
};
class DivideNode : public Node
{
public:
DivideNode();
};
class ModNode : public Node
{
public:
ModNode();
};
// level 2
class AddNode : public Node
{
public:
AddNode();
};
class SubNode : public Node
{
public:
SubNode();
};
// level 3
class EqualNode : public Node
{
public:
EqualNode();
};
class NotEqualNode : public Node
{
public:
NotEqualNode();
};
class GreaterNode : public Node
{
public:
GreaterNode();
};
class LessNode : public Node
{
public:
LessNode();
};
class GreaterEqualNode : public Node
{
public:
GreaterEqualNode();
};
class LessEqualNode : public Node
{
public:
LessEqualNode();
};
// level 4
class AndNode : public Node
{
public:
AndNode();
};
class OrNode : public Node
{
public:
OrNode();
};
//
class RootNode : public BracketNode
{
};
}
}
#endif
| true |
e492aed3295345c861d4498e42628c24f251b266 | C++ | jvastola/Crow-Projects | /Login/test/test.cpp | UTF-8 | 3,700 | 2.765625 | 3 | [] | no_license | #include <igloo/igloo.h>
#include <Authenticator.h>
#include <Database.h>
#include <User.h>
#include <stdio.h>
using namespace igloo;
Context(UserTest){
User user = User("jsoap", "abc123", "Joe", "Soap", "joe@yahoo.com", "123456");
Spec(CanGetUsername){
Assert::That(user.getUsername(), Equals("jsoap"));
}
Spec(CanGetPassword){
Assert::That(user.getPassword(), Equals("abc123"));
}
Spec(CanGetFirstName){
Assert::That(user.getFirstName(), Equals("Joe"));
}
Spec(CanGetLastName){
Assert::That(user.getLastName(), Equals("Soap"));
}
Spec(CanGetEmail){
Assert::That(user.getEmail(), Equals("joe@yahoo.com"));
}
Spec(CanGetToken){
Assert::That(user.getToken(), Equals("123456"));
}
};
Context(DatabaseTest){
Spec(fileExists){
std::string path = "misc/test_db.txt";
std::string wrong = "misc/something.txt";
Database db(path);
Assert::That(db.checkFile(path), IsTrue());
Assert::That(db.checkFile(wrong), IsFalse());
}
Spec(CreateDBFileIfNotExist){
remove("misc/newlyCreated.txt");
std::string wrong = "misc/newlyCreated.txt";
Database db(wrong);
Assert::That(db.checkFile(wrong), IsTrue());
}
Spec(ReadDB){
Database db("misc/test_db.txt");
Database expected;
expected.storage.insert({"angelo", new User("angelo", "abc123", "Angelo", "Kyrilov", "akyrilov@ucmerced.edu", "1a692274-c2c7-4571-8720-286b3ab2cbfe")});
expected.storage.insert({"john", new User("john", "abc123", "John", "Smith", "jsmith@ucmerced.edu", "529bd0bd-06d5-46d8-a465-2e2e166039ee")});
Assert::That(db, Equals(expected));
}
Spec(DatabaseHasKey){
Database db("misc/test_db.txt");
Assert::That(db.hasKey("angelo"), IsTrue());
Assert::That(db.hasKey("trudy"), IsFalse());
}
Spec(DatabaseCanWriteRecords){
Database db;
db.write("angelo", new User("angelo", "abc123", "Angelo", "Kyrilov", "akyrilov@ucmerced.edu", "1a692274-c2c7-4571-8720-286b3ab2cbfe"));
db.write("john", new User("john", "abc123", "John", "Smith", "jsmith@ucmerced.edu", "529bd0bd-06d5-46d8-a465-2e2e166039ee"));
Database expected;
expected.storage.insert({"angelo", new User("angelo", "abc123", "Angelo", "Kyrilov", "akyrilov@ucmerced.edu", "1a692274-c2c7-4571-8720-286b3ab2cbfe")});
expected.storage.insert({"john", new User("john", "abc123", "John", "Smith", "jsmith@ucmerced.edu", "529bd0bd-06d5-46d8-a465-2e2e166039ee")});
Assert::That(db, Equals(expected));
}
Spec(DatabaseGetRecord){
Database db("misc/test_db.txt");
User* expected = new User("angelo", "abc123", "Angelo", "Kyrilov", "akyrilov@ucmerced.edu", "1a692274-c2c7-4571-8720-286b3ab2cbfe");
User* actual = db.get("angelo");
Assert::That(*actual, Equals(*expected));
delete expected;
}
};
Context (AuthenticatorTest){
Spec(AuthenticateRealUser){
Database db("misc/test_db.txt");
Authenticator auth(&db);
ucm::json actual = auth.authenticate("angelo", "abc123");
ucm::json expected;
expected["success"] = true;
expected["token"] = "1a692274-c2c7-4571-8720-286b3ab2cbfe";
Assert::That(actual, Equals(expected));
}
Spec(DenyFakeUser){
Database db("misc/test_db.txt");
Authenticator auth(&db);
ucm::json attempt = auth.authenticate("trudy", "stolen_password");
Assert::That(attempt["success"], IsFalse());
}
Spec(SignupNewUser){
remove("misc/empty.txt");
Database db("misc/empty.txt");
Authenticator auth(&db);
ucm::json response = auth.signup("jane", "abc123", "Jane", "Smith", "jsmith2@ucmerced.edu");
Assert::That(response["success"], IsTrue());
}
Spec(TryToSignupExistingUser){
Database db("misc/empty.txt");
Authenticator auth(&db);
ucm::json response = auth.signup("jane", "abc123", "Jane", "Smith", "jsmith2@ucmerced.edu");
Assert::That(response["success"], IsFalse());
}
};
int main() {
// Run all the tests defined above
return TestRunner::RunAllTests();
}
| true |
2a8cf46a16da9483ee09831fe2d5ece0c884ec74 | C++ | wangzhe17/leetcodeTest | /N_687.cpp | UTF-8 | 593 | 3.296875 | 3 | [] | no_license | class Solution {
public:
int longestUnivaluePath(TreeNode* root)
{
if(!root) return 0;
int res = 0;
helper(root, root, res);
return res;
}
int helper(TreeNode *node, TreeNode *parent, int &res)
{
if(!node) return 0;
int left = helper(node->left, node, res);
int right = helper(node->right, node, res);
left = (node->left && node->val == node->left->val) ? left + 1 : 0;
right = (node->right && node->val == node->right->val) ? right + 1 : 0;
res = max(res, left + right);
return max(left, right);
}
}; | true |
11d4676d1ef7628d39432f5d71691087749d0703 | C++ | platicratic/advent-of-code-2020 | /day 1/main.cpp | UTF-8 | 617 | 3.078125 | 3 | [] | no_license | // Part Two
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("input.in");
ofstream fout("output.out");
void solve() {
vector<int> V;
int number;
while (fin >> number) {
V.push_back(number);
}
for (int i = 0; i < V.size(); i ++) {
for (int j = i + 1; j < V.size(); j ++) {
for (int k = j + 1; k < V.size(); k ++) {
if (V[i] + V[j] + V[k] == 2020) {
fout << V[i] * V[j] * V[k];
return;
}
}
}
}
}
int main()
{
solve();
return 0;
}
| true |
6a54810183600dcc5c07e95863679f381cbc4e34 | C++ | bluepine0808/cppplus | /sales.cpp | UTF-8 | 676 | 3.640625 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int weeklySales, sales1, sales2, sales3;
cout << "Enter the WeeklySales:" << endl;
if (!(cin >> weeklySales)) {
cout << "Please enter the Integer!" << endl;
return 0;
}
cout << "The WeeklySales is : " << weeklySales << endl;
sales1 = 600;
cout << "The choice of Method 1 is: " << "$" << sales1 << endl;
sales2 = 7 * 5 * 8;
sales2 += weeklySales * 0.1;
cout << "The choice of Method 2 is: " << "$" << sales2 << endl;
sales3 = weeklySales * 0.2 + weeklySales/225*0.2;
cout << "The choice of Method 3 is: " << "$" << sales3 << endl;
return 0;
}
| true |
cb63768b602631776a063cb4daef2402ad3ed94b | C++ | kanglanglang/danei | /CSD1404(待补充)/c++(CSD1404,GAJ)/day07/11use_ploy.cpp | UTF-8 | 1,125 | 3.484375 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Animal{
public:
void show(){
cout << "show()" << endl;
}
virtual void run(){
cout << "动物run()" << endl;
}
};
class Dog:public Animal{
public:
/* 函数重写 */
void run(){
cout << "狗用四条腿跑" << endl;
}
/* dog 的个性 */
void dogfun(){
cout << "狗的作用是看家" << endl;
}
};
class Fish:public Animal{
public:
void run(){
cout << "鱼使用鳍在水中游" << endl;
}
};
class Bird:public Animal{
public:
/*void run(){
cout << "鸟用翅膀飞" << endl;
} */
void show(){
cout << "bird show()" << endl;
}
};
/* 类型通用 损失个性 */
void testAnimal(Animal& a){
a.run();
// 恢复个性
}
Animal* getA(int x){
if(0==x){
return new Dog();
}else if(1==x){
return new Fish();
}else{
return new Bird();
}
}
int main(){
Dog dog;
Fish fish;
Bird bird;
testAnimal(dog);
testAnimal(fish);
testAnimal(bird);
Animal *a=getA(0);
a->run();
Animal *aa=getA(2);
aa->run();
}
| true |
4aeeec284eab188cef16355e4be03eea9b41d141 | C++ | snewell/codeeval | /challenge-0005.cpp | UTF-8 | 999 | 3.015625 | 3 | [
"MIT"
] | permissive | #include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
int main(int argc, char ** argv)
{
(void) argc;
std::ifstream input{argv[1]};
std::vector<int> vals;
int val;
input >> val;
while(input)
{
vals.push_back(val);
auto const last = vals.rend();
auto start = vals.rbegin();
std::advance(start, 1);
auto it = std::find(start, last, val);
if(it != last)
{
std::advance(it, 1);
auto first = it.base();
std::cout << *first;
std::advance(first, 1);
std::for_each(first, start.base(), [](int val) {
std::cout << ' ' << val;
});
std::cout << '\n';
vals.erase(std::begin(vals), std::end(vals));
char ch;
input.get(ch);
while(ch != '\n')
{
input.get(ch);
}
}
input >> val;
}
return 0;
}
| true |
7180f26163ca53b2653dd5cf1faf83204fd4d7ed | C++ | suryakiran/CodeSamples | /NG/get-ng-image-title.cpp | UTF-8 | 1,719 | 2.9375 | 3 | [] | no_license | #include<boost/filesystem/path.hpp>
#include <boost/program_options.hpp>
#include <boost/spirit.hpp>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <string>
#include <iostream>
using namespace boost::filesystem ;
using namespace boost::algorithm ;
using namespace boost::spirit ;
using namespace std ;
namespace po = boost::program_options ;
void parse_args (int argc, char** argv)
{
po::options_description desc ("Allowed Options") ;
desc.add_options()
("help", "Show this message")
("html-file", po::value <string>(), "Path to html file")
;
po::variables_map vm ;
try
{
po::store (po::parse_command_line (argc, argv, desc), vm) ;
po::notify (vm) ;
}
catch( std::exception& e)
{
cout << "Exception in reading command line variables: " << e.what() << endl ;
}
if (vm.count ("html-file"))
{
inputFile = vm["html-file"].as<string>() ;
}
}
string get_image_title (const string& s)
{
string ls (s) ;
cout << s << endl ;
ierase_all (ls, "<h3>") ;
ierase_all (ls, "</h3>") ;
cout << ls << endl ;
return ls ;
}
int main (int argc, char** argv)
{
parse_args (argc, argv) ;
if (!inputFile.empty())
{
fstream fin ;
fin.open (inputFile.c_str(), ios_base::in | ios_base::binary) ;
string l;
bool begins (false) ;
while (getline (fin, l, '\n'))
{
trim (l) ;
if (l.empty())
continue ;
if (iequals(l, "<div class=\"summary\">"))
begins = true ;
if (
icontains (l, "buy a print of this photo") ||
icontains (l, "a class=\"previous\"")
)
{
begins = false ;
}
if (!begins)
continue ;
if (istarts_with (l, "<h3>"))
get_image_title (l) ;
}
}
cin.get() ;
return 0 ;
}
| true |
4e2bfa41972c05fc2999f5782e268c30422793aa | C++ | trammell/test | /C++/TICPP-2e-v1/C03/reinterpret_cast.cpp | UTF-8 | 735 | 3.203125 | 3 | [
"Artistic-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | //: C03:reinterpret_cast.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
#include <iostream>
using namespace std;
const int sz = 100;
struct X { int a[sz]; };
void print(X* x) {
for(int i = 0; i < sz; i++)
cout << x->a[i] << ' ';
cout << endl << "--------------------" << endl;
}
int main() {
X x;
print(&x);
int* xp = reinterpret_cast<int*>(&x);
for(int* i = xp; i < xp + sz; i++)
*i = 0;
// Can't use xp as an X* at this point
// unless you cast it back:
print(reinterpret_cast<X*>(xp));
// In this example, you can also just use
// the original identifier:
print(&x);
} ///:~
| true |
ab6431e26264a59cfd22c29a22a0dd1860c18045 | C++ | liuhe3647/serialize | /src/json/encoder.cpp | UTF-8 | 4,402 | 2.65625 | 3 | [] | no_license | #include "json/encoder.h"
#include <assert.h>
namespace serialize {
JSONEncoder::JSONEncoder(std::string& str) : _writer(str) {
}
JSONEncoder::~JSONEncoder() {
}
void JSONEncoder::encodeValue(const char* sz, bool value, bool* pHas) {
_writer.Key(sz);
_writer.Bool(value);
}
void JSONEncoder::encodeValue(const char* sz, uint32_t value, bool* pHas) {
_writer.Key(sz);
_writer.Uint(value);
}
void JSONEncoder::encodeValue(const char* sz, int32_t value, bool* pHas) {
_writer.Key(sz);
_writer.Int(value);
}
void JSONEncoder::encodeValue(const char* sz, uint64_t value, bool* pHas) {
_writer.Key(sz);
_writer.Uint64(value);
}
void JSONEncoder::encodeValue(const char* sz, int64_t value, bool* pHas) {
_writer.Key(sz);
_writer.Int64(value);
}
void JSONEncoder::encodeValue(const char* sz, float value, bool* pHas) {
_writer.Key(sz);
_writer.Double(value);
}
void JSONEncoder::encodeValue(const char* sz, double value, bool* pHas) {
_writer.Key(sz);
_writer.Double(value);
}
void JSONEncoder::encodeValue(const char* sz, const std::string& value, bool* pHas) {
_writer.Key(sz);
_writer.String(value.c_str());
}
void JSONEncoder::encodeValue(const char* sz, const std::vector<bool>& value, bool* pHas) {
_writer.Key(sz);
_writer.StartArray();
int32_t count = (int32_t)value.size();
for (int32_t i = 0; i < count; i++) {
_writer.Bool(value.at(i));
}
_writer.EndArray();
}
void JSONEncoder::encodeValue(const char* sz, const std::vector<uint32_t>& value, bool* pHas) {
_writer.Key(sz);
_writer.StartArray();
int32_t count = (int32_t)value.size();
for (int32_t i = 0; i < count; i++) {
_writer.Uint(value.at(i));
}
_writer.EndArray();
}
void JSONEncoder::encodeValue(const char* sz, const std::vector<int32_t>& value, bool* pHas) {
_writer.Key(sz);
_writer.StartArray();
int32_t count = (int32_t)value.size();
for (int32_t i = 0; i < count; i++) {
_writer.Int(value.at(i));
}
_writer.EndArray();
}
void JSONEncoder::encodeValue(const char* sz, const std::vector<uint64_t>& value, bool* pHas) {
_writer.Key(sz);
_writer.StartArray();
int32_t count = (int32_t)value.size();
for (int32_t i = 0; i < count; i++) {
_writer.Uint64(value.at(i));
}
_writer.EndArray();
}
void JSONEncoder::encodeValue(const char* sz, const std::vector<int64_t>& value, bool* pHas) {
_writer.Key(sz);
_writer.StartArray();
int32_t count = (int32_t)value.size();
for (int32_t i = 0; i < count; i++) {
_writer.Int64(value.at(i));
}
_writer.EndArray();
}
void JSONEncoder::encodeValue(const char* sz, const std::vector<float>& value, bool* pHas) {
_writer.Key(sz);
_writer.StartArray();
int32_t count = (int32_t)value.size();
for (int32_t i = 0; i < count; i++) {
_writer.Double(value.at(i));
}
_writer.EndArray();
}
void JSONEncoder::encodeValue(const char* sz, const std::vector<double>& value, bool* pHas) {
_writer.Key(sz);
_writer.StartArray();
int32_t count = (int32_t)value.size();
for (int32_t i = 0; i < count; i++) {
_writer.Double(value.at(i));
}
_writer.EndArray();
}
void JSONEncoder::encodeValue(const char* sz, const std::vector<std::string>& value, bool* pHas) {
_writer.Key(sz);
_writer.StartArray();
int32_t count = (int32_t)value.size();
for (int32_t i = 0; i < count; i++) {
_writer.String(value.at(i).c_str());
}
_writer.EndArray();
}
void JSONEncoder::StartObject(const char* sz) {
if (sz)
_writer.Key(sz);
_writer.StartObject();
}
void JSONEncoder::EndObject() {
_writer.EndObject();
}
void JSONEncoder::StartArray(const char* sz) {
if (sz)
_writer.Key(sz);
_writer.StartArray();
}
void JSONEncoder::EndArray() {
_writer.EndArray();
}
}
| true |
4a2aba11a1b7374b4d7fdb09dfa903287259a4cc | C++ | Legend94rz/OJCodes | /ACM/[USACO]Twofive_记忆化搜索.cpp | UTF-8 | 1,498 | 2.75 | 3 | [] | no_license | /*
ID: rz109291
PROG: twofive
LANG: C++
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <memory.h>
using namespace std;
char cr;
int N;
int f[6][6][6][6][6];
string W;
char ans[26];
bool ok(int p, char c)
{
return (ans[p] == 0 || ans[p] == c);
}
int dfs(int a, int b, int c, int d, int e, char now)
{
if (now == 'Z')return 1;
if (f[a][b][c][d][e] > 0) return f[a][b][c][d][e];
int res = f[a][b][c][d][e];
if (a < 5 && ok(a, now)) res += dfs(a + 1, b, c, d, e, now + 1);
if (b < a && ok(b + 5, now)) res += dfs(a, b + 1, c, d, e, now + 1);
if (c < b && ok(c + 10, now)) res += dfs(a, b, c + 1, d, e, now + 1);
if (d < c && ok(d + 15, now)) res += dfs(a, b, c, d + 1, e, now + 1);
if (e < d && ok(e + 20, now)) res += dfs(a, b, c, d, e + 1, now + 1);
f[a][b][c][d][e] = res;
return res;
}
int main()
{
freopen("twofive.in", "r", stdin); freopen("twofive.out", "w", stdout);
cin >> cr;
int tmp=0;
if (cr == 'N')
{
cin >> N;
//map int -> string
for (int i = 0; i < 25; i++)
{
for (ans[i] = 'A'; ; ans[i]++)
{
memset(f, 0, sizeof(f));
if ((tmp = dfs(0, 0, 0, 0, 0, 'A')) < N)
N -= tmp;
else
break;
}
}
printf("%s\n", ans);
}
else
{
cin >> W;
//map string -> int
for (int i = 0; i < W.length(); i++)
{
for (ans[i] = 'A'; ans[i]<W[i]; ans[i]++)
{
memset(f, 0, sizeof(f));
tmp += dfs(0, 0, 0, 0, 0, 'A');
}
}
cout << tmp+1 << endl;
}
fclose(stdin); fclose(stdout);
} | true |
e4305ff1552c89ce51c937171a8ba74833ea1e48 | C++ | erestor/ctoolhu | /ctoolhu/thread/async.hpp | UTF-8 | 1,049 | 2.8125 | 3 | [
"MIT"
] | permissive | //----------------------------------------------------------------------------
// Author: Martin Klemsa
//----------------------------------------------------------------------------
#ifndef _ctoolhu_thread_async_included_
#define _ctoolhu_thread_async_included_
#include "pool.hpp"
namespace Ctoolhu::Thread {
//Schedules a job for asynchronous processing by the default thread pool.
//Returns a future for obtaining the result.
//
//Note:
// This is especially useful as a replacement for std::async for Emscripten WebAssembly builds,
// where std::async should be avoided, because the implementation is naive and doesn't use a thread pool.
// Moreover the WebAssembly pthread creation/destruction is flawed and threads/workers can be
// left dangling if the thread lifetime is extremely short (Emscripten 1.38.41).
template <typename Func, typename... Args>
auto Async(Func &&job, Args &&... args)
{
return SinglePool::Instance().submit(std::forward<Func>(job), std::forward<Args>(args)...);
}
} //ns Ctoolhu
#endif //file guard
| true |
89f9aea60d1fd756e19c371b954f634928d89f4d | C++ | jxliu1216/CPP-Primer-Plus | /chapter-5/forloop.cpp | UTF-8 | 579 | 3.234375 | 3 | [] | no_license | /*************************************************************************
> File Name: forloop.cpp
> Descriptions: introducing the forloop
> Compiler: GCC/ G++ (Version 7.3.0)
> Author: Jinxue Liu
> Mail: LiuJinxuepro@163.com
> Created Time: Sat 15 Sep 2018 10:13:08 PM CST
************************************************************************/
#include <iostream>
using namespace std;
int main()
{
int i; // create a integer
// initialize; test and update
for(i=0; i<5; i++)
cout << "C++ knows loop.\n";
cout << "C++ knows when to stop.\n";
return 0;
}
| true |
2007d99821f1a10e1e3ea65aecfbb74a86a38924 | C++ | ristri/Competitive-Programming | /LeetCode/424.cpp | UTF-8 | 489 | 2.859375 | 3 | [] | no_license | class Solution {
public:
int characterReplacement(string s, int k) {
int n = s.length();
vector<int>count(26);
int i = 0, maxCount = 0, maxLength = 0;
for(int j = 0; j < n; j++) {
maxCount = max(maxCount, ++count[s[j] - 'A']);
while(j - i + 1 - maxCount > k) {
count[s[i] - 'A']--;
i++;
}
maxLength = max(maxLength, j - i + 1);
}
return maxLength;
}
};
| true |
97ffe5712f4ecba47aa700c7bffcf5467d0b7070 | C++ | CursosIE/IE-0217-III-16-G0 | /Tarea1LuisDiegoFernandezB22492/Pokemon.cpp | UTF-8 | 543 | 2.953125 | 3 | [] | no_license | #include "Pokemon.h"
Pokemon::Pokemon() {
}
Pokemon::~Pokemon() {
}
string Pokemon::call() {
return cry;
}
//imprime informacion basica general de cualquier pokemon
void Pokemon::printInfo() {
cout << "Nombre: " << name << endl;
cout << "Especie: " << species << endl;
cout << "Estado: " << status << endl;
cout << "Speed: " << SPD << endl;
cout << "Hp: " << HP << endl;
cout << "Special attack: " << sATK << endl;
cout << "Special defense: " << sDEF << endl;
cout << "Experience: " << EXP << endl;
}
| true |
842be17fddfbfbe42c7d070ee504f7a003da858d | C++ | jastadj/john | /src/color.cpp | UTF-8 | 620 | 2.640625 | 3 | [] | no_license | #include "color.hpp"
using namespace tinyxml2;
COLOR loadColorFromXMLNode(XMLNode *tnode)
{
COLOR tcol;
XMLNode *anode = NULL;
anode = tnode->FirstChild();
while(anode != NULL)
{
if(!strcmp(anode->Value(), "bg")) anode->ToElement()->QueryIntText(&tcol.m_Background);
else if(!strcmp(anode->Value(), "fg")) anode->ToElement()->QueryIntText(&tcol.m_Foreground);
else if(!strcmp(anode->Value(), "bold"))
{
if( !strcmp(anode->ToElement()->GetText(), "true")) tcol.m_Bold = true;
}
anode = anode->NextSibling();
}
return tcol;
}
| true |
372e36237b09aa4313355707c3f886aa1557cd16 | C++ | tomasrggm/AVT_Template2 | /AVT_Template1/meshFromAssimp.cpp | ISO-8859-13 | 11,238 | 2.59375 | 3 | [] | no_license | /* --------------------------------------------------
Functions to handle with struct MyMesh based meshes from Assimp meshes:
- import 3D files to Assimp meshes
- creation of Mymesh array with VAO/VBO Geometry and Material
* it supports 3D files with till 2 diffuse textures, 1 specular map and 1 normal map
*
Joo Madeiras Pereira
----------------------------------------------------*/
#include <assert.h>
#include <stdlib.h>
#include <unordered_map>
// assimp include files. These three are usually needed.
#include "assimp/Importer.hpp"
#include "assimp/postprocess.h"
#include "assimp/scene.h"
#include "AVTmathLib.h"
#include "VertexAttrDef.h"
#include "basic_geometry.h"
#include "Texture_Loader.h"
using namespace std;
// Create an instance of the Importer class
Assimp::Importer importer;
// the global Assimp scene object
const aiScene* scene = NULL;
// scale factor for the Assimp model to fit in the window
float scaleFactor;
/* Directory name containing the OBJ file. The OBJ filename should be the same*/
extern char model_dir[50];
// unordered map which maps image filenames to texture units TU. This map is filled in the LoadGLTexturesTUs()
unordered_map<std::string, GLuint> textureIdMap;
#define aisgl_min(x,y) (x<y?x:y)
#define aisgl_max(x,y) (y>x?y:x)
void get_bounding_box_for_node(const aiNode* nd, aiVector3D* min, aiVector3D* max)
{
aiMatrix4x4 prev;
unsigned int n = 0, t;
for (; n < nd->mNumMeshes; ++n) {
const aiMesh* mesh = scene->mMeshes[nd->mMeshes[n]];
for (t = 0; t < mesh->mNumVertices; ++t) {
aiVector3D tmp = mesh->mVertices[t];
min->x = aisgl_min(min->x, tmp.x);
min->y = aisgl_min(min->y, tmp.y);
min->z = aisgl_min(min->z, tmp.z);
max->x = aisgl_max(max->x, tmp.x);
max->y = aisgl_max(max->y, tmp.y);
max->z = aisgl_max(max->z, tmp.z);
}
}
for (n = 0; n < nd->mNumChildren; ++n) {
get_bounding_box_for_node(nd->mChildren[n], min, max);
}
}
void get_bounding_box(aiVector3D* min, aiVector3D* max)
{
min->x = min->y = min->z = 1e10f;
max->x = max->y = max->z = -1e10f;
get_bounding_box_for_node(scene->mRootNode, min, max);
}
bool Import3DFromFile(const std::string& pFile)
{
scene = importer.ReadFile(pFile, aiProcessPreset_TargetRealtime_Quality);
// If the import failed, report it
if (!scene)
{
printf("%s\n", importer.GetErrorString());
return false;
}
// Now we can access the file's contents.
printf("Import of scene %s succeeded.\n", pFile.c_str());
aiVector3D scene_min, scene_max, scene_center;
get_bounding_box(&scene_min, &scene_max);
float tmp;
tmp = scene_max.x - scene_min.x;
tmp = scene_max.y - scene_min.y > tmp ? scene_max.y - scene_min.y : tmp;
tmp = scene_max.z - scene_min.z > tmp ? scene_max.z - scene_min.z : tmp;
scaleFactor = 1.f / tmp;
// We're done. Everything will be cleaned up by the importer destructor
return true;
}
bool LoadGLTexturesTUs(const aiScene* scene) // Create OGL textures objects and maps them to texture units.
{
aiString path; // filename
string filename;
/* scan scene's materials for textures */
for (unsigned int m = 0; m < scene->mNumMaterials; ++m)
{
// o fragment shader suporta material com duas texturas difusas, 1 especular e 1 normal map
for (unsigned int i = 0; i < scene->mMaterials[m]->GetTextureCount(aiTextureType_DIFFUSE); i++) {
scene->mMaterials[m]->GetTexture(aiTextureType_DIFFUSE, i, &path);
filename = model_dir;
filename.append(path.data);
//fill map with textures, OpenGL image ids set to 0
textureIdMap[filename] = 0;
}
for (unsigned int i = 0; i < scene->mMaterials[m]->GetTextureCount(aiTextureType_SPECULAR); i++) {
scene->mMaterials[m]->GetTexture(aiTextureType_SPECULAR, i, &path);
filename = model_dir;
filename.append(path.data);
textureIdMap[filename] = 0;
}
for (unsigned int i = 0; i < scene->mMaterials[m]->GetTextureCount(aiTextureType_NORMALS); i++) {
scene->mMaterials[m]->GetTexture(aiTextureType_NORMALS, i, &path);
filename = model_dir;
filename.append(path.data);
textureIdMap[filename] = 0;
}
}
int numTextures = textureIdMap.size();
printf("numeros de mapas %d\n", numTextures);
GLuint* textureIds = new GLuint[numTextures];
glGenTextures(numTextures, textureIds); /* Texture name generation */
/* get iterator */
unordered_map<std::string, GLuint>::iterator itr = textureIdMap.begin();
filename = (*itr).first; // get filename
//create the texture objects array and asssociate them with TU and place the TU in the key value of the map
for (int i = 0; itr != textureIdMap.end(); ++i, ++itr)
{
filename = (*itr).first; // get filename
glActiveTexture(GL_TEXTURE0 + i);
Texture2D_Loader(textureIds, filename.c_str(), i); //it already performs glBindTexture(GL_TEXTURE_2D, textureIds[i])
(*itr).second = i; // save texture unit for filename in map
//printf("textura = %s TU = %d\n", filename.c_str(), i);
}
//Cleanup
delete[] textureIds;
return true;
}
/// Can't send color down as a pointer to aiColor4D because AI colors are ABGR.
//void Color4f(const aiColor4D *color)
//{
// glColor4f(color->r, color->g, color->b, color->a);
//}
void set_float4(float f[4], float a, float b, float c, float d)
{
f[0] = a;
f[1] = b;
f[2] = c;
f[3] = d;
}
void color4_to_float4(const aiColor4D* c, float f[4])
{
f[0] = c->r;
f[1] = c->g;
f[2] = c->b;
f[3] = c->a;
}
vector<struct MyMesh> createMeshFromAssimp(const aiScene* sc) {
vector<struct MyMesh> myMeshes;
struct MyMesh aMesh;
GLuint buffer;
printf("Cena: numero total de malhas = %d\n", sc->mNumMeshes);
LoadGLTexturesTUs(sc); //it creates the unordered map which maps image filenames to texture units TU
// For each mesh
for (unsigned int n = 0; n < sc->mNumMeshes; ++n)
{
const aiMesh* mesh = sc->mMeshes[n];
// create array with faces
// have to convert from Assimp format to array
unsigned int* faceArray;
faceArray = (unsigned int*)malloc(sizeof(unsigned int) * mesh->mNumFaces * 3);
unsigned int faceIndex = 0;
for (unsigned int t = 0; t < mesh->mNumFaces; ++t) {
const aiFace* face = &mesh->mFaces[t];
memcpy(&faceArray[faceIndex], face->mIndices, 3 * sizeof(unsigned int));
faceIndex += 3;
}
struct MyMesh aMesh;
aMesh.numIndexes = mesh->mNumFaces * 3;
aMesh.type = GL_TRIANGLES;
aMesh.mat.texCount = 0;
// generate Vertex Array for mesh
glGenVertexArrays(1, &(aMesh.vao));
glBindVertexArray(aMesh.vao);
// buffer for faces
glGenBuffers(1, &buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * aMesh.numIndexes, faceArray, GL_STATIC_DRAW);
// buffer for vertex positions
if (mesh->HasPositions()) {
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * mesh->mNumVertices, mesh->mVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(VERTEX_COORD_ATTRIB);
glVertexAttribPointer(VERTEX_COORD_ATTRIB, 3, GL_FLOAT, 0, 0, 0);
}
// buffer for vertex normals
if (mesh->HasNormals()) {
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * mesh->mNumVertices, mesh->mNormals, GL_STATIC_DRAW);
glEnableVertexAttribArray(NORMAL_ATTRIB);
glVertexAttribPointer(NORMAL_ATTRIB, 3, GL_FLOAT, 0, 0, 0);
}
// buffers for vertex tangents and bitangents
if (mesh->HasTangentsAndBitangents()) {
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * mesh->mNumVertices, mesh->mTangents, GL_STATIC_DRAW);
glEnableVertexAttribArray(TANGENT_ATTRIB);
glVertexAttribPointer(TANGENT_ATTRIB, 3, GL_FLOAT, 0, 0, 0);
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * mesh->mNumVertices, mesh->mBitangents, GL_STATIC_DRAW);
glEnableVertexAttribArray(BITANGENT_ATTRIB);
glVertexAttribPointer(BITANGENT_ATTRIB, 3, GL_FLOAT, 0, 0, 0);
}
// buffer for vertex texture coordinates
if (mesh->HasTextureCoords(0)) {
float* texCoords = (float*)malloc(sizeof(float) * 2 * mesh->mNumVertices);
for (unsigned int k = 0; k < mesh->mNumVertices; ++k) {
texCoords[k * 2] = mesh->mTextureCoords[0][k].x;
texCoords[k * 2 + 1] = mesh->mTextureCoords[0][k].y;
}
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 2 * mesh->mNumVertices, texCoords, GL_STATIC_DRAW);
glEnableVertexAttribArray(TEXTURE_COORD_ATTRIB);
glVertexAttribPointer(TEXTURE_COORD_ATTRIB, 2, GL_FLOAT, 0, 0, 0);
}
// unbind buffers
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
// create material; each mesh has ONE material
aiMaterial* mtl = sc->mMaterials[mesh->mMaterialIndex];
aiString texPath; //contains filename of texture
string filename;
GLuint TU;
unsigned int TUcount = 0;
for (unsigned int i = 0; i < mtl->GetTextureCount(aiTextureType_DIFFUSE); i++) {
mtl->GetTexture(aiTextureType_DIFFUSE, i, &texPath);
filename = model_dir;
filename.append(texPath.data);
TU = textureIdMap[filename];
aMesh.texUnits[TUcount] = TU;
aMesh.texTypes[TUcount] = DIFFUSE;
aMesh.mat.texCount = TUcount + 1;
TUcount++;
}
for (unsigned int i = 0; i < mtl->GetTextureCount(aiTextureType_SPECULAR); i++) {
mtl->GetTexture(aiTextureType_SPECULAR, i, &texPath);
filename = model_dir;
filename.append(texPath.data);
TU = textureIdMap[filename];
aMesh.texUnits[TUcount] = TU;
aMesh.texTypes[TUcount] = SPECULAR;
aMesh.mat.texCount = TUcount + 1;
TUcount++;
}
for (unsigned int i = 0; i < mtl->GetTextureCount(aiTextureType_NORMALS); i++) {
mtl->GetTexture(aiTextureType_NORMALS, i, &texPath);
filename = model_dir;
filename.append(texPath.data);
TU = textureIdMap[filename];
aMesh.texUnits[TUcount] = TU;
aMesh.texTypes[TUcount] = NORMALS;
aMesh.mat.texCount = TUcount + 1;
TUcount++;
}
float c[4];
set_float4(c, 0.8f, 0.8f, 0.8f, 1.0f);
aiColor4D diffuse;
if (AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_DIFFUSE, &diffuse))
color4_to_float4(&diffuse, c);
memcpy(aMesh.mat.diffuse, c, sizeof(c));
set_float4(c, 0.2f, 0.2f, 0.2f, 1.0f);
aiColor4D ambient;
if (AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_AMBIENT, &ambient))
color4_to_float4(&ambient, c);
memcpy(aMesh.mat.ambient, c, sizeof(c));
set_float4(c, 0.0f, 0.0f, 0.0f, 1.0f);
aiColor4D specular;
if (AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_SPECULAR, &specular))
color4_to_float4(&specular, c);
memcpy(aMesh.mat.specular, c, sizeof(c));
set_float4(c, 0.0f, 0.0f, 0.0f, 1.0f);
aiColor4D emission;
if (AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_EMISSIVE, &emission))
color4_to_float4(&emission, c);
memcpy(aMesh.mat.emissive, c, sizeof(c));
float shininess = 0.0;
unsigned int max;
aiGetMaterialFloatArray(mtl, AI_MATKEY_SHININESS, &shininess, &max);
aMesh.mat.shininess = shininess;
myMeshes.push_back(aMesh);
}
// cleaning up
textureIdMap.clear();
return(myMeshes);
} | true |
3e283e5e157d788072c2d4ad1137641146589369 | C++ | Abhishek150598/Algorithms_for_cp | /sqrtdec.cpp | UTF-8 | 797 | 2.90625 | 3 | [] | no_license | //Square root decomposition
#include<bits/stdc++.h>
#define max 1000000
#define maxsqrt 1000
using namespace std;
int arr[max];
int block[maxsqrt];
int block_size;
void update(int index, int value)
{
int block_no=index/block_size;
block[block_no]=block[block_no]-arr[index]+value;
arr[index]=value;
}
int query(int l,int r)
{
int sum=0;
while(l<=r&&l%block_size!=0)
{
sum=sum+arr[l];
l++;
}
while(l+block_size<=r)
{
sum=sum+block[l/block_size];
l=l+block_size;
}
while(l<=r)
{
sum=sum+arr[l];
l++;
}
return sum;
}
void preprocess(int *input, int n)
{
block_size=sqrt(n);
int j=-1;
for(int i=0;i<n;i++)
{
arr[i]=input[i];
if(i%block_size==0)
{
j++;
block[j]=0;
}
block[j]+=arr[i];
}
}
| true |
d9bc2a8ea0945f6a769abd7a6d47060cee8d20be | C++ | StarkShang/Projects | /Check/v0.0.3/Release/cells/2016/5140729048/L51/L01/func.hpp | UTF-8 | 1,076 | 3.5 | 4 | [] | no_license | /*******************************************
* STUDENT结构体
* int类型成员 : 学号id
* char[1024]数组类型成员 : 姓名name
* double[3]数组类型成员 : 三门课成绩course
*******************************************/
struct STUDENT
{
int id;
char name[1024];
double course[3];//根据要求定义变量
};
/***************************************
* 计算各门课平均成绩及最高成绩
* 输入 : 学生数组指针stu
* 输入 : 学生数组大小size
* 输出 : 各门课平均成绩数组指针average
* 输出 : 各门课最高成绩数组指针high
***************************************/
void func(STUDENT* stu, int size, double* average, double* high)
{
int i=0;
for(i=0;i<size;i++)//逐个赋值
{
* (average+i)=((* (stu+i)).course[0]+(* (stu+i)).course[1]+(* (stu+i)).course[2])/3;//平均分
if((* (stu+i)).course[0]>=(* (stu+i)).course[1]) * (high+i)=(* (stu+i)).course[0];
else * (high+i)=(* (stu+i)).course[1];
if(* (high+i)<=(* (stu+i)).course[2]) * (high+i)=(* (stu+i)).course[2];
else 1;//选出最高分
}
} | true |
ce10f94816fb86f0e7ff0f8f646177f567603659 | C++ | calmdan/MyLeetcode | /Median of Two Sorted Arrays.cpp | UTF-8 | 7,047 | 3.453125 | 3 | [] | no_license | //============================================================================
// There are two sorted arrays A and B of size m and n respectively. Find the
// median of the two sorted arrays. The overall run time complexity should be
// O(log (m+n)).
//============================================================================
#include <iostream>
#include <climits>
#include <cassert>
using namespace std;
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
return findMedianSortedArrays1(A, m, B, n);
//O(m+n)
double findMedianSortedArrays1(int A[], int m, int B[], int n) {
int i = 0, j = 0;
int m1 = -1, m2 = -1;
int s = (m + n) / 2;
while (s >= 0) {
int a = (i < m) ? A[i] : INT_MAX;
int b = (j < n) ? B[j] : INT_MAX;
m1 = m2;
if (a < b) {
m2 = a;
i++;
}
else {
m2 = b;
j++;
}
s--;
}
if ((m + n) % 2 == 0) return (m1 + m2) / 2.0;
return m2;
};
//O(log(m+n))
double findMedianSortedArrays2(int A[], int m, int B[], int n) {
return findMedianHelper2(A, m, B, n, max(0, (m-n)/2), min(m-1, (m+n)/2));
};
double findMedianHelper2(const int A[], const int m, const int B[], const int n, const int l, const int r) {
if (l > r) return findMedianHelper2(B, n, A, m, max(0, (n-m)/2), min(n-1, (m+n)/2));
int i = (l+r)/2;
int j = (m+n)/2-i;
assert(i >= 0 && i <= m && j >= 0 && j <= n);
int Ai_1 = ((i == 0) ? INT_MIN : A[i-1]);
int Bj_1 = ((j == 0) ? INT_MIN : B[j-1]);
int Ai = ((i == m) ? INT_MAX : A[i]);
int Bj = ((j == n) ? INT_MAX : B[j]);
if (Ai < Bj_1) return findMedianHelper2(A, m, B, n, i+1, r);
if (Ai > Bj) return findMedianHelper2(A, m, B, n, l, i-1);
if (((m+n) % 2) == 1) return A[i];
return (max(Ai_1, Bj_1) + Ai) / 2.0;
};
};
//k-th number of two sorted arrays
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int total = n + m;
if (total % 2 == 0) {
return (findKth(A, m, B, n, total/2) + findKth(A, m, B, n, total / 2 + 1)) / 2;
}
else
return findKth(A, m, B, n, total / 2 + 1);
}
double findKth(int a[], int m, int b[], int n, int k) {
if (m > n) return findKth(b, n, a, m, k);
if (m == 0) return b[k-1];
if (k == 1) return min(a[0], b[0]);
int ia = min(k/2, m);
int ib = k - ia;
if (a[ia-1] < b[ib-1]) return findKth(a+ia, m - ia, b, n, k - ia);
else if (a[ia-1] > b[ib-1]) return findKth(a, m, b+ib, n - ib, k - ib);
else return a[ia-1];
}
};
//best solution
double MedianOfFour (int a, int b, int c, int d)
{
int minValue = min (d, min (a, min (b,c) ) );
int maxValue = max (d, max (a, max (b,c) ) );
return (a + b + c + d - minValue - maxValue) / 2.0 ;
}
double MedianOfThree (int a, int b, int c)
{
int minValue = min (a, min (b,c) ) ;
int maxValue = max (a, max (b,c) ) ;
return (a + b + c - minValue - maxValue);
}
//constraint : n <= m
double MedianSortedArrays (int A[MAX], int n, int B[MAX], int m)
{
//base case # 1
if ( n == 1 )
{
if ( m == 1 )
return (A[0] + B[0]) / 2.0;
if ( m % 2 == 1)
return ( B[m/2] + MedianOfThree (A[0], B[m/2-1], B[m/2+1]) ) / 2.0 ;
else
return MedianOfThree ( A[0], B[m/2-1], B[m/2] );
}
//base case # 2
if ( n == 2 )
{
if ( m == 2 )
return MedianOfFour (A[0], A[1], B[0], B[1]);
if ( m % 2 == 1 )
return MedianOfThree ( B[m/2], min(A[0], B[m/2+1]), max (A[1], B[m/2-1]) ) ;
else
return MedianOfFour ( B[m/2-1], B[m/2], min(A[0], B[m/2+1]), max(A[1], B[m/2-2]) );
}
int minRemoved, idxA = n/2 , idxB = m/2 ;
if ( A[idxA] < B[idxB] )
{
if ( n % 2 == 0 ) --idxA; //for even number of elements --idxA points to lower median of A[]
minRemoved = min ( idxA, m - idxB - 1) ;
return MedianSortedArrays ( A + minRemoved, n - minRemoved, B, m - minRemoved);
}
else
{
if ( m % 2 == 0 ) --idxB; //for even number of elements --idxB points to lower median of B[]
minRemoved = min ( n - idxA - 1, idxB) ;
return MedianSortedArrays ( A, n - minRemoved, B + minRemoved, m - minRemoved);
}
}
//my solution
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(m==0) return n%2==0?(B[(n-1)/2]+B[(n-1)/2+1])/2.0:B[(n-1)/2];
if(n==0) return m%2==0?(A[(m-1)/2]+A[(m-1)/2+1])/2.0:A[(m-1)/2];
if(m>=n) return findRec(A,m,B,n);
return findRec(B,n,A,m);
}
double MedianOfFour (int a, int b, int c, int d)
{
int minValue = min (d, min (a, min (b,c) ) );
int maxValue = max (d, max (a, max (b,c) ) );
return (a + b + c + d - minValue - maxValue) / 2.0 ;
}
double MedianOfThree (int a, int b, int c)
{
int minValue = min (a, min (b,c) ) ;
int maxValue = max (a, max (b,c) ) ;
return (a + b + c - minValue - maxValue);
}
double findRec(int A[], int m, int B[], int n)
{
if(n==1)
{
if(m==1) return (A[0]+B[0])/2.0;
if(m%2==0) return MedianOfThree(B[0],A[(m-1)/2],A[(m-1)/2+1]);
else return MedianOfFour(B[0],A[(m-1)/2],A[(m-1)/2+1],A[(m-1)/2-1]);
}
else if(n==2)
{
if(m==2) return MedianOfFour(A[0],A[1],B[0],B[1]);
else if(m%2==0) return MedianOfFour(A[(m-1)/2],A[(m-1)/2+1],max(A[(m-1)/2-1],B[0]),min(A[(m-1)/2+2],B[1]));
else return MedianOfThree(A[(m-1)/2],max(A[(m-1)/2-1],B[0]),min(A[(m-1)/2+1],B[1]));
}
double m1 = A[(m-1)/2];
double m2 = B[(n-1)/2];
if(m1==m2)
{
if(m%2==0 && n%2==0)
{
double t1 = A[(m-1)/2+1];
double t2 = B[(n-1)/2+1];
return t1>t2?(m1+t2)/2:(m1+t1)/2;
}
else return m1;
}
else if(m1>m2)
{
return findRec(A,m-(n-1)/2,B+(n-1)/2,n-(n-1)/2);
}
else
{
return findRec(A+(n-1)/2,m-(n-1)/2,B,n-(n-1)/2);
}
}
};
| true |
c37afdff79ccec395737bf34d0be973468a7ffae | C++ | emd22/arch-engine | /Game/ModelLoaders/ObjLoader.cpp | UTF-8 | 4,329 | 3.203125 | 3 | [] | no_license | #include "ObjLoader.h"
#include "../Math/vector2.h"
#include "../Math/vector3.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
void Split(const std::string &s, char delim, std::vector<std::string> &elems)
{
std::stringstream ss;
ss.str(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
}
std::vector<std::string> Split(const std::string &s, char delim)
{
std::vector<std::string> elems;
Split(s, delim, elems);
return elems;
}
static inline std::string &LeftTrim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(),
std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
static inline std::string &RightTrim(std::string &s)
{
s.erase(std::find_if(s.rbegin(), s.rend(),
std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
static inline std::string &Trim(std::string &s)
{
return LeftTrim(RightTrim(s));
}
static std::vector<std::string> RemoveEmpty(const std::vector<std::string> &strings)
{
std::vector<std::string> res;
for (auto &&str : strings) {
if (!str.empty()) {
res.push_back(str);
}
}
return res;
}
struct ObjFace {
unsigned int vertex;
unsigned int normal;
unsigned int texcoord;
};
ObjFace ParseObjIndex(const std::string &token)
{
auto tokens = Split(token, '/');
ObjFace res;
if (!tokens.empty()) {
res.vertex = std::stoi(tokens[0]) - 1;
if (tokens.size() > 1) {
if (!tokens[1].empty()) {
res.texcoord = std::stoi(tokens[1]) - 1;
}
if (tokens.size() > 2) {
if (!tokens[2].empty()) {
res.normal = std::stoi(tokens[2]) - 1;
}
}
}
}
return res;
}
std::shared_ptr<Mesh> ObjLoader::LoadMesh(const std::string &path)
{
std::vector<Vector3> positions;
std::vector<Vector3> normals;
std::vector<Vector2> texcoords;
std::vector<ObjFace> obj_faces;
std::ifstream file;
file.open(path);
if (!file.is_open()) {
std::cout << "Invalid file: " << path << ".\n";
return nullptr;
}
std::string line;
while (std::getline(file, line)) {
// check to make sure it is not a comment
if (line[0] != '#') {
// tokens are separated by spaces
auto tokens = Split(line, ' ');
if (!tokens.empty()) {
tokens = RemoveEmpty(tokens);
if (tokens[0] == "v") { // vertex position
Vector3 pos;
// read x
pos.x = std::stof(tokens[1]);
// read y
pos.y = std::stof(tokens[2]);
// read z
pos.z = std::stof(tokens[3]);
// add to list of positions
positions.push_back(pos);
} else if (tokens[0] == "vn") { // vertex normal
Vector3 norm;
// read x
norm.x = std::stof(tokens[1]);
// read y
norm.y = std::stof(tokens[2]);
// read z
norm.z = std::stof(tokens[3]);
// add to list of normals
normals.push_back(norm);
} else if (tokens[0] == "vt") { // vertex texture coordinate
Vector2 texcoord;
// read s
texcoord.x = std::stof(tokens[1]);
// read t
texcoord.y = std::stof(tokens[2]);
// add to list of texture coordinates
texcoords.push_back(texcoord);
} else if (tokens[0] == "f") {
for (int i = 0; i < tokens.size() - 3; i++) {
obj_faces.push_back(ParseObjIndex(tokens[1]));
obj_faces.push_back(ParseObjIndex(tokens[2 + i]));
obj_faces.push_back(ParseObjIndex(tokens[3 + i]));
}
}
}
}
}
const bool has_normals = !normals.empty();
const bool has_texcoords = !texcoords.empty();
std::vector<Vertex> final_vertices;
for (auto face : obj_faces) {
Vertex vertex;
// get the position
Vector3 pos = positions[face.vertex];
vertex.x = pos.x;
vertex.y = pos.y;
vertex.z = pos.z;
// get the texcoord (if there is one)
if (has_texcoords) {
Vector2 texcoord = texcoords[face.texcoord];
vertex.s = texcoord.x;
vertex.t = texcoord.y;
}
// get the normal (if there is one)
if (has_normals) {
Vector3 norm = normals[face.normal];
vertex.nx = norm.x;
vertex.ny = norm.y;
vertex.nz = norm.z;
}
final_vertices.push_back(vertex);
}
std::vector<unsigned int> final_faces;
for (size_t i = 0; i < final_vertices.size(); i++) {
final_faces.push_back(i);
}
return std::make_shared<Mesh>(final_vertices, final_faces);
} | true |
0c2958cdfcb0a456d87813c9834139cce2bfe1d8 | C++ | joe2hpimn/dg16.oss | /orca/gpos/libgpos/include/gpos/common/CSyncHashtableIter.h | UTF-8 | 2,939 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2011 EMC Corp.
//
// @filename:
// CSyncHashtableIter.h
//
// @doc:
// Iterator for allocation-less static hashtable; this class encapsulates
// the state of iteration process (the current bucket we iterate through
// and iterator position); it also allows advancing iterator's position
// in the hash table; accessing the element at current iterator's
// position is provided by the iterator's accessor class.
//
// Since hash table iteration/insertion/deletion can happen concurrently,
// the semantics of iteration output are defined as follows:
// - the iterator sees all elements that have not been removed; if
// any of them are removed concurrently, we may or may not see them
// - New elements may or may not be seen
// - No element is returned twice
//
//
// @owner:
//
// @test:
//
//
//---------------------------------------------------------------------------
#ifndef GPOS_CSyncHashtableIter_H
#define GPOS_CSyncHashtableIter_H
#include "gpos/base.h"
#include "gpos/common/clibwrapper.h"
#include "gpos/common/CSyncHashtable.h"
#include "gpos/common/CSyncHashtableAccessByIter.h"
namespace gpos
{
//---------------------------------------------------------------------------
// @class:
// CSyncHashtableIter<T, K, S>
//
// @doc:
// Iterator class has to know all template parameters of
// the hashtable class in order to link to a target hashtable.
//
//---------------------------------------------------------------------------
template <class T, class K, class S>
class CSyncHashtableIter
{
// iterator accessor class is a friend
friend class CSyncHashtableAccessByIter<T, K, S>;
private:
// target hashtable
CSyncHashtable<T, K, S> &m_ht;
// index of bucket to operate on
ULONG m_ulBucketIndex;
// a slab of memory to manufacture an invalid element; we enforce
// memory alignment here to mimic allocation of a class object
ALIGN_STORAGE BYTE m_rgInvalid[sizeof(T)];
// a pointer to memory slab to interpret it as invalid element
T *m_ptInvalid;
// no copy ctor
CSyncHashtableIter<T, K, S>(const CSyncHashtableIter<T, K, S>&);
// inserts invalid element at the head of current bucket
void InsertInvalidElement();
// advances invalid element in current bucket
void AdvanceInvalidElement();
// a flag indicating if invalid element is currently in the hash table
BOOL m_fInvalidInserted;
public:
// ctor
explicit
CSyncHashtableIter<T, K, S>(CSyncHashtable<T, K, S> &ht);
// dtor
~CSyncHashtableIter<T, K, S>();
// advances iterator
BOOL FAdvance();
// rewinds the iterator to the beginning
void RewindIterator();
}; // class CSyncHashtableIter
}
// include implementation
#include "gpos/common/CSyncHashtableIter.inl"
#endif // !GPOS_CSyncHashtableIter_H
// EOF
| true |
8fa81b5eed651bab490b3074d71a5e867e5caf8d | C++ | Ivanhan2018/zsbbserver | /src/computinghurt/skills.cpp | GB18030 | 10,984 | 2.78125 | 3 | [] | no_license | // @brief ϵͳΪܣܣܣ
// @author
#include "skills.h"
namespace
{
static bool isInRange(computinghurt::IRandomGenerator* randomGenerator, unsigned int probability)
{
MY_ASSERT(randomGenerator != 0, "randomGenerator == 0");
if (randomGenerator == 0 )
return false;
int random = randomGenerator->generator(1, 100);
return static_cast<unsigned int>(random) <= probability;
}
} // namespace
COMPUTINGHURT_NAMESPACE_BEGIN
AttackSkill::AttackSkill(const SkillInfo& skillInfo, IRandomGenerator* randomGenerator)
:skillInfo_(skillInfo), randomGenerator_(randomGenerator)
{
}
AttackSkill::AttackSkill()
{
skillInfo_.skillAndGradeStru.id = SKILLID_INVALID;
skillInfo_.effectType = INVALID_EFFECT;
}
AttackReleaseInfo AttackSkill::newAttackReleaseInfo(SKILL_TYPE id, EFFECT_TYPE effectType, const std::set<SOLDIER_TYPE> & otherOccupation, double effectVal)
{
AttackReleaseInfo attackInfo(new AttackOrDefendReleaseInfoValue);
attackInfo->skillId = id;
attackInfo->effectType = effectType;
attackInfo->otherOccupation = otherOccupation;
attackInfo->effectVal = effectVal;
return attackInfo;
}
//, double& factor, bool& isNothinking, bool& isAttackAll, int& additionalHurt
// @param hurt ˺ֵ
// @param isNothinking Ƿӷ
// @param isAttackAll Ƿȫ
// @return Ƿɹ, -1, ɹδ
AttackReleaseInfo AttackSkill::release(const IArmy* selfArmy, const SOLDIER_TYPE armyType) const
{
LAND_FORM landForm = selfArmy->getLandForm();
std::set<SOLDIER_TYPE>::const_iterator itFindZero = skillInfo_.objectOccupation.find(SOLDIERTYPE_NONE);
std::set<SOLDIER_TYPE>::const_iterator it = skillInfo_.objectOccupation.find(armyType);
if((itFindZero != skillInfo_.objectOccupation.end() || it != skillInfo_.objectOccupation.end())
&& (landForm == skillInfo_.landForm || LAND_INVALID == skillInfo_.landForm))
{
return newAttackReleaseInfo(skillInfo_.skillAndGradeStru.id, skillInfo_.effectType, skillInfo_.otherOccupation, skillInfo_.effectVal);
}
std::set<SOLDIER_TYPE> otherOccupation;
otherOccupation.insert(SOLDIERTYPE_NONE);
return newAttackReleaseInfo(SKILLID_INVALID, INVALID_EFFECT, otherOccupation, 0.0);
}
bool AttackSkill::isCanRelease() const
{
return isInRange(randomGenerator_, this->skillInfo_.probability);
}
SKILL_TYPE AttackSkill::getSkillType() const
{
return skillInfo_.skillAndGradeStru.id;
}
void AttackSkill::upgrade(const SkillInfo& skillInfo)
{
//
//MY_ASSERT(skillInfo_.skillAndGradeStru.level < skillInfo.skillAndGradeStru.level, "(*it).level >= skillInfo.level");
skillInfo_.probability = skillInfo.probability;
skillInfo_.skillAndGradeStru.level = skillInfo.skillAndGradeStru.level;
}
//////////////////////////////////////////////////////////////////////////
DefenceSkill::DefenceSkill(const SkillInfo& skillinfo, IRandomGenerator* randomGenerator)
:skillInfo_(skillinfo),randomGenerator_(randomGenerator)
{
}
DefenceSkill::DefenceSkill()
{
skillInfo_.skillAndGradeStru.id = SKILLID_INVALID;
skillInfo_.effectType = INVALID_EFFECT;
}
// @param defense ֵ
// @param isNothinking Ƿӷ
// @return Ƿɹ, -1, ɹδ
DefendReleaseInfo DefenceSkill::release(const IArmy* selfArmy, const SOLDIER_TYPE& armyType) const
{
LAND_FORM landForm = selfArmy->getLandForm();
std::set<SOLDIER_TYPE>::const_iterator itFindZero = skillInfo_.objectOccupation.find(SOLDIERTYPE_NONE);
std::set<SOLDIER_TYPE>::const_iterator it = skillInfo_.objectOccupation.find(armyType);
if((itFindZero != skillInfo_.objectOccupation.end() || it != skillInfo_.objectOccupation.end())
&& (landForm == skillInfo_.landForm || LAND_INVALID == skillInfo_.landForm))
{
return newDefendReleaseInfo(skillInfo_.skillAndGradeStru.id, skillInfo_.effectType, skillInfo_.otherOccupation, skillInfo_.effectVal);
}
std::set<SOLDIER_TYPE> otherOccupation;
otherOccupation.insert(SOLDIERTYPE_NONE);
return newDefendReleaseInfo(SKILLID_INVALID, INVALID_EFFECT, otherOccupation, 0.0);
}
bool DefenceSkill::isCanRelease() const
{
return isInRange(randomGenerator_, this->skillInfo_.probability);
}
SKILL_TYPE DefenceSkill::getSkillType() const
{
return skillInfo_.skillAndGradeStru.id;
}
void DefenceSkill::upgrade(const SkillInfo& skillInfo)
{
//
MY_ASSERT(skillInfo_.skillAndGradeStru.level < skillInfo.skillAndGradeStru.level, "(*it).level >= skillInfo.level");
skillInfo_.probability = skillInfo.probability;
skillInfo_.skillAndGradeStru.level = skillInfo.skillAndGradeStru.level;
}
DefendReleaseInfo DefenceSkill::newDefendReleaseInfo(SKILL_TYPE id, EFFECT_TYPE effectType, const std::set<SOLDIER_TYPE> &otherOccupation, double effectVal)
{
DefendReleaseInfo defendInfo(new AttackOrDefendReleaseInfoValue);
defendInfo->skillId = id;
defendInfo->effectType = effectType;
defendInfo->otherOccupation = otherOccupation;
defendInfo->effectVal = effectVal;
return defendInfo;
}
//////////////////////////////////////////////////////////////////////////
CatchOrPlasterSkill::CatchOrPlasterSkill(const SkillInfo& skillinfo, IRandomGenerator* randomGenerator)
:skillInfo_(skillinfo),randomGenerator_(randomGenerator)
{
}
// @return Ƿɹ
bool CatchOrPlasterSkill::release(const IArmy* selfArmy, const SOLDIER_TYPE armyType, int catchHeroRate, int basicBeCapturedRate) const
{
if(Chatch_Hero == skillInfo_.skillAndGradeStru.id
|| PLASTER == skillInfo_.skillAndGradeStru.id)
{
LAND_FORM landForm = selfArmy->getLandForm();
std::set<SOLDIER_TYPE>::const_iterator itFindZero = skillInfo_.objectOccupation.find(SOLDIERTYPE_NONE);
std::set<SOLDIER_TYPE>::const_iterator it = skillInfo_.objectOccupation.find(armyType);
if((itFindZero != skillInfo_.objectOccupation.end() || it != skillInfo_.objectOccupation.end())
&& (landForm == skillInfo_.landForm || LAND_INVALID == skillInfo_.landForm))
{
if (skillInfo_.probability / 100 * basicBeCapturedRate + catchHeroRate >= 100)
{
#ifdef _DEBUG
assert(0 && "ʴڵ100");
#endif
return true;
}
return isInRange(randomGenerator_, skillInfo_.probability / 100 * basicBeCapturedRate + catchHeroRate);
}
}
return false;
}
bool CatchOrPlasterSkill::canRelease() const
{
return isInRange(randomGenerator_, this->skillInfo_.probability);
}
SKILL_TYPE CatchOrPlasterSkill::getSkillType() const
{
return skillInfo_.skillAndGradeStru.id;
}
void CatchOrPlasterSkill::upgrade(const SkillInfo& skillInfo)
{
const SkillAndGradeStru &skillAndGradeStru = skillInfo.skillAndGradeStru;
SkillAndGradeStru &skillAndGradeStru_ = skillInfo_.skillAndGradeStru;
MY_ASSERT(skillAndGradeStru.id == skillAndGradeStru_.id, "IJIDͬ");
//
MY_ASSERT(skillAndGradeStru_.level < skillAndGradeStru.level, "(*it).level >= skillInfo.level");
skillAndGradeStru_.level = skillAndGradeStru.level;
skillInfo_.probability = skillInfo.probability;
}
//////////////////////////////////////////////////////////////////////////
GlorySkill::GlorySkill(const SkillInfo& skillInfo, IRandomGenerator* /*randomGenerator*/)
:skillInfo_(skillInfo)
{
}
GlorySkill::GlorySkill()
{
skillInfo_.skillAndGradeStru.id = SKILLID_INVALID;
skillInfo_.effectType = INVALID_EFFECT;
}
double GlorySkill::getAttackFactor(SOLDIER_TYPE armyType, SOLDIER_TYPE enemyType, LAND_FORM landForm) const
{
if (PERCENT_DEFEND_EFFECT == skillInfo_.effectType
|| PERCENT_ATT_DEF_EFFECT == skillInfo_.effectType)
{
return 0.0;
}
std::set<SOLDIER_TYPE>::const_iterator itFindZero = skillInfo_.objectOccupation.find(SOLDIERTYPE_NONE);
std::set<SOLDIER_TYPE>::const_iterator itFindArmy = skillInfo_.objectOccupation.find(armyType);
bool isFind = false;
std::set<SOLDIER_TYPE>::const_iterator itFind = skillInfo_.otherOccupation.find(enemyType);
if (skillInfo_.otherOccupation.end() != itFind)
{
isFind = true;
}
else
{
itFind = skillInfo_.otherOccupation.find(SOLDIERTYPE_NONE);
if (skillInfo_.otherOccupation.end() != itFind)
{
isFind = true;
}
}
if ((itFindZero != skillInfo_.objectOccupation.end() || itFindArmy!=skillInfo_.objectOccupation.end())
&& isFind
&& (landForm == skillInfo_.landForm || LAND_INVALID == skillInfo_.landForm))
{
return skillInfo_.effectVal;
}
return 0.0;
}
double GlorySkill::getAttDefFactor(SOLDIER_TYPE armyType, SOLDIER_TYPE enemyType, LAND_FORM landForm) const
{
if (PERCENT_ATT_DEF_EFFECT != skillInfo_.effectType)
{
return 0.0;
}
std::set<SOLDIER_TYPE>::const_iterator itFindZero = skillInfo_.objectOccupation.find(SOLDIERTYPE_NONE);
std::set<SOLDIER_TYPE>::const_iterator itFindArmy = skillInfo_.objectOccupation.find(armyType);
bool isFind = false;
std::set<SOLDIER_TYPE>::const_iterator itFind = skillInfo_.otherOccupation.find(enemyType);
if (skillInfo_.otherOccupation.end() != itFind)
{
isFind = true;
}
else
{
itFind = skillInfo_.otherOccupation.find(SOLDIERTYPE_NONE);
if (skillInfo_.otherOccupation.end() != itFind)
{
isFind = true;
}
}
if ((itFindZero != skillInfo_.objectOccupation.end() || itFindArmy!=skillInfo_.objectOccupation.end())
&& isFind
&& (landForm == skillInfo_.landForm || LAND_INVALID == skillInfo_.landForm))
{
return skillInfo_.effectVal;
}
return 0.0;
}
double GlorySkill::getDefenseFactor(SOLDIER_TYPE armyType, SOLDIER_TYPE enemyType, LAND_FORM landForm) const
{
if (PERCENT_ATTACK_EFFECT == skillInfo_.effectType
|| PERCENT_ATT_DEF_EFFECT == skillInfo_.effectType)
{
return 0.0;
}
std::set<SOLDIER_TYPE>::const_iterator itFindZero = skillInfo_.objectOccupation.find(SOLDIERTYPE_NONE);
std::set<SOLDIER_TYPE>::const_iterator itFindArmy = skillInfo_.objectOccupation.find(armyType);
bool isFind = false;
std::set<SOLDIER_TYPE>::const_iterator itFind = skillInfo_.otherOccupation.find(enemyType);
if (skillInfo_.otherOccupation.end() != itFind)
{
isFind = true;
}
else
{
itFind = skillInfo_.otherOccupation.find(SOLDIERTYPE_NONE);
if (skillInfo_.otherOccupation.end() != itFind)
{
isFind = true;
}
}
if ((itFindZero != skillInfo_.objectOccupation.end() || itFindArmy!=skillInfo_.objectOccupation.end())
&& isFind
&& (landForm == skillInfo_.landForm || LAND_INVALID == skillInfo_.landForm))
{
if (skillInfo_.effectVal >= 1)
{
return 0.98;
}
return skillInfo_.effectVal;
}
return 0.0;
}
SKILL_TYPE GlorySkill::getSkillType() const
{
return skillInfo_.skillAndGradeStru.id;
}
double GlorySkill::getEffectVal() const
{
return skillInfo_.effectVal;
}
void GlorySkill::upgrade(const SkillInfo& skillInfo)
{
//
MY_ASSERT(skillInfo_.skillAndGradeStru.level < skillInfo.skillAndGradeStru.level, "(*it).level >= skillInfo.level");
skillInfo_.probability = skillInfo.probability;
skillInfo_.skillAndGradeStru.level = skillInfo.skillAndGradeStru.level;
}
COMPUTINGHURT_NAMESPACE_END
| true |
992a32e6a5ddec9c55ede4411e7da15e973108f6 | C++ | dagil02/TaxiRevengeDLC | /GTT/EnemyPool.h | UTF-8 | 836 | 2.640625 | 3 | [] | no_license | #pragma once
#include "GameObject.h"
#pragma once
#include "GameObject.h"
#include "Enemy.h"
#include <vector>
class EnemyPool :public GameObject
{
public:
EnemyPool(EnemyPool&) = delete;
EnemyPool& operator=(const EnemyPool&) = delete;
static EnemyPool* GetInstance() {
if (instance_ == nullptr) {
instance_ = new EnemyPool();
}
return instance_;
}
inline static void destroyInstance() {
delete instance_; instance_ = nullptr;
}
virtual void update(Uint32 time);
virtual void render(Uint32 time);
virtual void handleInput(Uint32 time, const SDL_Event& event) {};
virtual Enemy* addEnemy(Vector2D pos, Vector2D vel, ProyectileInfo prType);
virtual ~EnemyPool();
private:
EnemyPool();
static const int MAXENEMIES = 100;
Enemy enemies_[MAXENEMIES];
Enemy* getUnusedEnemy();
static EnemyPool* instance_;
};
| true |
51476a5ceed3f9b74aef54f12a97202e9b64aaa6 | C++ | SJ-Innovation/TeensyVive | /src/SensorNode.cpp | UTF-8 | 4,200 | 2.71875 | 3 | [] | no_license | //
// Created by Sam Lane on 10/02/2018.
//
#include "SensorNode.h"
#include "config.h"
void SensorNode::SetLEDState(int LEDState) {
static int CurrentLEDState = LED_OFF;
if (LEDState != CurrentLEDState) {
switch (LEDState) {
case LED_OFF:
pinMode(_PinData.LED1Pin, INPUT);
pinMode(_PinData.LED2Pin, INPUT);
digitalWrite(_PinData.LED1Pin, LOW);
digitalWrite(_PinData.LED2Pin, LOW);
break;
case LED_RED:
pinMode(_PinData.LED1Pin, OUTPUT);
pinMode(_PinData.LED2Pin, INPUT);
digitalWrite(_PinData.LED1Pin, LOW);
digitalWrite(_PinData.LED2Pin, LOW);
break;
case LED_RED_YELLOW:
pinMode(_PinData.LED1Pin, OUTPUT);
pinMode(_PinData.LED2Pin, OUTPUT);
digitalWrite(_PinData.LED1Pin, HIGH);
digitalWrite(_PinData.LED2Pin, LOW);
break;
case LED_GREEN:
pinMode(_PinData.LED1Pin, INPUT);
pinMode(_PinData.LED2Pin, OUTPUT);
digitalWrite(_PinData.LED1Pin, LOW);
digitalWrite(_PinData.LED2Pin, HIGH);
break;
case LED_RED_GREEN:
pinMode(_PinData.LED1Pin, OUTPUT);
pinMode(_PinData.LED2Pin, OUTPUT);
digitalWrite(_PinData.LED1Pin, LOW);
digitalWrite(_PinData.LED2Pin, HIGH);
break;
}
CurrentLEDState = LEDState;
}
}
SensorNode::SensorNode(SensorPinData_t PinData) {
_PinData = PinData;
}
void SensorNode::Init() {
Serial.print("Sensor On Pin ");
Serial.print(_PinData.PulsePin);
pinMode(_PinData.PulsePin, INPUT);
pinMode(_PinData.LED1Pin, INPUT); //For tristate.
pinMode(_PinData.LED2Pin, INPUT);
Angles[STATION_A][HORZ] = 0;
Angles[STATION_A][VERT] = 0;
Angles[STATION_B][HORZ] = 0;
Angles[STATION_B][VERT] = 0;
Location[X_AXIS] = 0;
Location[Y_AXIS] = 0;
Location[Z_AXIS] = 0;
Serial.println(" Complete");
}
SensorNode::~SensorNode() {
}
u_int8_t SensorNode::GetPulsePin() {
return _PinData.PulsePin;
}
void SensorNode::NewSweepPinInterrupt(u_int32_t PulseLength, u_int32_t PulseStartTime){
LatestSweepInterrupt.Length = PulseLength;
LatestSweepInterrupt.StartTime = PulseStartTime;
LatestSweepInterrupt.New = true;
}
void SensorNode::MovingAverageAdd(float New, u_int8_t Source, u_int8_t Axis) {
AverageAngle[Source][Axis][AverageAnglePointers[Source][Axis]] = New;
++AverageAnglePointers[Source][Axis] %= AVERAGE_SIZE;
}
float SensorNode::MovingAverageCalc(u_int8_t Source, u_int8_t Axis) {
float Min=360,Max=0;
for (int i = 0; i < AVERAGE_SIZE; i++){
float This = AverageAngle[Source][Axis][i];
Min = min(Min,This);
Max = max(Max,This);
}
// Serial.print(Min);
// Serial.print(" ");
// Serial.println(Max);
float Total = 0;
for (int i = 0; i < AVERAGE_SIZE; i++) {
float This = AverageAngle[Source][Axis][i];
// Serial.print(This);
// Serial.print(" - ");
Total += This;
}
// Serial.println(" ");
return Total / (float) AVERAGE_SIZE;
}
void SensorNode::PrepareForReading() {
Angles[STATION_A][HORZ] = MovingAverageCalc(STATION_A, HORZ);
Angles[STATION_A][VERT] = MovingAverageCalc(STATION_A, VERT);
Angles[STATION_B][HORZ] = MovingAverageCalc(STATION_B, HORZ);
Angles[STATION_B][VERT] = MovingAverageCalc(STATION_B, VERT);
}
bool SensorNode::CheckAndHandleSweep(u_int32_t Now, u_int8_t SweepSource, u_int8_t SweepAxis, u_int32_t SweepStartTime,
u_int8_t CurrentStationLock) {
noInterrupts();
Pulse SafeCopy = LatestSweepInterrupt;
LatestSweepInterrupt.New = false;
interrupts();
if (SafeCopy.New) {
if (CurrentStationLock == DUAL_STATION_LOCK) {
float NewAngle = TICKS_TO_DEGREES(SafeCopy.StartTime - SweepStartTime);
MovingAverageAdd(NewAngle, SweepSource, SweepAxis);
return true;
}
}
}
| true |
04933431eea7e81cb2625fb32b59c8c92b2b5673 | C++ | dtbinh/M1S2 | /AlgoGeo/TP_Note/ARN.cc | UTF-8 | 12,167 | 3.28125 | 3 | [] | no_license | #include<iostream>
#include <stdlib.h>
#include <math.h>
#include "ARN.h"
using namespace std;
//Constructeurs**********************************//
ARN::ARN(bool (*EgaleCleUSER)(int cle1,int cle2), bool (*InferieurCleUSER)(int cle1,int cle2)){
//creer un arn vide et on fixe les operateurs de comparaison
nul=new noeud;
nul->pere=NULL;
nul->fd=NULL;
nul->fg=NULL;
nul->cle=-1;
nul->coul=noir;
racine=nul;
EgaleCle=EgaleCleUSER;
InferieurCle=InferieurCleUSER;
}
ARN::ARN(int val, bool (*EgaleCleUSER)(int cle1,int cle2), bool (*InferieurCleUSER)(int cle1,int cle2)){
//creer un arn avec une racine et on fixe les operateurs de comparaison
nul=new noeud;
nul->pere=NULL;
nul->fd=NULL;
nul->fg=NULL;
nul->cle=-1;
nul->coul=noir;
racine= new noeud;
racine->pere=nul;
racine->fd=nul;
racine->fg=nul;
racine->cle=val;
racine->coul=noir;
EgaleCle=EgaleCleUSER;
InferieurCle=InferieurCleUSER;
}
//Destructeur************************************//
ARN::~ARN(){
noeud* courant = racine;
if(racine!=nul){
while(racine->fg!=nul && racine->fd!=nul){// Tant qu'il ne reste plus que la racine
while(courant->fg!=nul && courant->fd!=nul){ //On descend dans l'arbre
if(courant->fg!=nul){
courant=courant->fg;}
if(courant->fd!=nul){
courant=courant->fd;}
}
if(courant==courant->pere->fg){// Le noeud courant est fils gauche de son pere
courant=courant->pere;//On remonte d'un cran
delete courant->fg; //On efface le fils gauche
courant->fg=nul;}
else{ //Le noeud courant est fils droit de son pere
courant=courant->pere;//On remonte d'un cran
delete courant->fd; //On efface le fils droit
courant->fd=nul;}
}
delete racine;
delete nul;
}
}
//I.O.*******************************************//
void ARN::afficheNoeud(noeud *courant, int profondeur){//Appel reccursif, la profondeur indique l'indentation necessaire.
if(courant->fg!=nul){
for(int i=0;i<profondeur;i++){
cout << '|';
}
cout << "-> Fils gauche de cle = " << courant->fg->cle << " et de couleur ";
( courant->fg->coul == noir ) ? cout << "noir" : cout << "rouge";
cout << " :"<<endl;
afficheNoeud(courant->fg,profondeur+1);
}
if(courant->fd!=nul){
for(int i=0;i<profondeur;i++){
cout << '|';
}
cout << "-> Fils droit de cle = " << courant->fd->cle << " et de couleur ";
( courant->fd->coul == noir ) ? cout << "noir" : cout << "rouge";
cout << " :"<<endl;
afficheNoeud(courant->fd,profondeur+1);
}
}
void ARN::Affichage(){ //Affichage ecran avec indentation, on affiche reccursivement.
if(racine!=nul){
cout<< endl;
cout<< "Racine de cle = " << racine->cle << " et de couleur ";
( racine->coul == noir ) ? cout << "noir" : cout << "rouge";
cout << " :"<<endl;
afficheNoeud(racine,1);
cout << endl;
}
else{
cout << "Arn vide." << endl;
}
}
//Chercher un noeud*******************************//
noeud* ARN::chercheNoeud(int val, noeud* courant){
if((*EgaleCle)(val,courant->cle)){
return courant;}
if((*InferieurCle)(courant->cle,val)){
if(courant->fd!=nul){
return chercheNoeud(val,courant->fd);}
else{
return courant;}
}
else{
if(courant->fg!=nul){
return chercheNoeud(val,courant->fg);}
else{
return courant;}
}
}
noeud* ARN::Trouve(int val){//Cherche le noeud correspondant reccursivement
//Si la valeur n'est pas presente, retourne un noeud ou val est inserable
//comme fils droit ou gauche
if(racine!=nul){
return chercheNoeud(val, racine);
}
else{
return nul;
}
}
noeud* ARN::successeur(noeud* x){//Trouve le successeur de x sous reserve que x soit non nul
if(x->fd!=nul){//Si x a un successeur droit, on prend le min de la sous arbo droite
x=x->fd;
while(x->fg!=nul){
x=x->fg;}
return x;
}
while(x->pere!=nul && x==x->pere->fd){//Sinon, on retourne le premier ancetre dont x descend a gauche
x=x->pere;
}
return x->pere;//Au pire, si x est la racine, l'element de depart etait le plus grand et on retourne nul
}
noeud* ARN::predecesseur(noeud* x){//Trouve le predecesseur de x sous reserve que x soit non nul
if(x->fg!=nul){//Si x a un successeur gauche, on prend le max de la sous arbo gauche
x=x->fg;
while(x->fd!=nul){
x=x->fd;}
return x;
}
while(x->pere!=nul && x==x->pere->fg){//Sinon, on retourne le premier ancetre dont x descend a droite
x=x->pere;
}
return x->pere;//Au pire, si x est la racine, l'element de depart etait le plus grand et on retourne nul
}
//Inserer un noeud********************************//
void ARN::RotationGauche(noeud* x){//pivote x et son fils droit y sous l'hypothese que celui-ci soit non null
noeud* y=x->fd;
x->fd=y->fg; //Le fils gauche de y devient fils droit de x
if(y->fg!=nul){
y->fg->pere=x;
}
y->pere=x->pere;//On met a jour pere dans y
if(x->pere==nul){//Cas ou x est racine
racine=y;}
else{//Sinon on met a jour le nouveau pere de y
if(x==x->pere->fg){
x->pere->fg=y;}
else{x->pere->fd=y;}
}
y->fg=x;//Nouveau lien entre x et y
x->pere=y;
}
void ARN::RotationDroite(noeud* x){//pivote x et son fils gauche y sous l'hypothese que celui-ci soit non null
noeud* y=x->fg;
x->fg=y->fd; //Le fils droit de y devient fils gauche de x
if(y->fd!=nul){
y->fd->pere=x;
}
y->pere=x->pere;//On met a jour pere dans y
if(x->pere==nul){//Cas ou x est racine
racine=y;}
else{//Sinon on met a jour le nouveau pere de y
if(x==x->pere->fg){
x->pere->fg=y;}
else{x->pere->fd=y;}
}
y->fd=x;//Nouveau lien entre x et y
x->pere=y;
}
noeud* ARN::insertionClassique(int val){
//Insere comme dans un arbre de recherche classique
noeud* point_insertion=Trouve(val);
if((*EgaleCle)(point_insertion->cle,val)){
cout << "Valeur deja existante..."<<endl;
return nul;}
else{
noeud *nouveau= new noeud;
nouveau->pere=point_insertion;
if((*InferieurCle)(point_insertion->cle,val)){
point_insertion->fd=nouveau;}
else{
point_insertion->fg=nouveau;
}
nouveau->fd=nul;
nouveau->fg=nul;
nouveau->cle=val;
nouveau->coul=rouge;
return nouveau;
}
}
void ARN::Insere(int val){
//On insere un noeud de cle val et reequilibre l'arbre.
if(racine!=nul){
noeud *x=insertionClassique(val); //x est insere comme feuille rouge
if(x!=nul){//Si le noeud n'existait pas deja, on reequilibre l'arbre
while(x->pere!=nul && x->pere->coul==rouge && x->pere->pere!=nul){ //Tant que le pere existe, est rouge, et que le grand-pere existe:
if(x->pere==x->pere->pere->fg){//Si le pere de x est un fils gauche
noeud *y=x->pere->pere->fd;// y est l'oncle de x
if(y!=nul && y->coul==rouge){ //x, son pere et son oncle sont rouges, on met son grand-pere a rouge et on remonte dans l'arbre
x->pere->coul=noir;
y->coul=noir;
x->pere->pere->coul=rouge;
x=x->pere->pere;
}
else{//l'oncle de x est noir ou n'existe pas
if(x==x->pere->fd){//Si x est fils droit
x=x->pere;
this->RotationGauche(x); //Maintenant, le noeud considere est fils gauche
}
x->pere->coul=noir;//On met le pere a noir, le grand-pere a rouge et on effectue une rot. droite sur le grand-pere, et c'est bon (le
//nouvel ancetre est le pere qui est noir).
x->pere->pere->coul=rouge;
this->RotationDroite(x->pere->pere);
}
}
else{ // Si le pere de x est un fils droit (on fait de meme)
noeud *y=x->pere->pere->fg;// y est l'oncle de x
if(y!=nul && y->coul==rouge){ //x, son pere et son oncle sont rouges, on met son grand-pere a rouge et on remonte dans l'arbre
x->pere->coul=noir;
y->coul=noir;
x->pere->pere->coul=rouge;
x=x->pere->pere;
}
else{//l'oncle de x est noir ou n'existe pas
if(x==x->pere->fg){//Si x est fils gauche
x=x->pere;
this->RotationDroite(x); //Maintenant, le noeud considere est fils droit
}
x->pere->coul=noir;//On met le pere a noir, le grand-pere a rouge et on effectue une rot. gauche sur le grand-pere, et c'est bon (le
//nouvel ancetre est le pere qui est noir).
x->pere->pere->coul=rouge;
this->RotationGauche(x->pere->pere);
}
}
}
racine->coul=noir; //on s'est peut etre arrete avec un fils de la racine rouge.
}
}
else{
racine= new noeud;
racine->pere=nul;
racine->fd=nul;
racine->fg=nul;
racine->cle=val;
racine->coul=noir;
}
}
//Supprimer un noeud *****************************//
void ARN::SupprimerCorrection(noeud* x){
while(x!=racine && x->coul==noir){//x a un pere et sa couleur est noire
if(x->pere->fg==x){//x est fils gauche
noeud* w=x->pere->fd;//Le frere de x, non nul car le nbre de noirs
//sous w est > celui sous x
if(w->coul==rouge){//cas 1, on se ramene a un w noir
w->coul=noir;
x->pere->coul=rouge;
RotationGauche(x->pere);
w=x->pere->fd;}
if(w->fg->coul==noir && w->fd->coul==noir){//pour les ms raisons w a 2 fils
w->coul=rouge; //cas 2
x=x->pere;}//on remonte d'un cran, si x est rouge on arete la boucle et on le mettra noir
else{//Au moins un des 2 fils de w est rouge
if(w->fd->coul==noir){//cas 3, on se ramene a un fils droit rouge
w->fg->coul=noir;
w->coul=rouge;
RotationDroite(w);
w=x->pere->fd;}
w->coul=x->pere->coul;//Cas 4, le fils droit de w est rouge
x->pere->coul=noir;//on reequilibre la branche deficiente
w->fd->coul=noir;
RotationGauche(x->pere);
x=racine;//on remet la racine a noir
}
}else{//x est fils droit
noeud* w=x->pere->fg;//Le frere de x, non nul car le nbre de noirs
//sous w est > celui sous x
if(w->coul==rouge){//cas 1, on se ramene a un w noir
w->coul=noir;
x->pere->coul=rouge;
RotationDroite(x->pere);
w=x->pere->fg;}
if(w->fg->coul==noir && w->fd->coul==noir){//pour les ms raisons w a 2 fils
w->coul=rouge; //cas 2
x=x->pere;}//on remonte d'un cran, si x est rouge on arete la boucle et on le mettra noir
else{//Au moins un des 2 fils de w est rouge
if(w->fg->coul==noir){//cas 3, on se ramene a un fils gauche rouge
w->fd->coul=noir;
w->coul=rouge;
RotationGauche(w);
w=x->pere->fg;}
w->coul=x->pere->coul;//Cas 4, le fils gauche de w est rouge
x->pere->coul=noir;//on reequilibre la branche deficiente
w->fg->coul=noir;
RotationDroite(x->pere);
x=racine;//on remet la racine a noir
}
}
}
x->coul=noir;
}
void ARN::Supprime(int val){
noeud*z = Trouve(val);
if(!(*EgaleCle)(z->cle,val)){
return;
}
noeud* y; //Un noeud qu'on va detacher de l'arbre
if(z->fg==nul || z->fd==nul){
y=z;}
else{y=successeur(z);}//Normalement, ici, z n'est pas le max, car sinon il lui manque un fils.
//On est sur que y n'est pas nul
noeud* x=nul; //x prend la valeur du fils de y non null (si il existe)
if(y->fg!=nul){
x=y->fg;}
else{x=y->fd;}
x->pere=y->pere;//On mets a jour le pere dans x, marche meme si x=nul
if(y->pere==nul)//Si y etait racine
{if(x==nul){//c'est le cas ou il n'y a plus qu'un seul sommet dans l'arn
delete z;
racine=nul;
return;
}else{//La nouvelle racine est le fils de y
racine=x;}
}else{//Si y n'etait pas racine
if(y==y->pere->fg){//le pere de y devient le pere de x
y->pere->fg=x;}
else{
y->pere->fd=x;
}
}
if(y!=z){//si le noeud supprime n'est pas z
z->cle=y->cle;
}
if(y->coul==noir){//On a supprimer un sommet noir, les hauteurs noires ont changees, il faut reequilibrer
SupprimerCorrection(x);
}
delete y;
}
//Predecesseur et Successeur*************************************//
//Retournent -1 comme cle si min (pour Predecesseur) ou max (pour
// Successeur)
int ARN::Successeur(int val){
noeud* x=successeur(Trouve(val));
if(x==nul){return -1;}
else{
return x->cle;
}
}
int ARN::Predecesseur(int val){
noeud* x=predecesseur(Trouve(val));
if(x==nul){return -1;}
else{
return x->cle;
}
}
| true |
419aea09a09e8d6ee1f16d3c1b48e7896433758b | C++ | mgcg216/Comp236 | /Project2/Savings.cpp | UTF-8 | 1,089 | 2.984375 | 3 | [] | no_license | // Michael Guerrero
// March 25, 2014
// CS 236 C++ Project 2
//4-29-14
//Inheritance/ Banking program
// Description: Savings Function .cpp that creates the functions that to restrict the input.
#include "Savings.h" //needed if files are separate
#include <string>
#include "string"
#include <iostream>
#include <sstream>
using namespace std;
Savings::Savings(){
}
Savings::Savings(string name, long taxID, double balance){
SetName(name);
SetTaxID(taxID);
Setbalance(balance);
}
void Savings::DoWithdraw(double amount){
if (amount <= Getbalance())
{
Setbalance(Getbalance() - amount);
}
if(numwithdraws < 10)
{
last10withdraws[numdeposits++] = amount;//place balance into array
}
else
{
int i;
for(i = 0; i <9;i++)
{
last10withdraws[i] =last10withdraws[i+1];
}
last10withdraws[i] = amount;
}
}
void Savings::display(){
Account::display(GetName(), GetTaxID(), Getbalance());
cout <<"The last few withdraws were: " << endl;
int k = 0;
for(k; k < numdeposits; k++){
cout << last10withdraws[k];
}
} | true |
f599dd2d0bfe724f754458c13be9294a5c9dd8f5 | C++ | Vieran/DataStructure | /Dendriform/Tree/Lib/Tree.h | UTF-8 | 854 | 3.5625 | 4 | [] | no_license | //树的抽象类
#ifndef TREE_H
#define tree_h
#include <iostream>
using namespace std;
template <class elemType>
class Tree
{
public:
virtual void clear() = 0;//删除树中所有的节点
virtual bool isEmpty() const = 0;//判断是否为空树
virtual elemType root(elemType flag) const = 0;//找出树的根节点;如果树空则返回特殊值
virtual elemType parent(elemType x,elemType flag) const = 0;//寻找x的父节点的值;如果树空则返回特殊值
virtual elemType child(elemType x,int i,elemType flag) const = 0;//寻找x的第i个子节点的值;如果树空则返回特殊值
virtual void remove(elemType x,int i) = 0;//删除节点x的第i颗子树
virtual void traverse() const = 0;//遍历整棵树访(问每一个节点一次)
virtual ~Tree() = 0;//漏了的析构函数
};
#endif | true |
8b44599839ae738d9ca5cd67e1191490efffb852 | C++ | DaniAngelov/Cpp_Programming | /Object_Oriented_Programming/Homeworks/First_Homework/Second Task/DNSCache.h | UTF-8 | 576 | 2.703125 | 3 | [] | no_license | #pragma once
#include "DNSRecord.h"
#include <iostream>
using namespace std;
class DNSCache
{
private:
DNSRecord* records = nullptr;
int size = 0;
void resize();
void increaseSize();
void decreaseSize(int n);
public:
DNSCache(); //constructors
DNSCache(const DNSCache&);
~DNSCache();
bool addRecord(const DNSRecord&);
const char* lookup(const DNSRecord&);
void flush(); // functions
void print()const;
const int getSize()const;
DNSRecord operator[](int index) const; // operators
DNSCache& operator=(const DNSCache&);
}; | true |
ecf492737f8ddc5cd768520c95f5771743e1f011 | C++ | Leonardo-Lourenco/Programacao-c | /Aula-39/Aula-39.cpp | UTF-8 | 454 | 3 | 3 | [] | no_license | #include <iostream>
#include <string.h>
// Ponteiros e Vetor ou Arrays
using namespace std;
int main(){
int num[] = {1,2,3,4,5};
int *direcao_numero;
//direcao_numero = &num[0];
direcao_numero = num;
for(int i =0; i< 5; i++){
//cout<<"Elementos do Vetor: [ "<<i<< " ] "<<*direcao_numero ++<<endl;
cout<<"Posição de memoria [ "<<num[i]<<" ] "<<direcao_numero ++<<endl;
}
return 0;
}
| true |
2671a0c70411950d1d0a27eee4880c9529a6ceb4 | C++ | ghost26/big_integer | /big_integer/main.cpp | UTF-8 | 412 | 2.828125 | 3 | [] | no_license | //
// main.cpp
// big_integer
//
// Created by Руслан Абдулхаликов on 06.06.15.
// Copyright (c) 2015 Руслан Абдулхаликов. All rights reserved.
//
#include <iostream>
#include "big_integer.h"
using namespace std;
int main()
{
big_integer a("2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001");
big_integer b("2");
cout << a * b / b;
return 0;
} | true |
a84c9fbd803cfd74290bedcb0844f9a92f3b86c2 | C++ | its-sachin/COP290 | /Inevitable/Sound.cpp | UTF-8 | 3,366 | 2.890625 | 3 | [] | no_license | //Using SDL and standard IO
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_mixer.h>
#include "constants.hpp"
class Sound {
private:
Mix_Music *bgm = NULL;
Mix_Chunk *coin = NULL;
Mix_Chunk *die = NULL;
Mix_Chunk *respawn = NULL;
Mix_Chunk *eat = NULL;
Mix_Chunk *mind = NULL;
bool success = true;
public:
Sound(){
if ( Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) {
cout << "SDL Audio could not be initialised! Error: " << SDL_GetError() << endl;
success = false;
}
bgm = Mix_LoadMUS((SOUND_PATH + "/bgm.mp3").c_str());
if (bgm == NULL) {
cout << "Failed to load BGM! Error: " << Mix_GetError() << endl;
}
string name = "coin";
coin = Mix_LoadWAV( (SOUND_PATH + "/" + name + ".wav").c_str() );
if( coin == NULL )
{
cout<< "Failed to load " << name << " sound effect! Error: " << Mix_GetError() << endl;
}
name = "die";
die = Mix_LoadWAV( (SOUND_PATH + "/" + name + ".wav").c_str() );
if( die == NULL )
{
cout<< "Failed to load " << name << " sound effect! Error: " << Mix_GetError() << endl;
}
name = "respawn";
respawn = Mix_LoadWAV( (SOUND_PATH + "/" + name + ".wav").c_str() );
if( respawn == NULL )
{
cout<< "Failed to load " << name << " sound effect! Error: " << Mix_GetError() << endl;
}
name = "eat";
eat = Mix_LoadWAV( (SOUND_PATH + "/" + name + ".wav").c_str() );
if( eat == NULL )
{
cout<< "Failed to load " << name << " sound effect! Error: " << Mix_GetError() << endl;
}
name = "mind";
mind = Mix_LoadWAV( (SOUND_PATH + "/" + name + ".wav").c_str() );
if( mind == NULL )
{
cout<< "Failed to load " << name << " sound effect! Error: " << Mix_GetError() << endl;
}
}
~Sound() {
Mix_FreeMusic(bgm);
Mix_FreeChunk(die);
Mix_FreeChunk(eat);
Mix_FreeChunk(respawn);
Mix_FreeChunk(coin);
Mix_FreeChunk(mind);
bgm = NULL;
coin = NULL;
die = NULL;
respawn = NULL;
eat = NULL;
mind = NULL;
Mix_Quit();
}
void playEat() {
if (eat != NULL) {
Mix_PlayChannel( -1, eat, 0 );
}
}
void playDie() {
if (die != NULL) {
Mix_PlayChannel( -1, die, 0 );
}
}
void playRespawn() {
if (respawn != NULL) {
Mix_PlayChannel( -1, respawn, 0 );
}
}
void playCoin() {
if (coin != NULL) {
Mix_PlayChannel( -1, coin, 0 );
}
}
void playMind() {
if (mind != NULL) {
Mix_PlayChannel( -1, mind, 0 );
}
}
void startBGM() {
if (bgm != NULL) {
if( Mix_PlayingMusic() == 0 ){
Mix_PlayMusic(bgm, -1 );
}
else{
if( Mix_PausedMusic() == 1 ){
Mix_ResumeMusic();
}
else{
Mix_PauseMusic();
}
}
}
}
void stopBGM() {
Mix_HaltMusic();
}
}; | true |
0585b81ce8cc54258b4eb20c9f59529112ffff0b | C++ | MuhammadHananAsghar/Binary-Maximun-Heap-in-Cpp | /heapmax.cpp | UTF-8 | 2,031 | 3.78125 | 4 | [] | no_license | // CREATED BY MUHAMMAD HANAN ASGHAR
// PYTHONIST
#include <iostream>
using namespace std;
class BinaryMaximumHeap{
private:
int *heap;
int heapSize;
int arraySize;
int getParent(int index){
return (index - 1) / 2;
}
int getRight(int index){
return (2 * index) + 2;
}
int getLeft(int index){
return (2 * index) + 1;
}
void swap(int i,int j){
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
bool hasLeft(int index){
return getLeft(index) < heapSize;
}
bool hasRight(int index){
return getRight(index) < heapSize;
}
public:
BinaryMaximumHeap(int size){
heap = new int[size];
arraySize = size;
heapSize = 0;
}
void heapifyUp(int index){
if(index!=0){
int parent = getParent(index);
if(heap[parent] < heap[index]){
swap(parent,index);
heapifyUp(parent);
}
}
}
void Insert(int data){
if(heapSize == arraySize){
cout<<"Data Structure Overflow"<<endl;
return;
}else{
heapSize++;
heap[heapSize - 1] = data;
cout<<endl<<"Data Added - "<<data<<endl;
heapifyUp(heapSize - 1);
}
}
void Display(){
for(int i = 0;i<heapSize;i++){
cout<<heap[i]<<" - ";
}
}
void heapifyDown(int index){
int leftSide = getLeft(index);
int rightSide = getRight(index);
int min = index;
if(heap[leftSide] > heap[min] && hasLeft(index)){
min = leftSide;
}
if(heap[rightSide] > heap[min] && hasRight(index)){
min = rightSide;
}
if(min != index){
swap(index,min);
heapifyDown(min);
}
}
int Remove(){
if(heapSize == 0){
return -1;
}else{
int root = heap[0];
heap[0] = heap[heapSize - 1];
heapSize--;
if(heapSize > 1){
heapifyDown(0);
}
return root;
}
}
};
int main() {
BinaryMaximumHeap heap(10);
heap.Insert(23);
heap.Insert(25);
heap.Insert(235);
heap.Insert(80);
heap.Display();
cout<<endl;
heap.Remove();
heap.Display();
}
| true |
4a991c15fce82a4234a09b9327a5f60cbb37061f | C++ | WFCSC112AlqahtaniFall2019/project0-Alexa-Brown | /main.cpp | UTF-8 | 1,153 | 3.5625 | 4 | [] | no_license |
// Alexa Brown, CSC 112, Project 0
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World! " << endl;
int i=-10;
int j=-10;
int firstEquationx;
int firstEquationy;
int equalto1;
int equalto2;
int secondEquationx;
int secondEquationy;
cout << "Enter the first x ";
cin>> firstEquationx;
cout << "Enter the first y ";
cin>> firstEquationy;
cout << "Enter the number the first equation is equal to ";
cin>> equalto1;
cout << "Enter the second x ";
cin>> secondEquationx;
cout << "Enter the second y ";
cin>> secondEquationy;
cout << "Enter the number the second equation is equal to ";
cin>> equalto2;
for (i = -10; i <11; i++){
for (j = -10; j <11; j++){
if ((firstEquationx * i) + (firstEquationy * i) == equalto1){
if ((secondEquationx * j) + (secondEquationy * j) == equalto2){
cout << "x = " << i << endl;
cout << "y = " << j << endl;
break;
}
}
}
}
cout << "No solution." <<endl;
return 0;
}
| true |
2142e731644863417c6cab908125377d68a3f7dc | C++ | smunj/InterviewBit | /Backtracking/palindromePartitioning.cpp | UTF-8 | 964 | 3.0625 | 3 | [] | no_license | bool pal(string s, int a, int b){
while(a < b){
if(s[a] != s[b]){
return false;
}
a++;
b--;
}
return true;
}
void fn(vector<vector<string> >& ans, vector<string> v, int i, int n, string A){
if(i == n){
ans.push_back(v);
return;
}
for(int k = i; k < n; k++){
if(pal(A, i, k)){
vector<string> temp(v);
temp.push_back(A.substr(i, k - i + 1));
fn(ans, temp, k+1, n, A);
}
}
}
vector<vector<string> > Solution::partition(string A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
int n = A.size();
vector<vector<string> > ans;
vector<string> v;
fn(ans, v, 0, n, A);
return ans;
}
| true |
5e1ffb2e1580746fcce6df258de002663f625149 | C++ | Rgeers/INOOP | /Lesson 5/Homework/Boeken.cpp | UTF-8 | 855 | 3.078125 | 3 | [] | no_license | #include "Boek.h"
#include <iostream>
#include "Boeken.h"
Boeken::Boeken() {
}
Boeken::~Boeken() {
boekenPlank.clear();
}
Boeken::Boeken(std::string gekregenNaam) {
naam = gekregenNaam;
}
Boeken::Boeken(const Boeken& andereBoeken) {
boekenPlank = andereBoeken.boekenPlank;
}
Boeken& Boeken::operator=(const Boeken& andereBoeken) {
if (this != &andereBoeken) {
int boekenPlankLength = (andereBoeken.boekenPlank.capacity() + 1);
Boek* boek = new Boek(*(andereBoeken.boekenPlank[0]));
}
return *this;
}
void Boeken::toon() {
std::cout << "Boeken op de boekenplank:" << std::endl;
for (int i = 0; i < boekenPlank.capacity(); i++) {
std::cout << boekenPlank[i]->_type << std::endl;
}
}
void Boeken::leenUit(Boek* boek) {
boek->isUitgeleend = true;
}
void Boeken::voegToe(std::string type) {
boekenPlank.push_back(new Boek(type));
}
| true |
e8aea9fe14f41000a39073cc95ad3799f448cb50 | C++ | tcShadowWalker/XKey | /test/CryptStreamOld.h | UTF-8 | 2,325 | 2.5625 | 3 | [] | no_license | #pragma once
#include <streambuf>
#include <vector>
struct bio_st;
struct evp_cipher_st;
namespace XKey {
namespace v12 {
enum ModeInfo {
NO_OPTIONS = 0,
/// Encode content in base64
BASE64_ENCODED = 1,
/// Encrypt file. If this is omitted, the file is stored in plaintext
USE_ENCRYPTION = 2,
/// If this is not set for reading, the cipher, IV and key iteration count
/// must be set explicity for decryption to succeed. Omitting not recommended.
EVALUATE_FILE_HEADER = 4
};
/**
* @brief File stream handling encryption
*/
class CryptStream
: public std::streambuf
{
public:
static const int DEFAULT_KEY_ITERATION_COUNT = 100000;
enum OperationMode {
READ = 1,
WRITE = 2
};
CryptStream (const std::string &filename, OperationMode open_mode, int mode = BASE64_ENCODED | USE_ENCRYPTION | EVALUATE_FILE_HEADER);
~CryptStream ();
bool isEncrypted () const;
bool isEncoded () const;
/**
* @brief Set the key for encryption and decryption, if not specified for the constructor
* @param passphrase The passphrase to derive the key from
* @param cipherName OpenSSL-name of the encryption cipher to use. Defaults to AES in CTR mode.
* @param iv initialization vector to use. If empty, a random one will be generated
* @param keyIterationCount number of iterations to derive the encryption key. If -1, defaults to DEFAULT_KEY_ITERATION_COUNT
*
* This method uses PBKDF2 to derive the real encryption key from the passphrase
*/
void setEncryptionKey (std::string passphrase, const char *cipherName = nullptr, const char *iv = nullptr, int keyIterationCount = -1);
static int Version () { return 12; }
private:
// overrides base class behaviour:
// Get:
int_type underflow();
// Put:
int_type overflow (int_type c);
int sync();
void _evaluateHeader (int *headerMode);
void _writeHeader ();
//streamsize xsputn(const char_type* __s, streamsize __n);
// Disallow copying and copy -assignment
CryptStream(const CryptStream &);
CryptStream &operator= (const CryptStream &);
std::vector<char> _buffer;
struct bio_st *_bio_chain;
struct bio_st *_crypt_bio;
struct bio_st *_file_bio;
struct bio_st *_base64_bio;
OperationMode _mode;
int _version;
bool _initialized;
//
int _pbkdfIterationCount;
std::string _iv;
const evp_cipher_st *_cipher;
};
}
}
| true |
8ab8e94953e915c7386333eaac83130f48036ba3 | C++ | sophiegri/programmiersprachen-aufgabenblatt-2 | /source/rectangle.hpp | UTF-8 | 701 | 2.9375 | 3 | [
"MIT"
] | permissive | #ifndef RECTANGLE_HPP
#define RECTANGLE_HPP
#include "color.hpp"
#include "vec2.hpp"
#include "window.hpp"
class Rectangle
{
private:
Vec2 max_height; //top right, x2, y2
Vec2 min_height; //bottom left, x1, y1
Color color;
public:
Rectangle ();
Rectangle (Vec2 const& _max_height, Vec2 const& _min_height, Color const& _color);
Color get_color() const;
float get_width () const;
float get_height () const;
float get_area () const;
float get_circumference () const;
//Aufgabe 2.10
void draw (Window const& w) const;
void draw (Window const& w, Color const& color) const;
bool is_inside (Vec2 const& point) const;
};
#endif | true |
a8c8b114610532b5e925d7b49666dff647a2e157 | C++ | fengqing-maker/manager | /Sid_Project_Manger/Sid_Project_Manger/Src/MainFrame/UI/CGridCtrl/AbstractGridViewManager.h | GB18030 | 19,458 | 2.671875 | 3 | [] | no_license | /*******************************************************/
/**
*@file AbstractGridViewManager.h
*@brief ͼģ
*@note ͼʵӦ̳ͨذ
* ûԼҪıͼ
*@author ߷
*@date [4/10/2014]
********************************************************/
#pragma once
#include "./NewCellTypes/GridCellCombo.h"
#include "./NewCellTypes/GridCellCheck.h"
#include "./NewCellTypes/GridCellDateTime.h"
#include "./NewCellTypes/GridCellNumeric.h"
#include "./NewCellTypes/GridCellRich.h"
#include "GridCtrl.h"
#define WM_GRID_POPUP_MENUID_MIN WM_USER+5000 /* бͼ˵IDСֵ */
#define WM_GRID_POPUP_MENUID_MAX WM_USER+5100 /* бͼ˵IDֵ */
/** @brief öٶ */
enum GridItemType
{
GridItemType_Edit, /**< @brief ༭ͱ */
GridItemType_MutilEdit, /**< @brief ༭ͱ */
GridItemType_Combo, /**< @brief Ͽͱ */
GridItemType_Check, /**< @brief ѡͱ */
GridItemType_DateTime, /**< @brief ʱؼͱ */
GridItemType_Extension, /**< @brief Զչͱ */
GridItemType_Button, /**< @brief */
GridItemType_NumEidt, /**< @brief ֣㣬зţԼ */
GridItemType_RichEidt, /**< @brief rich Eidt */
};
//class CGridCtrl;
/**@brief ıͼ */
class AbstractGridViewManager
{
public:
AbstractGridViewManager(void);
virtual ~AbstractGridViewManager(void) = 0;
/**
*@brief ͼעᱻıؼ
*@param [in] gridCtrl עͼܿرؼָ
*@return TRUE:עɹ;FALSEעʧ.
*@note ͼעؼʹñͼ
*@see AbstractGridViewManager::GetRegisteredGridView()
*/
BOOL RegisterAsGridView(CGridCtrl* gridCtrl);
/**
*@brief ȡǰͼעܿرָ
*@see AbstractGridViewManager::GetRegisteredGridView()
*/
CGridCtrl* GetRegisteredGridView() { return m_gridCtrl;};
/**
*@brief Ĭϵıͼ
*@return TRUEͼɹ;FALSEͼʧܡ
*@note ûδָûͼʱһĬϵıͼ
* ĬϱͼһExcelͷʹĸʶͷʹֱʶ
*@see AbstractGridViewManager::CreateGridView()
*/
BOOL CreateDefaultGridView();
/**
*@brief ûͼ
*@return TRUEͼɹ;FALSEͼʧܡ
*@note ûͼĺûûͼйصĺ
*@see
*/
BOOL CreateGridView();
/**
*@brief ûͼ
*@note ûд˺ʵضٲ
*@see AbstractGridViewManager::CreateGridView()
*/
virtual void DestroyGridView();
/**
*@brief ûͼҼ˵
*@param [in] point Ҽ˵,DZ꣬Ļ
*@return TRUE:ɹFALSE:ʧ
*@note Ҽ˵ȷ˵Ȼ̬˵ʾ
*/
virtual BOOL CreateGridViewContextMenu(CPoint clientPoint);
/**
*@brief ӦûͼҼ˵ָ˵
*@param [in] menuID ָIJ˵ID
*@return TRUE:ӦɹFALSE:Ӧʧ
*@note ڵ˵б˲˵map(˵ID˵)
*/
virtual BOOL RespGridViewContextMenu(UINT menuID);
/**
*@brief ӦҪ֤ͼʱøú
*@note ˴nRownColumnСкŰ̶ǿɱСк
*/
virtual BOOL ValidateGridView(int nRow,int nColumn);
/**
*@brief ӦҪдͼʱøú
*@note ˴nRownColumnСкŰ̶ǿɱСк
*/
virtual BOOL EndEditGridView(int nRow,int nColumn);
/**
*@brief ±ͼб
*@note бڵݺͱСĿͿ
*/
BOOL UpdateGridView();
/**
*@brief ±
*@note
*/
void RefreshRow( int nRow, int nColumn );
/**
*@brief ±ͼ
*@note lhz add
*/
BOOL UpdateGridRowView( int row );
BOOL UpdateGridFixedRowView( int row );
/******************************select operation***************************/
/**
*@brief ȡǰͼѡȡΧ
*@param [out] rowMin ѡΧСк(0~rowMax)
*@param [out] colMin ѡΧСк(0~colMax)
*@param [out] rowMax ѡΧк(rowMin~n)
*@param [out] colMax ѡΧк(colMin~n)
*@return TRUE:ȡɹFALSE:ȡʧܣ
*@note ǰͼѡȡһǰѡľηΧ
* صľηΧڻΧڡ
* ǰͼѡȡFALSE
* ηصľΪ(-1,-1,-1,-1)ʾǰδѡȡκα
*/
BOOL GetGridViewFlexSelection(int& rowMin,int& colMin,int& rowMax,int& colMax);
/********************************check operation******************************/
/**
*@brief ȡGridItemType_Check͵ıѡ״̬
*@param [in] nRow ɱк
*@param [in] nColumn ɱк
*@return TRUEѡ״̬
FALSEδѡ״̬GridItemType_Checkͱ
*/
BOOL GetCheckItemStatus(int nRow,int nColumn);
/**
*@brief ԱȫGridItemType_Check͵ıѡ
*@see AbstractGridViewManager::DeselectAllCheckItem()
*/
void SelectAllCheckItem();
/**
*@brief ԱȫGridItemType_Check͵ıзѡ
*@see AbstractGridViewManager::SelectAllCheckItem()
*/
void DeselectAllCheckItem();
void SelectRow(int nRow );
void SetColumnBkColor( int nColNum, const COLORREF &cofor );
protected:
/**
*@brief ԽĬͼǰijʼ
*@note ͼҪڴĬϱͼǰгʼӦ÷
*@see AbstractGridViewManager::AftCreateDefGridView()
*/
virtual void PreCreateDefGridView(){};
/**
*@brief ԽĬͼĺ
*@note ͼҪڴĬϱͼкӦ÷
*@see AbstractGridViewManager::PreCreateDefGridView()
*/
virtual void AftCreateDefGridView(){};
/**
*@brief Խûͼǰijʼ
*@note ͼҪڴûͼǰгʼӦ÷
*see AbstractGridViewManager::AftCreateGridView()
*/
virtual void PreCreateGridView(){};
/**
*@brief Խûͼĺ
*@note ͼҪڴûͼкӦ÷
*@see AbstractGridViewManager::PreCreateGridView()
*/
virtual void AftCreateGridView(){};
/**
*@brief ṩͼͼǰ
*@note ͼͼǰҪͼӦݣӶӰӦͼ
*/
virtual void PreUpdateGridView(){};
/**
*@brief ṩͼͼºĺ
*@note ͼͼºԶͼ
*/
virtual void AftUpdateGridView(){};
/**
*@brief ıĬͼͼб
*@note Ĭͼͼб0
*/
virtual CImageList* GetDefGridImageList() {return NULL;};
/**
*@brief ̳ıĬͼǷʹVirtual Mode
*@note ĬĬͼʹVirtual Mode
*/
virtual BOOL GetDefGridVirtualMode(){ return FALSE; };
virtual int GetDefFixedColumnCount(){return 1;}; /**<@brief ͼԸı<b>Ĭͼ</b><b>̶</b>Ŀ */
virtual int GetDefFixedRowCount(){return 1;}; /**<@brief ͼԸı<b>Ĭͼ</b><b>̶</b>Ŀ */
virtual int GetDefFlexColumnCount(){return 26;}; /**<@brief ͼԸı<b>Ĭͼ</b><b>ɱ</b>Ŀ */
virtual int GetDefFlexRowCount(){return 20;};/**<@brief ͼԸı<b>Ĭͼ</b><b>ɱ</b>Ŀ */
/** @brief ͼ<b>Ĭͼ</b><b>̶</b>ĸ߶ */
virtual int GetDefFixedRowHeight(int rowIndex){ return 25;};
/** @brief ͼ<b>Ĭͼ</b><b>̶</b>Ŀ */
virtual int GetDefFixedColumnWidth(int columnIndex){return 35;};
/** @brief ͼ<b>Ĭͼ</b><b>ɶ</b>ĸ߶ */
virtual int GetDefFlexRowHeight(int rowIndex) {return 25;};
/** @brief ͼ<b>Ĭͼ</b><b>ɶ</b>Ŀ */
virtual int GetDefFlexColumnWidth(int columnIndex){ return 50;};
/**
*@brief ͼԸı<b>Ĭͼ</b><b>ɱ</b>Ƿɱ༭
*note ֻпɱܹΪɱ༭״̬ģ̶Ϊɱ༭״̬
* ĬĬͼĿɱǿɱ༭״̬
*/
virtual BOOL GetDefFlexItemEditable(int nRow,int nColumn){return TRUE;};
/** @brief ͼԸı<b>Ĭͼ</b><b>̶</b> */
virtual CString GetDefFixedItemText(int nRow, int nColumn);
/** @brief ͼԸı<b>Ĭͼ</b><b>ɱ</b> */
virtual CString GetDefFlexItemText(int nRow, int nColumn){ CString text; return text;};
/**
*@brief ͼԻȡ<b>Ĭͼ</b><b>ɱ</b>ݸ
*@note ĬϱͼıǿдģûĬϱͼıú
* ᱻãûĺдͼ<b>ģ</b>С
*/
virtual BOOL SetDefFlexItemText(int nRow, int nColumn,CString text){ return FALSE;};
/**
*@brief ıûͼͼб
*@note ûͼͼб0
*/
virtual CImageList* GetGridImageList() { return NULL;};
/**
*@brief ̳ıûͼǷʹVirtual Mode
*@note ĬûͼʹVirtual Mode
*/
virtual BOOL GetGridVirtualMode(){ return FALSE;};
//Ĭ
virtual int GetFixedColumnCount() { return 1;}; /**<@brief ͼԸı<b>ûͼ</b><b>̶</b>Ŀ */
virtual int GetFixedRowCount() { return 1;}; /**<@brief ͼԸı<b>ûͼ</b><b>̶</b>Ŀ */
virtual int GetFlexColumnCount() {
return 26;}; /**<@brief ͼԸı<b>ûͼ</b><b>ɱ</b>Ŀ */
virtual int GetFlexRowCount() { return 20;}; /**<@brief ͼԸı<b>ûͼ</b><b>ɱ</b>Ŀ */
//иĬ
virtual int GetFixedRowHeight(int rowIndex){ return 25;};/** @brief ͼ<b>ûͼ</b><b>̶</b>ĸ߶ */
virtual int GetFixedColumnWidth(int columnIndex){ return 35;};/** @brief ͼ<b>ûͼ</b><b>̶</b>Ŀ */
virtual int GetFlexRowHeight(int rowIndex){ return 25;};/** @brief ͼ<b>ûͼ</b><b>ɶ</b>ĸ߶ */
virtual int GetFlexColumnWidth(int columnIndex){ return 50;};/** @brief ͼ<b>ûͼ</b><b>ɶ</b>Ŀ */
/**
*@brief ͼԸı<b>ûͼ</b><b>ɱ</b>
*@note ֻпɱܹı̶ͣı͡
* Ĭʹñ༭ؼ͵ı
*/
virtual GridItemType GetFlexItemType(int nRow,int nColumn){ return GridItemType_Edit;};
virtual GridItemType GetFixedItemType( int nRow, int nColumn ){ return GridItemType_Edit;}
/** @brief ͼԳʼ<b>ûͼ</b><b>Ͽ</b>͵Ŀɱ */
virtual BOOL InitFlexComboItem(CGridCellCombo* pCell,int nRow,int nColumn){return TRUE;};
/** @brief ͼԳʼ<b>ûͼ</b><b>ѡ</b>͵Ŀɱ */
virtual BOOL InitFlexCheckItem(CGridCellCheck* pCell,int nRow,int nColumn){return TRUE;};
/** @brief ͼԳʼ<b>ûͼ</b><b>ڿؼ</b>͵Ŀɱ */
virtual BOOL InitFlexDateTimeItem(CGridCellDateTime* pCell,int nRow,int nColumn){return TRUE;};
/** @brief ڳʼֿؼͣ*/
virtual BOOL InitFlexNumEditItem(CGridCellNumeric* pCell,int nRow,int nColumn){return TRUE;};
/** @brief ڳʼֿؼͣ*/
virtual BOOL InitFlexRichEditItem(CGridCellRich* pCell,int nRow,int nColumn){return TRUE;};
/** @brief Ĭ϶еһ֣ûԶչ */
virtual int GetFlexItemExtensionType(int nRow,int nColumn){return -1;};
/** @brief ͼԳʼ<b>ûͼ</b><b>Զչ</b>͵Ŀɱ */
virtual BOOL InitFlexExtensionItem(int extensionItemType,int nRow,int nColumn){return TRUE;};
/**
*@brief ͼԸı<b>ûͼ</b><b>ɱ</b>Ƿɱ༭
*note ֻпɱܹΪɱ༭״̬ģ̶Ϊɱ༭״̬
* ĬûͼĿɱǿɱ༭״̬
*/
virtual BOOL GetFlexItemEditable(int nRow,int nColumn){ return TRUE;};
virtual BOOL GetFixedItmeEditable( int nRow, int nColumn){ return FALSE;}
/** @brief ͼԸı<b>ûͼ</b><b>̶</b> */
virtual CString GetFixedItemText(int nRow, int nColumn);
/** @brief ͼԸı<b>ûͼ</b><b>ɱ</b> */
virtual CString GetFlexItemText(int nRow, int nColumn){ return CString();};
/**
*@brief ͼԻȡ<b>ûͼ</b><b>ɱ</b>ݸ
*@note ûͼıǿдģûûͼıú
* ᱻãûĺдͼ<b>ģ</b>С
*/
virtual BOOL SetFlexItemText(int nRow, int nColumn,CString text){return TRUE;}
/**
*@brief ͼ֤<b>ûͼ</b>ɱ
*@note ĬκУ飬ظ
*/
virtual BOOL ValidateFlexItemText(int nRow,int nColumn,CString text){ return TRUE;};
/**
*@brief ͼԳʼ<b>ûͼ</b><b>̶</b>˵
*@note ûpopupMenuӲ˵˵ɲ˵ʼ
* Ӳ˵Ҫ˵IDӦ˵
* Ӳ˵ҪȷӲ˵Ӳ˵롣
*/
virtual BOOL InitFixedItemPopupMenu(int nRow,int nColumn,CMenu* popupMenu){ return TRUE;};
/**
*@brief
*@note
*/
virtual BOOL ResponseFixedItemPopupMenu(UINT menuID) { return FALSE;};
/**
*@brief ͼԻȡ<b>ûͼ</b><b>ɱ</b>˵
*@note ûpopupMenuӲ˵˵ɲ˵ʼ
* Ӳ˵Ҫ˵IDӦ˵
* Ӳ˵ҪȷӲ˵Ӳ˵롣
*/
virtual BOOL InitFlexItemPopupMenu(int nRow,int nColumn,CMenu* popupMenu){ return FALSE;};
/**
*@brief
*@note
*/
virtual BOOL ResponseFlexItemPopupMenu(UINT menuID){ return FALSE;};
/**@brief עᵽıؼָ */
CGridCtrl* m_gridCtrl;
/**@brief ͼǷͼʶ */
BOOL m_bImageValid;
/**@brief ͼǷʹVirtual Modeʶ */
BOOL m_bVirtualMode;
/** @brief ǰͼ̶Ŀ */
int m_fixedRowCount;
/** @brief ǰͼ̶Ŀ */
int m_fixedColumnCount;
/** @brief ǰͼɶĿ */
int m_flexRowCount;
/** @brief ǰͼɶĿ */
int m_flexColumnCount;
int m_popupMenuRowIndex; /** @brief ˵ڵк */
int m_popupMenuColumnIndex; /** @brief ˵ڵк */
private:
/**
*@brief ñͼĬͼ
*@note ñĬͼơۡߴ硢
*@see
*/
void ResetDefGridView();
/**@brief Ĭͼ */
void SetDefGridName();
/**@brief Ĭͼ */
void SetDefGridLook();
/**@brief Ĭͼߴ */
void SetDefGridSize();
/**@brief Ĭͼ */
void SetDefGridContent();
/** @brief Ĭͼ */
void SetGridItemType(int nRow,int nColumn);
/** @brief Ĭͼ״̬ı */
void SetDefGridItemState(int nRow,int nColumn);
/**
*@brief ĬͼVirtual Modeص
*@param [in] lParam ͼthisָͨǿת뺯
*@param [out] pDispInfo ûĸýṹϢƱݡʽ
*@note ĬͼʹVirtual Modeʱûͼڱؼвб棬
* ʹøûصñݡ
*/
static BOOL CALLBACK DefCallBackFunction(GV_DISPINFO* pDispInfo,LPARAM lParam);
protected:
/**
*@brief ñͼûͼ
*@note ñûͼơۡߴ硢
*@see
*/
void ResetGridView();
/**@brief ûͼ */
void SetGridLook();
/**@brief ûͼߴ */
void SetGridSize();
/**@brief ûͼ */
void SetGridContent();
/** @brief ûͼ */
void SetGridItemState(int nRow,int nColumn);
/**
*@brief ûͼVirtual Modeص
*@param [in] lParam ͼthisָͨǿת뺯
*@param [out] pDispInfo ûĸýṹϢƱݡʽ
*@note ûͼʹVirtual Modeʱûͼڱؼвб棬
* ʹøûصñݡ
*/
static BOOL CALLBACK CallBackFunction(GV_DISPINFO* pDispInfo,LPARAM lParam);
};
| true |
73b3259660a21e53cbbf66fefdd151bf9333fe0e | C++ | benwhittington/3DTransformations | /src/main.cpp | UTF-8 | 3,909 | 2.53125 | 3 | [] | no_license | #define OLC_PGE_APPLICATION
#include <olcPixelGameEngine.h>
#include <vector>
#include <iostream>
#include "domain.hpp"
#include "mapRange.hpp"
#include "point.hpp"
#include "shape.hpp"
#include "transform.hpp"
static constexpr double pi = 3.141592;
class Transform : public olc::PixelGameEngine {
Shape<3> m_Shape0;
Shape<3> m_Shape1;
Point<3> m_N;
Point<3> m_Basis;
Point<2> m_ScreenOrigin;
Domain m_Domain;
Screen m_Screen;
double m_RadsPerSecond;
float m_SecondsSinceLastUpdate;
float m_MinDelta;
bool m_Pause;
public:
Transform() {
sAppName = "Transform";
}
public:
bool OnUserCreate() override {
// pyramid
m_Shape0 = Shape<3>(5)
<< Point<3>(-1, 0, 0)
<< Point<3>(1, 0, 0)
<< Point<3>(0, 1, 0)
<< Point<3>(0, 0, 1)
<< Point<3>(0, 0, -1);
// cube
m_Shape1 = Shape<3>(8)
<< Point<3>(0, 0, 0)
<< Point<3>(1, 0, 0)
<< Point<3>(1, 0, 1)
<< Point<3>(0, 0, 1)
<< Point<3>(0, 1, 0)
<< Point<3>(1, 1, 0)
<< Point<3>(1, 1, 1)
<< Point<3>(0, 1, 1);
m_Shape1 += Point<3>(1, 1, 1);
std::cout << m_Shape1[0].x() << ", " << m_Shape1[0].x() << ", " << m_Shape1[0].x() << std::endl;
m_N = Point<3>(0, 1, -1);
m_Basis = Point<3>(1, 1, 1);
m_Basis /= m_Basis.Norm();
m_Domain = Domain(-2, 2, -2, 2);
m_Screen = Screen(ScreenWidth(), ScreenHeight());
m_ScreenOrigin = Point<2>(ScreenWidth() / 2, ScreenHeight() / 2);
m_MinDelta = 0.005;
m_SecondsSinceLastUpdate = m_MinDelta + 1;
m_RadsPerSecond = pi / 2;
m_Pause = false;
return true;
}
void DrawShapeConsecutive(const Shape<3>& shapeIn) {
// iterates throught the points drawing lines from the current point to the next
const auto shapeDraw = ProjectAndMap(shapeIn);
for (size_t i = 0; i < shapeDraw.NumPoints(); ++i) {
const auto next = (i + 1) % shapeDraw.NumPoints();
DrawLine(shapeDraw[i].x(), shapeDraw[i].y(), shapeDraw[next].x(), shapeDraw[next].y());
}
}
void DrawShapeAll(Shape<3>& shapeIn) {
// draws line from each point to every other point
const auto shapeDraw = ProjectAndMap(shapeIn);
for (size_t i = 0; i < shapeDraw.NumPoints(); ++i) {
for (size_t j = i; j < shapeDraw.NumPoints(); ++j) {
DrawLine(shapeDraw[i].x(), shapeDraw[i].y(), shapeDraw[j].x(), shapeDraw[j].y());
}
}
}
Shape<2> ProjectAndMap(const Shape<3>& shape) {
const auto projected = trans::Project<X, Y>(shape, m_N);
return map::MapFromDomainToScreen(projected, m_Domain, m_Screen);
}
void GetUserInput() {
using K = olc::Key;
double angle = m_RadsPerSecond * pi / 2500;
if (GetKey(K::W).bHeld) {
trans::Rotate<X>(m_N, angle);
}
else if (GetKey(K::S).bHeld) {
trans::Rotate<X>(m_N, -angle);
}
else if (GetKey(K::D).bHeld) {
trans::Rotate<Y>(m_N, -angle);
}
else if (GetKey(K::A).bHeld) {
trans::Rotate<Y>(m_N, angle);
}
else if (GetKey(K::Q).bHeld) {
trans::Rotate<Z>(m_N, angle);
}
else if (GetKey(K::E).bHeld) {
trans::Rotate<Z>(m_N, -angle);
}
else if (GetKey(K::EQUALS).bHeld) {
m_Domain.ZoomOut();
}
else if (GetKey(K::MINUS).bHeld) {
m_Domain.ZoomIn();
}
else if (GetKey(K::SPACE).bPressed) {
m_SecondsSinceLastUpdate = 0;
m_Pause = !m_Pause;
}
}
bool OnUserUpdate(float secondsDelta) override {
m_SecondsSinceLastUpdate += secondsDelta;
if (m_Pause || m_SecondsSinceLastUpdate < m_MinDelta) {
return true;
}
GetUserInput();
const auto angle = m_RadsPerSecond * static_cast<float>(m_SecondsSinceLastUpdate);
trans::Rotate<Y>(m_Shape0, angle); // rotate the object
trans::Rotate<Z>(m_N, angle * 0.1); // rotate the reference frame more slowly
Clear(olc::BLACK);
DrawShapeAll(m_Shape0);
DrawShapeAll(m_Shape1);
m_SecondsSinceLastUpdate = 0;
return true;
}
};
int main() {
Transform demo;
if (demo.Construct(1024, 1024, 1, 1))
demo.Start();
return 0;
} | true |
fdb8a40878be92abc15c2612f051d555edc6e0ff | C++ | harsh735/practice | /ATM HS08TEST.cpp | UTF-8 | 304 | 2.953125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
// your code goes here
int x;
float y;
cin>>x>>y;
if(x%5 == 0 && y >=(x+.5))
{
y = y - (x + .5);
cout<<y;
}
else if(x > y)
{
cout<<y;
}
else
{
cout<<y;
}
return 0;
}
| true |
1089c5e7c55a04e29482041b2cbebc9c9d0133fd | C++ | BlueAndi/esp-rgb-led-matrix | /lib/AudioService/src/SpectrumAnalyzer.h | UTF-8 | 5,766 | 2.609375 | 3 | [
"GPL-3.0-only",
"LGPL-2.1-only",
"MIT",
"BSD-3-Clause",
"LGPL-3.0-only",
"Apache-2.0"
] | permissive | /* MIT License
*
* Copyright (c) 2019 - 2023 Andreas Merkle <web@blue-andi.de>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*******************************************************************************
DESCRIPTION
*******************************************************************************/
/**
* @brief Spectrum analyzer
* @author Andreas Merkle <web@blue-andi.de>
*
* @addtogroup audio_service
*
* @{
*/
#ifndef SPECTRUM_ANALYZER_H
#define SPECTRUM_ANALYZER_H
/******************************************************************************
* Includes
*****************************************************************************/
#include <stdint.h>
#include <arduinoFFT.h>
#include <Mutex.hpp>
#include "AudioDrv.h"
/******************************************************************************
* Compiler Switches
*****************************************************************************/
/******************************************************************************
* Macros
*****************************************************************************/
/******************************************************************************
* Types and Classes
*****************************************************************************/
/**
* A spectrum analyzer, which transforms time discrete samples to
* frequency spectrum bands.
*/
class SpectrumAnalyzer : public IAudioObserver
{
public:
/**
* Constructs the spectrum analyzer instance.
*/
SpectrumAnalyzer() :
m_mutex(),
m_real{0.0f},
m_imag{0.0f},
m_fft(m_real, m_imag, AudioDrv::SAMPLES, AudioDrv::SAMPLE_RATE),
m_freqBins{0.0f},
m_freqBinsAreReady(false)
{
}
/**
* Destroys the spectrum analyzer instance.
*/
~SpectrumAnalyzer()
{
/* Never called. */
}
/**
* The audio driver will call this method to notify about a complete available
* number of samples.
*
* @param[in] data Audio sample data buffer
* @param[in] size Number of audio samples
*/
void notify(int32_t* data, size_t size) final;
/**
* Get the number of frequency bins.
*
* @return Number of frequency bins
*/
size_t getFreqBinsLen() const
{
return FREQ_BINS;
}
/**
* Get frequency bins by copy.
*
* @param[out] freqBins Frequency bin buffer, where to write.
* @param[in] len Length of frequency bin buffer in elements.
*
* @return If successful, it will return true otherwise false.
*/
bool getFreqBins(float* freqBins, size_t len);
/**
* Are the frequency bins updated and ready?
*
* @return If the frequency bins are ready, it will return true otherwise false.
*/
bool areFreqBinsReady() const
{
MutexGuard<Mutex> guard(m_mutex);
return m_freqBinsAreReady;
}
private:
/**
* The number of frequency bins over the spectrum. Note, this is always
* half of the samples, because they are symmetrical around DC.
*/
static const uint32_t FREQ_BINS = AudioDrv::SAMPLES / 2U;
mutable Mutex m_mutex; /**< Mutex used for concurrent access protection. */
float m_real[AudioDrv::SAMPLES]; /**< The real values. */
float m_imag[AudioDrv::SAMPLES]; /**< The imaginary values. */
ArduinoFFT<float> m_fft; /**< The FFT algorithm. */
float m_freqBins[FREQ_BINS]; /**< The frequency bins as result of the FFT, with linear magnitude. */
bool m_freqBinsAreReady; /**< Are the frequency bins ready for the application? */
SpectrumAnalyzer(const SpectrumAnalyzer& drv);
SpectrumAnalyzer& operator=(const SpectrumAnalyzer& drv);
/**
* Transform from discrete time to frequency spectrum.
* Note, the magnitude will be calculated linear and not in dB.
*/
void calculateFFT();
/**
* Copy FFT result to frequency bins.
* This function is protected against concurrent access.
*/
void copyFreqBins();
};
/******************************************************************************
* Variables
*****************************************************************************/
/******************************************************************************
* Functions
*****************************************************************************/
#endif /* SPECTRUM_ANALYZER_H */
/** @} */ | true |
dc5152b393c046d96c3899778190f0d041a4ee4f | C++ | Hapiny/msu-compiler-course | /fdom/main.cpp | UTF-8 | 3,542 | 2.8125 | 3 | [] | no_license | #ifdef __cplusplus
#define export exports
extern "C" {
#include "qbe/all.h"
}
#undef export
#else
#include "qbe/all.h"
#endif
#include <iostream>
#include <unordered_map>
/*
Keith Cooper, Timothy Harvey, and Ken Kennedy.
A simple, fast dominance algorithm.
Rice University, CS Technical Report 06-33870, 01 2006
*/
// function intersect(b1, b2) returns node
// finger1 ← b1
// finger2 ← b2
// while (finger1 != finger2)
// while (finger1 < finger2)
// finger2 = doms[finger2]
// while (finger2 < finger1)
// finger1 = doms[finger1]
// return finger1
Blk* intersect(Blk* b1, Blk* b2, std::unordered_map<Blk*, Blk*> &doms) {
if (!b1) return b2;
if (!b2) return b1;
auto finger1 = b1, finger2 = b2;
while (finger1->id != finger2->id) {
while (finger1->id < finger2->id) {
// std::cout << "1" << std::endl;
finger2 = doms[finger2];
}
while (finger2->id < finger1->id) {
// std::cout << "2" << std::endl;
finger1 = doms[finger1];
}
}
return finger1;
}
// for all nodes, b /* initialize the dominators array */
// doms[b] ← Undefined
// doms[start node] ← start node
// Changed ← true
// while (Changed)
// Changed ← false
// for all nodes, b, in reverse postorder (except start node)
// new idom ← first (processed) predecessor of b /* (pick one) */
// for all other predecessors, p, of b
// if doms[p] != Undefined /* i.e., if doms[p] already calculated */
// new idom ← intersect(p, new idom)
// if doms[b] != new idom
// doms[b] ← new idom
// Changed ← true
void simple_fast_dominators(Fn* fn, std::unordered_map<Blk*, Blk*> &doms) {
doms[fn->start] = fn->start;
bool changed = true;
while (changed) {
changed = false;
uint all_nodes_num = fn->nblk;
Blk** rpo_blocks = fn->rpo;
for (uint b = 0; b < all_nodes_num; b++) {
Blk* blk = rpo_blocks[b];
// std::cout << (std::string)blk->name << std::endl;
Blk** predecessors = blk->pred;
uint predecessors_num = blk->npred;
Blk* new_idom = nullptr;
for (uint p = 0; p < predecessors_num; p++) {
Blk* pred_blk = predecessors[p];
if (doms[pred_blk]) {
new_idom = intersect(pred_blk, new_idom, doms);
}
}
if (new_idom && doms[blk] != new_idom) {
doms[blk] = new_idom;
changed = true;
}
}
}
}
static void readfn (Fn *fn) {
fillpreds(fn);
fillrpo(fn);
// init doms
std::unordered_map<Blk*, Blk*> doms;
// fill doms
simple_fast_dominators(fn, doms);
// print result
// std::cout << "END!!!" << std::endl;
// std::cout << doms.size() << std::endl;
// for ( auto it = doms.begin(); it != doms.end(); ++it )
// std::cout << " " << it->first << " : " << it->second;
// std::cout << std::endl;
for(Blk* blk = fn->start; blk; blk = blk->link) {
std::string blk_name = "@" + (std::string)blk->name;
std::string dom_name = "@" + (std::string)doms[blk]->name;
std::cout << blk_name << "\t" << dom_name << std::endl;
}
}
static void readdat (Dat *dat) {
(void) dat;
}
int main () {
parse(stdin, (char *)"<stdin>", readdat, readfn);
freeall();
} | true |
6d81ee1d445ab805b2cb2e233ac157b3b1728669 | C++ | ezraezra101/coursework | /WPI_3_IMGD_3000_Game_Engine/dragonfly_only_ezra/src/EventMouse.cpp | UTF-8 | 891 | 2.8125 | 3 | [] | no_license | #include "EventMouse.h"
df::EventMouse::EventMouse() {
setType(df::MOUSE_EVENT);
btn = df::UNDEFINED_MOUSE_BUTTON;
action = UNDEFINED_MOUSE_ACTION;
mouse_xy = Position();
}
df::EventMouse::EventMouse(EventMouseButton init_btn, EventMouseAction init_action, Position pos) {
setType(df::MOUSE_EVENT);
btn = init_btn;
action = init_action;
mouse_xy = pos;
}
void df::EventMouse::setMouseButton(df::EventMouseButton new_button) {
btn = new_button;
}
df::EventMouseButton df::EventMouse::getMouseButton() const {
return btn;
}
void df::EventMouse::setMouseAction(df::EventMouseAction new_action) {
action = new_action;
}
df::EventMouseAction df::EventMouse::getMouseAction() const {
return action;
}
void df::EventMouse::setMousePosition(df::Position pos) {
mouse_xy.setXY(pos.getX(), pos.getY());
}
df::Position df::EventMouse::getMousePosition() const {
return mouse_xy;
} | true |
7cad0aae9c3c4fe90583032579f53e2c7c3e623b | C++ | ryanulep/cs100_lab03 | /container.h | UTF-8 | 1,420 | 3.328125 | 3 | [] | no_license | #ifndef CONTAINER_H
#define CONTAINER_H
#include <stdexcept>
#include <stdlib.h>
#include <list>
#include <vector>
#include "Base.h"
#include "sort.h"
class Sort;
class Container {
protected:
Sort* sort_function;
public:
Container() : sort_function(NULL) { };
Container(Sort* function) : sort_function(function) { };
void set_sort_function(Sort* sort_function) {
this->sort_function = sort_function;
}
virtual void add_element(Base* element) = 0;
virtual void print() = 0;
virtual void sort() = 0;
// switch tree locations
virtual void swap(int i, int j) = 0;
// get top ptr of tree at index i
virtual Base* at(int i) = 0;
// return container size
virtual int size() = 0;
};
class ListContainer : public Container {
protected:
list<Base*> listcont;
public:
ListContainer() { };
ListContainer(Sort* sort_function) : Container(sort_function) { };
void add_element(Base* element);
void print();
void sort();
void swap(int i, int j);
Base* at(int i);
int size();
};
class VectorContainer : public Container {
protected:
vector<Base*> vectcont;
public:
VectorContainer();
VectorContainer(Sort* sort_function);
void add_element(Base* element);
void print();
void sort();
void swap(int i, int j);
Base* at(int i);
int size();
};
#endif
| true |
bd77fe0c5fc4d63228fac0caf55f75a82beac932 | C++ | bfelger/BloomFilter | /include/bjf/Hash/Murmur3.hpp | UTF-8 | 4,663 | 2.8125 | 3 | [] | no_license | ///////////////////////////////////////////////////////////////////////////////
// Murmur3.hpp
///////////////////////////////////////////////////////////////////////////////
#pragma once
#ifndef BJF__MURMUR3_HPP
#define BJF__MURMUR3_HPP
#include "hash.hpp"
namespace bjf::Hash {
constexpr hash_t rotl(const hash_t& x, const uint8_t& r)
{
return (x << r) | (x >> (hash_size - r));
}
constexpr hash_t get_block(const hash_t* p, const int& i)
{
return p[i];
}
#ifdef HASH_64
constexpr hash_t fmix(const hash_t& k)
{
auto k2 = k;
k2 ^= k2 >> 33;
k2 *= 0xff51afd7ed558ccd;
k2 ^= k2 >> 33;
k2 *= 0xc4ceb9fe1a85ec53;
k2 ^= k2 >> 33;
return k2;
}
constexpr std::size_t mm3_block_size = 16; // Work 128-bits at a time.
constexpr hash_t mm3_c1 = 0x87c37b91114253d5;
constexpr hash_t mm3_c2 = 0x4cf5ad432745937f;
#else // 32-bit
constexpr hash_t fmix(const hash_t& k)
{
k ^= k >> 16;
k *= 0x85ebca6b;
k ^= k >> 13;
k *= 0xc2b2ae35;
k ^= k >> 16;
return k;
}
constexpr std::size_t mm3_block_size = 4; // Work 32-bits at a time.
constexpr hash_t mm3_c1 = 0xcc9e2d51;
constexpr hash_t mm3_c2 = 0x1b873593;
#endif
struct mm3_result {
hash_t v1;
#ifdef HASH_64
hash_t v2;
constexpr mm3_result(hash_t v1, hash_t v2) noexcept
: v1{ v1 }, v2{ v2 }
{}
#else
constexpr mm3_result(hash_t v1) noexcept
: v1{ v1 }
{}
#endif
};
constexpr int mm3_chunk_size = mm3_block_size / hash_size;
constexpr mm3_result murmur3_hash(const char* str, const std::size_t& len, const hash_t& seed)
{
const char* data = str;
const std::size_t num_blocks = len / mm3_block_size;
hash_t h1 = seed;
#ifdef HASH_64
hash_t h2 = seed;
#endif
const hash_t* blocks = (const hash_t*)(&data);
for (int i = 0; i < num_blocks; i++) {
hash_t k1 = get_block(blocks, i * mm3_block_size + 0);
#ifdef HASH_64
hash_t k2 = get_block(blocks, i * mm3_block_size + 1);
k1 *= mm3_c1;
k1 = rotl(k1, 31);
k1 *= mm3_c2;
h1 ^= k1;
h1 = rotl(h1, 27);
h1 += h2;
h1 = h1 * 5 + 0x52dce729;
k2 *= mm3_c2;
k2 = rotl(k2, 33);
k2 *= mm3_c1;
h2 ^= k2;
h2 = rotl(h2, 31);
h2 += h1;
h2 = h2 * 5 + 0x38495ab5;
#else
k1 *= c1;
k1 = rotl(k1, 15);
k1 *= c2;
h1 ^= k1;
h1 = rotl(h1, 13);
h1 = h1 * 5 + 0xe6546b64;
#endif
}
const char* tail = data + num_blocks * mm3_block_size;
hash_t k1 = 0;
#ifdef HASH_64
hash_t k2 = 0;
const int rotl_shift = 33;
#else
const int rotl_shift = 15;
#endif
switch (len & (mm3_block_size - 1))
{
#ifdef HASH_64
case 15: k2 ^= ((hash_t)tail[14]) << 48; [[fallthrough]];
case 14: k2 ^= ((hash_t)tail[13]) << 40; [[fallthrough]];
case 13: k2 ^= ((hash_t)tail[12]) << 32; [[fallthrough]];
case 12: k2 ^= ((hash_t)tail[11]) << 24; [[fallthrough]];
case 11: k2 ^= ((hash_t)tail[10]) << 16; [[fallthrough]];
case 10: k2 ^= ((hash_t)tail[9]) << 8; [[fallthrough]];
case 9: k2 ^= ((hash_t)tail[8]) << 0;
k2 *= mm3_c2;
k2 = rotl(k2, 33);
k2 *= mm3_c1;
h2 ^= k2; [[fallthrough]];
case 8: k1 ^= ((hash_t)tail[7]) << 56; [[fallthrough]];
case 7: k1 ^= ((hash_t)tail[6]) << 48; [[fallthrough]];
case 6: k1 ^= ((hash_t)tail[5]) << 40; [[fallthrough]];
case 5: k1 ^= ((hash_t)tail[4]) << 32; [[fallthrough]];
case 4: k1 ^= ((hash_t)tail[3]) << 24; [[fallthrough]];
#endif
case 3: k1 ^= ((hash_t)tail[2]) << 16; [[fallthrough]];
case 2: k1 ^= ((hash_t)tail[1]) << 8; [[fallthrough]];
case 1: k1 ^= ((hash_t)tail[0]) << 0;
k1 *= mm3_c1;
k1 = rotl(k1, rotl_shift);
k1 *= mm3_c2;
h1 ^= k1;
};
h1 ^= len;
#ifdef HASH_64
h2 ^= len;
h1 += h2;
h2 += h1;
#endif
h1 = fmix(h1);
#ifdef HASH_64
h2 = fmix(h2);
h1 += h2;
h2 += h1;
#endif
#ifdef HASH_64
return mm3_result{ h1, h2 };
#else
return mm3_result{ h1 };
#endif
}
}
#endif // !BJF__MURMUR3_HPP
| true |
1d9430a751892b03b4faa4017a566ff954fc01cd | C++ | WardF/hycast | /test/inet/Socket_test.cpp | UTF-8 | 7,099 | 2.625 | 3 | [
"UCAR"
] | permissive | /**
* This file tests class `Socket`.
*
* Copyright 2019 University Corporation for Atmospheric Research. All rights
* reserved. See file "COPYING" in the top-level source-directory for usage
* restrictions.
*
* File: Socket_test.cpp
* Created On: May 17, 2019
* Author: Steven R. Emmerson
*/
#include "config.h"
#include "error.h"
#include <gtest/gtest.h>
#include <main/inet/Socket.h>
#include <condition_variable>
#include <mutex>
#include <signal.h>
#include <thread>
#undef USE_SIGTERM
namespace {
#ifdef USE_SIGTERM
static void signal_handler(int const sig)
{}
#endif
/// The fixture for testing class `Socket`
class SocketTest : public ::testing::Test
{
protected:
hycast::SockAddr srvrAddr;
std::mutex mutex;
std::condition_variable cond;
bool srvrReady;
std::thread srvrThread;
hycast::TcpSrvrSock acceptSock; ///< Server's `::accept()` socket
hycast::TcpSock srvrSock; ///< Socket from `::accept()`
// You can remove any or all of the following functions if its body
// is empty.
SocketTest()
: srvrAddr{"127.0.0.1:38800"} // Don't use "localhost" to enable comparison
, mutex{}
, cond{}
, srvrReady{false}
, srvrThread()
, acceptSock()
, srvrSock()
{
// You can do set-up work for each test here.
}
virtual ~SocketTest()
{
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
virtual void SetUp()
{
// Code here will be called immediately after the constructor (right
// before each test).
#ifdef USE_SIGTERM
struct sigaction sigact;
(void)::sigemptyset(&sigact.sa_mask);
sigact.sa_flags = 0;
sigact.sa_handler = signal_handler;
(void)sigaction(SIGTERM, &sigact, NULL);
#endif
}
virtual void TearDown()
{
// Code here will be called immediately after each test (right
// before the destructor).
#ifdef USE_SIGTERM
struct sigaction sigact;
(void)::sigemptyset(&sigact.sa_mask);
sigact.sa_flags = 0;
sigact.sa_handler = SIG_DFL;
(void)sigaction(SIGTERM, &sigact, NULL);
#endif
}
// Objects declared here can be used by all tests in the test case for Socket.
public:
void runServer()
{
{
std::lock_guard<decltype(mutex)> lock{mutex};
srvrReady = true;
cond.notify_one();
}
try {
srvrSock = acceptSock.accept();
if (srvrSock) {
for (;;) {
int readInt;
srvrSock.read(&readInt, sizeof(readInt));
srvrSock.write(&readInt, sizeof(readInt));
}
}
}
catch (std::exception const& ex) {
std::cout << "runserver(): Exception caught\n";
}
}
void startServer()
{
acceptSock = hycast::TcpSrvrSock(srvrAddr);
srvrThread = std::thread(&SocketTest::runServer, this);
// Necessary because `ClntSock` constructor throws if `connect()` fails
std::unique_lock<decltype(mutex)> lock{mutex};
while (!srvrReady)
cond.wait(lock);
}
};
// Tests copy construction
TEST_F(SocketTest, CopyConstruction)
{
hycast::TcpSrvrSock srvrSock{srvrAddr};
hycast::TcpSrvrSock sock(srvrSock);
}
// Tests setting the Nagle algorithm
TEST_F(SocketTest, SettingNagle)
{
hycast::TcpSrvrSock srvrSock(srvrAddr);
EXPECT_TRUE(&srvrSock.setDelay(false) == &srvrSock);
}
// Tests server-socket construction
TEST_F(SocketTest, ServerConstruction)
{
hycast::TcpSrvrSock srvrSock(srvrAddr);
hycast::SockAddr sockAddr(srvrSock.getLclAddr());
LOG_DEBUG("%s", sockAddr.to_string().c_str());
EXPECT_TRUE(!(srvrAddr < sockAddr) && !(sockAddr < srvrAddr));
}
#if 0
// Calling shutdown() on a TCP connection doesn't cause poll() to return
// Tests shutdown of socket while reading
TEST_F(SocketTest, ReadShutdown)
{
startServer();
hycast::TcpClntSock clntSock(srvrAddr);
::sleep(1);
acceptSock.shutdown();
srvrThread.join();
}
#endif
// Tests canceling the server thread while accept() is executing
TEST_F(SocketTest, CancelAccept)
{
startServer();
#ifdef USE_SIGTERM
::pthread_kill(srvrThread.native_handle(), SIGTERM);
#else
::pthread_cancel(srvrThread.native_handle());
#endif
srvrThread.join();
}
// Tests shutting down the server's accept-socket
TEST_F(SocketTest, ShutdownAccept)
{
startServer();
acceptSock.shutdown();
srvrThread.join();
}
// Tests canceling the server thread while read() is executing
TEST_F(SocketTest, CancelRead)
{
startServer();
hycast::TcpClntSock clntSock(srvrAddr);
::usleep(100000);
#ifdef USE_SIGTERM
::pthread_kill(srvrThread.native_handle(), SIGTERM);
#else
::pthread_cancel(srvrThread.native_handle());
#endif
srvrThread.join();
}
// Tests shutting down the server's socket while read() is executing
TEST_F(SocketTest, shutdownRead)
{
startServer();
hycast::TcpClntSock clntSock(srvrAddr);
::usleep(100000);
srvrSock.shutdown();
srvrThread.join();
}
// Tests shutting down the server's socket while write() is executing
TEST_F(SocketTest, shutdownWrite)
{
startServer();
hycast::TcpClntSock clntSock(srvrAddr);
int writeInt = 0xff00;
clntSock.write(&writeInt, sizeof(writeInt));
::usleep(100000);
srvrSock.shutdown();
srvrThread.join();
}
// Tests round-trip scalar exchange
TEST_F(SocketTest, ScalarExchange)
{
startServer();
hycast::TcpClntSock clntSock(srvrAddr);
int writeInt = 0xff00;
int readInt = ~writeInt;
clntSock.write(&writeInt, sizeof(writeInt));
clntSock.read(&readInt, sizeof(readInt));
EXPECT_EQ(writeInt, readInt);
::pthread_cancel(srvrThread.native_handle());
srvrThread.join();
}
// Tests round-trip vector exchange
TEST_F(SocketTest, VectorExchange)
{
startServer();
hycast::TcpClntSock clntSock(srvrAddr);
int writeInt[2] = {0xff00, 0x00ff};
int readInt[2] = {0};
struct iovec iov[2];
clntSock.write(writeInt, sizeof(writeInt));
clntSock.read(readInt, sizeof(writeInt));
EXPECT_EQ(writeInt[0], readInt[0]);
EXPECT_EQ(writeInt[1], readInt[1]);
::pthread_cancel(srvrThread.native_handle());
srvrThread.join();
}
} // namespace
int main(int argc, char **argv) {
/*
* Ignore SIGPIPE so that writing to a closed socket doesn't terminate the
* process (the return-value from write() is always checked).
*/
struct sigaction sigact;
sigact.sa_handler = SIG_IGN;
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = 0;
(void)sigaction(SIGPIPE, &sigact, NULL);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| true |
7cb4a9f9da5f63c729f0705a99d19f63943322e8 | C++ | SimKyuSung/Algorithm | /BeakJoon C++ Algorithm/1267핸드폰 요금.cpp | UHC | 382 | 3.046875 | 3 | [] | no_license | /// 1267ڵ
#include <iostream>
using namespace std;
int main()
{
int n; cin >> n;
unsigned long long y = 0, m = 0;
while (n--) {
unsigned long long input; cin >> input;
y += ((input + 30) / 30) * 10;
m += ((input + 60) / 60) * 15;
}
if (y > m) cout << "M " << m << endl;
else if (m > y) cout << "Y " << y << endl;
else cout << "Y M " << y << endl;
} | true |
41b87cf3f95770b7ddaa9428eec1c9ee4873368e | C++ | bonetblai/cp2fsc-and-replanner | /benchmarks/replanner/wumpus/kill/generator.cc | UTF-8 | 10,170 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <deque>
#include <set>
#include <cassert>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>
using namespace std;
struct Map {
int height;
int width;
int *map;
Map(istream &is) : height(0), width(0), map(0) {
string token;
is >> token;
assert(token == "type");
is >> token >> token;
assert(token == "height");
is >> height >> token;
assert(token == "width");
is >> width >> token;
assert(token == "map");
assert(height > 0);
assert(width > 0);
map = new int[height*width];
for( int y = height-1; y >= 0; --y ) {
for( int x = 0; x < width; ++x ) {
char c;
is >> c;
map[y*width + x] = c == '.' ? 0 : 1;
}
}
}
~Map() { delete map; }
bool wall(int x, int y) const { return map[y*width + x] == 1; }
};
struct Instance {
string mapfile;
string name;
Map *map;
int n_xpos;
int n_ypos;
int init;
int wumpus;
vector<bool> reachable;
vector<int> reachable_space;
vector<int> walls;
vector<int> non_walls;
Instance(string mfile)
: mapfile(mfile), map(0), n_xpos(0), n_ypos(0), init(0), wumpus(0) {
char *fname = strdup(mapfile.c_str()), *str = basename(fname);
char *ptr = &str[strlen(str)-4];
*ptr = '\0';
name = str;
// read map and calculate basic info
ifstream is(mapfile.c_str());
assert(!is.fail());
map = new Map(is);
is.close();
n_xpos = map->width;
n_ypos = map->height;
for( int x = 0; x < n_xpos; ++x ) {
for( int y = 0; y < n_ypos; ++y ) {
if( wall(x,y) )
walls.push_back(x*n_ypos + y);
else
non_walls.push_back(x*n_ypos + y);
}
}
if( non_walls.size() == 0 ) {
cerr << "Error: " << name << " has no free ground" << endl;
exit(-1);
}
// set initial position and calculate reachable positions
init = non_walls[lrand48() % non_walls.size()];
reachable = vector<bool>(n_xpos*n_ypos, false);
deque<int> q;
q.push_back(init);
reachable[init] = true;
reachable_space.push_back(init);
while( !q.empty() ) {
int s = q.front(), sx = s / n_ypos, sy = s % n_ypos;
q.pop_front();
for( int op = 0; op < 4; ++op ) { // 0=up, 1=right, 2=down, 3=left
int nx = sx, ny = sy;
if( op == 0 ) {
ny++;
if( (ny >= n_ypos) || wall(nx,ny) ) continue;
} else if( op == 1 ) {
nx++;
if( (nx >= n_xpos) || wall(nx,ny) ) continue;
} else if( op == 2 ) {
ny--;
if( (ny < 0) || wall(nx,ny) ) continue;
} else {
nx--;
if( (nx < 0) || wall(nx,ny) ) continue;
}
int n = nx*n_ypos + ny;
if( !reachable[n] ) {
q.push_back(n);
reachable[n] = true;
reachable_space.push_back(n);
}
}
}
// place wumpus in one of reachable positions except init
wumpus = init;
while( wumpus == init )
wumpus = reachable_space[lrand48() % reachable_space.size()];
}
~Instance() { delete map; }
bool adj(int p1, int p2) const {
int x1 = p1 / n_ypos, y1 = p1 % n_ypos;
int x2 = p2 / n_ypos, y2 = p2 % n_ypos;
if( (x1 == x2) && ((y1 == y2+1) || (y1 == y2-1)) )
return true;
if( ((x1 == x2+1) || (x1 == x2-1)) && (y1 == y2) )
return true;
return false;
}
bool wall(int x, int y) const { return map->wall(x, y); }
bool wall(pair<int, int> &p) const { return map->wall(p.first, p.second); }
void print(ostream &os, bool print_wall = true) const {
os << ";; dim=(" << n_xpos << "," << n_ypos << ")" << endl;
os << ";; init=(" << init/n_ypos << "," << init%n_ypos << ")" << endl;
os << ";; wumpus=(" << wumpus/n_ypos << "," << wumpus%n_ypos << ")" << endl;
for( int y = n_ypos-1; y >= 0; --y ) {
os << ";; ";
for( int x = 0; x < n_xpos; ++x ) {
int s = x*n_ypos + y;
if( init == s )
os << 'I';
else if( wumpus == s )
os << 'w';
else {
if( print_wall )
os << (wall(x,y) ? '@' : '.');
else
os << '.';
}
}
os << endl;
}
}
};
void generate_problem(ostream &os, const Instance &ins) {
int n_xpos = ins.n_xpos, n_ypos = ins.n_ypos;
ins.print(os);
os << endl;
os << "(define (problem " << ins.name << ")" << endl
<< " (:domain kill-wumpus)" << endl;
// objects
os << " (:objects";
for( int x = 0; x < n_xpos; ++x ) {
for( int y = 0; y < n_ypos; ++y ) {
int p = x*n_ypos + y;
if( ins.reachable[p] )
os << " p" << p;
}
}
os << " - pos)" << endl;
// initial situation
os << " (:init" << endl;
// adjacency
for( int p = 0; p < n_xpos*n_ypos; ++p ) {
if( ins.reachable[p] ) {
int x = p / n_ypos, y = p % n_ypos;
if( (y+1 < n_ypos) && ins.reachable[x*n_ypos + y+1] )
os << " (adj p" << p << " p" << x*n_ypos+y+1 << ")" << endl;
if( (x+1 < n_xpos) && ins.reachable[(x+1)*n_ypos + y] )
os << " (adj p" << p << " p" << (x+1)*n_ypos+y << ")" << endl;
if( (y-1 >= 0) && ins.reachable[x*n_ypos + y-1] )
os << " (adj p" << p << " p" << x*n_ypos+y-1 << ")" << endl;
if( (x-1 >= 0) && ins.reachable[(x-1)*n_ypos + y] )
os << " (adj p" << p << " p" << (x-1)*n_ypos+y << ")" << endl;
}
}
os << endl;
// initial position
assert(ins.reachable[ins.init]);
os << " (at p" << ins.init << ")" << endl
<< " (not (stench p" << ins.init << "))" << endl
<< " (not (wumpus p" << ins.init << "))" << endl;
// Invariants: (or wumpus(p) -wumpus(p))
os << endl << " ; Invariants: (or wumpus(p) -wumpus(p))" << endl;
for( int i = 0; i < ins.reachable_space.size(); ++i ) {
int p = ins.reachable_space[i];
os << " "
<< "(invariant (wumpus p" << p << ") (not (wumpus p" << p << ")))"
<< endl;
}
// Invariants: (or stench(p) -stench(p))
os << endl << " ; Invariants: (or stench(p) -stench(p))" << endl;
for( int i = 0; i < ins.reachable_space.size(); ++i ) {
int p = ins.reachable_space[i];
os << " "
<< "(invariant (stench p" << p << ") (not (stench p" << p << ")))"
<< endl;
}
// Invariants: (or -stench(p) wumpus(p1) ... wumpus(p4)) where adj(p,pi)
os << endl << " ; Invariants: (or -stench(p) wumpus(p1) .. wumpus(p4))" << endl;
for( int i = 0; i < ins.reachable_space.size(); ++i ) {
int p = ins.reachable_space[i];
os << " "
<< "(invariant (not (stench p" << p << "))";
for( int j = 0; j < ins.reachable_space.size(); ++j ) {
int q = ins.reachable_space[j];
if( ins.adj(p,q) )
os << " (wumpus p" << q << ")";
}
os << ")" << endl;
}
// Invariants: (or stench(p) -wumpus(p')) where adj(p,p')
os << endl << " ; Invariants: (or stench(p) -wumpus(p'))" << endl;
for( int i = 0; i < ins.reachable_space.size(); ++i ) {
int p = ins.reachable_space[i];
for( int j = 0; j < ins.reachable_space.size(); ++j ) {
int q = ins.reachable_space[j];
if( ins.adj(p,q) ) {
os << " "
<< "(invariant (stench p" << p << ") (not (wumpus p" << q << ")))" << endl;
}
}
}
// Invariants: (or -wumpus(p) -wumpus(p')) where -adj(p,p')
os << endl << " ; Invariants: (or -wumpus(p) -wumpus(p'))" << endl;
for( int i = 0; i < ins.reachable_space.size(); ++i ) {
int p = ins.reachable_space[i];
for( int j = 0; j < ins.reachable_space.size(); ++j ) {
int q = ins.reachable_space[j];
if( (p != q) && !ins.adj(p,q) ) {
os << " "
<< "(invariant (not (wumpus p" << p << ")) (not (wumpus p" << q << ")))" << endl;
}
}
}
// end of initial situation
os << " )" << endl;
// hidden situation
bool nline = false;
os << " (:hidden" << endl;
int x = ins.wumpus / n_ypos, y = ins.wumpus % n_ypos;
os << " (wumpus p" << ins.wumpus << ")";
if( (y+1 < n_ypos) && ins.reachable[x*n_ypos + y+1] )
os << " (stench p" << x*n_ypos + y+1 << ")";
if( (x+1 < n_xpos) && ins.reachable[(x+1)*n_ypos + y] )
os << " (stench p" << (x+1)*n_ypos + y << ")";
if( (y-1 >= 0) && ins.reachable[x*n_ypos + y-1] )
os << " (stench p" << x*n_ypos + y-1 << ")";
if( (x-1 >= 0) && ins.reachable[(x-1)*n_ypos + y] )
os << " (stench p" << (x-1)*n_ypos + y << ")";
os << endl << " )" << endl;
// goal situation
os << " (:goal (killed))" << endl;
// end
os << ")" << endl;
}
int main(int argc, const char **argv) {
unsigned short seed[3];
if( argc != 3 ) {
cerr << "Usage: generator <seed> <mapfilen>" << endl;
return -1;
}
++argv;
seed[0] = seed[1] = seed[2] = (unsigned short)atoi(*argv++);
seed48(seed);
string mapfile = *argv++;
Instance ins(mapfile);
generate_problem(cout, ins);
return 0;
}
| true |
757a2a1140c537c84ba13638759351e3fbefe8a1 | C++ | Khrishp/CS235 | /Week02/stack.h | UTF-8 | 6,789 | 3.5625 | 4 | [] | no_license | /***********************************************************************
* Header:
* stack
* Summary:
* This class contains the notion of an stack: a bucket to hold
* data for the user. This is just a starting-point for more advanced
* constainers such as the stack, set, stack, queue, deque, and map
* which we will build later this semester.
*
* This will contain the class definition of:
* stack : similar to std::stack
* stack :: iterator : an iterator through the stack
* Author
* Br. Helfrich/Aiden
************************************************************************/
#ifndef stack_H
#define stack_H
#include <cassert> // because I am paranoid
#include <iostream>
using namespace std;
// a little helper macro to write debug code
#ifdef NDEBUG
#define Debug(statement)
#else
#define Debug(statement) statement
#endif // !NDEBUG
namespace custom
{
template <class T>
class stack
{
public:
// constructors and destructors
stack();
stack(int cap) throw (const char *);
stack(const stack & rhs) throw (const char *);
~stack() { delete[] data; }
stack & operator = (const stack & rhs) throw (const char *);
friend ostream &operator << (ostream &out, const stack &v)
{
out << "{";
for (int i = 0; i < v.num; i++)
out << " " << v[i];
out << " }";
return out;
}
// standard container interfaces
// stack treats size and max_size the same
int size() const { return num; }
int max_size() const { return cap; }
int capacity() const { return cap; }
bool empty() const { return (size() > 0) ? false : true; }
void push(T t);
void pop();
T top();
void clear();
void resize();
// the various iterator interfaces
class iterator;
iterator begin() { return iterator(data); }
iterator end();
// a debug utility to display the stack
// this gets compiled to nothing if NDEBUG is defined
void display() const;
private:
T * data; // dynamically allocated stack of T
int num;
int cap;
// vector-specific interfaces
// what would happen if I passed -1 or something greater than cap?
T & operator [] (int index) throw (const char *)
{
return data[index];
}
const T & operator [] (int index) const throw (const char *)
{
return data[index];
}
};
/*******************************************
* stack :: Assignment
*******************************************/
template <class T>
stack <T> & stack <T> :: operator = (const stack <T> & rhs)
throw (const char *)
{
if (cap != rhs.capacity()) {
data = NULL;
delete[] data;
data = new T[rhs.capacity()];
cap = rhs.cap;
num = rhs.num;
}
for (int i = 0; i < rhs.size(); i++)
data[i] = rhs.data[i];
return *this;
}
/*******************************************
* stack :: COPY CONSTRUCTOR
*******************************************/
template <class T>
stack <T> ::stack(const stack <T> & rhs) throw (const char *)
{
assert(rhs.cap >= 0);
// do nothing if there is nothing to do
if (rhs.cap == 0)
{
cap = 0;
num = 0;
data = NULL;
return;
}
// attempt to allocate
try
{
data = new T[rhs.cap];
}
catch (std::bad_alloc)
{
throw "ERROR: Unable to allocate a new buffer for stack";
}
// copy over the capacity
num = rhs.num;
cap = rhs.cap;
// copy the items over one at a time using the assignment operator
for (int i = 0; i < rhs.size(); i++)
data[i] = rhs.data[i];
}
/**********************************************
* stack : NON-DEFAULT CONSTRUCTOR
* Preallocate the stack to "capacity"
**********************************************/
template <class T>
stack <T> ::stack(int cap) throw (const char *)
{
assert(cap >= 0);
// do nothing if there is nothing to do.
// since we can't grow an stack, this is kinda pointless
if (cap == 0)
{
this->cap = 0;
this->data = NULL;
this->num = 0;
return;
}
// attempt to allocate
try
{
data = new T[cap];
}
catch (std::bad_alloc)
{
throw "ERROR: Unable to allocate a new buffer for Stack";
}
// copy over the stuff
this->num = 0;
this->cap = cap;
}
/**********************************************
* stack : DEFAULT CONSTRUCTOR
* Preallocate the stack to "capacity"
**********************************************/
template <class T>
stack <T> ::stack()
{
this->cap = 0;
this->data = NULL;
this->num = 0;
return;
}
/**********************************************
* stack : PUSH
* Preallocate the stack to "capacity"
**********************************************/
template <class T>
void stack<T>::push(T t)
{
try {
resize();
}
catch (const char* s) {
cout << s << endl;
}
data[size()] = t;
num += 1;
return;
}
/**********************************************
* stack : POP
* Preallocate the stack to "capacity"
**********************************************/
template <class T>
void stack<T>::pop()
{
num -= 1;
return;
}
/**********************************************
* stack : TOP
* Preallocate the stack to "capacity"
**********************************************/
template <class T>
T stack<T>::top()
{
try {
if (size() > 0)
return data[size() - 1];
else
throw "Error: Unable to reference the element from an empty stack";
}
catch (const char* s) {
//cout << s << endl;
}
}
/**********************************************
* stack : clear
* Preallocate the stack to "capacity"
**********************************************/
template <class T>
void stack<T>::clear()
{
data = NULL;
delete[] data;
data = new T[capacity()];
num = 0;
return;
}
/**********************************************
* stack : resize
* Preallocate the stack to "capacity"
**********************************************/
template <class T>
void stack<T>::resize()
{
try {
if (size() + 1 > capacity())
{
T *temp = NULL;
cap = (capacity() > 0) ? capacity() * 2 : 1;
temp = new T[capacity()];
for (int i = 0; i < num; i++)
temp[i] = data[i];
delete[] this->data;
this->data = temp;
}
return;
}
catch (std::bad_alloc) {
throw "ERROR: Unable to allocate a new buffer for Stack";
}
}
/********************************************
* stack : DISPLAY
* A debug utility to display the contents of the stack
*******************************************/
template <class T>
void stack <T> ::display() const
{
#ifndef NDEBUG
std::cerr << "stack<T>::display()\n";
std::cerr << "\tcap = " << cap << "\n";
for (int i = 0; i < num; i++)
std::cerr << "\tdata[" << i << "] = " << data[i] << "\n";
#endif // NDEBUG
}
}; // namespace custom
#endif // stack_H | true |
7fe2ac531b570891a0a649cd3e40b2e0ff7f77b1 | C++ | zylzjucn/Leetcode | /100~199/115. Distinct Subsequences.cpp | UTF-8 | 628 | 2.640625 | 3 | [] | no_license | class Solution {
public:
int numDistinct(string s, string t) {
vector<vector<int>> m(s.length() + 1, vector<int> (t.length() + 1));
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m[0].size(); j++) {
if (i == 0)
m[i][j] = 0;
if (j == 0)
m[i][j] = 1;
if (i > 0 && j > 0) {
m[i][j] = m[i - 1][j];
if (s[i - 1] == t[j - 1])
m[i][j] += m[i - 1][j - 1];
}
}
}
return m.back().back();
}
};
| true |
29c86c1d5fe5ec2dafd33ba1d04a6ae25a577962 | C++ | bappy451/Competative-Code | /CodeForces/Brain's Photos.cpp | UTF-8 | 510 | 3.015625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
while(cin>>n>>m)
{
bool flag = true;
char temp;
for(int i=0;i<n; i++)
for(int k=0;k<m; k++)
{
cin>>temp;
if((temp == 'W' || temp == 'B' || temp == 'G') && flag) continue;
else flag = false;
}
if(flag) cout<<"#Black&White"<<endl;
else cout<<"#Color"<<endl;
}
return 0;
}
| true |
3dcc97fd017cadf47a1bd2912cb193d182387961 | C++ | johnnyczhong/xiangqi | /xiangqi/Board.h | UTF-8 | 4,016 | 2.875 | 3 | [
"MIT"
] | permissive | //board.h
//header file
#include <map>
#include "Board_Defaults.h"
#ifndef BOARD_H
#define BOARD_H
class Board
{
private:
bool b_north_turn = true; //north starts first
int turn = 1; //north: 1, south: -1
std::map<int, bool> m_in_check =
{
{1, false}, {-1, false}
};
std::map<int, int> m_general_pos =
{
{1, N_GENERAL}, {-1, S_GENERAL}
};
// std::map<int, int> m_camp_center =
// {
// {1, NORTH_CAMP_CENTER}, {-1, SOUTH_CAMP_CENTER}
// };
// starting board
//computer-view of board 14 (L) by 13 (W)
int ia_grid[182] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //12
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //25
-1, -1, 6, 5, 4, 7, 8, 7, 4, 5, 6, -1, -1, //38
-1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, //51
-1, -1, 0, 3, 0, 0, 0, 0, 0, 3, 0, -1, -1, //64
-1, -1, 2, 0, 2, 0, 2, 0, 2, 0, 2, -1, -1, //77
-1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, //riverbank 90
-1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, //riverbank 103
-1, -1, -2, 0, -2, 0, -2, 0, -2, 0, -2, -1, -1, //116
-1, -1, 0, -3, 0, 0, 0, 0, 0, -3, 0, -1, -1, //129
-1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, //142
-1, -1, -6, -5, -4, -7, -8, -7, -4, -5, -6, -1, -1, //155
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, //168
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 //181
};
public:
//function prototypes
void play();
//TODO:
//start game
//turn_start
//prompt player specify intial position
// determine if is valid, goto turn_start if not
//prompt player specify final position
// determine if is valid: goto turn_start if not
//if current player is attempting to finish move in-check, goto turn_start
// being in-check doesn't matter, ending turn in-check matters
//execute move
//determine ramifications (evaluate check, remove pieces from board, etc.)
//if this move would put the opposing player in-check,
// determine if there would be a valid move that would allow the opposing player to
// escape the check. if not, then declare checkmate
// valid moves: move general, remove threatening piece, block threatening piece
//next player turn
int determine_position(int, int); //given set of x, y find corresponding array position
//args: initial and final position of piece
//pieces cannot occupy the same position as an allied piece
//pieces cannot move off the board (into -1 territory)
//return: false if illegal move, true if valid
bool eval_move(int, int);
bool eval_dest(int, int);
//check unit collision for cannons and carts
int straight_collision_check(int, int);
//helper functions per different piece (should check rules of a particular piece)
//args: initial position, final position
//returns: true if valid, false if not
bool pawn_move(int, int);
bool cannon_move(int, int);
bool cart_move(int, int);
bool horse_move(int, int);
bool elephant_move(int, int);
bool guard_move(int, int);
bool general_move(int, int);
bool obstructed_generals(int);
//call from eval_move if general is threatened
//flips north_check or south_check from false to true and vice versa
bool get_in_check(int);
void set_in_check();
bool evaluate_threat(int, int);
bool pawn_threat(int, int);
bool straight_path_threat(int, int);
bool horse_threat(int, int);
void make_piece(int, int); //position, piece id
void remove_piece(int); //position
void update_general_pos(int, int);
void flip_turn(); //change turn from N to S and vice versa
int get_general_pos(int);
int check_pos(int); //returns piece at given position
bool n_camp_box_check(int); //given a position, determines if it's in the box
bool s_camp_box_check(int);
};
#endif | true |
edfb8437a8a3084d324a6fb425ca51f3ab6ddc24 | C++ | AnkitAnks/Paper---1 | /Q1.cpp | UTF-8 | 710 | 3.5 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"Enter the array size"<<"\n";
cin>>n;
int arr[n];
cout<<"Enter the array Elements"<<"\n";
for(int i=0;i<n;i++)
cin>>arr[i];
if (n < 2)
cout<<" Invalid Input ";
int f,s;
f=INT_MAX;
s=INT_MAX;
for (int i = 0; i < n ; i ++)
{
if (arr[i] < f)
{
s = f;
f = arr[i];
}
else if (arr[i]<s&&arr[i]!=f)
s = arr[i];
}
if (s== INT_MAX)
cout << "No second minimum"<<"\n";
else
cout << "The smallest element is " << f << " and second "
"Smallest element is " << s << endl;
}
| true |
2a5d8d43805a8db86e24306e2d7bdd08fbb5c7f0 | C++ | doanamo/Game-Engine-12-2013 | /Source/Common/ShelfPacker.hpp | UTF-8 | 683 | 2.953125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Precompiled.hpp"
//
// Shelf Packer
// Packs rectangles together to save as muhc space as possible.
// It's not the most optimal algorithm, but it's very straight forward.
//
class ShelfPacker
{
public:
ShelfPacker();
~ShelfPacker();
void Create(glm::ivec2 size, glm::ivec2 spacing);
void Cleanup();
bool AddElement(glm::ivec2 size);
const glm::ivec2& GetPosition();
public:
void Serialize(std::ofstream& stream);
void Deserialize(std::ifstream& stream);
private:
glm::ivec2 m_storeSize;
glm::ivec2 m_storeSpacing;
glm::ivec2 m_shelfPosition;
glm::ivec2 m_shelfElement;
int m_shelfHeight;
};
| true |
ffbd8d2e21d8aef94fee9ba2e419f17e1697d765 | C++ | Niraka/ThirdYearProject | /Include/UserInterface/UIProgressBarColored.h | UTF-8 | 2,954 | 3.28125 | 3 | [] | no_license | /**
A progress bar that supports colouring and sound effects on completion.
@author Nathan */
#ifndef UI_PROGRESS_BAR_COLORED_H
#define UI_PROGRESS_BAR_COLORED_H
#include "UIProgressBar.h"
#include "UIComponentListener.h"
#include "UIResourceManager.h"
class UIProgressBarColored :
public UIProgressBar,
public UIComponentListener
{
friend class UIDeleter;
private:
sf::VertexArray m_verticesForeground;
sf::VertexArray m_verticesBackground;
/**
Configures the size and position of the background bar.
@param globalBounds The global bounds of the bar. */
void configureBackground(Rect& globalBounds);
/**
Configures the size and position of the foreground bar.
@param globalBounds The global bounds of the bar. */
void configureForeground(Rect& globalBounds);
protected:
/**
Called periodically by the UIManager.
@see UIManager */
void onUpdate();
/**
This function is called by a UIComponent this UIComponentListener is listening to when the
component is moved.
@param fLeft The new left position in pixels
@param fTop The new top position in pixels */
void componentMoved(float fLeft, float fTop);
/**
This function is called by a UIComponent this UIComponentListener is listening to when the
component is resized.
@param fWidth The new width in pixels
@param fHeight The new height in pixels */
void componentResized(float fWidth, float fHeight);
/**
Called when the progress of the progress bar is updated.
@param fProgress The new progress value */
void onProgressUpdated(float fProgress);
public:
~UIProgressBarColored();
/**
Constructs a UIProgressBarColored with the given name.
@param sName The name */
explicit UIProgressBarColored(std::string sName);
/**
Constructs a UIProgressBarColored with the given name and size specification.
@param sName The name
@param xOffset The x offset
@param yOffset The y offset
@param width The width
@param height The height */
UIProgressBarColored(std::string sName, Size xOffset, Size yOffset, Size width, Size height);
/**
Sets the foreground bar color using a UIResourceManager color key. Defaults to solid black or a user
defined "black" if one existed in the resource manager.
@param sColor The color key. */
void setForegroundColor(std::string sColor);
/**
Sets the background bar color using a UIResourceManager color key. Defaults to solid white or a user
defined "white" if one existed in the resource manager.
@param sColor The color key. */
void setBackgroundColor(std::string sColor);
/**
Inverts the graphical display of the progress bar. Internally, progress continues to range from
0 (lowest) to 1 (highest).
@param bInverted True to invert the bar. */
void setInverted(bool bInverted);
/**
Draws the UIImage to the given RenderTarget.
@param target A reference to the target to draw to */
void onDraw(sf::RenderTarget& target);
};
#endif | true |
f120de0d71ba662bbef7a7f12598722a618a3ec5 | C++ | arturo182/QtCraft | /item/toolitem.cpp | UTF-8 | 1,755 | 2.671875 | 3 | [] | no_license | #include "toolitem.h"
#include <item/tooltype.h>
#include <gfx/screen.h>
#include <gfx/color.h>
#include <gfx/font.h>
#include <QStringList>
QStringList ToolItem::LEVEL_NAMES = QStringList() << "Wood"
<< "Rock"
<< "Iron"
<< "Gold"
<< "Gem";
QList<int> ToolItem::LEVEL_COLORS = QList<int>() << Color::get(-1, 100, 321, 431)
<< Color::get(-1, 100, 321, 111)
<< Color::get(-1, 100, 321, 555)
<< Color::get(-1, 100, 321, 550)
<< Color::get(-1, 100, 321, 45);
ToolItem::ToolItem(ToolType *type, int level)
{
this->type = type;
this->level = level;
}
int ToolItem::getColor() const
{
return LEVEL_COLORS[level];
}
int ToolItem::getSprite() const
{
return type->sprite + 160;
}
QString ToolItem::getName() const
{
return LEVEL_NAMES[level] + " " + type->name;
}
int ToolItem::getAttackDamageBonus(Entity *e)
{
if(type == ToolType::axe) {
return (level + 1) * 2 + qrand() % 4;
}
if(type == ToolType::sword) {
return (level + 1) * 3 + qrand() % (2 + level * level * 2);
}
return 1;
}
bool ToolItem::matches(Item *item)
{
if(ToolItem *other = dynamic_cast<ToolItem*>(item)) {
if(other->type != type) {
return false;
}
return other->level == level;
}
return false;
}
bool ToolItem::canAttack()
{
return true;
}
void ToolItem::renderIcon(Screen *screen, int x, int y)
{
screen->render(x, y, getSprite(), getColor(), 0);
}
void ToolItem::renderInventory(Screen *screen, const int &x, const int &y) const
{
screen->render(x, y, getSprite(), getColor(), 0);
Font::draw(getName(), screen, x + 8, y, Color::get(-1, 555, 555, 555));
}
| true |
177926f02a3d967d390a1d7634beb3b46b641e0c | C++ | vpsetter/HW-2sem | /HW 7 (19)/7.3.cpp | UTF-8 | 1,187 | 3.578125 | 4 | [] | no_license | #include <algorithm>
#include <future>
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>
template < typename Iterator, typename F >
void parallel_for_each(Iterator first, Iterator last, F function, const std::size_t max_size)
{
const std::size_t length = std::distance(first, last);
if (length <= max_size)
{
std::for_each(first, last, function);
}
else
{
Iterator middle = first;
std::advance(middle, length / 2);
std::future < void > first_half_result = std::async(parallel_for_each < Iterator, F >, first, middle, function, max_size);
parallel_for_each(middle, last, function, max_size);
first_half_result.get();
}
}
int main()
{
std::vector < int > v(10'000'000, 0);
auto increment = [](int& x) { ++x; };
const std::size_t max_size = v.size() / std::thread::hardware_concurrency();
parallel_for_each(std::begin(v), std::end(v), increment, max_size);
int errors = 0;
auto test = [&errors](int x) {if (x != 1) { ++errors; }; };
parallel_for_each(std::begin(v), std::end(v), test, max_size);
std::cout << "Parallel for_each errors = " << errors << '\n';
std::cout << (errors ? "Failure\n" : "Success\n");
return 0;
}
| true |
07b770cc7bbbb3099a755f6c6c2f28a37040422c | C++ | kangyeop/algorithm | /level2/62048.cpp | UTF-8 | 400 | 3.015625 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
using namespace std;
int GCD(int a, int b) {
if (a % b) {
return GCD(b, a % b);
}
return b;
}
long long solution(int w, int h) {
long long answer = 1;
int gcd = GCD(max(w, h), min(w, h));
long long x = w;
long long y = h;
long long total = x * y;
answer = total - (w + h - gcd);
return answer;
}
| true |
94795ccb5b02596ffc4ba4c86da6236291dd3507 | C++ | Nufflee/fm-dekoder | /fm/wave.hpp | UTF-8 | 2,724 | 3.390625 | 3 | [] | no_license | #pragma once
#include <stdint.h>
#include <iostream>
#include <fstream>
#include <cstring>
enum class WaveFormat : uint16_t
{
PCM = 0x0001
};
template <class T>
static void write_bytes(std::ofstream &stream, T value)
{
stream.write(reinterpret_cast<const char *>(&value), sizeof(T));
}
static void write_bytes(std::ofstream &stream, const char *value)
{
stream.write(value, sizeof(char) * strlen(value));
}
template <class T>
class Wave
{
private:
WaveFormat format;
uint16_t channelCount;
uint32_t bytesPerSample;
uint32_t sampleRate;
uint32_t sampleCount;
const T *samples;
public:
Wave(WaveFormat format, uint16_t channelCount, uint32_t sampleRate, uint32_t sampleCount)
: format(format), channelCount(channelCount), bytesPerSample(sizeof(T)), sampleRate(sampleRate), sampleCount(sampleCount)
{
}
void set_data(const T *samples)
{
this->samples = samples;
}
bool write_to_file(const char *path) const
{
std::ofstream file;
file.open(path, std::ios::out | std::ios::binary);
if (!file.is_open())
{
return false;
}
bool paddingRequired = false;
// The WAVE standard requires a padding byte at the end of the data chunk if
// the number of samples is odd
if (sampleCount % 2 != 0)
{
paddingRequired = true;
}
uint32_t dataSize = channelCount * sampleCount * bytesPerSample;
// Master Chunk
{
// Chunk ID
write_bytes(file, "RIFF");
// Chunk size
uint32_t chunkSize = 4 + (8 + 16) + (8 + dataSize + (int)paddingRequired);
write_bytes(file, chunkSize);
file.write("WAVE", 4);
}
// Format Chunk
{
// Chunk ID
write_bytes(file, "fmt ");
// Chunk size
uint32_t chunkSize = 16;
write_bytes(file, chunkSize);
// Format tag
write_bytes(file, format);
write_bytes(file, channelCount);
write_bytes(file, sampleRate);
// Average bytes per second
uint32_t bytesPerSecond = channelCount * sampleRate * bytesPerSample;
write_bytes(file, bytesPerSecond);
uint16_t blockAlign = channelCount * bytesPerSample;
write_bytes(file, blockAlign);
uint16_t bitsPerSample = 8 * bytesPerSample;
write_bytes(file, bitsPerSample);
}
// Data chunk
{
// Chunk ID
write_bytes(file, "data");
// Chunk size
write_bytes(file, dataSize);
file.write(reinterpret_cast<const char *>(samples), dataSize);
if (paddingRequired)
{
write_bytes<char>(file, 0);
}
}
return true;
}
}; | true |
b8d54755a441c11d26ae1e6708f157f8aaa5ce0b | C++ | Rysc0/Operating-systems-lab | /Lab02/Lamport.cpp | UTF-8 | 1,875 | 3.109375 | 3 | [] | no_license | #include <sys/shm.h>
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;
int *array, id, *broj, procesa;
int max(){
int max = broj[0];
for(int i = 0; i < procesa; i++){
if(max < broj[i]){
max = broj[i];
}
}
return max;
}
void kriticni_odsjecak(int i){
int j;
array[i] = 1;
broj[i] = max() + 1;
array[i] = 0;
for(j = 0; j < procesa; j++){
while(array[j] != 0){
}
while(broj[j] != 0 && (broj[j] < broj[i] || (broj[j] == broj[i] && j < i))){
}
}
}
void izadji_iz_kriticnog_odsjecka(int i){
broj[i] = 0;
}
void brisi(int sig){
shmdt(array);
shmdt(broj);
shmctl(id,IPC_RMID,NULL);
exit(1);
}
int main(int argc, char *argv[]) {
if(argc != 2){
cout << "Must enter two arguments! " << argv[0] << " included!" << endl;
exit(-1);
}
procesa = atoi(argv[1]);
if(procesa < 1 || procesa > 5){
cout << "Limited process count 1-5\n";
exit(-1);
}
id = shmget(IPC_PRIVATE,4*procesa*sizeof(int),0600);
if(id == -1){
cout << "ERROR, NO SHARED MEMORY!" << endl;
exit(1);
}
cout << "\033[1;40;93mSHMID = " << id << "\033[0m" << endl;
array = (int*) shmat(id,NULL,0);
broj = (int*) shmat(id,NULL,0) + (2*sizeof(int));
sigset(SIGINT, brisi);
for(int i = 0; i < procesa; i++){
broj[i] = i;
if (fork() == 0) {
cout << "\033[3;40;92mChild with PID: " << getpid() << " created!\033[0m" << endl;
sleep(1);
for(int k = 1; k <=5; k++){
kriticni_odsjecak(i);
for(int m = 1; m <=5; m++){
cout << "Proces " << i+1 << " K.O. br: " << k << " (" << m << "/5)" << endl;
sleep(1);
}
izadji_iz_kriticnog_odsjecka(i);
}
exit(1);
}
}
sleep(1);
for(int i = 0; i < procesa; i++){
wait(NULL);
}
brisi(0);
return 0;
}
| true |
3e298a64c8c2449b66a6ea0f7122a376264a426d | C++ | arthurherbout/crypto_code_detection | /data/code-jam/files/3014486_AVictor_5649687893770240_0_extracted_D_small.cpp | UTF-8 | 1,215 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <limits>
#include <set>
#include <map>
#include <cassert>
#include <fstream>
#include <queue>
#include <cstring>
using namespace std;
int N, M;
set< string > letters[10];
int best, cnt;
void rec(vector<set<string> > x, int i)
{
if (i==M)
{
int res = 0;
for(int j=0;j<N;j++) {
res += x[j].size();
if (x[j].size()==0) return;
}
if (res > best) { best = res; cnt = 1; }
else if (res == best) { cnt ++; }
return;
}
for(int j=0;j<N;j++)
{
vector<set<string> > y(x);
for(set< string >::iterator it = letters[i].begin(); it!=letters[i].end(); it ++)
y[j].insert(*it);
rec(y, i+1);
}
}
int main()
{
int test_cnt;
cin >> test_cnt;
for(int test_num=1;test_num<=test_cnt;test_num++)
{
cin >> M >> N;
for(int i=0;i<M;i++)
{
letters[i].clear();
string s;
cin >> s;
for(int j=0;j<=s.length();j++)
letters[i].insert(s.substr(0, j));
}
best = 0;
cnt = 0;
vector<set<string> > x(N);
rec(x, 0);
printf("Case #%d: %d %d\n", test_num, best, cnt);
}
return 0;
}
| true |
c3005c20bc1bd2a697f170cf6965fb50e1588894 | C++ | gregorymwillis/TicTacToeFileReader-c- | /T3Reader.cpp | UTF-8 | 2,386 | 3.515625 | 4 | [] | no_license | /*************************************************************************************
** Name: Greg Willis
** Date: 11/19/2017
** Description: (T3Reader.cpp)
************************************************************************************/
#include "T3Reader.hpp"
#include "Board.hpp"
#include <string>
#include <fstream>
#include <iostream>
using std::cout;
using std::endl;
using std::string;
using std::ifstream;
// Default constructor
T3Reader::T3Reader() {
// Create game board object
gB = Board();
// Set firstMove to x
firstMove = 'x';
}
// Constructor with player 'x' or 'o' as the first move
T3Reader::T3Reader(char fM) {
// Create game board object
gB = Board();
// Set firstMove to passed-in char
firstMove = fM;
}
// This function opens the file of moves, it reads a move and then makes that move.
// It alternates players depending on which constructor was used. This function
// will return true if 'x' won, 'o' won, or there was a draw AND there are no more
// moves in the file. If there are, it returns false. If a move is attempted on an
// occupied square, it returns false.
bool T3Reader::readGameFile(string fileName) {
// File object to read from
ifstream inputFile;
// row and column read from file
int row, col;
// Game state object
GmState status = UNFINISHED;
// Open the file to read from
inputFile.open(fileName.c_str());
if(inputFile) { // If able to open the file
// While the game is unfinished and not to the end of the file,
// keep looping
while(inputFile >> row) { // Keep looping while able to take int from file
// Read move
inputFile >> col;
// if the game has already finished, but we read another row for moves
// then return false, there should not be any more moves.
if(status != UNFINISHED) {
return false;
} else if(gB.makeMove(row, col, firstMove)) { // else if a move can be made
// Get game state
status = gB.gameState();
changePlayer(firstMove);
// gB.print();
} else {
inputFile.close();
return false;
}
}
// success: we either finished with X_WON, O_WON or DRAW:
inputFile.close();
return true;
} else { // File was unable to open
return false;
}
// When game has completed with a winner and no more moves return true
return true;
}
void T3Reader::changePlayer(char &fM) {
if(fM == 'x') {
fM = 'o';
}
else {
fM = 'x';
}
}
| true |
6920e2caeef8378fe618c10720297105946b56e6 | C++ | samuraiexx/competitiveProgramming | /cf/702/f.cpp | UTF-8 | 2,614 | 2.65625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define st first
#define nd second
const int INF = 0x3f3f3f3f;
mt19937_64 llrand(random_device{}());
struct node {
pair<int, int> val;
int cnt, lz;
int amt;
ll pri;
node *l, *r;
node(int x) : val(x), amt(0), cnt(1), rev(0), pri(llrand()), l(0), r(0), lz(0) {}
};
struct treap {
node *root = 0;
int cnt(node *t) { return t ? t->cnt : 0; }
void push(node *t) {
if(!t or !t->lz) return;
t->val -= t->lz;
if(t->l) t->l->lz += t->lz;
if(t->r) t->r->lz += t->lz;
t->amt++;
t->lz = 0;
}
void update(note *t){
if(!t) return;
t->cnt = cnt(t->l) + cnt(t->r) + 1;
}
node *merge(note *l, node *r){
push(l), push(r);
node *t;
if(!l or !r) return l ? l : r;
else if(l->pri > r->pri) l->r = merge(l->r, r), t = l;
else r->l = merge(l, r->l), t = r;
update(t);
return t;
}
pair<node*, node*> split(node *t, int pos){
if(!t) return {0, 0};
push(t);
if(cnt(t->l) < pos) {
auto x = split(t->r, pos - cnt(t->l) - 1);
t->r = x.st;
update(t);
return {t, x.nd};
}
auto x = split(t->l, pos);
t->l = x.nd;
update(t);
return {x.st, t};
}
int order(node* t, pair<int, int> val){
if(!t) return 0;
push(t);
if(t->val < val) return cnt(t->l) + 1 + order(t->r, val);
return order(t->r, val);
}
bool has(node* t, pair<int, int> val) {
if(!t) return 0;
push(t);
if(t->val == val) return 1;
return has((t->val > val ? t->l : t->r), val);
}
void insert(pair<int, int> val) {
if(has(root, val)) return;
push(root);
node* x = new node(c);
auto t = split(root, order(root, val));
root = merge(merge(t.st, x), t.nd);
}
void erase(pair<int, int> val){
if(!has(root, val)) return;
auto t1 = split(root, order(root, val));
auto t2 = split(t1.nd, 1);
delete t2.st;
root = merge(t1.se, t2.nd);
}
void query(int val){
auto t = split(root, order({2*val, -1}));
auto t2 = split(t.st, order({val, }));
}
};
const int N = 2e5 + 5;
pair<int, int> t-shirt[N];
int main(){
int n;
cin >> n;
for(int i = 0; i < n; i++)
cin >> t-shirt[i].nd >> t-shirt[i].nd;
sort(t-shirt, t-shirt + n, greater<pair<int, int>>);
int k;
cin >> k;
for(int i = 0; i< k; i++)
}
| true |
f754070db0c053157ca527b14720a68b45b1ef92 | C++ | dchwebb/Oscar | /Oscar446/src/config.cpp | UTF-8 | 3,115 | 2.78125 | 3 | [] | no_license | #include "config.h"
#include "ui.h"
#include "osc.h"
#include "fft.h"
#include "tuner.h"
Config cfg;
// called whenever a config setting is changed to schedule a save after waiting to see if any more changes are being made
void Config::ScheduleSave()
{
scheduleSave = true;
saveBooked = SysTickVal;
}
// Write calibration settings to Flash memory
void Config::SaveConfig() {
scheduleSave = false;
uint32_t address = ADDR_FLASH_SECTOR_7; // Store data in Sector 7 last sector in F446 to allow maximum space for program code
FLASH_Status flash_status = FLASH_COMPLETE;
uint32_t cfgSize = SetConfig();
__disable_irq(); // Disable Interrupts
FLASH_Unlock(); // Unlock Flash memory for writing
// Clear error flags in Status Register
FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR |FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR |FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);
// Erase sector 7 (has to be erased before write - this sets all bits to 1 as write can only switch to 0)
flash_status = FLASH_EraseSector(FLASH_Sector_7, VoltageRange_3);
// If erase worked, program the Flash memory with the config settings byte by byte
if (flash_status == FLASH_COMPLETE) {
for (unsigned int f = 0; f < cfgSize; f++) {
char byte = *((char*)(&configBuffer) + f);
flash_status = FLASH_ProgramByte((uint32_t)address + f, byte);
}
}
FLASH_Lock(); // Lock the Flash memory
__enable_irq(); // Enable Interrupts
}
uint32_t Config::SetConfig()
{
// Serialise config values into buffer
memset(configBuffer, 0, sizeof(configBuffer)); // Clear buffer
strncpy(reinterpret_cast<char*>(configBuffer), "CFG", 4); // Header
configBuffer[4] = configVersion;
uint32_t configPos = 8; // Position in buffer to store data
uint32_t configSize = 0; // Holds the size of each config buffer
uint8_t* cfgBuffer = nullptr;
// UI settings
configSize = ui.SerialiseConfig(&cfgBuffer);
memcpy(&configBuffer[configPos], cfgBuffer, configSize);
configPos += configSize;
// Oscilloscope settings
configSize = osc.SerialiseConfig(&cfgBuffer);
memcpy(&configBuffer[configPos], cfgBuffer, configSize);
configPos += configSize;
// FFT settings
configSize = fft.SerialiseConfig(&cfgBuffer);
memcpy(&configBuffer[configPos], cfgBuffer, configSize);
configPos += configSize;
// Tuner settings
configSize = tuner.SerialiseConfig(&cfgBuffer);
memcpy(&configBuffer[configPos], cfgBuffer, configSize);
configPos += configSize;
return configPos;
}
// Restore configuration settings from flash memory
void Config::RestoreConfig()
{
uint8_t* flashConfig = reinterpret_cast<uint8_t*>(ADDR_FLASH_SECTOR_7);
// Check for config start and version number
if (strcmp((char*)flashConfig, "CFG") == 0 && *reinterpret_cast<uint32_t*>(&flashConfig[4]) == configVersion) {
uint32_t configPos = 8; // Position in buffer of start of data
configPos += ui.StoreConfig(&flashConfig[configPos]);
configPos += osc.StoreConfig(&flashConfig[configPos]);
configPos += fft.StoreConfig(&flashConfig[configPos]);
configPos += tuner.StoreConfig(&flashConfig[configPos]);
}
}
| true |
ce3a3db98038d8ed4825c9960b4470c3a07778d6 | C++ | scottsidoli/CPP-Applications-for-Financial-Engineering-Pre-MFE | /Section 1.4/Exercise143/Exercise143/Exercise143.cpp | UTF-8 | 4,047 | 3.9375 | 4 | [
"MIT"
] | permissive | // Exercise 1.4.3 - Word Counter (Switch-Case Loop)
//
// by Scott Sidoli
//
// 3-29-19
//
// The goal of this exercise is to create a program that accepts the user input of a string
// and returns the count of characters, words, and lines using a switch-case loop.
// Preprocessor Directives
#include <stdio.h>
// Main Function
int main()
{
int c; // Variable Declarations. "c" is ascii code of the most recent keystroke.
int character_number = 0; // The statistics we are interested in computing are listed here.
int word_number = 0;
int line_number = 0;
int character = 0; // A int switch that is "1" if the user hits a character key. We think of it as a Boolean.
int line = 0; // A int switch that is "1" if the user starts a new line. We think of it as a Boolean.
// User Prompt
printf("Please enter a string. End your string with Ctrl+D and then press enter.\n");
c = getchar(); // 'c' takes the ascii code value of whatever was last typed. Note that
// 4 = ctrl+d (i.e. end of file), 9 = "tab", 10 = "new line", and 32 = "space",
while (c != 4)
{
switch (character_number)
{
case 0: // This is the case when we first start, i.e. there are no characters.
switch (c)
{
case 9: // Tab should do nothing.
break;
case 10: // New lines make int line = 1, but nothing counted.
line = 1;
break;
case 32: // Spaces should do nothing.
break;
default:
++line_number;
++character_number;
character = 1;
break;
}
c = getchar();
break;
default: // This is the case after we have counted at least one character.
switch (c)
{
case 9: // This is for a tab after a character.
character = 0;
break;
case 10: // If we hit enter, nothing should happen.
line = 1; // We should keep track of the fact that we are on a new line, in case we hit a character.
character = 0; // We can also keep track of the fact that we did not just hit a character.
c = getchar();
break;
case 32: // If we hit space, then we log that it is not a character.
character = 0;
c = getchar();
break;
default: // If we hit a character, then we first look at if we are on a new line.
switch (line) // If we are on a new line (i.e. line = 1) then we increase the line count
{ // and the word count. We increase the character count by 1 for each character.
case 0: // We set line = 0 to prepare for the next new line.
switch (character)
{
case 0:
++word_number;
++character_number;
break;
default: // If we just typed a character, then we do not want to increase the word count.
++character_number; // We only increase the character number.
break;
}
break;
default: // Here is code for when we are at the start of a new line, i.e. line = 1, and
++character_number; // type a character.
++line_number;
line = 0;
switch (character)
{
case 0:
++word_number;
break;
default:
break;
}
break;
}
character = 1; // Here we want to make sure that we log the previous entry as a character.
c = getchar();
break;
}
}
}
switch (character) // We want to now handle the case when we are at the end of the file.
{
case 0: // What follows ensure the we count the last word.
switch (line)
{
case 0:
break;
default:
++word_number;
break;
}
break;
default:
++word_number;
break;
}
// Finally, we print the result.
printf("The number of characters is %d.\nThe number of words is %d.\nThe number of lines is %d", character_number, word_number, line_number);
return 0;
}
| true |
a8c4e4082b452b893a8807b807547cb886f5d2d0 | C++ | Chimnii/Algospot | /Problems/Programmers/Lv2.172927.cpp | UTF-8 | 2,082 | 3.546875 | 4 | [] | no_license | #include <string>
#include <vector>
using namespace std;
int min(int a1, int a2) { return a1 < a2 ? a1 : a2; }
struct metal
{
int d, i, s;
metal() : d(0), i(0), s(0) {}
metal(int _d, int _i, int _s) : d(_d), i(_i), s(_s) {}
void emplace(const vector<int>& picks)
{
d += (picks.size() > 0 ? picks[0] : 0);
i += (picks.size() > 1 ? picks[1] : 0);
s += (picks.size() > 2 ? picks[2] : 0);
}
void emplace(const string& mineral)
{
d += (mineral == "diamond"s ? 1 : 0);
i += (mineral == "iron"s ? 1 : 0);
s += (mineral == "stone"s ? 1 : 0);
}
void print() const { printf("d=%d, i=%d, s=%d\n", d, i, s); }
bool is_empty() const { return d == 0 && i == 0 && s == 0; }
int calc_energy_by_dia() const { return (d + i + s); }
int calc_energy_by_iron() const { return (d*5 + i + s); }
int calc_energy_by_stone() const { return (d*25 + i*5 + s); }
};
int calc_minimum_energy(metal& pick, const vector<metal>& mines, int index)
{
if (pick.is_empty())
return 0;
if (index >= mines.size())
return 0;
int d = 1250, i = 1250, s = 1250;
if (pick.d > 0)
{
--pick.d;
d = mines[index].calc_energy_by_dia() + calc_minimum_energy(pick, mines, index+1);
++pick.d;
}
if (pick.i > 0)
{
--pick.i;
i = mines[index].calc_energy_by_iron() + calc_minimum_energy(pick, mines, index+1);
++pick.i;
}
if (pick.s > 0)
{
--pick.s;
s = mines[index].calc_energy_by_stone() + calc_minimum_energy(pick, mines, index+1);
++pick.s;
}
return min(min(d, s), i);
}
int solution(vector<int> picks, vector<string> minerals)
{
metal pick;
pick.emplace(picks);
vector<metal> mines;
for (int i = 0; i < minerals.size(); i += 5)
{
metal mine;
for (int j = 0; j < 5 && i + j < minerals.size(); ++j)
{
mine.emplace(minerals[i+j]);
}
mines.emplace_back(mine);
}
return calc_minimum_energy(pick, mines, 0);
} | true |
90bfb18532e0f4af395ab3d8fb1c4e6bdf6fc667 | C++ | kimlar/Packfile | /PackEngine.cpp | UTF-8 | 15,662 | 2.78125 | 3 | [] | no_license | #include "PackEngine.h"
#include "UtilDataType.h"
PackEngine::PackEngine(std::string packFileName)
{
this->packFileName = packFileName;
gotError = false;
}
PackEngine::~PackEngine()
{
ClosePackFile();
}
void PackEngine::Open()
{
Close();
gotError = false;
packFile = new PackFile(packFileName);
std::ifstream infile(packFileName, std::ios::binary | std::ios::ate);
unsigned int size = (unsigned int)infile.tellg();
infile.seekg(0, std::ios::beg);
// Check Format version: PACK1000
if (!CheckFormatVersion(infile))
return;
// Read ROOT section
if (!ReadRootSection(infile))
return;
// Read HEAD section
if (!ReadHeadSection(infile))
return;
// Read FLST section
if (!ReadFlstSection(infile))
return;
// Read FDAT section
if (!ReadFdatSection(infile))
return;
//
// Fill data into the pack file structure
//
// Fill HEAD section
if (!FillHeadSection(infile))
return;
// Fill FLST section
if (!FillFlstSection(infile))
return;
//infile.close();
}
void PackEngine::Close()
{
sourceFiles.clear();
ClosePackFile();
}
bool PackEngine::LoadFileToMemory(std::string file, std::vector<unsigned char>& buffer)
{
bool foundFile = false;
unsigned int fileIndex = 0;
for (unsigned int i = 0; i < packFile->HEAD_NumberOfFiles; i++)
{
if (file == packFile->FLST_FileNames[i])
{
fileIndex = i;
foundFile = true;
break;
}
}
if (!foundFile)
{
std::cout << "Error: Could not find file in the packfile" << std::endl;
std::cout << "Packfile: " << packFileName << std::endl;
std::cout << "File: " << file << std::endl;
gotError = true;
return false;
}
unsigned int bufferSize = packFile->FLST_FileSize[fileIndex];
char* bufferData = new char[bufferSize];
std::ifstream infile(packFileName, std::ios::binary);
infile.seekg(packFile->FLST_FilePosition[fileIndex], std::ios::beg);
infile.read(bufferData, bufferSize);
buffer.resize(bufferSize);
for (unsigned int i = 0; i < bufferSize; i++)
buffer[i] = bufferData[i];
delete[] bufferData;
return true;
}
void PackEngine::Compile(std::vector<std::string> sourceFiles)
{
this->sourceFiles = sourceFiles;
ClosePackFile();
packFile = new PackFile(packFileName);
// Get the ISO date and time
packFile->HEAD_DataVersion = utilDateTime.GetISODateTime();
// We already know the amount of files
unsigned int numFiles = (unsigned int)sourceFiles.size();
packFile->HEAD_NumberOfFiles = numFiles;
// And all the files.
packFile->FLST_FileNames.reserve(numFiles);
packFile->FLST_FilePosition.reserve(numFiles);
packFile->FLST_FileSize.reserve(numFiles);
for (unsigned int i = 0; i < numFiles; i++)
{
packFile->FLST_FileNames.push_back(sourceFiles[i]);
packFile->FLST_FilePosition.push_back(0);
packFile->FLST_FileSize.push_back(0);
}
// Let us find all file sizes and total file size (data container).
unsigned int totSize = 0;
for (unsigned int i = 0; i < numFiles; i++)
{
unsigned int tempFileSize = GetFileSize(packFile->FLST_FileNames[i]);
if (gotError)
return;
packFile->FLST_FileSize[i] = tempFileSize;
totSize += tempFileSize;
}
packFile->HEAD_TotalDataSize = totSize;
// Calculating section positions and sizes
packFile->ROOT_Position = 8; // const
packFile->ROOT_Size = 48; // const
packFile->HEAD_Position = 56; // const
packFile->HEAD_Size = 20; // const
packFile->FLST_Position = 76; // const
packFile->FLST_Size = GetFileListSize();
packFile->FDAT_Position = GetFileDataPosition();
packFile->FDAT_Size = packFile->HEAD_TotalDataSize;
// Calculating file positions
unsigned int relPosition = packFile->FDAT_Position;
for (unsigned int i = 0; i < numFiles; i++)
{
packFile->FLST_FilePosition[i] = relPosition;
relPosition += packFile->FLST_FileSize[i];
}
// Generate the pack structure
GeneratePackStructure();
// Write pack file
WritePackFile();
std::cout << "Done" << std::endl;
}
void PackEngine::Unpack()
{
ReadPackFile();
if (gotError)
return;
// Unpack each file to disk
for (unsigned int i = 0; i < packFile->HEAD_NumberOfFiles; i++)
{
UnpackFile(i);
if (gotError)
return;
}
std::cout << "Done" << std::endl;
}
void PackEngine::ReadPackFile()
{
ClosePackFile();
gotError = false;
packFile = new PackFile(packFileName);
std::ifstream infile(packFileName, std::ios::binary | std::ios::ate);
unsigned int size = (unsigned int)infile.tellg();
infile.seekg(0, std::ios::beg);
// Check Format version: PACK1000
if (!CheckFormatVersion(infile))
return;
// Read ROOT section
if (!ReadRootSection(infile))
return;
// Read HEAD section
if (!ReadHeadSection(infile))
return;
// Read FLST section
if (!ReadFlstSection(infile))
return;
// Read FDAT section
if (!ReadFdatSection(infile))
return;
//
// Fill data into the pack file structure
//
// Fill HEAD section
if (!FillHeadSection(infile))
return;
// Fill FLST section
if (!FillFlstSection(infile))
return;
infile.close();
}
void PackEngine::WritePackFile()
{
std::ofstream outfile(packFileName, std::ofstream::binary | std::ofstream::trunc);
// Get the total file size of the pack file
unsigned int packFileSize = 0;
packFileSize += 8; // PACK1000
packFileSize += packFile->ROOT_Size;
packFileSize += packFile->HEAD_Size;
packFileSize += packFile->FLST_Size;
packFileSize += packFile->FDAT_Size;
// allocate memory for the entire pack file
char* buffer = new char[packFileSize];
//
// fill buffer
//
unsigned int bufferIndex = 0;
// filling the pack structure
for (unsigned int i = 0; i < (unsigned int)packStructure.size(); i++)
buffer[i] = packStructure[i];
bufferIndex += (unsigned int)packStructure.size();
// add data from files (still filling the buffer)
for (unsigned int i = 0; i < packFile->HEAD_NumberOfFiles; i++)
{
std::vector<char> bufferData = ReadFile(packFile->FLST_FileNames[i]);
for (unsigned int j = 0; j < (unsigned int)bufferData.size(); j++)
{
buffer[bufferIndex] = bufferData[j];
bufferIndex++;
}
}
// write to file
outfile.write(buffer, packFileSize);
// release memory
delete[] buffer;
outfile.close();
}
void PackEngine::ClosePackFile()
{
if (packFile)
{
delete packFile;
packFile = nullptr;
}
}
unsigned int PackEngine::GetFileSize(std::string path)
{
unsigned int size = 0;
std::ifstream file(path, std::ios::binary | std::ios::ate);
if (!file)
{
printf("Error: Could not open file: %s\n", path.c_str());
gotError = true;
return 0;
}
size = (unsigned int)file.tellg();
file.close();
return size;
}
unsigned int PackEngine::GetFileListSize()
{
unsigned int tempSize = 0;
for (unsigned int i = 0; i < packFile->HEAD_NumberOfFiles; i++)
{
tempSize += (unsigned int)packFile->FLST_FileNames[i].size();
tempSize += 1; // for '\0' terminator
tempSize += 8; // for position and size
}
return tempSize;
}
unsigned int PackEngine::GetFileDataPosition()
{
unsigned int tempPos = 0;
tempPos += 8; // "PACK1000"
tempPos += packFile->ROOT_Size; // ROOT size
tempPos += packFile->HEAD_Size; // HEAD size
tempPos += packFile->FLST_Size; // FLST size
return tempPos;
}
void PackEngine::GeneratePackStructure()
{
packStructure.clear();
packStructure.reserve(packFile->FDAT_Position);
// Format version: PACK1000
AddStringToPackStructure("PACK1000");
// *** ROOT ***
// ROOT section
AddStringToPackStructure("ROOT");
AddUnsignedIntToPackStructure(packFile->ROOT_Position);
AddUnsignedIntToPackStructure(packFile->ROOT_Size);
// HEAD section
AddStringToPackStructure("HEAD");
AddUnsignedIntToPackStructure(packFile->HEAD_Position);
AddUnsignedIntToPackStructure(packFile->HEAD_Size);
// FLST section
AddStringToPackStructure("FLST");
AddUnsignedIntToPackStructure(packFile->FLST_Position);
AddUnsignedIntToPackStructure(packFile->FLST_Size);
// FDAT section
AddStringToPackStructure("FDAT");
AddUnsignedIntToPackStructure(packFile->FDAT_Position);
AddUnsignedIntToPackStructure(packFile->FDAT_Size);
// *** HEAD ***
AddUnsignedIntToPackStructure(packFile->HEAD_NumberOfFiles);
AddUnsignedIntToPackStructure(packFile->HEAD_TotalDataSize);
AddStringToPackStructure(packFile->HEAD_DataVersion);
// *** FLST ***
for (unsigned int i = 0; i < packFile->HEAD_NumberOfFiles; i++)
{
AddStringToPackStructure(packFile->FLST_FileNames[i]);
AddNullCharToPackStructure();
AddUnsignedIntToPackStructure(packFile->FLST_FilePosition[i]);
AddUnsignedIntToPackStructure(packFile->FLST_FileSize[i]);
}
//for (unsigned int i = 0; i < packStructure.size(); i++)
// printf("%X ", packStructure[i]);
}
std::vector<unsigned char> PackEngine::ConvertToChars(std::string text)
{
std::vector<unsigned char> chars;
chars.reserve(text.size());
for (unsigned int i = 0; i < text.size(); i++)
chars.push_back(text[i]);
return chars;
}
void PackEngine::AddStringToPackStructure(std::string text)
{
for (unsigned int i = 0; i < text.size(); i++)
packStructure.push_back(text[i]);
}
void PackEngine::AddUnsignedIntToPackStructure(unsigned int value)
{
std::string bytes = ConvertUnsignedIntToChar4(value);
// Writing unsigned int value as bytes
packStructure.push_back(bytes[0]);
packStructure.push_back(bytes[1]);
packStructure.push_back(bytes[2]);
packStructure.push_back(bytes[3]);
}
void PackEngine::AddNullCharToPackStructure()
{
packStructure.push_back('\0');
}
std::vector<char> PackEngine::ReadFile(std::string path)
{
unsigned fileSize = 0;
std::ifstream infile(path, std::ios::binary | std::ios::ate);
fileSize = (unsigned int)infile.tellg();
infile.seekg(0, std::ios::beg);
std::vector<char> buffer(fileSize);
if (infile.read(buffer.data(), fileSize))
{
return buffer;
}
std::cout << "Error: Could not read: " << path << std::endl;
return std::vector<char>();
}
bool PackEngine::CheckFormatVersion(std::ifstream& file)
{
unsigned int formatVersionBufferSize = (unsigned int)packFormatVersion.size();
std::vector<char> formatVersionBuffer(formatVersionBufferSize);
if (file.read(formatVersionBuffer.data(), formatVersionBufferSize))
{
std::string tempStr = formatVersionBuffer.data();
if (tempStr.substr(0, formatVersionBufferSize) != packFormatVersion)
{
printf("Error: Wrong format version.");
gotError = true;
return false;
}
}
file.seekg(formatVersionBufferSize);
return true;
}
bool PackEngine::ReadRootSection(std::ifstream& file)
{
PackSection packSection = ReadSection(file, 8);
if (gotError)
return false;
std::string sectionName = "";
sectionName.append(packSection.name, 0, 4);
if (sectionName != "ROOT")
{
gotError = true;
std::cout << "ROOT section not found" << std::endl;
return false;
}
packFile->ROOT_Position = packSection.position;
packFile->ROOT_Size = packSection.size;
return true;
}
bool PackEngine::ReadHeadSection(std::ifstream& file)
{
PackSection packSection = ReadSection(file, 20);
if (gotError)
return false;
std::string sectionName = "";
sectionName.append(packSection.name, 0, 4);
if (sectionName != "HEAD")
{
gotError = true;
std::cout << "HEAD section not found" << std::endl;
return false;
}
packFile->HEAD_Position = packSection.position;
packFile->HEAD_Size = packSection.size;
return true;
}
bool PackEngine::ReadFlstSection(std::ifstream& file)
{
PackSection packSection = ReadSection(file, 32);
if (gotError)
return false;
std::string sectionName = "";
sectionName.append(packSection.name, 0, 4);
if (sectionName != "FLST")
{
gotError = true;
std::cout << "FLST section not found" << std::endl;
return false;
}
packFile->FLST_Position = packSection.position;
packFile->FLST_Size = packSection.size;
return true;
}
bool PackEngine::ReadFdatSection(std::ifstream& file)
{
PackSection packSection = ReadSection(file, 44);
if (gotError)
return false;
std::string sectionName = "";
sectionName.append(packSection.name, 0, 4);
if (sectionName != "FDAT")
{
gotError = true;
std::cout << "FDAT section not found" << std::endl;
return false;
}
packFile->FDAT_Position = packSection.position;
packFile->FDAT_Size = packSection.size;
return true;
}
PackSection PackEngine::ReadSection(std::ifstream& file, unsigned int location)
{
PackSection packSection;
packSection.name[0] = '\0';
packSection.name[1] = '\0';
packSection.name[2] = '\0';
packSection.name[3] = '\0';
packSection.position = 0;
packSection.size = 0;
// Read 12 bytes
unsigned int bufferSize = 12;
std::vector<char> buffer(bufferSize);
if (!file.read(buffer.data(), bufferSize))
{
printf("Error: Could not read section.");
gotError = true;
return packSection;
}
// Fill in section name into the struct
for (unsigned int i = 0; i < 4; i++)
packSection.name[i] = buffer[i];
// Fill in position of the section
packSection.position = ConvertChar4ToUnsignedInt(&buffer[4]);
// Fill in size of the section
packSection.size = ConvertChar4ToUnsignedInt(&buffer[8]);
return packSection;
}
bool PackEngine::FillHeadSection(std::ifstream& file)
{
// Read 20 bytes
unsigned int bufferSize = packFile->HEAD_Size;
std::vector<char> buffer(bufferSize);
if (!file.read(buffer.data(), bufferSize))
{
printf("Error: Could not read section.");
gotError = true;
return false;
}
// Number of files
packFile->HEAD_NumberOfFiles = ConvertChar4ToUnsignedInt(&buffer[0]);
// Total data size
packFile->HEAD_TotalDataSize = ConvertChar4ToUnsignedInt(&buffer[4]);
// Data version
std::string dataVersion = "";
for (unsigned int i = 8; i < 20; i++)
dataVersion.append(&buffer[i]);
packFile->HEAD_DataVersion = dataVersion.substr(0, 12);;
return true;
}
bool PackEngine::FillFlstSection(std::ifstream& file)
{
// Read X bytes
unsigned int bufferSize = packFile->FLST_Size;
std::vector<char> buffer(bufferSize);
if (!file.read(buffer.data(), bufferSize))
{
printf("Error: Could not read section.");
gotError = true;
return false;
}
unsigned int last = 0;
std::string tempStr = "";
for (unsigned int i = 0; i < bufferSize; i++)
{
if (buffer[i] == '\0')
{
packFile->FLST_FileNames.push_back(tempStr);
tempStr.clear();
char tempC[4];
tempC[0] = buffer[i + 1];
tempC[1] = buffer[i + 2];
tempC[2] = buffer[i + 3];
tempC[3] = buffer[i + 4];
packFile->FLST_FilePosition.push_back(ConvertChar4ToUnsignedInt(tempC));
tempC[0] = buffer[i + 5];
tempC[1] = buffer[i + 6];
tempC[2] = buffer[i + 7];
tempC[3] = buffer[i + 8];
packFile->FLST_FileSize.push_back(ConvertChar4ToUnsignedInt(tempC));
i += 8;
last = i;
continue;
}
tempStr.append(&buffer[i], 1);
}
return true;
}
void PackEngine::UnpackFile(unsigned int fileIndex)
{
unsigned int bufferSize = packFile->FLST_FileSize[fileIndex];
char* buffer = new char[bufferSize];
std::ifstream infile(packFileName, std::ios::binary);
infile.seekg(packFile->FLST_FilePosition[fileIndex], std::ios::beg);
infile.read(buffer, bufferSize);
std::ofstream outfile(packFile->FLST_FileNames[fileIndex], std::ofstream::binary | std::ofstream::trunc);
outfile.write(buffer, bufferSize);
outfile.close();
delete[] buffer;
}
| true |
68211ba2f0566fbdc5bae7055522b77671c24774 | C++ | Hangtu/Arduino | /Ultrasonico/Ultrasonico.ino | UTF-8 | 1,547 | 2.828125 | 3 | [] | no_license |
//SR04
int PIN_TRIG=7;
int PIN_ECO=6;
long duracion=0;
long distancia=0;
void setup() {
// Inicializacion de la comunicacion serial
Serial.begin (9600);
// Inicializacion de pines digitales
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECO, INPUT);
}
void loop() {
mandar2();
recibir();
calculo();
respuesta();
delay(500);
// Retardo para disminuir la frecuencia de las lecturas
}
void mandar(){
/* Hacer el disparo */
digitalWrite(PIN_TRIG, LOW);
delayMicroseconds(2);
digitalWrite(PIN_TRIG, HIGH); // Flanco ascendente
delayMicroseconds(10); // Duracion del pulso
digitalWrite(PIN_TRIG, LOW); // Flanco descendente
}
void mandar2(){
digitalWrite(PIN_TRIG, HIGH); // Flanco ascendente
delayMicroseconds(1000); // Duracion del pulso
digitalWrite(PIN_TRIG, LOW); // Flanco descendente
}
void recibir(){
/* Recepcion del eco de respuesta */
duracion = pulseIn(PIN_ECO, HIGH);
}
void calculo(){
/* Calculo de la distancia efectiva */
distancia = (duracion/2) / 29;
}
void respuesta(){
/* Imprimir resultados a la terminal serial */
if (distancia >= 500 || distancia <= 0){
Serial.println("Fuera de rango");
}
if(distancia >=0 && distancia <=100 ){
Serial.print(distancia);
Serial.println(" cm - esta cerca");
}
if (distancia >=101 && distancia <=499) {
Serial.print(distancia);
Serial.println(" cm - esta lejos");
}
}
| true |
71dc49e9615bfd3ddfd4c953280bf9963a9044dd | C++ | Julian-guillermo-zapata-rugeles/udea-laboratorio-1 | /lab1_15/main.cpp | UTF-8 | 630 | 4.03125 | 4 | [] | no_license | /*
Ejercicio 15. Escriba un programa que pida constantemente números hasta que se ingrese el nú-
mero cero e imprima en pantalla la suma de todos los números ingresados.
Ej: si se ingresan 1, 2, 3, 0 se debe imprimir:
El resultado de la sumatoria es: 6
*/
#include <iostream>
using namespace std;
int main()
{
int numero=0 , suma=0, *ptr_numero=&numero ;
for (int i = 0 ; i < 1 ; ) {
cout << "Ingrese un numero : ";
cin >> *ptr_numero;
if(*ptr_numero != 0){
suma+=*ptr_numero;
}
else{ i++ ;
}
}
cout << "Sumatoria = "<<suma << endl;
return 0;
}
| true |
f984c27333d13847abddcc0b3a4cc1f8f2783dd1 | C++ | svens/pal | /pal/net/ip/basic_resolver.test.cpp | UTF-8 | 6,878 | 2.5625 | 3 | [
"MIT"
] | permissive | #include <pal/net/ip/basic_resolver>
#include <pal/net/test>
#include <catch2/catch_template_test_macros.hpp>
namespace {
using namespace pal_test;
TEMPLATE_TEST_CASE("net/ip/basic_resolver", "",
udp_v4,
tcp_v4,
udp_v6,
tcp_v6)
{
using protocol_t = std::remove_cvref_t<decltype(TestType::protocol_v)>;
using endpoint_t = typename protocol_t::endpoint;
using resolver_t = typename protocol_t::resolver;
resolver_t resolver;
SECTION("resolve")
{
auto resolve = resolver.resolve("localhost", "echo");
REQUIRE(resolve);
CHECK(resolve->max_size() > 0);
static_assert(resolve->max_size() > 0);
REQUIRE_FALSE(resolve->empty());
for (auto &it: *resolve)
{
CHECK(it.endpoint() == static_cast<endpoint_t>(it));
CHECK(it.endpoint().address().is_loopback());
CHECK(it.endpoint().port() == 7);
CHECK(it.host_name() == "localhost");
CHECK(it.service_name() == "echo");
}
}
SECTION("resolve with protocol")
{
auto resolve = resolver.resolve(TestType::protocol_v, "localhost", "echo");
REQUIRE(resolve);
REQUIRE_FALSE(resolve->empty());
for (auto &it: *resolve)
{
CHECK(it.endpoint().protocol() == TestType::protocol_v);
CHECK(it.endpoint().address().is_loopback());
CHECK(it.endpoint().port() == 7);
CHECK(it.host_name() == "localhost");
CHECK(it.service_name() == "echo");
}
}
SECTION("resolve passive")
{
auto resolve = resolver.resolve({}, "echo", resolver.passive);
REQUIRE(resolve);
REQUIRE_FALSE(resolve->empty());
for (auto &it: *resolve)
{
CHECK(it.endpoint().address().is_unspecified());
CHECK(it.endpoint().port() == 7);
}
}
SECTION("resolve passive with protocol")
{
auto resolve = resolver.resolve(TestType::protocol_v, {}, "echo", resolver.passive);
REQUIRE(resolve);
REQUIRE_FALSE(resolve->empty());
for (auto &it: *resolve)
{
CHECK(it.endpoint().protocol() == TestType::protocol_v);
CHECK(it.endpoint().address().is_unspecified());
CHECK(it.endpoint().port() == 7);
}
}
SECTION("resolve canonical name")
{
constexpr std::string_view host = "stun.azure.com";
auto resolve = resolver.resolve(host, {}, resolver.canonical_name);
REQUIRE(resolve);
REQUIRE_FALSE(resolve->empty());
for (auto &it: *resolve)
{
// Note: this test makes assumptions about setup
// if starts failing, find another where host name != canonical name
CHECK(it.host_name() != host);
}
}
SECTION("resolve numeric")
{
auto resolve = resolver.resolve("127.0.0.1", "7", resolver.numeric_host | resolver.numeric_service);
REQUIRE(resolve);
REQUIRE_FALSE(resolve->empty());
for (auto &it: *resolve)
{
CHECK(it.endpoint() == static_cast<endpoint_t>(it));
CHECK(it.endpoint().address().is_loopback());
CHECK(it.endpoint().port() == 7);
CHECK(it.host_name() == "127.0.0.1");
CHECK(it.service_name() == "7");
}
}
SECTION("resolve endpoint")
{
auto resolve = resolver.resolve({TestType::loopback_v, 7});
REQUIRE(resolve);
REQUIRE(resolve->size() == 1);
auto entry = *resolve->begin();
CHECK_FALSE(entry.host_name().empty());
CHECK(entry.service_name() == "echo");
}
SECTION("resolve endpoint invalid address")
{
sockaddr_storage blob{};
auto resolve = resolver.resolve(*reinterpret_cast<const endpoint_t *>(&blob));
REQUIRE_FALSE(resolve);
CHECK(resolve.error().message() != "");
}
SECTION("resolve endpoint unknown port")
{
auto resolve = resolver.resolve({TestType::loopback_v, 65535});
REQUIRE(resolve);
REQUIRE(resolve->size() == 1);
auto entry = *resolve->begin();
CHECK_FALSE(entry.host_name().empty());
CHECK(entry.service_name() == "65535");
}
SECTION("resolve endpoint not enough memory")
{
pal_test::bad_alloc_once x;
auto resolve = resolver.resolve({TestType::loopback_v, 7});
REQUIRE_FALSE(resolve);
CHECK(resolve.error() == std::errc::not_enough_memory);
}
SECTION("resolve numeric host invalid")
{
auto resolve = resolver.resolve("localhost", {}, resolver.numeric_host);
REQUIRE_FALSE(resolve);
CHECK(resolve.error() == pal::net::ip::resolver_errc::host_not_found);
CHECK_FALSE(resolve.error().message().empty());
CHECK(resolve.error().category().name() == std::string{"resolver"});
}
SECTION("resolve numeric service invalid")
{
auto resolve = resolver.resolve({}, "echo", resolver.numeric_service);
REQUIRE_FALSE(resolve);
CHECK(resolve.error() == pal::net::ip::resolver_errc::service_not_found);
CHECK_FALSE(resolve.error().message().empty());
CHECK(resolve.error().category().name() == std::string{"resolver"});
}
SECTION("resolve host not found")
{
auto resolve = resolver.resolve(pal_test::case_name(), {});
REQUIRE_FALSE(resolve);
CHECK(resolve.error() == pal::net::ip::resolver_errc::host_not_found);
CHECK_FALSE(resolve.error().message().empty());
CHECK(resolve.error().category().name() == std::string{"resolver"});
}
SECTION("resolve service not found")
{
auto resolve = resolver.resolve({}, pal_test::case_name());
REQUIRE_FALSE(resolve);
CHECK(resolve.error() == pal::net::ip::resolver_errc::service_not_found);
CHECK_FALSE(resolve.error().message().empty());
CHECK(resolve.error().category().name() == std::string{"resolver"});
}
SECTION("resolve not enough memory")
{
pal_test::bad_alloc_once x;
auto resolve = resolver.resolve("localhost", "echo");
REQUIRE_FALSE(resolve);
CHECK(resolve.error() == std::errc::not_enough_memory);
}
SECTION("entry and iterator")
{
auto resolve = resolver.resolve("localhost", "echo");
REQUIRE(resolve);
REQUIRE_FALSE(resolve->empty());
auto it = resolve->begin();
CHECK(it->endpoint().address().is_loopback());
CHECK(it->endpoint().port() == 7);
CHECK(it->host_name() == "localhost");
CHECK(it->service_name() == "echo");
CHECK(it->endpoint() == (*it).endpoint());
CHECK(it->host_name() == (*it).host_name());
CHECK(it->service_name() == (*it).service_name());
auto i1 = it++;
CHECK(it != resolve->cbegin());
CHECK(i1 == resolve->cbegin());
CHECK(i1 != it);
auto i2 = ++i1;
CHECK(i1 == i2);
CHECK(i2 == it);
it = resolve->end();
CHECK(it == resolve->cend());
CHECK(it != resolve->begin());
CHECK(it != resolve->cbegin());
}
SECTION("empty basic_resolver_results")
{
pal::net::ip::basic_resolver_results<protocol_t> results;
REQUIRE(results.empty());
CHECK(results.begin() == results.end());
CHECK(results.cbegin() == results.cend());
}
SECTION("swap")
{
auto echo = resolver.resolve({}, "echo");
REQUIRE(echo);
REQUIRE_FALSE(echo->empty());
CHECK(echo->begin()->endpoint().port() == 7);
auto time = resolver.resolve({}, "time");
REQUIRE(time);
REQUIRE_FALSE(time->empty());
CHECK(time->begin()->endpoint().port() == 37);
echo->swap(*time);
CHECK(echo->begin()->endpoint().port() == 37);
CHECK(time->begin()->endpoint().port() == 7);
}
}
} // namespace
| true |