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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0b24ed442b2414f49751a9b9a4c7e5279743d33e | C++ | FlowBo/Cinder_Apps | /coding_01/src/coding_01App.cpp | UTF-8 | 1,981 | 2.609375 | 3 | [] | no_license | #include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/Text.h"
#include "cinder/Font.h"
#include "cinder/gl/Texture.h"
#include "cinder/CinderMath.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class coding_01App : public AppNative {
public:
void setup();
void mouseDown( MouseEvent event );
void update();
void draw();
void prepareSettings( Settings *settings);
TextBox text;
cinder::Font font;
gl::Texture texture;
int division;
float angle;
};
void coding_01App::prepareSettings( Settings *settings ){
settings->setWindowSize( 800, 600 );
settings->setFrameRate( 60.0f );
}
void coding_01App::setup()
{
division = 20;
angle = 10;
font = Font("Helvetica", 15);
text = TextBox();
text.setColor(Color(0,0,0));
text.setFont(font);
text.setBackgroundColor(ColorA(0,0,0,0));
}
void coding_01App::mouseDown( MouseEvent event )
{
}
void coding_01App::update()
{
}
void coding_01App::draw()
{
// clear out the window with black
gl::clear( Color( 1, 1, 1 ) );
angle = 1;
angle *= getMousePos().x/50;
console() << angle << endl;
gl::enableAlphaBlending();
for(int x = 0; x < division ; x++)
{
float xValue = x * getWindowWidth()/(division-1);
float yValue = 100;
gl::color(0.6, 0.3, 0.0);
if(x%2 == 0){yValue+=50;};
gl::drawLine(Vec2f(xValue,0), Vec2f(xValue,yValue));
text.setText(to_string(x));
texture = text.render();
gl::draw(texture, Vec2f(xValue+5,yValue-10));
}
gl::disableAlphaBlending();
gl::pushMatrices();
gl::translate(getWindowCenter());
for(float t = 0; t < 360 ; t += angle)
{
Vec2f v = Vec2f(math<float>::cos(toRadians(t))*100,math<float>::sin(toRadians(t))*100);
gl::drawSolidCircle(v, 2);
}
gl::popMatrices();
}
CINDER_APP_NATIVE( coding_01App, RendererGl )
| true |
1bc304744f5b14de2198aa0435bce7777289a8dd | C++ | atakandrmz/Nautilus | /Multiplexer/Multiplexer.ino | UTF-8 | 4,965 | 2.84375 | 3 | [] | no_license | int val = 0; // variable to store the read value
int A_zero = 8;
int A_one = 9;
int A_two = 10;
int A_three = 11;
int z = 12;
void setup()
{
pinMode(z, INPUT); // sets the digital pin "z" as input
pinMode(A_zero, OUTPUT); // sets the digital pin "A_zero" as output
pinMode(A_one, OUTPUT); // sets the digital pin "A_one" as output
pinMode(A_two, OUTPUT); // sets the digital pin "A_two" as output
pinMode(A_three, OUTPUT); // sets the digital pin "A_three" as output
Serial.begin(9600);
}
void loop()
{
// Select address 0000
digitalWrite(A_zero, LOW);
digitalWrite(A_one, LOW);
digitalWrite(A_two, LOW);
digitalWrite(A_three, LOW);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 1");
delay(50);
}
// Select address 0001
digitalWrite(A_zero, HIGH);
digitalWrite(A_one, LOW);
digitalWrite(A_two, LOW);
digitalWrite(A_three, LOW);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 2");
delay(50);
}
// Select address 0010
digitalWrite(A_zero, LOW);
digitalWrite(A_one, HIGH);
digitalWrite(A_two, LOW);
digitalWrite(A_three, LOW);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 3");
delay(50);
}
// Select address 0011
digitalWrite(A_zero, HIGH);
digitalWrite(A_one, HIGH);
digitalWrite(A_two, LOW);
digitalWrite(A_three, LOW);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 4");
delay(50);
}
// Select address 0100
digitalWrite(A_zero, LOW);
digitalWrite(A_one, LOW);
digitalWrite(A_two, HIGH);
digitalWrite(A_three, LOW);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 5");
delay(50);
}
// Select address 0101
digitalWrite(A_zero, HIGH);
digitalWrite(A_one, LOW);
digitalWrite(A_two, HIGH);
digitalWrite(A_three, LOW);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 6");
delay(50);
}
// Select address 0110
digitalWrite(A_zero, LOW);
digitalWrite(A_one, HIGH);
digitalWrite(A_two, HIGH);
digitalWrite(A_three, LOW);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 7");
delay(50);
}
// Select address 0111
digitalWrite(A_zero, HIGH);
digitalWrite(A_one, HIGH);
digitalWrite(A_two, HIGH);
digitalWrite(A_three, LOW);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 8");
delay(50);
}
// Select address 1000
digitalWrite(A_zero, LOW);
digitalWrite(A_one, LOW);
digitalWrite(A_two, LOW);
digitalWrite(A_three, HIGH);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 9");
delay(50);
}
// Select address 1001
digitalWrite(A_zero, HIGH);
digitalWrite(A_one, LOW);
digitalWrite(A_two, LOW);
digitalWrite(A_three, HIGH);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 10");
delay(50);
}
// Select address 1010
digitalWrite(A_zero, LOW);
digitalWrite(A_one, HIGH);
digitalWrite(A_two, LOW);
digitalWrite(A_three, HIGH);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 11");
delay(50);
}
// Select address 1011
digitalWrite(A_zero, HIGH);
digitalWrite(A_one, HIGH);
digitalWrite(A_two, LOW);
digitalWrite(A_three, HIGH);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 12");
delay(50);
}
// Select address 1100
digitalWrite(A_zero, LOW);
digitalWrite(A_one, LOW);
digitalWrite(A_two, HIGH);
digitalWrite(A_three, HIGH);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 13");
delay(50);
}
// Select address 1101
digitalWrite(A_zero, HIGH);
digitalWrite(A_one, LOW);
digitalWrite(A_two, HIGH);
digitalWrite(A_three, HIGH);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 14");
delay(50);
}
// Select address 1110
digitalWrite(A_zero, LOW);
digitalWrite(A_one, HIGH);
digitalWrite(A_two, HIGH);
digitalWrite(A_three, HIGH);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 15");
delay(50);
}
// Select address 1111
digitalWrite(A_zero, HIGH);
digitalWrite(A_one, HIGH);
digitalWrite(A_two, HIGH);
digitalWrite(A_three, HIGH);
if(digitalRead(z)==1)
{
Serial.println("Switch pressed is 16");
delay(50);
}
}
| true |
0e579ddf2d562f5b436582f44d340b6be668a2d3 | C++ | Minusie357/Algorithm | /BackjoonAlgorithm/9205. 맥주 마시면서 걸어가기.cpp | UTF-8 | 1,668 | 2.609375 | 3 | [
"Unlicense"
] | permissive | //#include <iostream>
//#include <cmath>
//#include <queue>
//#include <vector>
//#include <utility>
//using namespace std;
//
//#ifdef _DEBUG
//#include "Utility.h"
//#endif // _DEBUG
//
//
//
//typedef pair<int, int> mcoord;
//constexpr int max_limit = 100;
//int main()
//{
// ios::sync_with_stdio(false);
// cin.tie(NULL);
//
// int t;
// cin >> t;
//
// vector<int> graph[max_limit + 2];
// mcoord points[max_limit + 2];
//
// queue<int> q;
// bool visit[max_limit + 2];
// while (t--)
// {
// for (int i = 0; i < max_limit + 2; ++i)
// {
// graph[i].clear();
// visit[i] = false;
// }
//
//
// int n;
// cin >> n;
//
// int x, y;
// for (int i = 0; i < n + 2; ++i)
// {
// cin >> x >> y;
// points[i] = { x,y };
// for (int j = i - 1; j >= 0; --j)
// {
// int manhatten = abs(points[i].first - points[j].first) + abs(points[i].second - points[j].second);
// if (manhatten <= 1000)
// {
// //cout << i << " and " << j << " are connected\n";
// graph[i].push_back(j);
// graph[j].push_back(i);
// }
// }
// }
//
// q.push(0);
// visit[0] = true;
//
// bool loop = true;
// while (q.empty() == false && loop)
// {
// auto curr = q.front();
// q.pop();
//
// int next;
// for (int s = 0; s < graph[curr].size(); ++s)
// {
// next = graph[curr][s];
//
// // check already visited
// if (visit[next] == true)
// continue;
//
// // check end point
// if (next == n + 1)
// {
// cout << "happy\n";
// loop = false;
// break;
// }
//
// visit[next] = true;
// q.push(next);
// }
// }
//
// if (loop == true)
// cout << "sad\n";
// }
//
//
// return 0;
//} | true |
254a6efe7bac7e0c7f624887637f2e589564f065 | C++ | skakri09/StarTris---Tetris-school-project-fall-2011 | /StarTris/NITHris/Piece.cpp | UTF-8 | 10,751 | 2.859375 | 3 | [] | no_license |
/********************************************************
* File: Piece.cpp
* Orginal Author: Kristian Skarrseth / NITH / 2011
* Changed by: -
*
* Description: Handles the basic needs of any piece in a tetris
* game. Trough public functions another class
* spawn new current and new pieces, move current piece
* left/right/down/(up to revert bad movement)
* and rotate piece. Also includes some helpfull
* functions to give other classes references to current/nextpiece
*
* Special notes: Can not directly draw a piece. Drawing must be done
* trough another class as is now.
*
/********************************************************/
#include "Piece.h"
/*|---------------------------------------|*/
/*| P U B L I C F U N C T I O N S |*/
/*| |*/
CPiece::CPiece()
{
//Seeds srand with timme, casting to int to avoid unnecessary warning
srand (static_cast<int>(time(0)));
// Makes nextPiecePointer pointer point to a new random piece
m_makeNewRandNextPiece();
// Sets currentPiecePointer to point to m_aCurrentPieceOne
m_pCurrentPiecePointer = &m_aCurrentPieceOne[0][0];
// Says It's "true" that we are currently pointing to currentPieceOne
m_bCurrPieceIsFirstArray = true;
}
CPiece::~CPiece()
{
}
// Returns a reference to the nextPiece array
ETileColor* CPiece::getNextPieceReference() const
{
return m_pNextPiecePointer;
}//end getNextPieceReference()
// Returns a reference to the currentPiece array
ETileColor* CPiece::getCurrentPieceReference() const
{
return m_pCurrentPiecePointer;
}//end getCurrentPieceReference()
// Gives the CPiece class a reference to the background array to use for collision checks etc
void CPiece::setLocalBackgroundArrayReference(ETileColor* backgroundArrayReference)
{
m_pLocalBackgroundArrayReferencePointer = backgroundArrayReference;
}
// Increses and decreses X/Y position for currentpiece. Will move
// currentPiece one tile in the specified direction
void CPiece::moveCurrentPieceOneTileLeft()
{
m_sCurrPieceXPos--;
if(m_bIsWallCollision() || bIsCollisionBetweenCurrPieceAndLandedPieces(m_pLocalBackgroundArrayReferencePointer))
{
m_sCurrPieceXPos++;
}
}
void CPiece::moveCurrentPieceOneTileRight()
{
m_sCurrPieceXPos++;
if(m_bIsWallCollision() || bIsCollisionBetweenCurrPieceAndLandedPieces(m_pLocalBackgroundArrayReferencePointer))
{
m_sCurrPieceXPos--;
}
}
void CPiece::moveCurrentPieceOneTileDown()
{
m_sCurrPieceYPos++;
if(m_bIsWallCollision())
{
m_sCurrPieceYPos--;
}
}
void CPiece::moveCurrentPieceOneTileUp()
{
m_sCurrPieceYPos--;
}
// Returns current X and Y position for the active currentPiece
short CPiece::getCurrentPieceXPos() const
{
return m_sCurrPieceXPos;
}
short CPiece::getCurrentPieceYPos() const
{
return m_sCurrPieceYPos;
}
// Copies the values from the array that nextPiecePointer is pointing to,
// to the currently active currentActive, then calls makeNewRandNextPiece()
// function to get a new random nextPiece
void CPiece::makeNewNextPiece()
{
m_setCurrentPieceStartPosition();
m_eCurrentPieceType = m_eNextPieceType; // Sets currentPieceType to what nextPieceType was. Is used to decide if rotation is needed (not needed on BoxPiece)
memcpy(m_pCurrentPiecePointer, m_pNextPiecePointer, // Copies what nextPiecePointer points to, to what currentPiecePointer points to
sizeof(int)*((g_usPIECE_ARRAY_SIZE)*(g_usPIECE_ARRAY_SIZE)));
m_makeNewRandNextPiece(); // Makes a new random nextPiece
}
// Checks for collision between current piece and landed pieces.
// Returns true if there is collision
bool CPiece::bIsCollisionBetweenCurrPieceAndLandedPieces(ETileColor* backgroundReference)
{
for(unsigned int x = 0; x < g_usPIECE_ARRAY_SIZE; ++x)
{
for(unsigned int y = 0; y < g_usPIECE_ARRAY_SIZE; ++y)
{
m_pCurrentPiecePointerForCollisionCheck = (m_pCurrentPiecePointer + (x * g_usPIECE_ARRAY_SIZE) + y );//piece
m_pBackgroundPointerForCollisionCheck = (m_pLocalBackgroundArrayReferencePointer + ( (y+m_sCurrPieceXPos)*g_usGAME_TILEHEIGHT) + (x+m_sCurrPieceYPos));//background
if(*(m_pBackgroundPointerForCollisionCheck) != TC_BACKGROUND && m_sCurrPieceYPos != g_sPIECE_STARTPOS_Y && *(m_pCurrentPiecePointerForCollisionCheck) != TC_NO_DRAW)
{
return true;
}
else if(*(m_pCurrentPiecePointerForCollisionCheck) != TC_NO_DRAW && (m_sCurrPieceYPos + x) >= g_usGAME_TILEHEIGHT && m_sCurrPieceYPos != g_sPIECE_STARTPOS_Y)
{
return true;
}
}
}
return false;
}
// Copies values of the active currentArray to the inactive currentArray
// with a simple algorithm that turns the piece 90 degrees clockwise. Then
// sets the inactive array as the active one. If not-allowed collision should
// happen after a turn, the first currentArray is still the active one.
void CPiece::rotateCurrentPiece()
{
// Not allowing rotating a piece untill its base position is inside the screen, in case starting position is outside.
// Also not rotating the piece if its a BoxPiece since it has no meaning
if(m_sCurrPieceYPos >= -1 && m_eCurrentPieceType != BoxPiece)
{
if(m_bCurrPieceIsFirstArray)
{
for(unsigned int x = 0; x < g_usPIECE_ARRAY_SIZE; ++x)
{
for(unsigned int y = 0; y < g_usPIECE_ARRAY_SIZE; ++y)
{
m_aCurrentPieceTwo[x][3-y] = m_aCurrentPieceOne[y][x];
}
}
m_pCurrentPiecePointer = &m_aCurrentPieceTwo[0][0];
m_bCurrPieceIsFirstArray = false;
//If there is collision after the rotation, the pointer is not changed, and currentPieceOne is still the active one
if(m_bIsWallCollision() || bIsCollisionBetweenCurrPieceAndLandedPieces(m_pLocalBackgroundArrayReferencePointer))
{
m_pCurrentPiecePointer = &m_aCurrentPieceOne[0][0];
m_bCurrPieceIsFirstArray = true;
}
}
else
{
for(unsigned int x = 0; x < 4; ++x)
{
for(unsigned int y = 0; y < 4; ++y)
{
m_aCurrentPieceOne[x][3-y] = m_aCurrentPieceTwo[y][x];
}
}
m_pCurrentPiecePointer = &m_aCurrentPieceOne[0][0];
m_bCurrPieceIsFirstArray = true;
//If there is collision after the rotation, the pointer is not changed, and currentPieceTwo is still the active one
if(m_bIsWallCollision() || bIsCollisionBetweenCurrPieceAndLandedPieces(m_pLocalBackgroundArrayReferencePointer))
{
m_pCurrentPiecePointer = &m_aCurrentPieceTwo[0][0];
m_bCurrPieceIsFirstArray = false;
}
}
}
}//end rotateCurrentPiece()
/*|------------------------------------------|*/
/*| P R I V A T E F U N C T I O N S |*/
/*| |*/
// Returns false as long as there is not collision between the walls
// and currentPiece
bool CPiece::m_bIsWallCollision()
{
for(unsigned int x = 0; x < g_usPIECE_ARRAY_SIZE; ++x)
{
for(unsigned int y = 0; y < g_usPIECE_ARRAY_SIZE; ++y)
{
m_pCurrentPieceCollisionCheckPointer = ((getCurrentPieceReference()) + (x * g_usPIECE_ARRAY_SIZE) + y );
if(*(m_pCurrentPieceCollisionCheckPointer) != TC_NO_DRAW && m_sCurrPieceXPos+y >= g_usPLAYAREA_TILEWIDTH)
{
return true;
}
else if(*(m_pCurrentPieceCollisionCheckPointer) != TC_NO_DRAW && m_sCurrPieceXPos+y < 0)
{
return true;
}
}
}
return false;
}
// Sets currentPiece to the correct starting possition
void CPiece::m_setCurrentPieceStartPosition()
{
m_sCurrPieceXPos = g_usPIECE_STARTPOS_X;
m_sCurrPieceYPos = g_sPIECE_STARTPOS_Y;
}
// Makes a new random piece and sets eNextPieceType
void CPiece::m_makeNewRandNextPiece()
{
randNumber = (rand() % 7+1);
switch(randNumber)
{
case 1:
m_pNextPiecePointer = &m_aBoxPiece[0][0];
m_eNextPieceType = BoxPiece;
break;
case 2:
m_pNextPiecePointer = &m_aTowerPiece[0][0];
m_eNextPieceType = TowerPiece;
break;
case 3:
m_pNextPiecePointer = &m_aPyramidPiece[0][0];
m_eNextPieceType = PyramidPiece;
break;
case 4:
m_pNextPiecePointer = &m_aLeftHookPiece[0][0];
m_eNextPieceType = LeftHookPiece;
break;
case 5:
m_pNextPiecePointer = &m_aRightHookPiece[0][0];
m_eNextPieceType = RightHookPiece;
break;
case 6:
m_pNextPiecePointer = &m_aLeftStairPiece[0][0];
m_eNextPieceType = LeftStairPiece;
break;
case 7:
m_pNextPiecePointer = &m_aRightStairPiece[0][0];
m_eNextPieceType = RightStairPiece;
break;
// memcpy(&m_nextPiece[0][0], &m_aRightStairPiece[0][0], sizeof(int)*((g_usPIECE_ARRAY_SIZE)*(g_usPIECE_ARRAY_SIZE)));
}
}
/* ----------- Arrays with the base layout for all the 7 pieces ----------- */
ETileColor CPiece::m_aTowerPiece[g_usPIECE_ARRAY_SIZE][g_usPIECE_ARRAY_SIZE] =
{ { TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, },
{ TC_RED, TC_RED, TC_RED, TC_RED, },
{ TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, }
};
ETileColor CPiece::m_aRightStairPiece[g_usPIECE_ARRAY_SIZE][g_usPIECE_ARRAY_SIZE] =
{ { TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_GREEN, TC_GREEN, TC_NO_DRAW, },
{ TC_GREEN, TC_GREEN, TC_NO_DRAW, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, }
};
ETileColor CPiece::m_aRightHookPiece[g_usPIECE_ARRAY_SIZE][g_usPIECE_ARRAY_SIZE] =
{ { TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_MAGENTA, TC_MAGENTA, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_MAGENTA, TC_NO_DRAW, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_MAGENTA, TC_NO_DRAW, TC_NO_DRAW, }
};
ETileColor CPiece::m_aPyramidPiece[g_usPIECE_ARRAY_SIZE][g_usPIECE_ARRAY_SIZE] =
{ { TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_YELLOW, TC_NO_DRAW, TC_NO_DRAW, },
{ TC_YELLOW, TC_YELLOW, TC_YELLOW, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, }
};
ETileColor CPiece::m_aLeftStairPiece[g_usPIECE_ARRAY_SIZE][g_usPIECE_ARRAY_SIZE] =
{ { TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, },
{ TC_CYAN, TC_CYAN, TC_NO_DRAW, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_CYAN, TC_CYAN, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, }
};
ETileColor CPiece::m_aLeftHookPiece[g_usPIECE_ARRAY_SIZE][g_usPIECE_ARRAY_SIZE] =
{ { TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_ORANGE, TC_ORANGE, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_NO_DRAW, TC_ORANGE, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_NO_DRAW, TC_ORANGE, TC_NO_DRAW, }
};
ETileColor CPiece::m_aBoxPiece[g_usPIECE_ARRAY_SIZE][g_usPIECE_ARRAY_SIZE] =
{ { TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_BLUE, TC_BLUE, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_BLUE, TC_BLUE, TC_NO_DRAW, },
{ TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, TC_NO_DRAW, }
};
| true |
b33f1171e2c7897992c8f08188b2071fab42d27b | C++ | letsjdosth/GtCP | /helloworld/vector_return.cpp | UTF-8 | 246 | 3.015625 | 3 | [] | no_license | #include <vector>
#include <iostream>
using namespace std;
vector<int> vector_return(int a, int b){
vector<int> temp;
temp.push_back(a);
temp.pop_back();
return temp;
}
int main(){
int a = 42;
cout << &a << endl;
} | true |
df2d539eaccd775b6b0bff49ef370e47783be2a9 | C++ | BCS-MLi/spr_multitarget_tracking | /Definitions.hpp | UTF-8 | 1,097 | 2.5625 | 3 | [] | no_license | //
// Created by Nikita Kruk on 27.11.17.
//
#ifndef SPRMULTITARGETTRACKING_DEFINITIONS_HPP
#define SPRMULTITARGETTRACKING_DEFINITIONS_HPP
#include <cstdlib> // size_t
#include <iostream>
#include <string>
#include <cassert>
#include <cmath>
#define PARTIAL_IMAGE_OUTPUT
typedef double Real;
typedef long CostInt;
const int kNumOfStateVars = 4; // x,y,v_x,v_y
const int kNumOfDetectionVars = 2; // x,y
const int kNumOfExtractedFeatures = 8; // x,y,v_x,v_y,area,slope,width,height
/*
* Transform numerator into [0, denominator)
*/
inline Real WrappingModulo(Real numerator, Real denominator)
{
return numerator - denominator * std::floor(numerator / denominator);
}
/*
* Transform x into [0, 2\pi)
*/
inline Real ConstrainAnglePositive(Real x)
{
x = std::fmod(x, 2.0 * M_PI);
if (x < 0.0)
{
x += 2.0 * M_PI;
}
return x;
}
/*
* Transform x into [-\pi, \pi)
*/
inline Real ConstrainAngleCentered(Real x)
{
x = std::fmod(x + M_PI, 2.0 * M_PI);
if (x < 0.0)
{
x += 2.0 * M_PI;
}
return x - M_PI;
}
#endif //SPRMULTITARGETTRACKING_DEFINITIONS_HPP
| true |
50930da54a85db3b1cf0c97eb74173f9a2c401c1 | C++ | mdqyy/OpenVision | /ImgML/hmm.hpp | UTF-8 | 6,870 | 2.765625 | 3 | [] | no_license | #ifndef HMM_H
#define HMM_H
#include "ImgML/eigenutils.hpp"
#include "Common/OpenCVCommon.hpp"
/**
* @brief The HMM class :
* This class encapsulates the representation of a Discrete Hidden Markov model
* A hidden markov model is composed of transition matrix,emission matrix
* and initial probability matrix
*/
class HMM
{
public:
MatrixXf _transition;
MatrixXf _initial;
MatrixXf _emission;
int _nstates;
int _nobs;
int _seqlen;
MatrixXf _alpha;
MatrixXf _beta;
MatrixXf _scale;
/**
* @brief setData : method to set the parameters of the model
* @param transition
* @param emission
* @param initial
* @param seqlen : the maximum sequence length of sequence,for
* allocating matrices
*/
void setData(Mat transition,Mat emission,Mat initial,int seqlen=30)
{
_transition=EigenUtils::setData(transition);
_initial=EigenUtils::setData(initial);
_emission=EigenUtils::setData(emission);
_nstates=_transition.rows();
_nobs=_emission.rows();
_seqlen=seqlen;
_alpha=MatrixXf(_nstates,_seqlen+1);
_scale=MatrixXf(1,_seqlen+1);
}
//computing p(xn.....xN,zn)
void backwardMatrix(vector<int> &sequence)
{
_beta=MatrixXf(_nstates,sequence.size()+1);
int len=sequence.size()+1;
for(int i=len-1;i>=0;i--)
{
for(int j=0;j<_nstates;j++)
{
if(i==len-1)
{
_beta(j,i)=1;
}
else
{
float s=0;
for(int k=0;k<_nstates;k++)
s=s+_beta(k,i+1)*_emission(k,sequence[i])*_transition(j,k);
_beta(j,i)=s*_scale(0,i+1);
}
}
}
}
/**
* @brief forwardMatrix : method computes probability //compute p(x1 ... xn,zn)
* using the forward algorithm
* @param sequence : is input observation sequence
*/
void forwardMatrix(vector<int> &sequence)
{
int len=sequence.size()+1;
for(int i=0;i<len;i++)
{
for(int j=0;j<_nstates;j++)
{
if(i==0)
_alpha(j,i)=_emission(j,sequence[i])*_initial(0,j);
else
{
float s=0;
for(int k=0;k<_nstates;k++)
s=s+_transition(k,j)*_alpha(k,i-1);
_alpha(j,i)=_emission(j,sequence[i-1])*s;
}
}
float scale=0;
for(int j=0;j<_nstates;j++)
{
scale=scale+_alpha(j,i);
}
scale=1.f/scale;
if(i==0)
_scale(0,i)=1;
else
_scale(0,i)=scale;
for(int j=0;j<_nstates;j++)
{
_alpha(j,i)=scale*_alpha(j,i);
}
}
}
void forwardMatrixI(vector<int> &sequence)
{
int len=sequence.size()+1;
for(int i=0;i<len;i++)
{
for(int j=0;j<_nstates;j++)
{
if(i==0)
if(j==0)
_alpha(j,i)=1;//_emission(j,sequence[i])*_initial(0,j);
else
_alpha(j,i)=0;
else
{
float s=0;
for(int k=0;k<_nstates;k++)
s=s+_transition(k,j)*_alpha(k,i-1);
_alpha(j,i)=_emission(j,sequence[i-1])*s;
}
}
float scale=0;
for(int j=0;j<_nstates;j++)
{
scale=scale+_alpha(j,i);
}
scale=1.f/scale;
if(i==0)
_scale(0,i)=1;
else
_scale(0,i)=scale;
for(int j=0;j<_nstates;j++)
{
_alpha(j,i)=scale*_alpha(j,i);
}
}
}
/**
* @brief likelyhood : method to compute the log
* likeyhood of observed sequence
* @param sequence :input observation sequence
* @return
*/
float likelyhood(vector<int> sequence)
{
float prob=0;
//computing the probability of observed sequence
//using forward algorithm
forwardMatrix(sequence);
backwardMatrix(sequence);
for(int i=0;i<sequence.size()+1;i++)
{
//for(int j=0;j<_nstates;j++)
{
prob=prob+std::log(_scale(0,i));
}
}
return -prob;
}
};
/*class Gaussian
{
Matrix _mu;
Matrix _sigma;
Matrix _invsigma;
float _detsigma;
float _detinvsigma;
float scale;
// enum class MTYPE:char{FULL=1,DIAGONAL=2,SHPERICAL=3};
class gtype
{
public:
enum type {TYPE_FULL, TYPE_DIAGONAL, TYPE_SPHERICAL};
type t;
};
gtype t;
void setParams(Mat mu,Mat sigma)
{
_mu.setData(mu);
_sigma.setData(sigma);
_invsigma=_sigma.inverse();
_detsigma=_sigma.determinant();
_detinvsigma=_invsigma.determinant();
scale=1.f/pow(2*PI*_detsigma,0.5);
}
float Prob(Mat &x)
{
Matrix tmp;
tmp.setData(x);
float res=0;
if(t.t==gtype::TYPE_FULL)
{
MatrixXf tmp1=(tmp._data-_mu._data).transpose();
MatrixXf tmp2=tmp1*_invsigma._data*tmp1;
res=tmp2(0,0);
}
else if(t.t==gtype::TYPE_SPHERICAL)
{
}
else if(t.t==gtype::TYPE_DIAGONAL)
{
}
res=exp(-0.5*res);
if(res<0)
res=0;
if(res>1)
res=1;
if(isnan(res))
res=0;
return res;
}
float logProb(Mat &x)
{
///
Matrix tmp;
tmp.setData(x);
float res;
if(t.t==gtype::TYPE_FULL)
{
MatrixXf tmp1=(tmp._data-_mu._data).transpose();
MatrixXf tmp2=tmp1*_invsigma._data*tmp1;
res=tmp2(0,0);
}
else if(t.t==gtype::TYPE_SPHERICAL)
{
}
else if(t.t==gtype::TYPE_DIAGONAL)
{
}
if(isnan(res))
res=0;
return res;
}
};
/*
class GaussianMixture
{
int nmix;
enum class Type {FULL,DIAGONAL,TIED,SPHERICAL};
Vector mu;
Matrix sigma;
float computeProbability(Vector x)
{
}
};
/*
class HMM
{
public:
HMM();
int nstates;
int hmmLogprob()
{
/*
nobs = numel(X);
logp = zeros(nobs, 1);
pi = model.pi;
A = model.A;
for i=1:nobs
logB = mkSoftEvidence(model.emission, X{i});
[logB, scale] = normalizeLogspace(logB');
B = exp(logB');
logp(i) = hmmFilter(pi, A, B);
logp(i) = logp(i) + sum(scale);
end
}
};
*/
#endif // HMM_H
| true |
029b6dda4a298fb700f86f2439eec6425c961ad9 | C++ | cosunae/stencil_benchmarks | /src/blockgen.cpp | UTF-8 | 780 | 3 | 3 | [
"BSD-3-Clause"
] | permissive | #include <cmath>
#include <iostream>
#include "blockgen.h"
std::vector<int> prime_factors(int n) {
if (n < 2)
return std::vector<int>();
std::vector<int> primes;
std::vector<bool> sieve(n / 2, true);
for (int i = 2; i <= std::sqrt(n / 2); ++i) {
if (sieve[i]) {
primes.push_back(i);
for (std::size_t j = i * i; j < sieve.size(); j += i)
sieve[j] = false;
}
}
std::vector<int> factors;
for (int prime : primes) {
std::cout << prime << std::endl;
if (prime * prime > n)
break;
while (n % prime == 0) {
factors.push_back(prime);
n /= prime;
}
}
if (n > 1)
factors.push_back(n);
return factors;
}
| true |
9278a1da01c95d32e3ca2287404ba9f153d7113d | C++ | andsssf/cg_2d_line_drawing | /WM/WindowManager.cpp | UTF-8 | 668 | 2.65625 | 3 | [] | no_license | #include "WindowManager.h"
#include "Elems/Line_DDA.h"
#include "Elems/Line_MP.h"
#include "Elems/Circle_MP.h"
void WindowManager::init() {
}
void WindowManager::pushElem(Drawable *elem) {
elems->push_back(elem);
}
void WindowManager::popElem() {
if (elems->empty()) {
return; //需要完善
} else {
Drawable *result = elems->at(elems->size() - 1);
elems->pop_back();
delete result;
return;
}
}
void WindowManager::clearAll() {
elems->clear();
}
void WindowManager::drawAll() {
for (Drawable* a : *elems) {
a->draw();
}
}
int WindowManager::size() {
return elems->size();
} | true |
95864e2b4e48874f851381f6618c1d6387ba1147 | C++ | yu3mars/proconcpp | /aoj/ITP1_6_A.cpp | UTF-8 | 271 | 2.53125 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
int main(){
int n;
scanf("%d",&n);
int a[100] = {0};
for(int i=0;i<n;i++)
{
scanf("%d",&a[n-1-i]);
}
for(int i=0;i<n;i++)
{
printf("%d",a[i]);
if(i<n-1) printf(" ");
else printf("\n");
}
return 0;
}
| true |
2e5cab202a3889468b394d1e20ed69d22fe79784 | C++ | mellowLoveGH/cpp_OOP_objected_oriented_programming | /cpp_bingo_game-main/Bingo/Bingo_2016000000.h | UTF-8 | 1,591 | 3.109375 | 3 | [] | no_license | /********************************************************
This is the code you need to modify.
IMPORTANT NOTE
1. Change "2016000000" in the filename, class name,
preprocessing statements to your real student id.
2. Change "MyName" in the constructor to your real name.
These two changes are very important to grade your submission.
If you miss the changes, you will have a penalty.
**********************************************************/
// change "2016000000" to your real student id
#ifndef _BINGO_2016000000_H_
#define _BINGO_2016000000_H_
#include "setting.h"
#include "Bingo.h"
// change "2016000000" to your real student id
class Bingo_2016000000 : public Bingo
{
public:
// change "2016000000" to your real student id
Bingo_2016000000() {
mName = "MyName"; // change "MyName" to your real name in English
}
// change "2016000000" to your real student id
~Bingo_2016000000() { /* add whatever */ }
int myCall(int *itscalls,int *mycalls,int ncalls);
private:
// declare whatever you want
};
/********************************************************
itcalls: a vector of int variables with size of "ncalls"
showing the opponent's calls for the previous turns
mycalls: a vector of int variables with size of "ncalls"
showing my calls for the previous turns
ncalls: number of previous turns
**********************************************************/
int Bingo_2016000000::myCall(int *itscalls,int *mycalls,int ncalls)
{
// implement your strategy
return 1;
}
#endif
| true |
ae54b0b1fc4d48f8c9d9b590fd741db893e619dc | C++ | axax002/DeviceControl | /DeviceDetect/Win_Thread.h | UTF-8 | 578 | 2.6875 | 3 | [] | no_license | #ifndef _WIN_THREAD_H_
#define _WIN_THREAD_H_
#include "Win_WaitObject.h"
namespace DeviceDetectLibrary
{
class CThread : public CWaitObject
{
public:
typedef void (*ThreadFunction)(void * state);
explicit CThread(ThreadFunction routine);
virtual ~CThread(void);
public:
void Start(void * state);
bool Wait(unsigned int milliseconds);
private:
static unsigned int __stdcall Routine(void * state);
CThread(const CThread&);
CThread& operator=(const CThread&);
private:
ThreadFunction routine_;
void * currentState_;
};
}
#endif // _WIN_THREAD_H_ | true |
fd34b7d2e7d2175ab7ab822e902bc813c200cae0 | C++ | arrows-1011/CPro | /AOJ/Volume21/2102.cpp | UTF-8 | 1,011 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int T,card[10];
string str;
bool check1(int a,int b,int c){
if(a == b && b == c) return true;
return false;
}
bool check2(int a,int b,int c){
if(a+2 == b+1 && b+1 == c) return true;
return false;
}
bool check3(int a,int b,int c){
return check1(a,b,c) || check2(a,b,c);
}
bool check4(int card[10]){
return check3(card[0],card[1],card[2])&&check3(card[3],card[4],card[5])
&&check3(card[6],card[7],card[8]);
}
int judge(){
sort(card,card+9);
do{
if(check4(card)) return 1;
}while(next_permutation(card,card+9));
return 0;
}
int main(){
cin >> T;
while(T--){
for(int i = 0 ; i < 9 ; i++){
cin >> card[i];
}
for(int i = 0 ; i < 9 ; i++){
cin >> str;
if(str == "G") card[i] += 10;
else if(str == "B") card[i] += 20;
}
cout << judge() << endl;
}
return 0;
}
| true |
6eccd9174a75f45dbc49d392b6c67e49be48c80f | C++ | TheToaster202/2802ICT-NQueensSolver | /nQueens.cpp | UTF-8 | 16,946 | 3.1875 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <cstdlib>
#include <queue>
#include <utility>
#include <vector>
#include <chrono>
#include <random>
using namespace std;
//Note this program needs to be complied with -O3 optimization to be relatively quick
class Problem{//Holds information regarding the given problem
public:
//Constructors
Problem(int const & nP): n{nP}{}
//Destructor
~Problem(){}
int getN(){return n;}
int getNXN(){return n*n;}
private:
int n;
};
class State{//Holds information about a current state, ie the positions of the queens current "on the board"
public:
//Constructors
State():qPos{0}, sDepth{0}{} //For the intial state
State(pair<int, int> const & pos):qPos{pos}, sDepth{0} {sDepth = qPos.size();} //First node push
State(const State & that){//Copy Constructor
qPos = that.qPos;
sDepth = qPos.size();
}
//Getters
vector<pair<int, int>> getPos(){
return qPos;
}
int getDepth(){
return sDepth;
}
void newDepth(int const & i, int const & j){//Pushes a new queen pos into the positions list
qPos.push_back(pair<int, int>(i,j));
sDepth = qPos.size();
}
void remove(){
qPos.erase(qPos.begin());
sDepth = qPos.size();
}
void printPos(){
cout << "[ ";
for(int i=0; i<qPos.size(); i++){
cout << "(" << qPos[i].first << " " << qPos[i].second << ")";
}
cout << " ] \n";
}
private:
vector<pair<int, int>> qPos; //A vector of queen positions
long unsigned int sDepth; //Current Depth of the search tree
};
class State2{//Holds information about a current state, ie the positions of the queens current "on the board"
public:
//Constructors
State2():qPos{0}, sDepth{0}{} //For the intial state
State2(int const & pos):qPos{pos}, sDepth{0} {sDepth = qPos.size();} //First node push
State2(const State2 & that){//Copy Constructor
qPos = that.qPos;
sDepth = qPos.size();
}
//Getters
vector<int> getPos(){
return qPos;
}
int getDepth(){
return sDepth;
}
void newDepth(int const & i){//Pushes a new queen pos into the positions list
qPos.push_back(i);
sDepth = qPos.size();
}
void remove(){
qPos.erase(qPos.begin());
sDepth = qPos.size();
}
void printPos(){
cout << "[ ";
for(int i=0; i<qPos.size(); i++){
cout << "(" << i << " " << qPos[i] << ")";
}
cout << " ] \n";
}
private:
vector<int> qPos; //A vector of queen positions
long unsigned int sDepth; //Current Depth of the search tree
};
void printFrontier(queue<State> frontier){
while(!frontier.empty()){
frontier.front().printPos();
frontier.pop();
}
cout << endl;
}
int goalState(Problem & problem, queue<State> frontier, bool pruned = false){//Function that will test if the current solution is a goal state
//Alter this to take the whole frontier
int solutions = 0;
bool isSolved = true;
while (!frontier.empty()){
isSolved = true;
for (int i=0; i<problem.getN()-1; i++){
for (int j=i+1; j<problem.getN(); j++){
if (frontier.front().getPos()[i].first == frontier.front().getPos()[j].first){
isSolved = false;
break;
}
if (frontier.front().getPos()[i].second == frontier.front().getPos()[j].second){
isSolved = false;
break;
}
//Removes the subtracts two positions from each other, and if they produce the same value then they are diagonal to each other
//(0,1) - (2,3) = -2, 2 * itself == 4,4 therefore they are diagonal
int xHold=0, yHold=0;
xHold = frontier.front().getPos()[i].first - frontier.front().getPos()[j].first;
yHold = frontier.front().getPos()[i].second - frontier.front().getPos()[j].second;
xHold*=xHold, yHold*=yHold;
if (xHold == yHold){
/*cout << "HOLD: (" << xHold << " " << yHold << ") " << endl;
cout << "I: (" << frontier.front().getPos()[i].first << " " << frontier.front().getPos()[i].second << ") J: ("
<< frontier.front().getPos()[j].first << " " << frontier.front().getPos()[j].second << ")" << endl;*/
isSolved = false;
break;
}
}
}
if (isSolved == true){
if (pruned){
frontier.front().printPos();
return 1;
}
solutions ++;
if(problem.getN() < 7){
frontier.front().printPos();
}
}
frontier.pop();
}
return solutions;
}
bool isValid(State & node, int & width, int & depth, Problem & prob){//Tests whether the new positions is directly diagonal to the prior positions
if (node.getDepth() == 0){
return true;
}
for (int i=0; i<node.getDepth(); i++){
if(width == node.getPos()[i].second){
return false;
}
int xHold = node.getPos()[i].first - depth;
int yHold = node.getPos()[i].second - width;
yHold *= yHold, xHold *= xHold;
if (xHold == yHold){
return false;
}
}
return true;
}
int bfs(Problem & problem, bool oneAnswer = false){ //Breadth First Search Algorithm
//POTENTIALLY: Re write this so that instead of using a vector of pairs you just use the index as the depth indicator...
//Rewrite this to remove the need for the isVaild check
//Currently finds all paths to the lowest depth
queue<State> qq; //queue of queen's positionsd
qq.push(State()); //Pushes empty "State"
State nodeHold; //Independent sate holder, does not change within the for loop
int depth = 0; //The depth of the tree
long unsigned int solutions = 0; //Number of found, non unique solutions
while (!qq.empty()){//Loops until either the queue is empty or the depth of N is reached
nodeHold = qq.front();
depth = nodeHold.getPos().size();
if(depth > problem.getN()-1){
solutions += goalState(problem, qq, oneAnswer);
if (oneAnswer && solutions > 0){
return solutions;
}
break;
}
qq.pop();
for(int i=0; i < problem.getN(); i++){
State node = nodeHold;
//if (isValid(nodeHold, i, depth, problem)){
node.newDepth(depth, i);
qq.push(node);
//}
}
}
return solutions;
}
bool isVisited(vector<pair<int, int>> const & nodes, int const & depth, int const & width){
if(nodes.empty()){
return false;
}
for (auto i=nodes.begin(); i!=nodes.end(); i++){
if ((*i).first == depth && (*i).second == width){
return true;
}
}
return false;
}
int bfsP(Problem & problem, bool oneAnswer = false){ //BFS But with pruned searches
//Currently finds all paths to the lowest depth
//Rewrite this to be as the original bfs function was
queue<State> qq; //queue of queen's positionsd
qq.push(State()); //Pushes empty "State"
State nodeHold; //Independent sate holder, does not change within the for loop
//vector<pair<int, int>> visited;
int depth = 0; //The depth of the tree
long unsigned int solutions = 0; //Number of found, non unique solutions
while (!qq.empty()){//Loops until either the queue is empty or the depth of N is reached
nodeHold = qq.front();
depth = nodeHold.getPos().size();
if(depth > problem.getN()-1){
solutions += goalState(problem, qq, oneAnswer);
break;
}
qq.pop();
for(int i=0; i < problem.getN(); i++){
State node = nodeHold;
if (isValid(nodeHold, i, depth, problem)){
node.newDepth(depth, i);
qq.push(node);
}
}
}
return solutions;
}
vector<int> genRandomState(Problem & prob){ //Generates a random state where all queens are on the board
vector<int> randState;
vector<int> usedNumbers;
for(int i=0; i<prob.getN(); i++){
usedNumbers.push_back(0);
}
int i=0;
while (i<prob.getN()){
int randNumber = rand()%prob.getN();
if (usedNumbers[randNumber]==0){
randState.push_back(randNumber);
i++;
usedNumbers[randNumber] = 1;
}
}
return randState;
}
int stateEval(vector<int> & positions, Problem & prob){
int level = 0;
for (int i=0; i<prob.getN()-1; i++){
for (int j=i+1; j<prob.getN(); j++){
if (positions[i] == positions[j]){
level ++;
}
int xH = positions[i] - positions[j];
xH *= xH;
int yH = i - j;
yH *= yH;
if (xH == yH){
level++;
}
}
}
return level;
}
void hillClimbing(Problem & prob, vector<int> initState, bool shotgun = false){
//Note INDEX is BREADTH on the vector of positions
int confidence = stateEval(initState, prob);
cout << "INITIAL STATE" << endl;
cout << "EVAL: " << confidence << endl;
for (int i=0; i<prob.getN(); i++){
for (int j=0; j<prob.getN(); j++){
if(i == initState[j]){
cout << "Q\t";
}else{
cout << "-\t";
}
}
cout << endl << endl;
}
if(shotgun){
cout << "Shotgun Mode" << endl;
}
while (confidence != 0){ //Shotgun Hill Climbing
for (int i=0; i<prob.getN(); i++){
for (int j=0; j<prob.getN(); j++){
if (i != initState[j]){
vector<int> newState = initState;
newState[j] = i;
int newConfidence = stateEval(newState, prob);
if (newConfidence < confidence){
initState = newState;
confidence = newConfidence;
}
}
}
}
if (shotgun && confidence != 0){
initState = genRandomState(prob);
confidence = stateEval(initState, prob);
}else{
break;
}
}
cout << "FINAL STATE" << endl;
cout << "EVAL: " << confidence << endl;
for (int i=0; i<prob.getN(); i++){
for (int j=0; j<prob.getN(); j++){
if(i == initState[j]){
cout << "Q\t";
}else{
cout << "-\t";
}
}
cout << endl << endl;
}
return;
}
void simulatedAnnealing(Problem & prob, vector<int> initState, double const decayRate = 0.5, int const constantMultiplyer = 10){ //SA, similar to HC and SHC but as the evaluation gets lower the probability for it to pick an answer anyway increases
//Note: Index is breadth
int confidence = stateEval(initState, prob);
double temperature = prob.getN() * constantMultiplyer; //Adjusts the adjustment to be relative to the size of the problem
int tempMax = temperature;
int iterTemp = 0;
cout << "INITIAL STATE" << endl;
cout << "EVAL: " << confidence << endl;
for (int i=0; i<prob.getN(); i++){
for (int j=0; j<prob.getN(); j++){
if(i == initState[j]){
cout << "Q\t";
}else{
cout << "-\t";
}
}
cout << endl << endl;
}
while (confidence != 0){
for (int i=0; i<prob.getN(); i++){
for (int j=0; j<prob.getN(); j++){
if (i != initState[j]){
vector<int> newState = initState;
newState[j] = i;
int newConfidence = stateEval(newState, prob);
if (newConfidence == 0){
initState = newState;
confidence = newConfidence;
break;
}
int skipP = rand() % tempMax;
if (newConfidence < confidence || (skipP * newConfidence) < temperature){//IF the random value - new confidence is greater than the adjusted value /2 then it will skip
initState = newState;
confidence = newConfidence;
}
}
}
}
temperature = tempMax * pow(exp(1), -(decayRate * iterTemp));
iterTemp++;
}
cout << "FINAL STATE" << endl;
cout << "EVAL: " << confidence << endl;
for (int i=0; i<prob.getN(); i++){
for (int j=0; j<prob.getN(); j++){
if(i == initState[j]){
cout << "Q\t";
}else{
cout << "-\t";
}
}
cout << endl << endl;
}
}
int main(int const argc, char const ** argv){// Main Code Driver
if (argc < 2){
cerr << "Program needs an N value of 1-20 to run" << endl;
return EXIT_FAILURE;
}
if (atoi(argv[1]) < 1 || atoi(argv[1]) > 20){
cerr << "Program needs an N value of 1-20 to run" << endl;
return EXIT_FAILURE;
}
if (atoi(argv[1]) == 1){
cout << "[(0,0)]" << endl << "1" << endl;
return EXIT_SUCCESS;
}
srand((int)time(NULL)); //Seeding rand() for later
Problem queens(atoi(argv[1]));
using namespace std::chrono;
auto start = high_resolution_clock::now(); //Timing how long the bfs function takes to run and complete
cout << "PROBLEM:\n";
cout << bfs(queens, false) << endl;
auto stop = high_resolution_clock::now();
auto duration = duration_cast<seconds>(stop - start);
auto duration2 = duration_cast<milliseconds>(stop - start);
cout << "BFS TIME TAKEN" << endl << "Seconds: " << duration.count() << " Milliseconds: " << duration2.count() << endl;
//BFS Pruned Call
/*start = high_resolution_clock::now(); //Timing how long the bfs function takes to run and complete
cout << bfsP(queens, false) << endl;
stop = high_resolution_clock::now();
duration = duration_cast<seconds>(stop - start);
duration2 = duration_cast<milliseconds>(stop - start);
cout << "BFS ONE SOLUTION, TIME TAKEN" << endl << "Seconds: " << duration.count() << " Milliseconds: " << duration2.count() << endl;*/
/*vector<int> initState = genRandomState(queens);
cout << "HILL CLIMBING" << endl;
start = high_resolution_clock::now();
hillClimbing(queens, initState, true);
stop = high_resolution_clock::now();
duration = duration_cast<seconds>(stop - start);
duration2 = duration_cast<milliseconds>(stop - start);
cout << "TIME TAKEN:" << endl << "Seconds: " << duration.count() << " Milliseconds: " << duration2.count() << endl;
cout << "SIMULATED ANNEALING" << endl;
start = high_resolution_clock::now();
simulatedAnnealing(queens, initState);
stop = high_resolution_clock::now();
duration = duration_cast<seconds>(stop - start);
duration2 = duration_cast<milliseconds>(stop - start);
cout << "TIME TAKEN:" << endl << "Seconds: " << duration.count() << " Milliseconds: " << duration2.count() << endl;*/
return EXIT_SUCCESS;
} | true |
208dfa62e4b11a059ad32b1904eb71af35e61125 | C++ | strategist614/ACM-Code | /刷题比赛/LUOGU/P1030求先序遍历.cpp | UTF-8 | 513 | 2.640625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
char a[10];
char b[10];
struct node
{
char f;
char l;
char r;
}t[10];
int lenb = 0;
int lena = 0;
int find(char c)
{
for(int i= 0;i<lena;i++)
if(a[i] == c)
return i;
}
void dfs(int l1,int r1,int l2,int r2)
{
int m = find(b[r2]);
cout<<b[r2];
if(m > l1) dfs(l1,m-1,l2,r2-r1+m-1);
if(m < r1) dfs(m+1,r1,l2+m-l1,r2-1);
}
int main ()
{
scanf("%s",a);
scanf("%s",b);
lena = strlen(a);
lenb = strlen(b);
dfs(0,lena-1,0,lenb-1);
return 0 ;
} | true |
81a4b5be5e9ca645fe4385d4899e52f8bb1ebde2 | C++ | saimadanmohan/Cplusplus-Tutorials | /vector_operations.cpp | UTF-8 | 817 | 3 | 3 | [] | no_license | class Compare {
public:
bool operator()(const pair<string,int>& pr1, const pair<string,int>& pr2) {
return pr1.second == pr2.second ?
lexicographical_compare(pr1.first.begin(), pr1.first.end(), pr2.first.begin(), pr2.first.end()) :
pr1.second > pr2.second;
}
};
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
map<string, int> freq;
for(auto word: words) {
freq[word]++;
}
vector<pair<string, int> > vec;
vec.insert(vec.begin(), freq.begin(), freq.end());
sort(vec.begin(), vec.end(), Compare());
vector<string> result;
for(int i = 0; i < k; i++) {
result.push_back(vec[i].first);
}
return result;
}
}; | true |
1fa7424b8804e59e05b824cb697df9aabe634469 | C++ | i-radwan/Image2Code | /src/LineSegmentation/Components/Chunk.h | UTF-8 | 1,330 | 2.625 | 3 | [] | no_license | //
// Created by Ibrahim Radwan on 11/29/17.
//
#ifndef IMAGE2LINES2_CHUNK_H
#define IMAGE2LINES2_CHUNK_H
#include "Peak.h"
#include "Valley.h"
#include "../../Utilities/Utilities.h"
/// Image Chunk.
class Chunk {
friend class LineSegmentation;
/// Valleys and peaks detection in this image chunk.
/// \param map_valley to fill it
/// \return int the average line height in this chunk.
int
find_peaks_valleys(map<int, Valley *>& map_valley);
private:
int index;
/// The index of the chunk.
int start_col;
///< The start column position.
int width;
///< The width of the chunk.
Mat img;
///< The grey level image
vector<int> histogram;
///< The values of the y histogram projection profile.
vector<Peak> peaks;
///< The found peaks in this chunk.
vector<Valley *> valleys;
///< The found valleys in this chunk.
int avg_height;
///< The average line height in this chunk.
int avg_white_height;
///< The average space height in this chunk.
int lines_count;
///< The estimated number of lines in this chunk.
Chunk(int o, int c, int w, Mat i);
/// Calculate the chunk histogram (Y projection profile).
/// This function is called by find_peaks_valleys.
void calculate_histogram();
};
#endif //IMAGE2LINES2_CHUNK_H
| true |
4ccd2a9344296e957daf42f82b34176b4d1d029a | C++ | macton/DDLParser | /src/Set.h | UTF-8 | 1,915 | 2.9375 | 3 | [
"BSD-2-Clause"
] | permissive | #pragma once
#include <stdint.h>
#include "BlockAllocator.h"
namespace DDLParser
{
template< typename T > class Set
{
private:
struct Element
{
uint32_t m_Key;
T m_Payload;
Element* m_Next;
};
BlockAllocator< Element > m_Elements;
Element* m_First;
Element* m_Last;
Element* FindInternal ( uint32_t key ) const
{
Element* element = m_First;
while ( element != 0 )
{
if ( element->m_Key == key )
{
return element;
}
element = element->m_Next;
}
return 0;
}
public:
inline bool Init ( LinearAllocator* alloc )
{
m_First = m_Last = 0;
return m_Elements.Init ( alloc );
}
inline void Destroy()
{
m_Elements.Destroy();
}
const T* Find ( uint32_t key ) const
{
Element* element = FindInternal ( key );
if ( element )
{
return &element->m_Payload;
}
return 0;
}
const T* Insert ( uint32_t key, const T& payload )
{
Element* element = FindInternal ( key );
if ( element != 0 )
{
element->m_Payload = payload;
return &element->m_Payload;
}
element = m_Elements.Allocate();
if ( element != 0 )
{
if ( m_First != 0 )
{
m_Last->m_Next = element;
}
else
{
m_First = element;
}
m_Last = element;
element->m_Key = key;
element->m_Payload = payload;
element->m_Next = 0;
return &element->m_Payload;
}
return 0;
}
};
}
| true |
06558943e1587e2c1794c4a7effba20253f9c136 | C++ | FahimSifnatul/problem_solving_with_FahimSifnatul_cpp_version | /codeforces round 409 div2 B.cpp | UTF-8 | 305 | 2.53125 | 3 | [] | no_license | //bismillahir rahmanir rahim
#include<bits/stdc++.h>
using namespace std;
string x,z;
int len;
int main()
{
cin>>x>>z;
len=x.length();
for(int i=0;i<len;i++)
{
if(x[i]<z[i])
{
cout<<-1;
return 0;
}
}
cout<<z<<endl;
return 0;
}
| true |
82431b38b83134d96c63ced058ceb568773e76c4 | C++ | miemiemi/zju_ds_mooc_pa | /04-树6 Complete Binary Search Tree.cpp | UTF-8 | 619 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, k;
int tree[N], val[N];
//完全二叉树按照堆存
//得到中序序列后还原二叉树
void dfs(int u)
{
if(u * 2 <= n)
dfs(u * 2);
tree[u] = val[k++];
if(u * 2 + 1 <= n)
dfs(u * 2 + 1);
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
cin >> val[i];
sort(val + 1, val + n + 1);
k = 1;
dfs(1);
cout << tree[1];
for(int i = 2; i <= n; i++)
cout << " " << tree[i];
cout << endl;
return 0;
} | true |
61c2b016e8e475f28952674afd3a1ea387f186e7 | C++ | ec2822460/ContrerasEmmanuel_CIS5_41366 | /Homework/Gaddis chap2 hw/Gaddis_9thEd_Ch02_Prob10_MPG/main.cpp | UTF-8 | 996 | 3.359375 | 3 | [] | no_license |
/*
* File: main.cpp
* Author: Emmanuel M. Contreras
* Created on January 10, 2021, 5:29 PM
* Purpose: Miles Per Gallon Assignment Problem #10
*/
//System Libraries
#include <iostream> //I/O Library
using namespace std;
//User Libraries
//Global Constants
//Math, Science, Universal, Conversions, High Dimensioned Arrays
//Function Prototypes
//Execution Begins Here
int main(int argc, char** argv) {
//Initialize the Random Number Seed
//Declare Variables
float gasTnk, //The number of gallons the car gas tank can hold
milesDrv, //The number of miles driven before refueling
MPG; //The Miles per Gallon efficiency of the car
//Initialize Variables
gasTnk=15;
milesDrv=375;
//Map Inputs to Outputs -> Process
MPG = milesDrv / gasTnk;
//Display Inputs/Outputs
cout<<"The car's Miles Per Gallon (MPG) rating = "<<MPG<<" miles/gallon"<<endl;
//Exit the Program - Cleanup
return 0;
} | true |
7a8c0ff83d065b5243a86eac76556886d993e187 | C++ | Mokona/La-Grille | /sources/wordgrid/DictionaryTreeImpl.h | UTF-8 | 770 | 2.515625 | 3 | [] | no_license | #ifndef WORDGRID_DICTIONARYTREEIMPL
#define WORDGRID_DICTIONARYTREEIMPL
#include "wordgrid/Dictionary.h"
#include "wordgrid/CharTree.h"
#include <vector>
#include <string>
namespace Wordgrid
{
class DictionaryTreeImpl : public Dictionary
{
public:
DictionaryTreeImpl();
virtual ~DictionaryTreeImpl();
virtual FoundWords Search(const PartialWord & partialWord) const;
virtual void InsertWord(const std::string & word);
virtual void RemoveWord(const std::string & word);
virtual bool IsWordValid(const std::string & word) const;
virtual i32 GetWordCount() const;
private:
CharTree m_charTree;
ui32 m_wordCount;
};
}
#endif
| true |
4ec2cde8aec9b4fb35814e6debf72a54b7fc3787 | C++ | Melnikoo/HovercraftGame_OpenGL | /Hovercraft/RigidBody2D.h | UTF-8 | 681 | 2.515625 | 3 | [] | no_license | #include <string>
#include <iostream>
#include "GameObject.h"
#include "SphereCollider.h"
class RigidBody2D : public GameObject
{
private:
float inertia;
float mass;
float orient = 0;
float length;
float width;
glm::vec3 testPos = glm::vec3(1, 1, 0);
glm::vec3 testForce = glm::vec3(2, 0, 0);
glm::vec3 forces;
glm::vec3 accel;
glm::vec3 velocity;
glm::vec3 angVelocity;
glm::vec3 angAccel;
glm::vec3 angForces;
std::string shape;
public:
glm::vec3 pos;
RigidBody2D();
RigidBody2D(glm::vec3 position, float m, float length, float width);
~RigidBody2D();
glm::vec3 ReturnPos();
void CalculateForces();
void Draw();
void Update(float delta);
};
| true |
1c618a556b4bffd3c3f205e508d226c5618b8a93 | C++ | SuYuxi/yuxi | /Algorithms/Tree/116. Populating Next Right Pointers in Each Node.cpp | UTF-8 | 1,284 | 3.640625 | 4 | [] | no_license | /**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
if(root == nullptr) return;
queue<TreeLinkNode*> que;
TreeLinkNode *node;
que.push(root);
int count = 0;
int length = que.size();
while(!que.empty()){
++count;
node = que.front();
que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
if(count == length) {
length = que.size();
count = 0;
}
else {
node->next = que.front();
}
}
}
};
class Solution {
public:
void connect(TreeLinkNode *root) {
if(root == nullptr) return;
if(root->left) root->left->next = root->right;
if(root->right && root->next) root->right->next = root->next->left;
connect(root->left);
connect(root->right);
}
};
class Solution {
public:
void connect(TreeLinkNode *root) {
if(!root) return;
TreeLinkNode *node;
while(root->left) {
node = root;
while(node) {
node->left->next = node->right;
if(node->next) node->right->next = node->next->left;
node = node->next;
}
root = root->left;
}
}
};
| true |
e9caabb63b5729cff57ddeede91d7692c1e51755 | C++ | Dinghow/MyRoadToAlgorithm | /JobDo/1008_the_shortest_route.cpp | UTF-8 | 1,598 | 2.78125 | 3 | [] | no_license | #include<iostream>
#include<vector>
#define MAX 10000000
using namespace std;
struct Edge{
int des;
int dis;
int cos;
Edge(int a, int d, int c):des(a),dis(d),cos(c){}
};
bool vis[1001] = {0};
int dis[1001];
int cost[1001];
int main(){
int n, m, s, t;
while(cin>>n>>m){
vector<Edge> adj[1001];
fill(vis+1,vis+n+1,false);
fill(dis+1, dis+n+1, MAX);
fill(cost+1, cost+n+1, MAX);
if(!n && !m) break;
for(int i = 0; i < m; i++){
int a, b, d, p;
cin>>a>>b>>d>>p;
adj[a].push_back(Edge(b,d,p));
adj[b].push_back(Edge(a,d,p));
}
cin>>s>>t;
dis[s] = 0;
cost[s] = 0;
while(1) {
int u = -1;
int min = MAX;
for (int i = 1; i <= n; i++) {
if (dis[i] <= min && !vis[i]) {
min = dis[i];
u = i;
}
}
if(u == -1) break;
vis[u] = true;
int bound = adj[u].size();
for(int i = 0; i < bound; i++){
int des = adj[u][i].des;
if(!vis[des] && dis[u]+adj[u][i].dis < dis[des]){
dis[des] = dis[u]+adj[u][i].dis;
cost[des] = cost[u]+adj[u][i].cos;
}
else if(dis[u]+adj[u][i].dis == dis[des] && cost[u]+adj[u][i].cos < cost[des]){
cost[des] = cost[u]+adj[u][i].cos;
}
}
}
cout<<dis[t]<<" "<<cost[t]<<endl;
}
return 0;
} | true |
e525cd3f1783f5ca4faedd395fca90731461d899 | C++ | ChrisLidbury/CLSmith | /src/CLSmith/StatementAtomicReduction.h | UTF-8 | 1,730 | 2.5625 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | // Atomic reduction statement representing a series of instructions used to
// exercise atomic operations, while still keeping the program generated
// deterministic
#ifndef _CLSMITH_STATEMENTATOMICREDUCTION_H_
#define _CLSMITH_STATEMENTATOMICREDUCTION_H_
#include "CLSmith/CLStatement.h"
#include "Block.h"
#include "Constant.h"
#include "Expression.h"
#include "FactMgr.h"
#include "Type.h"
#include "Variable.h"
namespace CLSmith {
class StatementAtomicReduction : public CLStatement {
public:
enum AtomicOp {
kAdd = 0,
kSub,
// kInc,
// kDec,
// kXchg,
// kCmpxchg,
kMin,
kMax,
kAnd,
kOr,
kXor
};
enum MemoryLoc {
kLocal = 0,
kGlobal
};
StatementAtomicReduction(Expression* e, const bool add_global,
Block* b, AtomicOp op, MemoryLoc mem) : CLStatement(kAtomic, b), expr_(e),
op_(op), mem_loc_(mem), add_global_(add_global),
type_(Type::get_simple_type(eUInt)) {}
static StatementAtomicReduction* make_random(CGContext& cg_context);
static MemoryBuffer* get_local_rvar();
static MemoryBuffer* get_global_rvar();
static void AddVarsToGlobals(Globals* globals);
static void RecordBuffer();
// Pure virtual methods from Statement
void get_blocks(std::vector<const Block*>& blks) const {};
void get_exprs(std::vector<const Expression*>& exps) const
{ exps.push_back(expr_); };
void Output(std::ostream& out, FactMgr* fm = 0, int indent = 0) const;
private:
Expression* expr_;
AtomicOp op_;
MemoryLoc mem_loc_;
const bool add_global_;
const Type& type_;
static Variable* get_hash_buffer();
DISALLOW_COPY_AND_ASSIGN(StatementAtomicReduction);
};
}
#endif | true |
b22da4d84a0734d9148f262fc9cac43db17a3d69 | C++ | beebdev/FashionMNIST-CNN-Accelerator | /cnn_classification/src/fashionMNIST.cpp | UTF-8 | 1,999 | 2.890625 | 3 | [] | no_license | #include <stdint.h>
#include <stdlib.h>
#include <iostream>
#include <sys/time.h>
#include "../include/utils.h"
#include "../include/cnn.h"
int main() {
/* Read test cases */
cases_t cases = read_test_cases();
/* Stats var */
double total_duration = 0.0;
long int correct = 0;
// for (int i = 0; i < 28; i++) {
// for (int j = 0; j < 28; j++) {
// std::cout << cases.c_data[0].img[i][j] << ", " << std::ends;
// }
// std::cout << std::endl;
// }
// for (int i = 0; i < 10; i++) {
// std::cout << cases.c_data[0].output[i] << ", " << std::ends;
// }
// std::cout << std::endl;
/* Run classification on test cases */
std::cout << "Starting classification!" << std::endl;
for (int c = 0; c < cases.case_count; c++) {
if (c % 10000 == 0 && c != 0) {
std::cout << "case " << c;
std::cout << " [acc: " << float(correct) / float(c) << "]" << std::endl;
}
/* Current test case */
case_t curr_case = cases.c_data[c];
VALUE_TYPE results[10];
/* Task interval stats */
struct timeval t1, t2;
gettimeofday(&t1, NULL);
cnn(curr_case.img, results);
gettimeofday(&t2, NULL);
total_duration += (t2.tv_sec - t1.tv_sec) * 1000;
total_duration += (t2.tv_usec - t1.tv_usec) / 1000;
/* Current Accuracy */
correct += max_bin(curr_case.output, results) ? 1 : 0;
}
/* Report time stats */
std::cout << "=====================" << std::endl;
std::cout << "Total classifcations ran: " << cases.case_count << std::endl;
std::cout << "Total task duration (cnn task time): " << total_duration << "ms" << std::endl;
std::cout << "Average task duration: " << total_duration / cases.case_count << "msec" << std::endl;
std::cout << "Accuracy: " << float(correct) / cases.case_count << std::endl;
/* Free cases */
free_test_cases(cases);
return 0;
}
| true |
906de05a8bfe1dc5839ee8cf30ef6ca12060dcc8 | C++ | hazzus/os-net-multiplexing | /socket/socket_wrapper.cpp | UTF-8 | 2,613 | 3.109375 | 3 | [] | no_license | #include "socket_wrapper.h"
ssocket::ssocket() : descriptor(socket(AF_INET, SOCK_STREAM, 0)) {
if (descriptor == -1) {
throw socket_exception("Cannot create a socket");
}
flags = fcntl(descriptor, F_GETFL);
if (flags == -1) {
throw socket_exception("Cannot get socket status");
}
}
ssocket::ssocket(int fd) : descriptor(fd) {}
ssocket::ssocket(ssocket&& other) noexcept : descriptor(other.descriptor) {
other.descriptor = -1;
}
ssocket& ssocket::operator=(ssocket&& other) noexcept {
descriptor = other.descriptor;
other.descriptor = -1;
return *this;
}
void ssocket::bind(sockaddr_in& address) {
if (::bind(descriptor, reinterpret_cast<sockaddr*>(&address),
sizeof(address)) == -1) {
throw socket_exception("Cannot bind socket");
}
}
void ssocket::listen(int connections) {
if (::listen(descriptor, connections) == -1) {
throw socket_exception("Cannot set socket to listening state");
}
}
ssocket ssocket::accept() {
int new_descriptor = ::accept(descriptor, nullptr, nullptr);
if (descriptor == -1) {
throw socket_exception("Cannot accept new connection");
}
return ssocket(new_descriptor);
}
int ssocket::connect(sockaddr_in& address) {
if (::connect(descriptor, reinterpret_cast<sockaddr*>(&address),
sizeof(address)) == -1) {
if (flags & SOCK_NONBLOCK) {
return -1;
} else {
throw socket_exception("Cannot connect to server");
}
}
return 0;
}
size_t ssocket::send(std::string data) {
ssize_t was_sent = ::send(descriptor, data.data(), data.size(), 0);
if (was_sent == -1) {
throw socket_exception("Error while sending");
}
return static_cast<size_t>(was_sent);
}
std::string ssocket::read() {
std::vector<char> buffer(BUFF_SIZE);
ssize_t was_read = recv(descriptor, buffer.data(), BUFF_SIZE, 0);
if (was_read == -1) {
throw socket_exception("Cannot recieve data from socket");
}
buffer.resize(static_cast<size_t>(was_read));
return std::string(buffer.data());
}
int ssocket::get_desc() { return descriptor; }
void ssocket::unblock() {
if (!(flags & O_NONBLOCK)) {
if (::fcntl(descriptor, F_SETFL, flags | O_NONBLOCK) == -1) {
throw socket_exception("Cannot change socket status");
}
flags |= O_NONBLOCK;
}
}
ssocket::~ssocket() {
if (descriptor != -1) {
if (close(descriptor) == -1) {
std::cerr << "Cannot close socket's file descriptor" << std::endl;
}
}
}
| true |
ada2d293f1d8bc658b66fa9063659e7cb232a6d0 | C++ | Conny14156/OneFlower | /Project/OLD/Model/TextureMapPoint.hpp | UTF-8 | 584 | 2.703125 | 3 | [] | no_license | #ifndef TEXTUREMAPPOINT_HPP
#define TEXTUREMAPPOINT_HPP
#include <Core/Vector.h>
#include <SFML\Graphics\Color.hpp>
struct TextureMapPoint
{
inline TextureMapPoint() : pos(0, 0), size(0, 0), rotated(false), color(255, 255, 255) {};
Core::Vector2i pos;
Core::Vector2i size;
bool rotated;
sf::Color color;
template <class Archive>
void save(Archive& ar) const
{
ar(pos);
ar(size);
ar(rotated);
ar(color.r, color.g, color.b);
}
template <class Archive>
void load(Archive& ar)
{
ar(pos);
ar(size);
ar(rotated);
ar(color.r, color.g, color.b);
}
};
#endif | true |
8cb975c808a3459ea2844ad33e2658fbd8fe8bed | C++ | jaguar-paw33/CODE_AAI | /6.Data Structures/3.Queue/queue_using_linked_list.h | UTF-8 | 937 | 3.609375 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
template<typename T>
class Node {
public:
T data;
Node<T> * next;
Node(T data) {
this->data = data;
this->next = NULL;
}
};
template<typename W>
class Queue {
Node<W> * head;
Node<W> * tail;
int size;
public:
Queue() {
head = NULL;
tail = NULL;
size = 0;
}
bool isEmpty() {
return size == 0;
}
int getSize() {
return size;
}
void enqueue(W value) {
Node<W> * newNode = new Node<W> (value);
if (!head) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = tail->next;
}
size++;
}
W dequeue() {
if (isEmpty()) {
cout << "Queue is Empty" << endl;
return 0;
}
Node<W> * temp = head;
head = head->next;
size--;
W ans = temp->data;
temp->next = NULL;
delete temp;
return ans;
}
W front() {
if (isEmpty()) {
cout << "Queue is Empty" << endl;
return 0;
}
return head->data;
}
}; | true |
d43134ca5df7a09be6e75f816901d6d0379f2096 | C++ | palmerst/CS-4ZP6 | /Proof of Concept Demo/include/DynamicObject.h | UTF-8 | 1,223 | 2.71875 | 3 | [] | no_license | #ifndef DYNAMICOBJECT_H_INCLUDED
#define DYNAMICOBJECT_H_INCLUDED
#include "PhysicsObject.h"
/*! The DynamicObject class is derived from the Obj class. This type of object is subject to all physics calculations.
*/
class DynamicObject : public PhysicsObject {
public:
//! DynamicObject constructor
DynamicObject();
//! DynamicObject constructor
/*!
\param space Chipmunk 2D space to attach object to
\param pos Coordinates of the initial center of the object
\param mass Mass of the object
\param scale Scalar factor by which to scale the object during GPU rendering
\param elast Elasticity of the object
\param fric Friction factor of the object
\param gpuData Pointer to the gpu data associated with the object
\param type Type of object (different values affect collision routines)
\param noRotation Flag to ignore angular momentum in the physics calculations (default = false)
*/
DynamicObject(float x, float y, float scale, float mass, float elast, float fric, int type, std::string gpuPath, std::string vPath, std::string fPath);
};
#endif // DYNAMICOBJECT_H_INCLUDED
| true |
fa393bf1d36c109ec12653d1eb77f86723fbfc4f | C++ | yameenjavaid/Online-Judge-Solutions | /UVa/uva10706.cpp | UTF-8 | 1,173 | 2.59375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
// Number Sequence
#define num long long int
inline string build(num l){
string s = "";
for(num i = 1; i <= l; i++)
s += to_string(i);
return s;
}
vector<num> seq;
int main(){
num last = 1, inc = 1, cnt = 2;
seq.push_back(1);
while(true){
if(floor(log10(cnt)) == log10(cnt))
inc++;
num now = last + inc;
last = now;
now += seq[seq.size()-1];
if(now > 3000000000)
break;
seq.push_back(now);
cnt++;
}
int t;
cin >> t;
while(t--){
num i;
cin >> i;
if(i == 1){
cout << 1 << endl;
continue;
}
auto lo = lower_bound(seq.begin(), seq.end(), i);
auto hi = upper_bound(seq.begin(), seq.end(), i);
if(*lo == i){
num len = *lo - *prev(lo);
string ans = build(len);
cout << ans[ans.size()-1] << endl;
}
else{
auto pr = prev(hi);
num len = *hi - *pr;
string ans = build(len);
cout << ans[i - *pr - 1] << endl;
}
}
} | true |
f4c2fb60f4508e3c044de12131b72aa09c01d626 | C++ | Unrealf1/RootExtraction | /General/source/JSON/JSONWriter.cpp | UTF-8 | 2,764 | 2.703125 | 3 | [] | no_license | //
// Created by fedor on 9/29/19.
//
#include "JSON/JSONWriter.hpp"
JSONWriter::JSONWriter(std::ostream &stream): stream(stream) {
}
void JSONWriter::BeginBlock() {
stream << block_begin;
last_property = false;
++current_depth;
}
void JSONWriter::BeginBlock(const std::string &name) {
CheckForComma();
Depth();
stream << '\"' << name << "\": ";
last_property = true;
BeginBlock();
}
void JSONWriter::EndBlock() {
--current_depth;
stream << '\n';
Depth();
stream << block_end;
}
void JSONWriter::AddProperty(const std::string& name, const std::string& value) {
CheckForComma();
Depth();
stream << '\"' << name << "\": \"" << value << '\"';
last_property = true;
}
void JSONWriter::AddProperty(const std::string& name, const int64_t& value) {
CheckForComma();
Depth();
stream << '\"' << name << "\": " << std::to_string(value);
last_property = true;
}
void JSONWriter::AddProperty(const std::string& name, const double& value) {
CheckForComma();
Depth();
stream << '\"' << name << "\": " << std::to_string(value);
last_property = true;
}
void JSONWriter::AddProperty(const std::string& name, const std::vector<std::string>& array) {
CheckForComma();
Depth();
stream << '\"' << name << "\": [ ";
bool first = true;
for (auto& value : array) {
if (first) {
first = false;
} else {
stream << ", ";
}
stream << '\"' << value << '\"';
}
stream << " ]";
last_property = true;
}
void JSONWriter::AddProperty(const std::string& name, const std::vector<int64_t>& array) {
CheckForComma();
Depth();
stream << '\"' << name << "\": [ ";
bool first = true;
for (auto& value : array) {
if (first) {
first = false;
} else {
stream << ", ";
}
stream << std::to_string(value);
}
stream << " ]";
last_property = true;
}
void JSONWriter::AddProperty(const std::string& name, const std::vector<double>& array) {
CheckForComma();
Depth();
stream << '\"' << name << "\": [ ";
bool first = true;
for (auto& value : array) {
if (first) {
first = false;
} else {
stream << ", ";
}
stream << std::to_string(value);
}
stream << " ]";
last_property = true;
}
void JSONWriter::Flush() {
stream << std::flush;
}
uint32_t JSONWriter::GetDepth() const {
return current_depth;
}
void JSONWriter::CheckForComma() {
if (last_property) {
stream << ",\n";
} else {
stream << '\n';
}
}
void JSONWriter::Depth() {
stream << std::string(4 * current_depth, ' ');
}
//ClassImp(JSONWriter);
| true |
c2a856c024651f31053d4283ca2689891bd41cf3 | C++ | smsguy927/UltimateOmaha | /Card.cpp | UTF-8 | 5,211 | 3.203125 | 3 | [] | no_license | #include "Card.h"
Card::Card()
{
}
Card::Card(int ID)
{
setId(ID);
}
Card::Card(int rankID, int suitID)
{
}
Card::~Card()
{
}
void Card::setId(int id)
{
this->id = id;
setRank(id % NUM_RANKS);
setRankId(id % NUM_RANKS);
//setSuit(id % NUM_SUITS);
//setSuitId(id % NUM_SUITS);
setSuit(id / NUM_RANKS);
setSuitId(id / NUM_RANKS);
}
void Card::setRankId(int num)
{
this->rankId = num;
}
void Card::setSuitId(int num)
{
this->suitId = num;
}
void Card::setRank(int rank)
{
// Use Switch
switch (rank)
{
case int(ERankNames::two) :
rank = '2';
setRankName(RANK_NAMES[int(ERankNames::two)]);
break;
case int(ERankNames::three) :
rank = '3';
setRankName(RANK_NAMES[int(ERankNames::three)]);
break;
case int(ERankNames::four) :
rank = '4';
setRankName(RANK_NAMES[int(ERankNames::four)]);
break;
case int(ERankNames::five) :
rank = '5';
setRankName(RANK_NAMES[int(ERankNames::five)]);
break;
case int(ERankNames::six) :
rank = '6';
setRankName(RANK_NAMES[int(ERankNames::six)]);
break;
case int(ERankNames::seven) :
rank = '7';
setRankName(RANK_NAMES[int(ERankNames::seven)]);
break;
case int(ERankNames::eight) :
rank = '8';
setRankName(RANK_NAMES[int(ERankNames::eight)]);
break;
case int(ERankNames::nine) :
rank = '9';
setRankName(RANK_NAMES[int(ERankNames::nine)]);
break;
case int(ERankNames::ten) :
rank = 'T';
setRankName(RANK_NAMES[int(ERankNames::ten)]);
break;
case int(ERankNames::jack) :
rank = 'J';
setRankName(RANK_NAMES[int(ERankNames::jack)]);
break;
case int(ERankNames::queen) :
rank = 'Q';
setRankName(RANK_NAMES[int(ERankNames::queen)]);
break;
case int(ERankNames::king) :
rank = 'K';
setRankName(RANK_NAMES[int(ERankNames::king)]);
break;
case int(ERankNames::ace) :
rank = 'A';
setRankName(RANK_NAMES[int(ERankNames::ace)]);
break;
default:
std::cout << "Invalid rank." << std::endl;
rank = '0';
throw std::invalid_argument("Not a rank");
}
this->rank = rank;
}
void Card::setSuit(int suit)
{
// Use Switch
switch (suit)
{
case(int(ESuitNames::clubs)):
suit = 'c';
setSuitName(SUIT_NAMES[int(ESuitNames::clubs)]);
break;
case(int(ESuitNames::diamonds)):
suit = 'd';
setSuitName(SUIT_NAMES[int(ESuitNames::diamonds)]);
break;
case(int(ESuitNames::hearts)):
suit = 'h';
setSuitName(SUIT_NAMES[int(ESuitNames::hearts)]);
break;
case(int(ESuitNames::spades)):
suit = 's';
setSuitName(SUIT_NAMES[int(ESuitNames::spades)]);
break;
default:
std::cerr << "Invalid suit." << std::endl;
suitId = NUM_SUITS;
suit = 'e';
throw std::invalid_argument("Not a suit symbol");
break;
}
this->suit = suit;
}
void Card::setRankName(std::string rankName)
{
this->rankName = rankName;
}
void Card::setSuitName(std::string suitName)
{
this->suitName = suitName;
}
int Card::getId()
{
return this->id;
}
char Card::getRank()
{
return this->rank;
}
char Card::getSuit()
{
return this->suit;
}
int Card::getRankId() const
{
return this->rankId;
}
int Card::getSuitId() const
{
return this->suitId;
}
std::string Card::getRankName()
{
return this->rankName;
}
std::string Card::getSuitName()
{
return this->suitName;
}
void Card::print()
{
std::cout << this->rankName << " of " << this->suitName << " ";
}
void Card::printSymbol()
{
std::cout << this->rank << this->suit << " ";
}
bool Card::operator<(Card card2) const
{
if (this->rankId < card2.rankId)
{
return true;
}
else if (this->rankId > card2.rankId)
{
return false;
}
else if (this->suitId < card2.suitId)
{
return true;
}
else if (this->suitId > card2.suitId)
{
return false;
}
else
{
return false;
}
}
bool Card::operator>(Card card2) const
{
if (this->rankId > card2.rankId)
{
return true;
}
else if (this->rankId < card2.rankId)
{
return false;
}
else if (this->suitId > card2.suitId)
{
return true;
}
else if (this->suitId < card2.suitId)
{
return false;
}
else
{
return false;
}
}
// Used when checking to see if a card already exists in a container
bool Card::operator==(Card card2) const
{
return this->rankId == card2.rankId && this->suitId == card2.suitId;
}
bool Card::isLowerSuit(const Card &card1 , const Card &card2)
{
if (card1.suitId < card2.suitId)
{
return true;
}
else if (card1.suitId > card2.suitId)
{
return false;
}
else if (card1.rankId < card2.rankId)
{
return true;
}
else if (card1.rankId > card2.rankId)
{
return false;
}
else
{
return false;
}
}
bool Card::isHigherSuit(Card card1, Card card2)
{
if (card1.suitId > card2.suitId)
{
return true;
}
else if (card1.suitId < card2.suitId)
{
return false;
}
else if (card1.rankId > card2.rankId)
{
return true;
}
else if (card1.rankId < card2.rankId)
{
return false;
}
else
{
return false;
}
}
| true |
ccbf456d56c43b1b70efee2dcd496e0fc068403c | C++ | dbwls89876/Ru | /BAEKJOON/Step/7. string/11720_char_sum.cpp | UTF-8 | 215 | 2.625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int n, sum = 0;
char arr[101];
cin>>n;
for(int i = 0; i<n; i++)
cin>>arr[i];
for(int i = 0; i<n; i++){
sum += (arr[i]-'0');
}
cout<<sum;
return 0;
}
| true |
f35f753014cfa975fd435a86152901ba124aefd6 | C++ | tngo0508/Cplusplus-OCC- | /A250_TEMP_E6_Ngo_NhatTan-2016-04-13/A250_TEMP_E6_Ngo_NhatTan/Project/Movie.cpp | UTF-8 | 649 | 3.390625 | 3 | [] | no_license | #include "Movie.h"
ostream& operator<<(ostream& out, const Movie& otherMovie)
{
out << otherMovie.getMovieTitle() << "(" << otherMovie.getYear() << ")";
return out;
}
Movie::Movie()
{
year = 0;
}
Movie::Movie(const string& newMovieTile, int newYear)
{
movieTitle = newMovieTile;
year = newYear;
}
string Movie::getMovieTitle() const
{
return movieTitle;
}
int Movie::getYear() const
{
return year;
}
void Movie::setMovieTitle(const string& newMovieTile)
{
movieTitle = newMovieTile;
}
void Movie::print() const
{
cout << movieTitle << "(" << year << ")";
cout << endl;
}
Movie::~Movie()
{}
| true |
db09455ceba2dd30875eb6be11d9555bae4e8ac0 | C++ | Rayyan06/Snake_Game | /Apple.h | UTF-8 | 465 | 2.546875 | 3 | [] | no_license | #ifndef APPLE_H
#define APPLE_H
// #include "Point.h"// When I learn inheritance
#include "Point.h"
#include <Arduino.h>
#include "snakegame.h"
class Snake;
class Point;
class Apple
{
private:
uint8_t m_x;
uint8_t m_y;
public:
Apple() = default;
Apple(uint8_t x, uint8_t y)
: m_x{ x }, m_y{ y }
{
}
bool isTouching(const Point& other) const;
void spawn(const Snake& snake);
void display(uint8_t* screen);
};
#endif | true |
5ad4cef2a5896741628345e1b76f57b9fe5a283d | C++ | david-docteur/DataStructures | /DoublyLinkedList/Node.cpp | UTF-8 | 872 | 3.4375 | 3 | [] | no_license | #include <string>
#include "Node.h"
using namespace std;
template<typename T>
Node<T>::Node(T value)
{
data = value;
previous = NULL;
next = NULL;
}
template<typename T>
Node<T>::~Node()
{
}
template<typename T>
const Node<T>* Node<T>::operator=(const Node<T>* n)
{
cout << "Calling Node Assignment Operator." << endl;
if(n == this)
return this;
data = n->data;
if(n->previous)
previous = n->previous;
if(n->next)
next = n->next;
return this;
}
template<typename T>
T Node<T>::getData()
{
return data;
}
template<typename T>
Node<T>* Node<T>::getPrevious()
{
return previous;
}
template<typename T>
Node<T>::setPrevious(Node<T>* n)
{
previous = n;
}
template<typename T>
Node<T>* Node<T>::getNext()
{
return next;
}
template<typename T>
Node<T>::setNext(Node<T>* n)
{
next = n;
}
template class Node<int>;
template class Node<string>; | true |
172f6852dc2231706539d3f12f68d28bad44a1d1 | C++ | zhengyunhai/CCFCSP | /code/CCF201712-2 游戏.cpp | UTF-8 | 1,152 | 2.953125 | 3 | [] | no_license | #include<cstdio>
#include<cstdlib>
struct dl{
int id;
int num;
dl* pre;
dl* next;
}dl;
void gendl(struct dl*temp,int n)
{
int i;
struct dl* r=temp;
struct dl* head;
head=r;
for(i=0;i<n;i++)
{
struct dl* temp1;
temp1=(struct dl*)malloc(sizeof(struct dl));
temp1->id=i+2;
temp1->num=0;
temp1->next=NULL;
r->next=temp1;
temp1->pre=r;
r=temp1;
}
r->next=head;
head->pre=r;
}
int pd(int a,int k)
{
int b,c;
b=a%k;
c=a%10;
if(b==0)return 1;
else if(c==k)return 1;
else return 0;
}
int main(void)
{
int n,k,count,temp;
scanf("%d %d",&n,&k);
count=n;
struct dl *head,*h,*temp1;
head=(struct dl*)malloc(sizeof(struct dl));
h=head;
head->id=1;
head->num=1;
head->pre=NULL;
head->next=NULL;
int i;
gendl(head,n-1);
/* for(i=0;i<n;i++)
{
printf("%d ",head->num);
head=head->pre;
}
*/
head=h;
while(count!=1)
{
temp=head->num;
temp1=head;
head=head->next;
if(pd(temp1->num,k))
{
temp1->pre->next=temp1->next;
temp1->next->pre=temp1->pre;
temp1->pre=NULL;
temp1->next=NULL;
free(temp1);
count--;
}
head->num=temp+1;
}
printf("%d",head->id);
}
| true |
da9bd6e57722aa62d45d741dfcb1882580722a1b | C++ | aaaaaepp1/tapin | /ArduinoProgram/Smoothing.cpp | UTF-8 | 755 | 3.140625 | 3 | [] | no_license | #include "Arduino.h"
#include "Smoothing.h"
Smoothing::Smoothing () { }
void Smoothing::setNext(Smoothing *smoothing_) {
next = smoothing_;
length = smoothing_->getLength ();
}
void Smoothing::setLength (int length_) {
length = length_;
}
void Smoothing::setValue (int value_) {
value = value_;
}
int Smoothing::smooth () {
if (next != NULL)
return next->smooth (1, value);
return -1;
}
int Smoothing::smooth (int currentLength_, int currentValue_) {
if (next != NULL) {
if (currentLength_ >= length) {
delete next;
next = NULL;
} else {
return next->smooth (++currentLength_, currentValue_ + value);
}
}
return currentValue_ / currentLength_;
}
int Smoothing::getLength () {
return length;
} | true |
073b3eed64d087a40c21675612f8d95065da9fe9 | C++ | Julsperez/Practicas-distribuidos | /practica10-23-27marzo/practica10/Solicitud.cpp | UTF-8 | 1,037 | 2.59375 | 3 | [] | no_license | #include "SocketDatagrama.h"
#include "Solicitud.h"
#include "mensaje.h"
Solicitud::Solicitud() {
}
char * Solicitud::doOperation(char* IP, int puerto, int operationId, char* arguments) {
struct mensaje msj;
char* resultado;
int res;
for(int i=0;i<1;i++){
msj.messageType = 0;
msj.requestId = id;
id++;
memcpy(msj.IP, IP, 16);
msj.puerto = puerto;
msj.operationId = operationId;
//cout << "Id operacion: " << msj.operationId << endl;
//cout << "ip: " << msj.IP << endl;
memcpy(msj.arguments, arguments, 4000);
//cout << "puerto: " << msj.puerto << endl;
//cout << "argumentos: " << msj.arguments << endl;
PaqueteDatagrama paq((char*) &msj, sizeof(msj), IP, puerto);
socketlocal->envia(paq);
PaqueteDatagrama paq1(sizeof(msj));
res = socketlocal->recibe(paq1);
//cout<<"Resultado: " <<res <<endl;
/*if(res>=0){
resultado = paq1.obtieneDatos();
break;
}*/
}
if(res>=0)
cout << "resultado: 12\n" << endl;
else
cout << "No se pudo conectar al servidor :(" << endl;
return res;
}
| true |
09a1949deea741171ca8cc6eba8d5f3ee76ffd48 | C++ | nickcharron/lidar_snow_removal | /src/radiusOutlierFilter.cpp | UTF-8 | 2,979 | 2.59375 | 3 | [] | no_license | #include <ros/ros.h>
#include <iostream>
#include <vector>
// PCL specific includes
#include <sensor_msgs/PointCloud2.h>
#include <std_msgs/Float64.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/filters/radius_outlier_removal.h>
ros::Publisher pubOutputPoints; // pubAvgDuration, pubAvgRate;
ros::Duration currentDuration(0), accumDuration(0);
ros::Time begin;
std::string inputTopic;
double radius;
std_msgs::Float64 averageDuration, averageRate;
int minNeighbours, noCloudsProcessed = 0;
void cloud_cb (const sensor_msgs::PointCloud2ConstPtr& cloud_msg)
{
// Count number of point clouds processed
noCloudsProcessed++;
// Container for original & filtered data
pcl::PCLPointCloud2* cloud = new pcl::PCLPointCloud2;
pcl::PCLPointCloud2ConstPtr cloudPtr(cloud);
pcl::PCLPointCloud2 cloud_filtered;
// Convert to PCL data type
pcl_conversions::toPCL(*cloud_msg, *cloud);
// Perform the actual filtering
pcl::RadiusOutlierRemoval<pcl::PCLPointCloud2> outrem;
outrem.setInputCloud(cloudPtr);
outrem.setRadiusSearch(radius);
outrem.setMinNeighborsInRadius(minNeighbours);
// Get current time:
ros::Time begin = ros::Time::now();
// apply filter
outrem.filter (cloud_filtered);
// Get duration
currentDuration = ros::Time::now() - begin;
// Calculate average duration
accumDuration = accumDuration + currentDuration;
averageDuration.data = accumDuration.toSec() / noCloudsProcessed;
averageRate.data = 1/averageDuration.data;
// Convert to ROS data type
sensor_msgs::PointCloud2 output;
pcl_conversions::fromPCL(cloud_filtered, output);
// Publish the data
pubOutputPoints.publish (output);
//pubAvgDuration.publish (averageDuration);
//pubAvgRate.publish (averageRate);
}
int
main (int argc, char** argv)
{
// Initialize ROS
ros::init (argc, argv, "radiusOutlierFilter");
ros::NodeHandle nh;
std::cout << std::endl;
ROS_INFO("Radius Outlier Removal Node Initialize");
// Get parameters from ROS parameter server
ros::param::get("radius/inputTopic", inputTopic);
ros::param::get("radius/radius_search", radius);
ros::param::get("radius/minNeighbours", minNeighbours);
ROS_INFO("The input topic is %s" , inputTopic.c_str());
ROS_INFO("Radius search dimension is set to: %.2f", radius);
ROS_INFO("Minimum neighbours required in each search radius is set to: %d", minNeighbours);
// Create a ROS subscriber for the input point cloud
ros::Subscriber sub = nh.subscribe (inputTopic, 1, cloud_cb);
// Create a ROS publisher for the output point cloud
pubOutputPoints = nh.advertise<sensor_msgs::PointCloud2> ("radius/output", 1);
//pubAvgDuration = nh.advertise<std_msgs::Float64> ("/radius/AverageProcessTime", 1);
//pubAvgRate = nh.advertise<std_msgs::Float64> ("/radius/AverageProcessRate", 1);
// Spin
ros::spin ();
}
| true |
83c1a430008a23ea8e43a417b7be006342c99963 | C++ | Kattjakt/kolv-hardware | /kolv.ino | UTF-8 | 3,193 | 3.140625 | 3 | [] | no_license | #include <SoftwareSerial.h>
#include <MD5.h>
SoftwareSerial bluetooth(4, 2); // RX, TX
struct Entry {
String name;
unsigned pin;
int(*callback)(unsigned, String);
};
class Handler {
private:
Entry **list;
size_t size;
public:
Handler();
~Handler();
bool bind(String name, unsigned pin, int(*callback)(unsigned, String));
bool update(String data);
void shutdown();
bool sendStates();
bool POST();
};
Handler::Handler() {
this->list = (Entry **)malloc(0);
this->size = 0;
};
Handler::~Handler() {
delete []list;
}
bool Handler::bind(String name, unsigned pin, int(*callback)(unsigned, String)) {
list = (Entry **)realloc(this->list, (size + 1) * sizeof(Entry *));
if (this->list != NULL) {
list[size] = new Entry{name, pin, callback};
pinMode(pin, OUTPUT);
Serial.println(" * listening for: \"" + list[size]->name + "\"");
size++;
} else {
this->shutdown();
return false;
}
return true;
}
bool Handler::update(String data) {
int argstart = data.indexOf('(');
int argend = data.indexOf(')');
// Send all the current pin states when successfully connected
if (data == "Connected") {
this->sendStates();
return true;
}
// Start checking for commands with arguments
if (argstart == -1 || argend == -1) {
Serial.println("Got invalid command: " + data);
return false;
}
String command = data.substring(0, argstart);
String args = data.substring(argstart + 1, argend);
for (int i = 0; i < size; i++) {
if (this->list[i]->name == command) {
int response = this->list[i]->callback(list[i]->pin, args);
Serial.print("Got response from Hardware: ");
Serial.println(response);
return true;
}
}
return false;
}
void Handler::shutdown() {
for (int i = 0; i < size; i++) {
// If we don't do this, all pins will be left in their current state
digitalWrite(this->list[i]->pin, LOW);
}
}
bool Handler::POST() {
return true;
}
int setLamp(unsigned pin, String value) {
if (value == "on") {
digitalWrite(pin, HIGH);
}
if (value == "off") {
digitalWrite(pin, LOW);
}
return true;
}
bool Handler::sendStates() {
for (int i = 0; i < size; i++) {
String name = list[i]->name;
int state = digitalRead(list[i]->pin);
bluetooth.println("State(" + name + "," + String(state) + ")");
}
return true;
}
Handler *handler = new Handler();
String inData = "";
void setup() {
Serial.begin(9600);
bluetooth.begin(9600);
handler->bind("headlight", 13, setLamp);
handler->bind("blinkers_left", 12, setLamp);
handler->bind("blinkers_right", 11, setLamp);
handler->POST();
}
void loop() {
while (bluetooth.available() > 0) {
char recieved = (char)bluetooth.read();
if (recieved == '\n') {
Serial.println("Recieved: " + inData);
handler->update(inData);
inData = "";
} else {
inData += recieved;
}
}
if (Serial.available()){
delay(10); // The delay is necessary to get this working!
bluetooth.println(Serial.readString());
}
}
| true |
2ff55ed186b8b1e6fa794b31a5e6c457bc2abbb8 | C++ | Fantendo2001/FORKED---CourseMaterials | /2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 05/06 Programs/PointWithFreeFuncsAndOps/point.cpp | UTF-8 | 927 | 3.578125 | 4 | [
"MIT"
] | permissive | /*
* File: point.cpp
* ---------------
* This file implements the point.h interface. The comments have been
* eliminated from this listing so that the implementation fits on a
* single page.
*/
#include <string>
#include <math.h>
#include "point.h"
using namespace std;
Point::Point() {
x = 0;
y = 0;
}
Point::Point(int xc, int yc) {
x = xc;
y = yc;
}
int Point::getX() {
return x;
}
int Point::getY() {
return y;
}
string Point::toString() {
return "(" + to_string(x) + "," + to_string(y) + ")";
}
ostream & operator<<(ostream & os, Point pt) {
return os << pt.toString();
}
bool operator==(Point p1, Point p2) {
return p1.getX() == p2.getX() && p1.getY() == p2.getY();
}
bool operator!=(Point p1, Point p2) {
return !(p1 == p2);
}
double dist(Point p1, Point p2) {
double dx = p2.getX() - p1.getX();
double dy = p2.getY() - p1.getY();
return sqrt(dx * dx + dy * dy);
}
| true |
8ff98b4bb29f178f3690871e4cd54035d1d3c2d1 | C++ | Ali-Fawzi-Lateef/C-PrimerPlus | /Chapter4/pe4-1.cpp | UTF-8 | 899 | 3.921875 | 4 | [] | no_license | // pe4-1.cpp -- this program requests and displays information
// This is exercise 1 of chapter 4 in C++ Primer Plus by Stephen Prata
#include<iostream>
int main(void)
{
using namespace std;
cout << "What is your first name? ";
char first_name[20];
cin.getline(first_name, 20); // we can see that cin does not leave a new line character after reading text
first_name[19] = '\0';
//cin.get(); // This is unnecessary because the member function getline() does not leave a newline character in the input
cout << "What is your last name? ";
char last_name[20];
cin.getline(last_name, 20);
last_name[19] = '\0';
cout << "What letter grade do you deserve? ";
char grade;
cin >> grade;
cout << "What is your age? ";
int age;
cin >> age;
cout << "Name: " << last_name << ", " << first_name << endl
<< "Grade: " << char (grade + 1) << endl
<< "Age: " << age << endl;
return 0;
}
| true |
c24fb7359f570b058bb1edb2517cd2d0e7f93caa | C++ | saushirur1/Justify_Text | /Text_Justification.cpp | UTF-8 | 1,369 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include "Text_Justfication.h"
using namespace std;
greedy_justify::greedy_justify(string text)
{
string word="";
for(int i=0;i<text.length();i++)
{
if(text[i]==' ' || i==text.length()-1 || text[i]=='.')
{
v.push_back(word);
word="";
}
else
{
word=word+text[i];
}
}
for(int i=0;i<v.size();i++)
{
l.push_back(v[i].length());
}
}
void greedy_justify::justify(int justify_length)
{
int length=0;
for(int j=0;j<l.size();j++)
{
if(length >= justify_length)
{
result.push_back(j-1);
j=j-1;
length=0;
}
if(j==l.size()-1)
{
result.push_back(j);
}
else
{
length=length+l[j]+1;
}
}
}
void greedy_justify::print_justify()
{
int index=0;
// for(int i=0;i<result.size();i++)
// {
// cout << result[i] << endl;
// }
for(int i=0;i<result.size();i++)
{
for(int j=index;j<result[i];j++)
{
cout << v[j] << " ";
}
index=result[i];
cout << "|";
cout << endl;
}
}
dynamic_justify::dynamic_justify(string text)
{
int word="";
for(int i=0;i<text.length();i++)
{
if(text[i]==' ' || i==text.length()-1)
{
v.push_back(word);
word="";
}
else
{
word=word+text[i];
}
}
for(int i=0;i<v.size();i++)
{
l.push_back(v[i].length());
}
}
int dynamic_justify::badness(int index1,int index2)
{
cout << "badness function" << endl;
}
| true |
00af5181bd0b3e7f51eb04f594d8c3a21d867be1 | C++ | DrewGaard/Comp-53-Labs-Data-Structures | /Lab 14 Queues/Lab 14 Queues/Node.h | UTF-8 | 260 | 2.984375 | 3 | [] | no_license | #ifndef NODE_H
#define NODE_H
#include "Student.h"
class Node
{
protected:
Student data;
Node* next;
public:
Node();
Node(Student item, Node* n = NULL);
Student getData();
Node* getNext();
void setData(Student item);
void setNext(Node* n);
};
#endif | true |
5375d4d38b33eca6ab8b9ac62cf5d3233738c328 | C++ | BrandonAO/Estructura-Datos | /Taller1/Blackjack.cpp | UTF-8 | 6,710 | 2.96875 | 3 | [] | no_license | #include "Blackjack.h"
#include "Croupier.h"
#include "Admin.h"
#include "Jugador.h"
#include <iostream>
#include <Windows.h>
using namespace std;
Blackjack::Blackjack()
{
this->croupier = Croupier();
this->mazo = Mazo();
this->cantActual = 0;
this->max = 6; //maximo de jugadores en mesa, minimo 1
this->jugadores = new Jugador[max];
}
Blackjack::~Blackjack() {
}
Mazo& Blackjack::getMazo()
{
return mazo;
}
bool Blackjack::agregarJugador(Jugador& jug) {
if (cantActual >= max) {
cout << "* No se pueden agregar mas jugadores a la mesa. " << endl;
return false;
}
if (jug.getMonto() < 5000) {
cout << "* No se pueden agregar al jugador porque tiene menos de 5.000 en su billetera, por favor cargue saldo. " << endl;
return false;
}
this->jugadores[cantActual] = jug;
cantActual++;
return true;
}
//metodo que elimina al jugador segun rut
bool Blackjack::eliminarJugador(string rut)
{
for (int i = 0; i < cantActual; i++) {
if (jugadores[i].getRut().compare(rut) == 0) {
cout << "Encontrado" << endl;
cout << "Jugador rut: " << jugadores[i].getRut() << endl;
jugadores[i] = jugadores[cantActual - 1];
cantActual--;
return true;
}
}
cout << "No encontrado" << endl;
return false;
}
bool Blackjack::eliminarTodosJugadores()
{
Jugador j = Jugador();
for (int i = 0; i < cantActual; i++) {
jugadores[i] = j;
cantActual--;
}
cout << "No encontrado" << endl;
return false;
}
void Blackjack::imprimirJugadores() {
for (int i = 0; i < max; i++) {
cout << "Nombre: " << jugadores[i].getNombre() << " Id: " << jugadores[i].getMonto() << endl;
}
}
// iniciar partida
void Blackjack::partida() {
if (cantActual == 0) {
cout << "* Debe agregar jugadores para iniciar una ronda." << endl;
return;
}
cout << "Iniciar Partida: " << endl;
cout << "Repartiendo cartas: " << endl;
bool terminoPartida = false;
// apuestas por jugador
for (int i = 0; i < cantActual; i++) {
while (true) {
int montoApuesta = 0;
cout << "Apuestas:" << endl;
cout << "Jugador " << jugadores[i].getNombre() << ":" << endl;
cout << "Saldo Disponible: " << jugadores[i].getMonto() << endl;
cout << "Ingresar monto a apostar: " << endl;
cin >> montoApuesta;
if (montoApuesta <= jugadores[i].getMonto()) {
apuestas[i] = montoApuesta;
jugadores[i].setMontoMenos(montoApuesta);
break;
}
else {
cout << "El monto ingresado excede de su saldo." << endl;
}
}
}
//reparte al jugador
for (int i = 0; i < cantActual; i++) {
bool cartasMano = jugadores[i].ingresarCarta(mazo.sacarCarta());
cartasMano = jugadores[i].ingresarCarta(mazo.sacarCarta());
if (jugadores[i].getPuntaje() == 21) {
jugadores[i].setPartidasGanadas(1);
apuestas[i] = apuestas[i] * 2;
jugadores[i].setMonto(apuestas[i]);
cout << "Jugador " << jugadores[i].getNombre() << " a GANADO!!" << endl;
}
}
//reparte al croupier
bool as = false;
bool cartasMano = croupier.ingresarCarta(mazo.sacarCarta());
if (croupier.getPuntaje() == 11) {
as = true;
}
imprimirCartas();
//sigue partida
for (int i = 0; i < cantActual; i++) {
int opcion = 0;
if (!as) {
cout << "Jugador" << jugadores[i].getNombre() << " ¿Quiere rendirse? SI[1] NO[0]" << endl;
cin >> opcion;
if (opcion == 1) {
//rendirse
jugadores[i].setMonto(apuestas[i] / 2);
jugadores[i].setRetiroRonda(true);
break;
}
}
else {
cout << "* El Croupier tiene un AS. Ningun jugador puede rendir." << endl;
}
if (!jugadores[i].getRetiroRonda()) {
cout << "Jugador" << jugadores[i].getNombre() << " Sacar carta [1], No sacar carta [2] " << endl;
cin >> opcion;
if (opcion == 1) {
//sacar carta
bool masCartas = true;
while (masCartas) {
imprimirCartas();
cout << "Jugador " << jugadores[i].getNombre() << " ¿sacar carta? Si [1], No [2] " << endl;
int opcion2 = 0;
cin >> opcion2;
if (opcion2 == 1) {
cartasMano = jugadores[i].ingresarCarta(mazo.sacarCarta());
verificarGanador(21, true);
}
if (opcion2 == 2) {
masCartas = false;
break;
}
}
}
}
}
//sacar cartas croupier > 16
while (croupier.getPuntaje() < 16) {
bool cartasMano = croupier.ingresarCarta(mazo.sacarCarta());
imprimirCartas();
}
verificarGanador(croupier.getPuntaje(), false);
}
void Blackjack::imprimirCartas() {
system("cls");
Carta c = mazo.sacarCarta();
string v = c.getValor();
string pinta = c.getPinta();
for (int i = 0; i < cantActual; i++) {
if (!jugadores[i].getRetiroRonda()) {
cout << "Jugador " << jugadores[i].getNombre() << " sus cartas: " << endl;
for (int i = 0; i < jugadores[i].getCartasActual();i++) {
cout << v << pinta << ", " ;
}
}
cout << "" << endl;
}
cout << "Croupier sus cartas: " << endl;
for (int i = 0; i < jugadores[i].getCartasActual(); i++) {
cout << v << pinta << ", ";
}
cout << "" << endl;
}
bool Blackjack::verificarGanador(int comparador, bool forma)
{
bool terminoPartida = false;
if (!forma) {
if (croupier.getPuntaje() > 21) {
cout << "Croupier a PERDIDO!!. Todos ganan." << endl;
for (int i = 0; i < cantActual; i++) {
if (!jugadores[i].getRetiroRonda()) {
jugadores[i].setPartidasGanadas(1);
apuestas[i] = apuestas[i] * 2;
jugadores[i].setMonto(apuestas[i]);
cout << "Jugador" << jugadores[i].getNombre() << " a GANADO!!" << endl;
}
}
return true;
}
for (int i = 0; i < cantActual; i++) {
if (!jugadores[i].getRetiroRonda()) {
if (jugadores[i].getPuntaje() > comparador) {
jugadores[i].setPartidasGanadas(1);
apuestas[i] = apuestas[i] * 2;
jugadores[i].setMonto(apuestas[i]);
cout << "Jugador" << jugadores[i].getNombre() << " obtuvo puntaje igual al croupier. a GANADO!!" << endl;
terminoPartida = true;
}
if (jugadores[i].getPuntaje() == comparador) {
jugadores[i].setMonto(apuestas[i] / 2);
jugadores[i].setRetiroRonda(true);
cout << "Jugador" << jugadores[i].getNombre() << " obtuvo puntaje mayor a 21. Ha EMPATADO!!" << endl;
}
if (jugadores[i].getPuntaje() < comparador) {
cout << "Jugador" << jugadores[i].getNombre() << " obtuvo puntaje menor a 21. Ha PERDIDO!!" << endl;
}
//falta cuando es menor.
}
}
}
else { //cartas adicionales
for (int i = 0; i < cantActual; i++) {
if (!jugadores[i].getRetiroRonda()) {
if (jugadores[i].getPuntaje() > 21) {
cout << "Jugador" << jugadores[i].getNombre() << " obtuvo puntaje mayor a 21. Ha PERDIDO!!" << endl;
jugadores[i].setRetiroRonda(true);
}
}
}
}
return terminoPartida;
}
int Blackjack::getCantActual()
{
return cantActual;
}
| true |
30e9db3c841b6e87d8c9343ee13ef44264de5679 | C++ | keith-mcqueen/MessageServer | /MessageStore.h | UTF-8 | 603 | 2.765625 | 3 | [] | no_license | /*
* File: MessageStore.h
* Author: keith
*
* Created on September 23, 2013, 10:29 PM
*/
#ifndef MESSAGESTORE_H
#define MESSAGESTORE_H
#include <string>
#include <semaphore.h>
#include <map>
#include <vector>
#include "Message.h"
class MessageStore {
public:
MessageStore();
virtual ~MessageStore();
void addMessage(string recipient, Message* message);
vector<Message*> getMessages(string recipient);
void clear();
private:
void lock();
void unlock();
map<string, vector<Message*> > messagesByRecipient;
sem_t lock_;
};
#endif /* MESSAGESTORE_H */
| true |
910586bdce8c8fe4b35692fb82f8bd59267adf19 | C++ | WickedLukas/BMP388_Test | /src/main.cpp | UTF-8 | 1,865 | 2.84375 | 3 | [] | no_license | // BMP388_DEV - I2C Communications, Default Configuration, Normal Conversion, Interrupt
#include <Arduino.h>
#include <BMP388_DEV.h> // Include the BMP388_DEV.h library
#include "Plotter.h"
#define BAROMETER_INTERRUPT_PIN 7
volatile boolean barometerInterrupt = false;
float temperature, pressure, altitude;
BMP388_DEV bmp388; // Instantiate (create) a BMP388_DEV object and set-up for I2C operation (address 0x77)
Plotter p;
void barometerReady() {
barometerInterrupt = true;
}
void setup() {
Serial.begin(115200); // Initialise the serial port
bmp388.begin(); // Default initialisation, place the BMP388 into SLEEP_MODE
bmp388.enableInterrupt(); // Enable the BMP388's interrupt (INT) pin
attachInterrupt(digitalPinToInterrupt(BAROMETER_INTERRUPT_PIN), barometerReady, RISING); // Set interrupt to call interruptHandler function on D2
bmp388.setTimeStandby(TIME_STANDBY_20MS); // Set the standby time to 0.02 seconds
bmp388.setTempOversampling(OVERSAMPLING_X1); // Set temperature oversampling to 1
bmp388.setPresOversampling(OVERSAMPLING_X8); // Set pressure oversampling to 8
bmp388.setIIRFilter(IIR_FILTER_2); // Set the IIR filter coefficient to 2
bmp388.startNormalConversion(); // Start BMP388 continuous conversion in NORMAL_MODE
p.Begin();
//p.AddTimeGraph("Barometer Data", 100, "Temperature", temperature, "Pressure", pressure, "Altitude", altitude);
p.AddTimeGraph("Altitude", 500, "Altitude", altitude);
}
void loop() {
if (barometerInterrupt) {
barometerInterrupt = false; // Clear the dataReady flag
bmp388.getMeasurements(temperature, pressure, altitude); // Read the measurements
// Plot
p.Plot();
}
}
| true |
8047f781a73b9db736fe37996127a6e713e516dc | C++ | burakcoskun/programming_contests | /codeforces/411div2/B/soln.cpp | UTF-8 | 552 | 2.515625 | 3 | [] | no_license | #include<cstdio>
#include<cstdlib>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<algorithm>
#include<iostream>
#include<cmath>
using namespace std;
#define pb push_back
#define mp make_pair
#define fs first
#define sc second
int n;
void read_input(){
cin >> n;
string s;
for(int i = 0 ; i < 2 && i < n ;++i)
s+='a';
for(int i = 2; i < n; ++i){
if(s[i-2] == 'a')
s+='b';
else
s+='a';
}
cout << s << endl;
}
int main(){
read_input();
return 0;
}
| true |
66dd790e29f5cc723f5800793278ac21dab3f207 | C++ | sankalpkotewar/algorithms-1 | /tree/path-sum-iv.cpp | UTF-8 | 993 | 3.578125 | 4 | [] | no_license | #include "tree.h"
/*
* If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digits integers.
For each integer in this list:
The hundreds digit represents the depth D of this node, 1 <= D <= 4.
The tens digit represents the position P of this node in the level it belongs to, 1 <= P <= 8.
The position is the same as that in a full binary tree.
The units digit represents the value V of this node, 0 <= V <= 9.
Given a list of ascending three-digits integers representing a binary with the depth smaller than 5.
You need to return the sum of all paths from the root towards the leaves.
Example 1:
Input: [113, 215, 221]
Output: 12
Explanation:
The tree that the list represents is:
3
/ \
5 1
The path sum is (3 + 5) + (3 + 1) = 12.
Example 2:
Input: [113, 221]
Output: 4
Explanation:
The tree that the list represents is:
3
\
1
The path sum is (3 + 1) = 4.
*/
int pathSumIV(vector<int>& nums) {
return 0;
} | true |
5e9f3bd4d79d7a8cbed777f44be0af4068014caa | C++ | s0lstice/carto-qt | /askdatabase.cpp | ISO-8859-1 | 4,295 | 2.6875 | 3 | [] | no_license | /**
* \file askdatabase.cpp
* \brief Fenetre de gestion des bases de donnees, permet de choisir ou creer une nouvelle base
* \author Guillaume Lastecoueres & Mickael Puret
* \version 0.1
*
* La creation ou la selection d'une base de donn necessite la selection de son emplacement. La creation necessite de creer toutes les table de la base.
*
*/
/*! \class AskDataBase askdatabase.cpp
\brief fenetre de selection de la base de donnee
*/
#include "askdatabase.h"
#include "ui_askdatabase.h"
#include "carte.h"
#include "QDebug"
#include "database.h"
#include "data_categories.h"
#include <QSettings>
//#include <string>
/*!
@brief Construit la fentre et initialise les donnes importantes
@fn AskDataBase::AskDataBase(QWidget *parent) : QMainWindow(parent), ui(new Ui::AskDataBase)
\note Cette fentre que nous allons crer est faite pour permettre l'utilisateur de choisir une base de donne.\n
Il y a 4 bouttons :\n
-pushbutton_3 permet de quitter\n
-pushbutton_2 permet de creer ou selectionner une BDD\n
-pushbutton permet de creer ou selectionner une BDD\n
-pushbutton_4 permet d'ouvrir un explorateur pour choisir un fichier\n
Deplus la fentre liste tout les fichiers en .db dans son repertoire.\n
*/
AskDataBase::AskDataBase(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::AskDataBase)
{
ui->setupUi(this);
connect(ui->pushButton_3,SIGNAL(clicked()),this,SLOT(close()));
connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(ValidateFile()));
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(CreateFile()));
connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(SelectFile()));
QString MyAppDirPath = QCoreApplication::applicationDirPath();
QStringList listFilter;
listFilter << "*.db";
QDir *DirA = new QDir(MyAppDirPath);
QStringList FIL = DirA->entryList(listFilter);
int i = 0;
for(i=0;i<FIL.count();i++)
{
ui->comboBox->addItem(FIL[i]);
}
free(DirA);
}
AskDataBase::~AskDataBase()
{
delete ui;
}
/*!
@fn void AskDataBase::SelectFile(void)
@brief Creer une fentre qui permet la selection d'un fichier .
\note Une fois la selection faite on met automatiquement dans la combobox le fichier qui vient d'tre selectionn.
*/
void AskDataBase::SelectFile(void)
{
QString File = QFileDialog::getOpenFileName(this,tr("Choisir base de donne"), QDir::currentPath(), tr("Database files (*.db)"));
if (!File.isEmpty())
{
if (ui->comboBox->findText(File) == -1)
ui->comboBox->addItem(File);
ui->comboBox->setCurrentIndex(ui->comboBox->findText(File));
}
}
/*!
@fn void AskDataBase::CreateFile(void)
@brief Cree ou recupere une BDD puis lance la feetre principale.
\note Dans les faits la recuperation ou la creation de la base de donne se fait l'appel de datacreate on rcupre aussi les catagories qui ont t sauvergard dans les QSettings.
*/
void AskDataBase::CreateFile(void)
{
filename= ui->comboBox->currentText().remove(".db");
database::dataCreate(filename)->initTable();
int i = 0 ;
QStringList Categories;
QSettings settings("CartoTeam", "Cartographe");
Categories.append(settings.value("Categories").toStringList());
for(i=0;i<Categories.count();i++)
{
addCategorie(Categories.value(i));
}
Carte * WCarte = new Carte();
WCarte->show();
this->close();
}
/*!
@fn void AskDataBase::ValidateFile(void)
@brief Cree ou recupere une BDD puis lance la feetre principale.
\note Dans les faits la recuperation ou la creation de la base de donne se fait l'appel de datacreate on rcupre aussi les catagories qui ont t sauvergard dans les QSettings.
*/
void AskDataBase::ValidateFile(void)
{
filename= ui->comboBox->currentText().remove(".db");
database::dataCreate(filename);
int i = 0 ;
QStringList Categories;
QSettings settings("CartoTeam", "Cartographe");
Categories.append(settings.value("Categories").toStringList());
for(i=0;i<Categories.count();i++)
{
addCategorie(Categories.value(i));
}
Carte * WCarte = new Carte();
WCarte->show();
this->close();
}
| true |
54f1be788404c2b3a178e53a10ac720481276648 | C++ | jmoraes7/Elements-of-Programming-Interviews | /Linked Lists/DeleteNode.cpp | UTF-8 | 914 | 3.171875 | 3 | [] | no_license | /*
* DeleteNode.cpp
* -----------------
*
* Chapter 8 Question 7
*/
#include <cassert>
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <unordered_map>
#include "./Linked_list_Prototype.h"
using namespace std;
void deleteNode(shared_ptr<ListNode<int> >& node) {
node->data = node->next->data;
node->next = node->next->next;
}
void SimpleTest() {
shared_ptr<ListNode<int> > L0 = make_shared<ListNode<int> >(ListNode<int>{4, nullptr});
shared_ptr<ListNode<int> > L1 = make_shared<ListNode<int> >(ListNode<int>{3, L0});
shared_ptr<ListNode<int> > L2 = make_shared<ListNode<int> >(ListNode<int>{2, L1});
shared_ptr<ListNode<int> > L3 = make_shared<ListNode<int> >(ListNode<int>{1, L2});
cout << "BEFORE: ";
PrintList(L3);
cout << endl;
cout << "AFTER: ";
deleteNode(L1);
PrintList(L3);
cout << endl;
}
int main()
{
SimpleTest();
return 0;
} | true |
cd1f8d2795725a7f8e9a882f62707a6f0cf65a6c | C++ | lieroz/CourseOnCompilers | /lab_04/main.cc | UTF-8 | 227 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include "parser.h"
int main()
{
auto &&[f, r] = parse({"a", "and", "c", "xor", "(", "b", "or", "c", ")", "and", "1"});
std::cout << std::boolalpha << f << ": " << r << std::endl;
return 0;
}
| true |
91506784efa3dc6ceed71eacaa0ba9cb6a9a69f1 | C++ | LyudmilaPetrashko/useful_information | /tree/theory.cpp | UTF-8 | 6,631 | 2.90625 | 3 | [] | no_license | Введение:
Для того чтобы граф T считался деревом, он должен следовать всем следующим ограничениям
(которые могут быть доказаны как эквивалентные ограничения):
1)T соединен и не имеет неориентированных циклов (т. Е. Если бы направленные направленные ребра T не были направлены, циклов не было бы)
2)T является ациклическим, и образуется простой цикл, если к T добавляется любое ребро
3)T подключен, но не подключен, если какой-либо один край удален из T
4)Существует единственный простой путь, соединяющий любые две вершины из T
сли T имеет n вершин (где n - конечное число), то приведенные выше утверждения эквивалентны следующим двум условиям:
1. T связно и имеет n-1 ребра
2. T не имеет простых циклов и имеет n-1 ребра
---------------------------------------------------------------------------------------------------------------------------------------
Виды обходов
1,2,3- обходы в глубину.
1)При pre-order(префиксный) мы сначала посещаем текущий узел, затем мы рекурсируем на левом дочернем элементе (если он существует),
а затем мы рекурсируем на правый ребенок (если он существует). Проще говоря, VLR (Визит-Влево-Вправо).
2)В in-order(инфиксный) мы сначала рекурсируем на левом дочернем элементе (если таковой существует), то мы посещаем текущий узел, а затем
мы рекурсируем на правый ребенок (если он существует). Проще говоря, LVR (Left-Visit-Right).
3)В post-order(постфиксный) мы сначала рекурсируем на левом дочернем элементе (если он существует), то мы рекурсируем на нужном ребенке (если
он существует), а затем мы посетим текущий узел. Проще говоря, LRV (Left-Right-Visit).
4)В обходе по уровням(обход в ширину), мы посещаем узлы поэтапно (где корень является «первым уровнем», его дети являются «вторым уровнем» и т. Д.), И на данном
уровне мы посещаем узлы, направо.
----------------------------------------------------------------------------------------------------------------------------------------
HEAP(куча)
Куча - это дерево, которое удовлетворяет Свойству кучи: для всех узлов A и B, если узел A является родительским элементом узла B,
то узел A имеет более высокий приоритет (или равный приоритет), чем узел B. В этом тексте мы будем обсуждают только двоичные кучи
(т. е. кучи, которые являются бинарными деревьями), но это ограничение двоичного дерева не требуется от куч вообще. Бинарная куча
имеет три ограничения:
1)Свойство двоичного дерева: все узлы в дереве должны иметь либо 0, 1, либо 2 ребенка
2)Свойство кучи (объяснено выше)
3)Свойство формы: куча - полное дерево. Другими словами, все уровни дерева, кроме, возможно, нижнего, полностью заполняются, и, если
последний уровень дерева не завершен, узлы этого уровня заполняются слева направо
MIN-куча - это куча, где каждый узел меньше (или равен) всем своим детям (или не имеет детей). Другими словами, считается,
что узел A имеет более высокий приоритет, чем узел B, если A <B (то есть при сравнении двух узлов меньший из них имеет более
высокий приоритет).
MAX-куча - это куча, где каждый узел больше (или равен) всем своим детям (или не имеет детей). Другими словами, считается, что узел A
имеет более высокий приоритет, чем узел B, если A> B (то есть, сравнивая два узла, более высокий из них имеет более высокий приоритет).
Визуализация-> https://www.cs.usfca.edu/~galles/visualization/Heap.html
----------------------------------------------------------------------------------------------------------------------------------------
Binary Search Tree
Бинарное дерево - это структура данных, дерево, у которого не более двух потомков для одного родителя.
Сбалансированное дерево - бинарное дерево, у которого глубина логарифмически зависит от кол-ва элементов.
Идеально сбалансированное дерево - дерево, у которого все уровни заполнены, кроме последнего.
Деревья поиском - те же бинарные деревья, только у левого поддерева потомки должны быть меньше значения родителя,
а у правого больше либо равно.
Визуализация-> https://www.cs.usfca.edu/~galles/visualization/BST.html
| true |
21483623cfd3884f26f10815f0485eb94fcca1c0 | C++ | christopheryou/EarthquakeData | /a3-earthquake/earthquake.h | UTF-8 | 713 | 3.109375 | 3 | [] | no_license | /** CSci-4611 Assignment 3: Earthquake
*/
#ifndef EARTHQUAKE_H_
#define EARTHQUAKE_H_
#include <string>
#include "date.h"
/** Small data structure for storing earthquake data.
*/
class Earthquake {
public:
// Create an earthquake from a datafile's line of text
Earthquake(std::string s);
Earthquake();
Date date();
double longitude();
double latitude();
double magnitude();
bool equals(Date date, double longitude, double latitude, double magnitude, Date date2, double longitude2, double latitude2, double magnitude2);
private:
double ParseFloat(std::string s);
int ParseInt(std::string s);
std::string line;
};
#endif
| true |
4ea7cf5a211a3fa1fee5b5d45a5e5c069d71115b | C++ | sikao1990/XFramework | /Mem/MemMgr.cpp | UTF-8 | 3,010 | 2.984375 | 3 | [] | no_license | #include "MemMgr.h"
#include <stdlib.h>
#include <new>
MemMgr::MemMgr():pEleHead(NULL),nUnit(0){
}
MemMgr::~MemMgr(){
EleNode* pBegin = pEleHead;
EleNode* pBak = NULL;
for(;NULL!=pBegin;pBegin = pBak)
{
pBak = pBegin->pNext;
destoryImpl(pBegin);
if(NULL==pBak)
break;
}
}
bool MemMgr::Init(int blockSize){
nUnit = blockSize;
char* p = (char*)AllocImpl(SYSMEMPAGE);
Expend(p,SYSMEMPAGE);
return pEleHead;
}
void* MemMgr::Alloc(int n){
int nIndex = -1;
EleNode* pBegin = pEleHead;
EleNode** ppNewNode = NULL;
for(;NULL!=pBegin;pBegin = pBegin->pNext)
{
if(-1!=(nIndex=FindAvailable(pBegin->pFlag,n)))
break;
}
if(-1==nIndex){
char* pNew = (char*)AllocImpl(SYSMEMPAGE);
EleNode* pNodeNew = (EleNode*)pNew;
if(NULL!=pNew){
Expend(pNew,SYSMEMPAGE);
nIndex=FindAvailable(pNodeNew->pFlag,n);
if(-1==nIndex)
return NULL;
pBegin = pNodeNew;
}else
return NULL;
}
if(-1!=nIndex){
int i=0;
while(n--){
pBegin->pFlag[nIndex+i++]='1';
if(nIndex+n<pBegin->nIndex)pBegin->nIndex=nIndex+n;
}
return pBegin->pStart+nIndex*nUnit;
}
return NULL;
}
void MemMgr::Free(void* p,int n)
{
EleNode* pBegin = pEleHead;
int nIndex = -1;
for(;NULL!=pBegin;pBegin = pBegin->pNext)
{
if(p >= pBegin->pStart && p <= pBegin->pStart+pBegin->nCount*nUnit){
nIndex = ((char*)p-pBegin->pStart)/nUnit;
break;
}
}
if(-1!=nIndex){
int i=0;
while(n--){
pBegin->pFlag[nIndex+i] = '0';
memset(pBegin->pStart+(nIndex+i++)*nUnit,0,nUnit);
}
if (nIndex < pBegin->nIndex)pBegin->nIndex = nIndex;
}else
throw "the MemMgr lib error";
}
void* MemMgr::AllocImpl(int n){
return malloc(n);
}
void MemMgr::destoryImpl(void* p){
free(p);
}
void MemMgr::Expend(char* p,int len){
//|EleNode|flagStr|NodeList| => sizeof(EleNode)+x*sizeof(T)+x*sizeof(char)+1 = len;
memset(p,0,len);
int x = ( len-sizeof(EleNode)-1 )/(nUnit+sizeof(char));
EleNode** ppEleNode = NULL;
if(NULL==pEleHead){
pEleHead = (EleNode*)p;
new (pEleHead) EleNode(p+sizeof(EleNode),p+(len-x*nUnit),x);
}else{
EleNode* pBegin = pEleHead;
for(;NULL!=pBegin->pNext;pBegin = pBegin->pNext);
ppEleNode = &(pBegin->pNext);
*ppEleNode = (EleNode*)p;
new ( *ppEleNode ) EleNode(p+sizeof(EleNode),p+(len-x*nUnit),x);
}
}
int MemMgr::FindAvailable(char* p,int n){
int count = 0;
bool bFlag = false;
const char* pTag = NULL;
const char* pStart = strchr(p,'0');
const char* pBegin = pStart;
const char* pTmp = pStart;
if(NULL==pStart)return -1;
if(1==n){
return pStart - p;
}else{
count = 1;
while(NULL!=(pTag=strchr(pStart+1,'0'))){
if(pTag-1==pTmp){
if(!bFlag)
pBegin = pStart,bFlag = true;
if(n==++count)
return pBegin - p;
pStart+=1;
}else
pStart = pTag,count = 1, bFlag = false;
pTmp = pTag;
}
}
return -1;
}
MemMgr::MemMgr(const MemMgr& th)
{
Init(th.nUnit);
}
MemMgr& MemMgr::operator=(const MemMgr& th)
{
if(this->nUnit > 0 && NULL!=this->pEleHead)
this->~MemMgr();
Init(th.nUnit);
return *this;
}
| true |
85ae0f4e03a735eb189276972f4961f288d1f03a | C++ | BYOA/MonsterGame | /main.cpp | UTF-8 | 7,001 | 3.53125 | 4 | [] | no_license | //Author:BYOA
//Program: MonsterGame
#include <iostream>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include "monstergame.hpp" //contains function prototypes, user-defined types and global variables.
using namespace std;
int main ()
{
srand (time(NULL));/* initialize random seed for enemy movement */
char board[ROWSIZE][COLUMNSIZE];
initializeGrid (board);
Move treasure = {8, 8, treasuretype};
initalizeType (board, treasure);
Move player = {1, 1, playertype};
initalizeType (board, player);
Move enemy1 = {4, 6, enemytype};
initalizeType (board, enemy1);
Move enemy2 = {6, 2, enemytype};
initalizeType (board, enemy2);
Move enemy3 = {3, 4, enemytype};
initalizeType (board, enemy3);
IntroScreen();
bool gameover = 0; //intialized as false
int turncount;
while (!(gameover)) //while gameover is not true (i.ie if false the loop is still true and will re-iterate
{
system("CLS");
DisplayGrid (board);
cout << "Turn " << ++turncount << endl;
EnemyMove (board, enemy1);
EnemyMove (board, enemy2);
EnemyMove (board, enemy3);
gameover = EnemyMoveCheck (board, enemy1);
if (!(gameover))
gameover = EnemyMoveCheck (board, enemy2);
if (!(gameover))
gameover = EnemyMoveCheck (board, enemy3);
if (!(gameover)) //an if-statement is needed to ensure that if an enemy results in a game-over, the player cannot make a move.
{
PlayerMove (board, player);
gameover = PlayerMoveCheck (board, player);
}
}
cout << "\n\n\nGame span: " << turncount << " turns.";
return 0;
}
void EnemyMove(char grid[ROWSIZE][COLUMNSIZE], Move &e)
{
int number = rand() % 4 + 1; //number generation between 1 to 4.
switch(number)
{
case 1://move left
if ((e.column -1 <= bordermin) || (grid[e.row][e.column -1] == treasuretype) || (grid[e.row][e.column-1] == enemytype))
{
EnemyMove (grid, e);
}
else
{
grid [e.row][e.column] = DisplayChar;
e.column -= 1;
}
break;
case 2://move right
if ((e.column + 1 >= bordermax) || (grid[e.row][e.column+ 1] == treasuretype) || (grid[e.row][e.column+1] == enemytype))
{
EnemyMove (grid, e); //recursion
}
else
{
grid [e.row][e.column] = DisplayChar;
e.column += 1;
}
break;
case 3://move up
if ((e.row - 1 <= bordermin) || (grid[e.row- 1][e.column] == treasuretype) || (grid[e.row- 1][e.column] == enemytype))
{
EnemyMove (grid, e); //recursion
}
else
{
grid [e.row][e.column] = DisplayChar;
e.row-= 1;
}
break;
case 4://move down
if ((e.row + 1 >= bordermax) || (grid[e.row+ 1][e.column] == treasuretype) || (grid[e.row+ 1][e.column] == enemytype))
{
EnemyMove (grid, e); //recursion
}
else
{
grid [e.row][e.column] = DisplayChar;
e.row+= 1;
}
break;
}
}
bool EnemyMoveCheck (char grid[ROWSIZE][COLUMNSIZE], Move e)
{
if (grid [e.row][e.column] == playertype)
{
grid [e.row][e.column] = e.type;
system("CLS");
DisplayGrid (grid);
cout << "You have been caught (on the enemy's turn)!.\n\nGAME OVER!";
return true;
}
else
{
grid [e.row][e.column] = e.type;
return false;
}
}
void PlayerMove (char grid[ROWSIZE][COLUMNSIZE], Move &p)
{
char choice;
cout << "Which way will you move? (use WASD keys to move)\n";
cin >> choice;
switch(choice)
{
case 'a': case 'A'://move left
if ((p.column - 1 <= bordermin)) //if/else choice instead of while loop as while loop causes to include else statement
{
cout << "Wrong choice, try again!.\n";
PlayerMove (grid, p); //recursion
}
else
{
grid [p.row][p.column] = DisplayChar;
p.column-= 1;
}
break;
case 'd': case 'D'://move right
if ((p.column + 1 >= bordermax))
{
cout << "Wrong choice, try again!.\n";
PlayerMove (grid, p); //recursion
}
else
{
grid [p.row][p.column] = DisplayChar;
p.column+= 1;
}
break;
case 'w': case 'W'://move up
if ((p.row - 1 <= bordermin))
{
cout << "Wrong choice, try again!.\n";
PlayerMove (grid, p); //recursion
}
else
{
grid [p.row][p.column] = DisplayChar;
p.row-= 1;
}
break;
case 's': case 'S'://move down
if ((p.row + 1 >= bordermax))
{
cout << "Wrong choice, try again!.\n";
PlayerMove (grid, p); //recursion
}
else
{
grid [p.row][p.column] = DisplayChar;
p.row += 1;
}
break;
}
}
bool PlayerMoveCheck ( char grid[ROWSIZE][COLUMNSIZE], Move p)
{
if (grid [p.row][p.column] == enemytype)
{
grid [p.row][p.column] = enemytype;
system("CLS");
DisplayGrid (grid);
cout << "You have been caught (on player's turn)!.\n\nGAME OVER!";
return true;
}
else if (grid [p.row][p.column]== treasuretype)
{
grid [p.row][p.column] = p.type;
system("CLS");
DisplayGrid (grid);
cout << "Congratulations! You got the treaure (on player side)! \n\nYOU WIN!";
return true;
}
else
{
grid [p.row][p.column] = p.type;
return false;
}
}
void initializeGrid (char grid[ROWSIZE][COLUMNSIZE])
{
for (int x = 0; x < ROWSIZE; x++)
{
for (int y = 0; y < COLUMNSIZE; y++)
{
grid[x][y] = DisplayChar;
}
}
}
void initalizeType (char grid[ROWSIZE][COLUMNSIZE], Move typeref)
{
grid[typeref.row][typeref.column] = typeref.type;
}
void DisplayGrid (char grid[ROWSIZE][COLUMNSIZE])
{
for (int x = 0; x < ROWSIZE; x++)
{
for (int y = 0; y < COLUMNSIZE; y++)
{
cout << ' ' << grid [x][y] << ' ';
}
cout << '\n';
}
}
void IntroScreen ()
{
cout << " MONSTER GAME -- BYOA\n\n\n\n";
cout << "Monster Game premise is to get to the treasure (marked '"<<treasuretype << "') but don't get caught by ";
cout << "the enemies! (marked '"<< enemytype << "')\n";
cout << "You are able to move using the WASD keys.\n";
cout << "You control '" << playertype << "'. Good luck! Don't get caught!!!\n";
cin.ignore();
}
| true |
090a02c6e1abb329c1137b1203647acae02074bf | C++ | chinann6213/TouristInformationSystem | /Attraction.h | UTF-8 | 1,350 | 2.953125 | 3 | [] | no_license | /*************************************
Program: Attraction.h
Course: OOPDS
Year: 2015/16 Trimester 2
Name: NG CHIN ANN
ID: 1142701684
Lecture: TC01
Lab: TT03
Email: chinann6213@gmail.com
Phone: 011 - 1076 6957
*************************************/
#ifndef ATTRACTION_HPP
#define ATTRACTION_HPP
#include "LinkedList.cpp"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Attraction
{
private:
int typeID;
string name, openHrs, openDay, address, contact;
public:
Attraction();
Attraction(int typeID, string name, string openHrs, string openDay, string address, string contact);
virtual ~Attraction();
virtual void display() = 0;
void settypeID(int typeID);
void setName(string name);
void setHrs(string openHrs);
void setDay(string openDay);
void setAddress(string address);
void setContact(string contact);
int gettypeID();
string getName();
string getOpenHrs();
string getDay();
string getAddress();
string getContact();
virtual ostream& output(ostream& out);// Function to help overloading extraction operator
virtual istream& input(istream& in) = 0; // Function to help overloading insertion operator
};
#endif // end ATTRACTION_H
| true |
e52d0e56979727623ad5c6634fb989213cf30360 | C++ | ccl1616/programming-10802 | /mid02/hw3/lab03-11413Rational.cpp | UTF-8 | 2,259 | 3.75 | 4 | [] | no_license | #include <iostream>
//#include "function.h" // include definition of class Rational
using namespace std;
class Rational
{
public:
Rational( int = 0, int = 1 ); // default constructor
Rational addition( const Rational & ) const; // function addition
Rational multiplication( const Rational & ) const; // function multi.
void printRational () const; // print rational format
private:
int numerator; // integer numerator
int denominator; // integer denominator
void reduce();
}; // end class Rational
int gcd(int a, int b);
Rational::Rational( int a, int b )
{
numerator = a;
denominator = b;
}
Rational Rational::addition( const Rational & b)const
{
Rational ans;
ans.numerator = this->numerator * b.denominator + b.numerator * this->denominator;
ans.denominator = this->denominator * b.denominator;
int saver = gcd (ans.numerator, ans.denominator);
ans.numerator /= saver;
ans.denominator /= saver;
if(ans.denominator < 0){
ans.denominator *= -1;
ans.numerator *= -1;
}
return ans;
}
Rational Rational::multiplication( const Rational & b )const
{
Rational ans;
ans.numerator = this->numerator * b.numerator;
ans.denominator = this->denominator * b.denominator;
int saver = gcd (ans.numerator, ans.denominator);
ans.numerator /= saver;
ans.denominator /= saver;
if(ans.denominator < 0){
ans.denominator *= -1;
ans.numerator *= -1;
}
return ans;
}
void Rational::printRational()const
{
cout << numerator << "/" << denominator << endl;
}
int main()
{
char s1;
int s2, s3, s4, s5;
Rational x;
while(cin >>s1>>s2>>s3>>s4>>s5)
{
if(cin.eof())
{
break;
}
Rational c(s2, s3), d(s4, s5);
if(s1 == '+')
{
x = c.addition( d ); // adds object c and d; sets the value to x
x.printRational(); // prints rational object x
}
else if(s1 == '*')
{
x = c.multiplication( d ); // multiplies object c and d
x.printRational(); // prints rational object x
}
}
}
int gcd(int a, int b){
return (b == 0) ? a : gcd(b, a % b);
} | true |
51586e4f43361ea42bb05a7586b0cc67f7b339f9 | C++ | Arc-Pintade/GraphMaker | /src/function.cpp | UTF-8 | 626 | 3.21875 | 3 | [] | no_license | #include "../include/function.hpp"
#include <iostream>
double Function::factorial(int n){
double foo = 1;
if(n > 0)
for(int i=1; i<(n+1); i++){
foo *= i;
}
return foo;
}
Function::Function(int precision_user){
precision = precision_user;
x = std::vector<double>(precision);
y = std::vector<double>(precision);
}
double Function::getx(int i){return x[i];};
double Function::gety(int i){return y[i];};
double Function::getPrecision(){return precision;};
void Function::setx(int i, double d){
x[i] = d;
}
void Function::sety(int i, double d){
y[i] = d;
}
| true |
0ecc56e9328835be6687141a800296172f64b2b7 | C++ | M-Schenk-91/forschungsseminar2018 | /cpp/processing/datastructures/document.cpp | UTF-8 | 1,108 | 2.515625 | 3 | [] | no_license | #include <opencv2/core/types.hpp>
#include "document.h"
#include "../tracking/TrackableTypes.h"
document::document(long id, std::vector<uint8_t> & marker_bits, uint8_t marker_size, std::string const & name, int type) :
m_id(id), m_marker_bits(marker_bits), m_marker_size(marker_size), Trackable(TrackableTypes::PHYSICAL_DOCUMENT, name)
{}
document::~document() = default;
/*
bool document::stamped()
{
return false;
}
void document::set_stamped()
{
this->m_stamped = true;
}
const std::vector<stamp::stamp_type> & document::get_stamp_signatures() const {
return m_stamp_signatures;
}6A
void document::add_stamp_signature(stamp const & s)
{
for(auto sts = m_stamp_signatures.begin(); sts != m_stamp_signatures.end(); ++ sts)
{
if(s.type() == * sts)
return;
}
m_stamp_signatures.push_back(s.type());
}
*/
uint8_t const document::id() const
{
return this->m_id;
}
uint8_t document::marker_size()
{
return m_marker_size;
}
std::vector<uint8_t> & document::marker_bits()
{
return m_marker_bits;
}
int document::type() const
{
return -1;
} | true |
097f46c6ec534d1d8f397e183133e894b17eaf67 | C++ | justin95214/c-add-add-study | /c++study2/Random.cpp | UTF-8 | 495 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include "Random.h"
using namespace std;
Random::Random()
{
}
int Random::nextInRange(int a, int b)
{
int random = rand();
if (random > b || random < a)
{
return random % 3 + 2;
}
else
return random;
}
int Random::nextEvenInRange(int a, int b)
{
int random = rand();
if (random > b || random < a)
{
return (random%((b-a)/2)) *2+2;
}
else
return random;
}
int Random::next()
{
int random = rand();
return random;
} | true |
089436af32e2d31a7a3f97050c351ff342c45a20 | C++ | liqihao2000/VEM_project | /freefunc.cpp | UTF-8 | 1,613 | 2.984375 | 3 | [] | no_license | #include "freefunc.hpp"
//computes the degrees in the order 00,10,01,20...
std::vector<std::array<int,2> > Polynomials(int k) {
std::vector<std::array<int,2> > degree;
for (int i=0; i<=k; i++) {
for (int j=i; j>=0; j--){
degree.push_back(std::array<int,2>{{j,i-j}});
}
}
return degree;
}
//gives the GLL weights and points (naive way, can be made generic)
void computeDOF(std::vector<Point> const & points,unsigned int k,std::vector<double> & weights,std::vector<Point> & nodes){
std::vector<double> W,N;
double length;
nodes.clear(); weights.clear();
if (k==1) {W.push_back(1.0); W.push_back(1.0);}
if (k==2) {N.push_back(0.0); W.push_back(1.0/3.0); W.push_back(4.0/3.0); W.push_back(1.0/3.0);}
if (k==3) {N.push_back(-1.0/std::sqrt(5.0)); N.push_back(1.0/std::sqrt(5.0));
W.push_back(1.0/6.0); W.push_back(5.0/6.0); W.push_back(5.0/6.0); W.push_back(1.0/6.0);}
if (k==4) {N.push_back(-std::sqrt(3.0/7.0)); N.push_back(0.0); N.push_back(std::sqrt(3.0/7.0));
W.push_back(1.0/10.0); W.push_back(49.0/90.0); W.push_back(32.0/45.0); W.push_back(49.0/90.0); W.push_back(1.0/10.0);}
if (k>=5) {std::cout<<"Error"<<std::endl; return;}
//loop over all edges
for (unsigned int i=0; i<points.size(); ++i){
Point a=points[i], b=points[(i+1)%points.size()];
length=distance(a,b);
//map nodes and weights on each edge
weights.push_back(length/2*W[0]);
for (unsigned int j=0; j<N.size(); ++j) {
nodes.push_back(Point((b[0]-a[0])/2*(1+N[j])+a[0],(b[1]-a[1])/2*(1+N[j])+a[1]));
weights.push_back(length/2*W[j+1]);
}
weights.push_back(length/2*W[W.size()-1]);
}
return;
}
| true |
84548beda728a9f79e0b9af93b67cf462a6094aa | C++ | danjr26/game-engine | /Utilities/include/internal/misc.h | UTF-8 | 3,303 | 2.640625 | 3 | [] | no_license | #ifndef MISC_H
#define MISC_H
#include <random>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <iostream>
#include "windows_misc.h"
#include "definitions.h"
#define fail() exit(fprintf(stdout, "error @%s:%d\nwin: %s", __FILE__, __LINE__, getWindowsErrorMessage().c_str()) & std::cin.get())
inline void fileToString(const std::string& i_filename, std::string& o_data) {
std::ifstream file;
file.open(i_filename);
if (!file.is_open()) fail();
std::stringstream ss;
ss << file.rdbuf();
o_data = ss.str();
}
template<class T>
inline T clamp(T n, T floor, T ceiling) {
if (n < floor)
return floor;
if (n > ceiling)
return ceiling;
return n;
}
template<class T>
inline T regress(T start, T step, T towards) {
step = (step < 0) ? -step : step;
if (start > towards + step) return start - step;
else if (start < towards - step) return start + step;
return towards;
}
template<class T>
inline T mean(T a, T b) {
return (a + b) * 0.5;
}
template<class T>
inline bool betwExc(T a, T b1, T b2) {
if (b1 < b2) {
return a > b1 && a < b2;
}
else {
return a > b2 && a < b1;
}
}
template<class T>
inline bool betwInc(T a, T b1, T b2) {
if (b1 < b2) {
return a >= b1 && a <= b2;
}
else {
return a >= b2 && a <= b1;
}
}
template<class T>
inline T diff(T a, T b) {
return (a > b) ? (a - b) : (b - a);
}
template<class T>
inline T closest(T t, T a, T b) {
return (diff(t, a) > diff(t, b)) ? b : a;
}
template<class T>
inline T farthest(T t, T a, T b) {
return (diff(t, a) < diff(t, b)) ? b : a;
}
template<class T>
inline int compare(T a, T b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
template<class T>
inline bool ceqSwitch(T a, T b, bool geq) {
return (geq) ? a >= b : a <= b;
}
template<class T>
inline T lerp(T a, T b, T t) {
return a * (1 - t) + b * t;
}
template<class T>
inline T invLerp(T a, T b, T t) {
return (a == b) ? 0 : (t - a) / (b - a);
}
template<class T>
inline T lerp(T a, T b, T t, T ta, T tb) {
return lerp(a, b, invLerp(ta, tb, t));
}
template<class T>
inline T cerp(T a, T b, T t) {
return lerp<T>(a, b, t * t * (3 - 2 * t));
}
template<class T>
inline T qerp(T a, T b, T t) {
return lerp<T>(a, b, t * t * t * (10 + t * (-15 + t * 6)));
}
template<class T>
inline T sign(T n) {
return (n > (T)0) ? (T)1 : ((n < (T)0) ? (T)-1 : (T)0);
}
template<class T>
inline uint solveQuadratic(T a, T b, T c, T& x1, T& x2) {
T disc = b * b - 4 * a * c;
if (disc < 0) return 0;
T sqrtDisc = sqrt(disc);
T denom = 1 / (2 * a);
x1 = (-b - sqrtDisc) * denom;
x2 = (-b + sqrtDisc) * denom;
return (disc == 0) ? 1 : 2;
}
template<class T>
T random();
template<> bool random<bool>();
template<> uint random<uint>();
template<> int random<int>();
template<> ullong random<ullong>();
template<> llong random<llong>();
template<class T>
T random(T high);
template<> uint random<uint>(uint);
template<> int random<int>(int);
template<> ullong random<ullong>(ullong);
template<> llong random<llong>(llong);
template<> float random<float>(float);
template<> double random<double>(double);
template<class T>
T random(T low, T high);
template<class T>
inline T gauss() {
static std::default_random_engine generator;
static std::normal_distribution<T> distribution;
return distribution(generator);
}
#endif
| true |
17b266fdd01a0018d45bbf4fd6975b08cc525d75 | C++ | euns2ol/algo | /백준/dp/11057/11057/소스.cpp | UTF-8 | 462 | 2.515625 | 3 | [] | no_license | #include <iostream>
using namespace std;
long long arr[1001][10] = { 0 };
int main() {
int N;
cin >> N;
for (int i = 0; i <= 9; i++)
arr[1][i] = 1;
for (int i = 2; i <= N; i++) {
for (int j = 0; j <= 9; j++) {
for (int k = j; k <= 9; k++) {
arr[i][j] += arr[i-1][k];
arr[i][j] %= 10007;
}
}
}
long long ans=0;
for (int i = 0; i <= 9; i++) {
ans += arr[N][i];
}
ans %= 10007;
cout << ans << endl;
return 0;
} | true |
cfc3a4c61ec18948b857789bcc24642b953a6441 | C++ | 021800527/C-Review | /5.5.1_BST.cpp | UTF-8 | 926 | 3.328125 | 3 | [] | no_license | #include <iostream>
using namespace std;
typedef struct BSTNode{
int data;
struct BSTNode *lchild,*rchild;
}BSTNode,*BiTree;
/*
* 查找
*/
BSTNode *BST_Search(BiTree T , int key , BSTNode *&p){
p = NULL;
while (T!=NULL && key != T ->data){
p = T;
if (key < T ->data)
T = T ->lchild;
else
T = T ->rchild;
}
return T;
}
/*
* 插入
*/
int BST_Insert(BiTree &T , int k){
if (T ==NULL){
T = (BiTree)malloc(sizeof(BSTNode));
T -> data = k;
T ->lchild = T ->rchild = NULL;
return 1;
}
else if (k == T -> data)
return 0;
else if (k < T -> data)
return BST_Insert(T -> lchild,k);
else
return BST_Insert(T -> rchild,k);
}
/*
* 构造
*/
void Create_BST(BiTree &T, int str[] ,int n){
T = NULL;
int i = 0;
while (i<n){
BST_Insert(T,str[i]);
i++;
}
} | true |
45e9dd3c582015248bb4fe2d9a93af094de9066d | C++ | SDPoplar/Binaland | /src/config/ConfigPropertyTpl.cpp | UTF-8 | 3,937 | 2.515625 | 3 | [] | no_license | #include "ConfigItem.h"
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include <iostream>
using namespace SeaDrip::Binaland;
ConfigPropertyTpl::ConfigPropertyTpl( std::string tpl ) : m_b_well_loaded( false )
{
// +f, , class std::string, m_s_input_file, InputFileName, defaultValue
std::vector<std::string> ret;
boost::split( ret, tpl, boost::is_any_of( "," ), boost::token_compress_on );
if( ret.size() < 6 )
{
return;
}
this->m_s_shell_flag = ret[ 0 ];
this->m_s_config_file_item = ret[ 1 ];
this->m_s_property_type = ret[ 2 ];
this->m_s_property_name = ret[ 3 ];
this->m_s_method_name = ret[ 4 ];
this->m_s_default_value = ret[ 5 ];
this->m_b_well_loaded = true;
if( this->HasDefVal() )
{
return;
}
if( boost::iends_with( this->m_s_property_type, "string" ) )
{
this->m_s_default_value = "\"\"";
return;
}
if( boost::ends_with( this->m_s_property_type, "*" ) )
{
this->m_s_default_value = "nullptr";
}
}
bool ConfigPropertyTpl::IsValid( void ) const noexcept
{
return !( !this->m_b_well_loaded
|| ( this->m_s_shell_flag == "c" )
|| this->m_s_property_type.empty()
|| this->m_s_property_name.empty()
|| this->m_s_method_name.empty()
|| false );
}
bool ConfigPropertyTpl::IsBoolProperty( void ) const noexcept
{
return this->m_s_property_type == "bool";
}
std::string ConfigPropertyTpl::GetPropertyType( void ) const noexcept
{
return this->m_s_property_type;
}
bool ConfigPropertyTpl::CanBeSetByConfigFile( void ) const noexcept
{
return !this->m_s_config_file_item.empty();
}
bool ConfigPropertyTpl::CanBeSetByShell( void ) const noexcept
{
return !this->m_s_shell_flag.empty();
}
bool ConfigPropertyTpl::HasDefVal( void ) const noexcept
{
return !this->m_s_default_value.empty();
}
std::string ConfigPropertyTpl::GetDeclears( void ) const noexcept
{
return "\n// Declear " + this->m_s_property_name + "\npublic:\n " + this->GetMethodDeclear() + "\nprotected:\n " + this->GetPropertyDeclear();
}
std::string ConfigPropertyTpl::GetMethodDeclear() const noexcept
{
std::string ret = this->m_s_property_type + ( this->IsBoolProperty() ? " Is" : " Get" )
+ this->m_s_method_name + "( void ) const noexcept;\n void Set"
+ this->m_s_method_name + "( " + this->m_s_property_type + " );";
return ret;
}
std::string ConfigPropertyTpl::GetPropertyDeclear( void ) const noexcept
{
std::string ret = "TConfigProperty<" + this->m_s_property_type + "> " + this->m_s_property_name + ";";
return ret;
}
std::string ConfigPropertyTpl::GetDefValInit( void ) const noexcept
{
return this->m_s_property_name + "( " + this->m_s_default_value + " )";
}
std::string ConfigPropertyTpl::GetMethodCode( std::string configName ) const noexcept
{
return "void " + configName + "::Set" + this->m_s_method_name + "( " + this->m_s_property_type + " val )\n{\n this->"
+ this->m_s_property_name + ".Set( EConfigSetFrom::RUNTIME, val );\n}\n\n" + this->m_s_property_type + " " + configName
+ ( this->IsBoolProperty() ? "::Is" : "::Get" ) + this->m_s_method_name + "( void ) const noexcept\n{\n return this->"
+ this->m_s_property_name + ".Get();\n}\n";
}
std::string ConfigPropertyTpl::GetShellOption( void ) const noexcept
{
return this->m_s_shell_flag + ( this->IsBoolProperty() ? "" : ":" );
}
std::string ConfigPropertyTpl::GetShellOverrideCase() const noexcept
{
return "case '" + this->m_s_shell_flag + "': this->" + this->m_s_property_name + ".Set( EConfigSetFrom::SHELL, "
+ ( this->IsBoolProperty() ? "true" : "optarg" ) + " ); break;\n";
}
std::string ConfigPropertyTpl::GetBoolShellSetter( void ) const noexcept
{
return "this->m_map_bool_props[ '" + this->m_s_shell_flag + "' ] = &this->" + this->m_s_property_name + ";";
}
| true |
cc9ce30ba9ad4f9b6928a34dad3b2abaa2d6f913 | C++ | nathaliandrad/hell_dimension_game | /Game Project/Game Project/IdleGameState.cpp | UTF-8 | 487 | 2.5625 | 3 | [] | no_license | #include "IdleGameState.h"
#include "Entity.h"
IdleGameState::IdleGameState()
{
}
IdleGameState::~IdleGameState()
{
}
void IdleGameState::update(float dt){
idleTimer -= dt;
if (idleTimer <= 0){
done = true;
}
}
void IdleGameState::render(){
}
bool IdleGameState::onEnter(){
idleTimer = rand() % 20 + 1;//1 - 10 seconds of idle time
done = false;
return true;
}
bool IdleGameState::onExit(){
return true;
}
std::string IdleGameState::getStateID(){
return "idleState";
}
| true |
bb72f97a336d980de7a0188dd45ad77305a74c64 | C++ | Fox-Rain/C_Plus_Plus | /C++/050 new와 delete 동적할당.cpp | UHC | 1,696 | 3.578125 | 4 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
// int var;
// var = 7; Ʒ new int ̿ .
int *ptr = new int; // new int? osκ ƿ 4bytesũ ּ
*ptr = 7; // ptr de-referenceϿ 7
// int *ptr = new int(7); <<< ̷ ѹ
cout << ptr << endl; // os Ҵ (new int) ּҰ µ
cout << *ptr << endl; // os Ҵ ּҿ ִ 7 µ
// os ٽ ֱ (ʴ os ֱ)
delete ptr;
ptr = nullptr;
// memory leak " " <ſ >
while (1) // ̷ԵǸ os ּҴ Ҵµ, ʴ ѷ Ͼ.
{ // غ 뷮 Ѵ 뷮 þ ִ.
int *ptr = new int;
cout << ptr << endl;
// delete ptr; <<<<<<< ****(ذ) ̰ ָ ٷιٷ ּҸ os ٽ ֹǷ 뷮 Ȯ ϰ ȴ.
}
// int *ptr = new int; Ҵް delete ptr; ٽ ְ.. ݺϹǷ 뷮 .
// *** new int delete os ְǷ ð ɸ ̴. ʿ α new int delete
// *** ϴ αϴ° ߿ϴ. ( ȭ )
return 0;
} | true |
fe0dd39f497b8c2db60de0a944edb17ee2a602f0 | C++ | JMAR-DNY/School_CPlusPlus | /CS121_LABS/Lab 4/Lab 4.cpp | UTF-8 | 574 | 3.53125 | 4 | [] | no_license | //***************************
//Jeffrey Marron
//CS - 121
//Mr. Mackay
//Lab 4
//10/15/2014
//***************************
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num, remainder;
string x, y;
cout << "Please input an integer: ";
cin >> num;
remainder = num % 2;
if (num > 0)
x = "positive";
else if (num < 0)
x = "negative";
else
x = "zero";
if (remainder == 0)
y = "even";
else
y = "odd";
cout << "The number " << num << " is: " << x << " and " << y << endl << endl;
return 0;
} | true |
eb8c0f37d59b7d05bc5263ebe34c7b9a79f162b5 | C++ | twonaja/Lab3-OOP- | /Point.cpp | WINDOWS-1251 | 1,259 | 3.703125 | 4 | [] | no_license | #include "Point.h"
Point::Point(int x, int y)
{
this->m_x = x;
this->m_y = y;
}
const Point& Point::operator+=(const Point& rObj)
{
if (this != &rObj)
{
this->m_x += rObj.m_x;
this->m_y += rObj.m_y;
return *this;
}// TODO: return
return *this;
}
Point Point::operator+=(const int& tmp)
{
return Point(this->m_x + tmp, this->m_y);
}
const Point& Point::operator+(const Point& rObj)
{
if (this != &rObj)
{
this->m_x += rObj.m_x;
this->m_y += rObj.m_y;
return *this;
}// TODO: return
return *this;
}
const Point& Point::operator-(const Point& rObj)
{
if (this != &rObj)
{
this->m_x -= rObj.m_x;
this->m_y -= rObj.m_y;
return *this;
}
return *this;
// TODO: return
}
Point Point::operator+(const int& tmp)
{
return Point(this->m_x + tmp, this->m_y);
}
Point Point::operator-(const int& tmp)
{
return Point(this->m_x - tmp, this->m_y - tmp);
}
Point operator+(int tmp, const Point& rObj)
{
return Point(tmp + rObj.m_x, tmp + rObj.m_y);
}
const Point& operator+(const Point& rObj)
{
return rObj;
}
const Point& operator-(const Point& rObj)
{
return Point( -rObj.m_x, -rObj.m_y);
}
| true |
5529086d7b62fe656ff99c3a2d128c209ac4bd1f | C++ | Graphics-Physics-Libraries/RenderLibrary | /TFMEngine/src/SceneObject.cpp | UTF-8 | 1,635 | 2.625 | 3 | [] | no_license | #include "SceneObject.h"
#include "EngineInstance.h"
#include "SceneManager.h"
namespace RenderLib
{
SceneObject::SceneObject() : initialized(false), parent(NULL)
{
transform.object = this;
transform.update();
}
SceneObject::~SceneObject()
{
}
void
SceneObject::initialize()
{
initialized = true;
}
ComponentList &
SceneObject::getComponentList()
{
return componentList;
}
void
SceneObject::setParent(SceneObject * parentToBe)
{
if (parentToBe == this)
{
return;
}
if (this->parent != NULL)
{
this->parent->removeChildren(this);
}
// Avoid circular dependency
if (parentToBe != NULL && parentToBe->parent != this)
{
this->parent = parentToBe;
parentToBe->children.push_back(this);
}
}
void
SceneObject::addChildren(SceneObject * object)
{
if (object == this)
{
return;
}
if (object != NULL)
{
if (object->parent != NULL && object->parent != this)
{
object->parent->removeChildren(object);
}
object->parent = this;
object->children.push_back(object);
}
}
SceneObject *
SceneObject::getParent()
{
return parent;
}
std::vector<SceneObject *> &
SceneObject::getChildren()
{
return children;
}
void
SceneObject::removeChildren(SceneObject * object)
{
if (object->parent == this)
{
auto it = children.begin();
while (it != children.end())
{
if ((*it) == object)
{
children.erase(it);
break;
}
}
}
}
} // namespace RenderLib | true |
1d769e7096c49f76649c6bde7a6c83a4eca7da6e | C++ | Caster89/Sql_Data | /mystackedwidget.cpp | UTF-8 | 1,049 | 2.75 | 3 | [] | no_license | #include "mystackedwidget.h"
#include <QDebug>
#include <QVBoxLayout>
MyStackedWidget::MyStackedWidget(QWidget * parent, Qt::WindowFlags f)
: QWidget(parent, f),
curr_index(0)
{
}
int MyStackedWidget::count()
{ return widgets.count(); }
void MyStackedWidget::addWidget(QWidget * w)
{
widgets.append(w);
layout->addWidget(w);
showCurrentWidget();
}
QWidget * MyStackedWidget::currentWidget()
{ return widgets.at(curr_index); }
void MyStackedWidget::setCurrentIndex(int i)
{
curr_index = i;
showCurrentWidget();
}
void MyStackedWidget::showCurrentWidget()
{
if (widgets.count() > 0)
{
foreach (QWidget * widget, widgets)
widget->hide();
widgets.at(curr_index)->show();
updateGeometry();
}
}
QSize MyStackedWidget::sizeHint()
{
if (auto_resize
&& count() > 0)
return currentWidget()->minimumSize();
else
return QWidget::sizeHint();
}
| true |
c00fa471fd6af1a3d76555a27d81b0c9456ace3b | C++ | Winterpuma/bmstu_OOP | /lab4/iterator/cameraiterator.cpp | UTF-8 | 1,042 | 3.015625 | 3 | [
"MIT"
] | permissive | #include "cameraiterator.h"
#include "scene.h"
#include <iostream>
CameraIterator::CameraIterator()
{
this->scene = nullptr;
this->current_child = std::shared_ptr<ObjectPosition>(nullptr);
}
CameraIterator::CameraIterator(Scene *_ch)
{
this->scene = _ch;
if (this->scene->cameras.size() > 0)
this->current_child = this->scene->cameras[0];
else
this->current_child = std::shared_ptr<ObjectPosition>(nullptr);
}
ObjectPosition &CameraIterator::operator *()
{
return *(this->current_child.lock().get());
}
ObjectPosition *CameraIterator::operator ->()
{
return this->current_child.lock().get();
}
CameraIterator &CameraIterator::operator ++()
{
this->child_id++;
if (this->child_id >= this->scene->cameras.size())
this->current_child = std::shared_ptr<ObjectPosition>(nullptr);
else
this->current_child = this->scene->cameras[this->child_id];
return *this;
}
bool CameraIterator::operator !=(CameraIterator &iter)
{
return this->child_id != iter.child_id;
}
| true |
ce0c1aa741a351f6b5e855c90d4a29a5d6e36d54 | C++ | i0r/i0rTech | /OpenGL/FrameBuffer.cpp | UTF-8 | 8,643 | 2.515625 | 3 | [
"BSD-3-Clause",
"Zlib"
] | permissive | #include "Common.hpp"
#include "FrameBuffer.hpp"
FrameBuffer::FrameBuffer( const i32 frameWidth, const i32 frameHeight ) : m_Object( 0 ),
m_DepthAttachement( { 0, false } ) {
m_FrameWidth = frameWidth;
m_FrameHeight = frameHeight;
glGenFramebuffers( 1, &m_Object );
}
FrameBuffer::FrameBuffer() : m_Object( 0 ),
m_DepthAttachement( { 0, false } ) {
m_FrameWidth = 0;
m_FrameHeight = 0;
}
FrameBuffer::~FrameBuffer() {
if( m_DepthAttachement.Attachement && !m_DepthAttachement.IsShared ) {
glDeleteTextures( 1, &m_DepthAttachement.Attachement );
m_DepthAttachement.Attachement = 0;
}
for( framebuffer_attachement_t attachement : m_Attachements ) {
if( !attachement.IsShared ) {
glDeleteTextures( 1, &attachement.Attachement );
}
attachement.Attachement = 0;
}
m_Attachements.clear();
glDeleteFramebuffers( 1, &m_Object );
m_Object = 0;
}
bool FrameBuffer::Build() {
GLenum* buffers = new GLenum[m_Attachements.size()];
for( u32 i = 0; i < m_Attachements.size(); ++i ) {
buffers[i] = ( GL_COLOR_ATTACHMENT0 + i );
}
glDrawBuffers( (i32)m_Attachements.size(), buffers );
delete[] buffers;
return ( glCheckFramebufferStatus( GL_FRAMEBUFFER ) == GL_FRAMEBUFFER_COMPLETE );
}
void FrameBuffer::BindAttachement( const u32 attachementIndex, const i32 attachementSlot ) {
if( attachementIndex >= m_Attachements.size() ) {
CONSOLE_PRINT_ERROR( "FrameBuffer::BindAttachement => Attachement index %i out of bounds!\n", attachementIndex );
return;
}
glActiveTexture( attachementSlot );
glBindTexture( GL_TEXTURE_2D, m_Attachements[attachementIndex].Attachement );
}
void FrameBuffer::BindDepthAttachement( const i32 attachementSlot ) {
if( !m_DepthAttachement.Attachement ) {
CONSOLE_PRINT_ERROR( "FrameBuffer::BindDepthAttachement => Framebuffer %i have no depth buffer registered!\n", m_Object );
return;
}
glActiveTexture( attachementSlot );
glBindTexture( GL_TEXTURE_2D, m_DepthAttachement.Attachement );
}
void FrameBuffer::AttachDepth( const i32 depthAttachement ) {
m_DepthAttachement.Attachement = depthAttachement;
m_DepthAttachement.IsShared = true;
glBindTexture( GL_TEXTURE_2D, m_DepthAttachement.Attachement );
const static GLfloat borderColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glTexParameterfv( GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor );
glFramebufferTexture2D( GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_DepthAttachement.Attachement, 0 );
}
void FrameBuffer::TemporaryAttach2D( const GLuint attachement, const GLuint stencil ) {
for( i32 i = 0; i < m_Attachements.size(); ++i ) {
glFramebufferTexture( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, 0, 0 );
}
m_Attachements.clear();
if( m_Object ) {
glDeleteFramebuffers( 1, &m_Object );
m_Object = NULL;
}
glGenFramebuffers( 1, &m_Object );
glBindFramebuffer( GL_FRAMEBUFFER, m_Object );
if( stencil ) {
AttachDepth( stencil );
}
glDrawBuffer( GL_COLOR_ATTACHMENT0 );
GLenum buffers[1] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers( 1, buffers );
glBindTexture( GL_TEXTURE_2D, attachement );
framebuffer_attachement_t attach = {
attachement,
false
};
m_Attachements.push_back( attach );
glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + ( GLenum )m_Attachements.size() - 1, GL_TEXTURE_2D,
attachement, 0 );
}
void FrameBuffer::Attach2D( const u32 attachement ) {
const framebuffer_attachement_t attachement2D = { attachement, true };
glBindTexture( GL_TEXTURE_2D, attachement2D.Attachement );
glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + (i32)m_Attachements.size(), GL_TEXTURE_2D,
attachement2D.Attachement, 0 );
m_Attachements.push_back( attachement2D );
}
void FrameBuffer::Attach3D( const u32 attachement ) {
const framebuffer_attachement_t attachement3D = { attachement, true };
glBindTexture( GL_TEXTURE_3D, attachement3D.Attachement );
glFramebufferTexture3D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + (i32)m_Attachements.size(), GL_TEXTURE_3D,
attachement3D.Attachement, 0, 0 );
m_Attachements.push_back( attachement3D );
}
void FrameBuffer::AddAttachementDepth( const GLint depthInternalFormat, const i32 depthType,
const GLint textureWrapping ) {
if( m_DepthAttachement.Attachement ) {
CONSOLE_PRINT_WARNING( "FrameBuffer::AddAttachementDepth => Framebuffer %i already have a depth buffer registered!\n",
m_Object );
return;
}
glGenTextures( 1, &m_DepthAttachement.Attachement );
glBindTexture( GL_TEXTURE_2D, m_DepthAttachement.Attachement );
glTexImage2D( GL_TEXTURE_2D, 0, depthInternalFormat, m_FrameWidth, m_FrameHeight, 0, GL_DEPTH_COMPONENT, depthType, 0 );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, textureWrapping );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, textureWrapping );
const static GLfloat borderColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glTexParameterfv( GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor );
glFramebufferTexture2D( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_DepthAttachement.Attachement, 0 );
}
void FrameBuffer::AddAttachement2D( const GLint internalFormat, const i32 format, const i32 type, const GLint textureWrapping,
const void* data, const GLint border ) {
framebuffer_attachement_t attachement = { 0, false };
glGenTextures( 1, &attachement.Attachement );
glBindTexture( GL_TEXTURE_2D, attachement.Attachement );
glTexImage2D( GL_TEXTURE_2D, 0, internalFormat, m_FrameWidth, m_FrameHeight, border, format, type, data );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, textureWrapping );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, textureWrapping );
glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + (i32)m_Attachements.size(), GL_TEXTURE_2D,
attachement.Attachement, 0 );
m_Attachements.push_back( attachement );
}
void FrameBuffer::WriteBuffer( const std::vector<u32> indexes ) {
GLenum* buffers = new GLenum[indexes.size()];
for( u32 i = 0; i < indexes.size(); ++i ) {
buffers[i] = ( GL_COLOR_ATTACHMENT0 + i );
}
glDrawBuffers( (i32)indexes.size(), buffers );
delete[] buffers;
}
void FrameBuffer::BindDepthWrite( const u32 pos ) {
Instance.GraphicsApiContext->UpdateViewport( 0, 0, m_FrameWidth, m_FrameHeight );
glBindFramebuffer( GL_DRAW_FRAMEBUFFER, m_Object );
glFramebufferTextureLayer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, (GLuint)m_DepthAttachement.Attachement, 0, pos );
}
void FrameBuffer::BindDepthMap( const u32 pos ) {
glActiveTexture( pos );
glBindTexture( GL_TEXTURE_2D_ARRAY, (GLuint)m_DepthAttachement.Attachement );
}
void FrameBuffer::AddAttachementDepthArray2D( const i32 depthInternalFormat, const i32 format, const i32 depthType,
const i32 textureWrapping, const i32 layerCount, const void* data,
const i32 border ) {
m_DepthAttachement.IsShared = false;
glGenTextures( 1, &m_DepthAttachement.Attachement );
glBindTexture( GL_TEXTURE_2D_ARRAY, m_DepthAttachement.Attachement );
glTexImage3D( GL_TEXTURE_2D_ARRAY, 0, depthInternalFormat, m_FrameWidth, m_FrameHeight, layerCount, 0,
format, depthType, data );
glTexParameteri( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_R, textureWrapping );
glTexParameteri( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, textureWrapping );
glTexParameteri( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, textureWrapping );
glTexParameteri( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL );
glTexParameterf( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE );
const f32 color[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
glTexParameterfv( GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BORDER_COLOR, color );
glFramebufferTexture( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_DepthAttachement.Attachement, 0 );
glDrawBuffer( GL_NONE );
glReadBuffer( GL_NONE );
} | true |
b7189fe5ae07493473d6e285d6483165ecd7812c | C++ | KShaleev/Reports | /main.cpp | WINDOWS-1251 | 4,949 | 2.765625 | 3 | [] | no_license | /*
" ".
, :
- ;
- ;
- ;
- ;
- .
, , XML Windows-1251.
.
:
<parts_list ...>
<part .../>
<part .../>
...
<part .../>
</parts_list>
"parts_list" - . "root_uid" - .
"part" - , .
:
uid - ;
item_id - ;
rev_id - ;
type - ;
name - ;
desc - .
txt, .
. : < > - < >.txt.
"", .
" ": | | . I8_Assy, sdb_AssyItem, AS2_assembly.
"": | | . I8_Part, sbd_DetailItem, AS2_Detail.
" ": | . I8_PKI, I8_PKI_draft, sdb_PKI, AS2_PKI.
" ": . I8_Sti, sdb_Fast, sdb_Standard, AS2_STI.
" ": | | | | . , .
report_gui.h report_gui.cpp report_GUI, .
class_part.h class_part.cpp part, , , XML-
txt.
reports_generator.h reports_generator.cpp reports_generator,
.
resources.qrc .
*/
#include <QApplication>
#include "report_gui.h" // .
int main(int argc, char * argv[])
{
QApplication report(argc, argv);
report_GUI * rg = new report_GUI;
rg->setWindowIcon(QIcon(":/new/prefix1/Irkut_logo")); // .
rg->setWindowTitle(QString::fromLocal8Bit(" "));
rg->resize(300, 100);
rg->show();
return report.exec();
} | true |
e4ad903fe39c8c5d366604d30f7ffced84396122 | C++ | roneiberlezi/one-real | /map-editor/Source/MapSelection.cpp | UTF-8 | 1,617 | 2.921875 | 3 | [] | no_license | //
// MapSelection.cpp
// Map Editor
//
// Created by Ronei Berlezi on 27/09/14.
// Copyright (c) 2014 Ronei Berlezi. All rights reserved.
//
#include "MapSelection.h"
MapSelection::MapSelection(int tileWidth, int tileHeight){
this->tileHeight = tileHeight;
this->tileWidth = tileWidth;
}
bool MapSelection::updateSelection(int x, int y, int offsetX, int offsetY){
// if ((x >= startPosition.x && y >= startPosition.y) && (offsetX >= startOffset.x && offsetY >= startOffset.y)) {
if ((x + offsetX >= startPosition.x + startOffset.x) && (y + offsetY >= startPosition.y + startOffset.y)) {
rect.x = (startPosition.x - (offsetX - startOffset.x)) * tileWidth;
rect.y = (startPosition.y - (offsetY - startOffset.y)) * tileHeight;
rect.w = tileWidth + (tileWidth * ((x - startPosition.x) + (offsetX - startOffset.x)));
rect.h = tileHeight + (tileHeight * ((y - startPosition.y) +(offsetY - startOffset.y)));
valid = true;
return true;
}else{
valid = false;
return false;
}
}
void MapSelection::startSelection(int x, int y, int offsetX, int offsetY){
startPosition.x = x;
startPosition.y = y;
startOffset.x = offsetX;
startOffset.y = offsetY;
rect.x = x * tileWidth;
rect.y = y * tileHeight;
rect.w = tileWidth;
rect.h = tileHeight;
isSelecting = true;
}
void MapSelection::endSelection(int x, int y, int offsetX, int offsetY){
endPosition.x = x + offsetX;
endPosition.y = y + offsetY;
isSelecting = false;
}
void MapSelection::cancelSelection(){
isSelecting = false;
valid = false;
} | true |
44697c2796217de08485927212e34cd1c3a81af8 | C++ | cristianfrasineanu/stackplusplus | /app/QuestionModel.cpp | UTF-8 | 5,545 | 2.796875 | 3 | [] | no_license | #include "QuestionModel.h"
Question QuestionModel::setAfterUserId(int userId)
{
this->io.seekg(0, this->io.beg);
while (this->io.read(reinterpret_cast<char *>(&this->question), sizeof(question)))
{
if (this->question.user_id == userId)
{
return this->question;
}
}
throw invalid_argument("Question not found!");
}
Question QuestionModel::setAfterId(int id)
{
this->io.seekg((id - 1) * sizeof(Question), this->io.beg);
this->io.read(reinterpret_cast<char *>(&this->question), sizeof(Question));
return this->question;
}
bool QuestionModel::setActiveIfAny()
{
if (this->question.active == true)
{
return true;
}
this->io.seekg(0, this->io.beg);
while (this->io.read(reinterpret_cast<char *>(&this->question), sizeof(Question)))
{
if (this->question.active == true)
{
return true;
}
}
return false;
}
vector<Question> QuestionModel::retrieveAll()
{
vector<Question> questions;
this->io.seekg(0, this->io.beg);
while (this->io.read(reinterpret_cast<char *>(&this->question), sizeof(Question)))
{
if (string(this->question.deleted_at) == "")
{
questions.push_back(this->question);
}
}
return questions;
}
vector<Question> QuestionModel::retrieveForUserId(int userId)
{
vector<Question> userQuestions;
this->io.seekg(0, this->io.beg);
while (this->io.read(reinterpret_cast<char *>(&this->question), sizeof(Question)))
{
if (this->question.user_id == userId)
{
userQuestions.push_back(this->question);
}
}
return userQuestions;
}
int QuestionModel::getId()
{
return this->question.id;
}
char *QuestionModel::getTitle()
{
return this->question.title;
}
char *QuestionModel::getBody()
{
return this->question.body;
}
char *QuestionModel::getCategory()
{
return "category";
}
bool QuestionModel::questionTitleExists(string &title)
{
Question question;
this->io.seekg(0, this->io.beg);
while (this->io.read(reinterpret_cast<char *>(&question), sizeof(Question)))
{
if (question.title == title)
{
return true;
}
}
return false;
}
void QuestionModel::markAnswered(int id)
{
this->setAfterId(id);
this->question.hasAnswer = true;
this->save();
}
void QuestionModel::markAs(const string &status, int id)
{
if (id != NULL)
{
this->setAfterId(id);
}
this->question.active = (status == "active") ? true : false;
this->save();
}
// Serialize the question.
void QuestionModel::save()
{
this->io.seekp((this->question.id - 1) * sizeof(Question), this->io.beg);
this->io.clear();
if (!this->io.write(reinterpret_cast<char *>(&this->question), sizeof(Question)))
{
throw system_error(error_code(3, generic_category()), "Failed persisting data to file!");
}
// Flush the buffer and update the destination.
this->io.flush();
}
void QuestionModel::setAttributes(map<string, string> &cleanInputs)
{
for (map<string, string>::iterator it = cleanInputs.begin(); it != cleanInputs.end(); it++)
{
if (isInVector(this->protectedAttributes, it->first))
{
continue;
}
else if (it->first == "title")
{
strcpy(this->question.title, it->second.c_str());
}
else if (it->first == "body")
{
strcpy(this->question.body, it->second.c_str());
}
else if (it->first == "userId")
{
this->question.user_id = atoi(it->second.c_str());
}
else if (it->first == "category")
{
this->question.category_id = 1;
// TODO: get the id from the category model.
}
}
// If there's a new user, assign created_at with the current date.
if (cleanInputs.find("action")->second == "create")
{
time_t t = time(nullptr);
strftime(this->question.created_at, sizeof(this->question.created_at), "%c", localtime(&t));
this->question.active = true;
}
this->question.id = ++this->lastId;
}
void QuestionModel::dumpFile()
{
Question question;
ifstream db(QuestionModel::pathToFile, ios::in | ios::binary);
ofstream dump((QuestionModel::pathToFile.substr(0, QuestionModel::pathToFile.find(".store")).append(".txt")), ios::out | ios::trunc);
if (db.is_open() && dump.is_open())
{
db.seekg(0, db.beg);
while (db.read(reinterpret_cast<char *>(&question), sizeof(Question)))
{
dump << "Id: " << question.id << endl
<< "User ID: " << question.user_id << endl
<< "Category ID: " << question.category_id << endl
<< "Votes: " << question.votes << endl
<< "Title: " << question.title << endl
<< "Body: " << question.body << endl
<< "Created at: " << question.created_at << endl
<< "Deleted at: " << question.deleted_at << endl
<< "Has answer: " << question.hasAnswer << endl
<< "Active: " << question.active << endl << endl;
}
db.close();
dump.close();
}
}
QuestionModel::~QuestionModel()
{
this->io.close();
}
string QuestionModel::pathToFile = "..\\database\\questions.store";
void QuestionModel::openIOStream()
{
this->io.open(QuestionModel::pathToFile, ios::in | ios::out | ios::binary);
this->io.seekp(0, this->io.end);
this->fileSize = this->io.tellp();
if (!this->io.is_open())
{
toast(string("Couldn't open the file stream!"), string("error"));
}
}
void QuestionModel::setLastId()
{
if (this->fileSize == 0)
{
this->lastId = 0;
}
else
{
this->io.seekg((this->fileSize / sizeof(Question) - 1) * sizeof(Question), this->io.beg);
this->io.read(reinterpret_cast<char *>(&this->question), sizeof(Question));
this->lastId = this->question.id;
}
}
QuestionModel::QuestionModel()
{
this->openIOStream();
this->protectedAttributes = { "id", "user_id", "category_id", "created_at", "deleted_at", "votes", "hasAnswer" };
this->setLastId();
}
| true |
8ded8f10ad347879a59eb445de1370f591a32042 | C++ | yikouniao/basic-surpervised-classifications | /h-k/H-K.cpp | UTF-8 | 3,121 | 2.59375 | 3 | [] | no_license | #include "H-K.h"
#include <iostream>
#include <fstream>
namespace HK {
using namespace std;
using namespace Eigen;
void InitDatSet(DatSet& ds, char* f_name) {
ifstream f(f_name);
if (!f)
{
cerr << f_name << " could not be opened!\n" << endl;
exit(1);
}
array<double, 2> xy;
array<char, 5> c;
while (1) {
f.getline(&c[0], 65532, '\t'); // read x_
if (c[0] == '#')
break;
xy[0] = char2double(&c[0]);
f.getline(&c[0], 65532, '\t'); // read y_
xy[1] = char2double(&c[0]);
f.getline(&c[0], 65532, '\n'); // read type_
DatType dat_type;
if (c[0] == 'a') {
dat_type = TYPE_A;
} else if (c[0] == 'b') {
dat_type = TYPE_B;
} else {
dat_type = TYPE_ALL;
}
ds.push_back(Dat{ xy, dat_type });
} // while (1)
}
static double char2double(char* s) {
char* p{ s }; // save the start position of the string
double a{ 0 };
while (*s) { // let s point to '\0'
++s;
}
int i{ 0 };
while (!(--s < p)) {
a += (*s - 48) * pow(10, i++);
}
return a;
}
D_F::D_F()
{
w_ = Vector3d(0,0,0);
p_ = 1;
threshold_ = 0.1;
}
D_F::~D_F() {}
void D_F::SetP(double p) {
p_ = p;
}
void D_F::SetThreshold(double threshold) {
threshold_ = threshold;
}
void D_F::Train(DatSet& ds) {
MatrixXd X(ds.size(), 3); // data
VectorXd b(ds.size()); // margin vector
for (unsigned int i = 0; i < ds.size(); ++i) {
X.row(i) = (ds[i].type_ == TYPE_A) ? ds[i].xy_ : -ds[i].xy_;
b(i) = 1;
}
std::cout << "X\n" << X << '\n';
std::cout << "b\n" << b << '\n';
// pseudo-inverse matrix
MatrixXd X_pi = (X.transpose() * X).inverse() * X.transpose();
std::cout << "X+\n" << X_pi<< '\n';
MatrixXd e(ds.size(), 1); // error vector
w_ = X_pi * b;
e = X * w_ - b;
std::cout << "w\n" << w_ << '\n';
std::cout << "e\n" << e << '\n';
while (!IsLittle(e, threshold_)) {
w_ += p_ * X_pi * (e + e.cwiseAbs());
b += p_ * (e + e.cwiseAbs());
w_ = X_pi * b;
e = X * w_ - b;
}
}
void D_F::Test(DatSet& ds) {
for (auto& e : ds) {
double d; // discriminant function
d = w_.transpose() * e.xy_;
e.type_ = (d > 0) ? TYPE_A : TYPE_B;
}
}
void D_F::Out() {
cout << "\nH-K algorithm's discriminant parameter:\n";
cout << "w: [" << w_.transpose() << "]'\n";
}
void D_F::ErrRate(DatSet& standard, DatSet& comparison) {
cout << "\nH-K algorithm error rate:\n";
array<int, TYPE_ALL_PLUS_1> n;
array<int, TYPE_ALL_PLUS_1> n_err;
array<double, TYPE_ALL_PLUS_1> rate_err;
n.fill(0);
n_err.fill(0);
rate_err.fill(0);
for (unsigned int i = 0; i < standard.size(); ++i) {
if (standard[i].type_ != comparison[i].type_) {
++(n_err[standard[i].type_]);
++(n_err[TYPE_ALL]);
}
++(n[standard[i].type_]);
++(n[TYPE_ALL]);
}
cout << "\nType\tError/Total num\tError rate\n";
for (int i = 0; i < TYPE_ALL_PLUS_1; ++i) {
rate_err[i] = static_cast<double>(n_err[i]) / n[i];
(i == TYPE_ALL) ? cout << "all:\t" : cout << i + 1 << ":\t";
cout << n_err[i] << "/" << n[i] << "\t\t";
cout << rate_err[i] * 100 << "%\n";
}
}
} // namespace HK | true |
ad0b0571724f43a52d3df0bc25df9e2960f3b933 | C++ | sevakon/2nd-semester-ITMO-Cplusplus-labs | /Lab3/methods.cpp | UTF-8 | 1,177 | 3.421875 | 3 | [] | no_license | //
// methods.cpp
// secondSemesterThirdLab
//
// Copyright © 2019 Vsevolod Konyakhin. All rights reserved.
//
#include <stdio.h>
#include <string>
#include "header.h"
#include <iostream>
using namespace std;
Queue::Queue(Queue &q) : queueSize(q.queueSize){
queue = new string[queueSize];
head = 0;
tail = 0;
}
Queue::Queue(int size) : queueSize(size){
queue = new string[queueSize];
head = 0;
tail = 0;
}
Queue::Queue() : queueSize(10) {
queue = new string[queueSize];
head = 0;
tail = 0;
}
int Queue::length() {
return tail - head;
}
void Queue::push(string line) {
if(line.length() > 255)
cout << "String is too big" << endl;
else{
tail++;
if (tail == queueSize)
tail = 0;
queue [tail] = line;
}
}
void Queue::pop() {
if (head == tail)
cout << "Queue is empty" << endl;
else {
head++;
if (head == queueSize)
head = 0;
}
}
void Queue::show() {
for(int i = head + 1; i <= tail; i++)
cout << queue[i] << endl;
}
string Queue::first() {
return queue[head + 1];
}
string Queue::last() {
return queue[tail];
}
| true |
67a51aa1cffa4f2eace5ec89a7b6f30871f617ad | C++ | DonCastillo/go-fish-mvc | /test/TestDeck.cpp | UTF-8 | 2,997 | 3.453125 | 3 | [] | no_license | #include <vector>
#include "Deck.h"
#include "Card.h"
#include "gtest/gtest.h"
enum suits { Club, Diamond, Heart, Spade };
enum ranks { Ace = 1, Two, Three, Four, Five, Six,
Seven, Eight, Nine, Ten, Jack, Queen, King };
TEST(TestDeck, createAndClearDeck) {
Deck* deck = new Deck();
deck->createDeck();
// check of a complete deck of card is created
EXPECT_EQ(deck->getDeck().size(), 52);
EXPECT_FALSE(deck->getDeck().empty());
deck->clearDeck();
// check if deck is cleared
EXPECT_EQ(deck->getDeck().size(), 0);
EXPECT_TRUE(deck->getDeck().empty());
deck->createDeck();
// check if deck is created again
EXPECT_EQ(deck->getDeck().size(), 52);
EXPECT_FALSE(deck->getDeck().empty());
delete deck;
}
TEST(TestDeck, shuffle) {
Deck* deck = new Deck();
// test unshuffled
std::vector<Card*>unshuffledCards;
std::vector<Card*>shuffledCards;
std::vector<Card*>original;
deck->createDeck();
for (Card* c : deck->getDeck()) {
unshuffledCards.push_back(c);
}
Card* a = new Card(Club, Ace);
Card* b = new Card(Club, Two);
Card* c = new Card(Club, Three);
Card* d = new Card(Club, Four);
Card* e = new Card(Club, Five);
Card* f = new Card(Club, Six);
Card* g = new Card(Club, Seven);
Card* h = new Card(Club, Eight);
Card* i = new Card(Club, Nine);
Card* j = new Card(Club, Ten);
original.push_back(a);
original.push_back(b);
original.push_back(c);
original.push_back(d);
original.push_back(e);
original.push_back(f);
original.push_back(g);
original.push_back(h);
original.push_back(i);
original.push_back(j);
// compare unshuffled cards and unshuffle compare
for (int i = 0; i < 10; ++i) {
EXPECT_EQ(unshuffledCards[i]->getSuit(),
original[i]->getSuit());
EXPECT_EQ(unshuffledCards[i]->getRank(),
original[i]->getRank());
}
// test shuffled
deck->shuffle();
for (Card* c : deck->getDeck()) {
shuffledCards.push_back(c);
}
int numberOfTrues = 0;
for (int i = 0; i < 10; ++i) {
if (shuffledCards[i]->getSuit() !=
original[i]->getSuit() ||
shuffledCards[i]->getRank() !=
original[i]->getRank()) {
numberOfTrues++;
}
}
// should have 60% trues to be completely shuffled
EXPECT_GT(numberOfTrues, 4);
for (Card* c : original) {
delete c;
}
delete deck;
}
TEST(TestDeck, getTopCard) {
Deck* deck = new Deck();
// check empty deck
deck->clearDeck();
EXPECT_EQ(deck->getTopCard(), nullptr);
// check non empty deck
deck->createDeck();
Card* original = new Card(Spade, King);
Card* topCard = deck->getTopCard();
EXPECT_TRUE(original->getSuit() == topCard->getSuit());
EXPECT_TRUE(original->getRank() == topCard->getRank());
delete original;
delete deck;
}
| true |
6f2d9ddca1d18f43d5c5c533afe019f13af305c1 | C++ | derickfelix/pppucpp_answers | /Part02/11.Customizing-Input-and-Output/ex11.cpp | UTF-8 | 910 | 3.875 | 4 | [] | no_license | /*
Write a function vector<string> split(const string& s, const string& w) that
returns a vector of whitespace-separated substrings from the argument s, where
whitespace is defined as "ordinary whitespace" plus the characters in w.
*/
#include "std_lib_facilities.h"
vector<string> split(const string& s, const string& w)
{
vector<string> split;
istringstream is {s};
for (string w; is >> w; ) {
ostringstream os;
for (char& ch : w) {
if (ch == ',') {
if (os.str() != "") {
split.push_back(os.str());
}
os.str("");
} else {
os << ch;
}
}
if (os.str() != "") {
split.push_back(os.str());
}
}
return split;
}
int main()
{
vector<string> words = split("if you write any,thing on your comp,uter, you'll need to get ,gram,rly,", ",");
for (string& w : words) {
cout << w << '\n';
}
return 0;
}
| true |
4fca91b71f84f9bc0b46f9265f1d73e9e17bea3b | C++ | wang17/nanahan | /map/benchmark.cc | UTF-8 | 2,606 | 2.765625 | 3 | [
"CC-PDDC"
] | permissive | #include <boost/chrono.hpp>
#include <string>
#include <boost/unordered_map.hpp>
#include <boost/lexical_cast.hpp>
#include <tr1/unordered_map>
#include <boost/random.hpp>
#include <google/sparse_hash_map>
#include <google/dense_hash_map>
#include "map.hpp"
using namespace boost::chrono;
using namespace nanahan;
using namespace google;
enum eval_name{
insert,
find,
erase
};
template <typename TargetType>
void measure_speed(const std::string& name,TargetType& target, size_t num, eval_name doing){
boost::mt19937 gen( static_cast<unsigned long>(0) );
boost::uniform_smallint<> dst( 0, 1 << 30 );
boost::variate_generator<boost::mt19937&, boost::uniform_smallint<>
> rand( gen, dst );
system_clock::time_point start = system_clock::now();
switch(doing){
case insert:
for (size_t i = 0; i < num; ++i){
target.insert(std::make_pair(rand(),i));
}
break;
case find:
for (size_t i = 0; i < num; ++i){
target.find(rand());
}
break;
case erase:
{
for (size_t i = 0; i < num; ++i){
size_t r = rand();
if(target.find(r) == target.end()){ continue; }
target.erase(target.find(r));
}
break;
}
default:
std::cout << "invalid target";
}
duration<double> sec = system_clock::now() - start;
std::cout << " " << name << ":" << num << "\t" << int(double(num) / sec.count()) << " qps\n";
}
int main(void)
{
for(int i = 100000; i <= 700000; i += 100000){
for(int j =0; j<10; ++j){
boost::unordered_map<int, int> bmap;
Map<int, int> nmap;
std::tr1::unordered_map<int, int> tmap;
sparse_hash_map<int, int> gsmap;
dense_hash_map<int, int> gdmap;
gdmap.set_empty_key(NULL);
std::cout << "insert:" << std::endl;
measure_speed("nanahan",nmap, i, insert);
/*
measure_speed("boost ",bmap, i, insert);
measure_speed("tr1 ",tmap, i, insert);
measure_speed("g_sparse",gsmap, i, insert);
measure_speed("g_dense",gdmap, i, insert);
std::cout << "find:" << std::endl;
measure_speed("nanahan",nmap, i, find);
measure_speed("boost ",bmap, i, find);
measure_speed("tr1 ",tmap, i, find);
measure_speed("g_sparse",gsmap, i, find);
measure_speed("g_dense",gdmap, i, find);
std::cout << "erase:" << std::endl;
measure_speed("nanahan",nmap, i, erase);
measure_speed("boost ",bmap, i, erase);
measure_speed("tr1 ",tmap, i, erase);
measure_speed("g_sparse",gsmap, i, erase);
measure_speed("g_dense",gdmap, i, erase);
*/
}
}
}
| true |
f6eb4b73f858be4862c0733466bb4eaaad881654 | C++ | prgwiz/lurker-ng | /reg2c/sml/grep.cpp | UTF-8 | 1,263 | 2.796875 | 3 | [] | no_license | #define longfn find_url_end
#define scanner find_url_starts
#include <string>
#include <cstdio>
#include <cstdlib>
using namespace std;
extern char* scanner(const char* start, const char* end);
extern const char* longfn(const char* start, const char* end);
void dump_yes(const char* start, const char* end) {
fwrite(start, 1, end-start, stdout);
fwrite(start, 1, end-start, stderr);
fputc('\n', stderr);
}
void dump_no(const char* start, const char* end) {
fwrite(start, 1, end-start, stdout);
}
void process(const char* start, const char* end) {
char* map_start = scanner(start, end);
char* map_end = map_start + (end - start);
const char* i = start;
char* map_i = map_start;
while (map_i != map_end) {
if (*map_i) {
dump_no(i, start + (map_i-map_start));
i = start + (map_i - map_start);
const char* mid = longfn(i, end);
dump_yes(i, mid);
i = mid;
map_i = map_start + (mid - start);
} else {
++map_i;
}
}
dump_no(i, end);
free(map_start);
}
int main() {
string buf;
char sect[8192];
int got;
while ((got = fread(sect, 1, sizeof(sect), stdin)) != 0)
buf.append(sect, got);
process(buf.c_str(), buf.c_str() + buf.length());
return 0;
}
| true |
c69b0a2bf7976b3f82e498f71b66bbf7775d8062 | C++ | pmiddend/fcppt | /examples/cast.cpp | UTF-8 | 888 | 2.90625 | 3 | [
"BSL-1.0"
] | permissive | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/cast/float_to_int.hpp>
#include <fcppt/cast/to_unsigned.hpp>
#include <fcppt/config/external_begin.hpp>
#include <iostream>
#include <ostream>
#include <fcppt/config/external_end.hpp>
namespace
{
void
float_to_int()
{
// ![float_to_int]
float const f(
3.5f
);
int const i(
fcppt::cast::float_to_int<
int
>(
f
)
);
// prints 3
std::cout
<< i
<< '\n';
// ![float_to_int]
}
// ![to_unsigned]
template<
typename T
>
void
test(
T const _t
)
{
std::cout
<<
fcppt::cast::to_unsigned(
_t
)
<< '\n';
}
void
g()
{
test(
4
);
// error
/*
test(
4u
);*/
}
// ![to_unsigned]
}
int
main()
{
float_to_int();
g();
}
| true |
78677d511230689e57fe26755f35396a46ab0fc0 | C++ | kuenzhao/NiukeC-Code | /牛客网在线编程/牛客网在线编程/第二题.cpp | UTF-8 | 396 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
string str;
while (cin >> str)
{
string tmp;
for (string::size_type i = 0; i < str.size()-1; i++)
{
if (str[i] == '0'&&str[i + 1] == 'x')
{
tmp += str[i + 3];
if (str[i + 2] >= '0'&& str[i + 2] <= '9')
{
tmp += str[i + 2];
}
}
}
cout << tmp<< endl;
}
return 0;
} | true |
fdb8d2225593d5542b11252c196c26571a6f8eb7 | C++ | hnefatl/Connect4 | /Engine/AssetManager_impl.h | UTF-8 | 3,267 | 3.203125 | 3 | [] | no_license | #ifndef _ASSETMANAGER_IMPL_H
#define _ASSETMANAGER_IMPL_H
#include "AssetManager.h"
enum UnloadBehaviour
{
Immediate,
OnEmpty,
};
template<typename AssetType, typename KeyType, typename SettingsType>
AssetManager<AssetType, KeyType, SettingsType>::AssetManager(const std::string &AssetDir, const UnloadBehaviour Behaviour)
: AssetDir(AssetDir), Behaviour(Behaviour)
{
}
template<typename AssetType, typename KeyType, typename SettingsType>
AssetManager<AssetType, KeyType, SettingsType>::~AssetManager()
{
UnloadAll();
}
template<typename AssetType, typename KeyType, typename SettingsType>
AssetType *AssetManager<AssetType, KeyType, SettingsType>::Load(const SettingsType &Settings)
{
KeyType Key = GetKey(Settings);
std::map<KeyType, AssetType *>::iterator Loc = Cache.find(Key);
if (Loc != Cache.end()) // If contained
{
Usage[Loc->second]++; // One more reference being handed out
return Loc->second;
}
AssetType *Asset = LoadAsset(Settings);
if (Asset == nullptr)
return nullptr;
Cache.emplace(Key, Asset); // Store in cache
Reverse.emplace(Asset, Key);
Usage.emplace(Asset, 1); // Record our one reference so far
return Asset;
}
template<typename AssetType, typename KeyType, typename SettingsType>
void AssetManager<AssetType, KeyType, SettingsType>::Unload(AssetType *Asset)
{
std::map<AssetType *, unsigned int>::iterator Use = Usage.find(Asset);
if (Use == Usage.end()) // Not stored in the usage list
return;
Use->second--; // Unload one use
if (Use->second == 0 && Behaviour == UnloadBehaviour::Immediate) // If no more references to it and we're set to unload immediately
{
std::map<AssetType *, KeyType>::iterator Name = Reverse.find(Asset); // Get the name
if (Name == Reverse.end()) // Unloading a texture that's no longer loaded
return;
Cache.erase(Name->second);
Usage.erase(Asset);
Reverse.erase(Asset);
DestroyAsset(Asset);
}
}
template<typename AssetType, typename KeyType, typename SettingsType>
bool AssetManager<AssetType, KeyType, SettingsType>::IsLoaded(const KeyType &Key) const
{
return Cache.find(Key) != Cache.end();
}
template<typename AssetType, typename KeyType, typename SettingsType>
void AssetManager<AssetType, KeyType, SettingsType>::UnloadUnused()
{
for (std::map<KeyType, AssetType *>::iterator i = Cache.begin(); i != Cache.end(); i++)
{
if (Usage[i->second] == 0) // No references
{
AssetType *Ref = i->second;
Usage.erase(Ref);
Reverse.erase(Ref);
Cache.erase(i->first);
DestroyAsset(Ref);
if (i != Cache.begin())
i--;
}
}
}
template<typename AssetType, typename KeyType, typename SettingsType>
void AssetManager<AssetType, KeyType, SettingsType>::UnloadAll()
{
Reverse.clear();
Usage.clear();
for (std::map<KeyType, AssetType *>::iterator i = Cache.begin(); i != Cache.end(); i++)
DestroyAsset(i->second);
Cache.clear();
}
template<typename AssetType, typename KeyType, typename SettingsType>
UnloadBehaviour AssetManager<AssetType, KeyType, SettingsType>::GetUnloadBehaviour() const
{
return Behaviour;
}
template<typename AssetType, typename KeyType, typename SettingsType>
void AssetManager<AssetType, KeyType, SettingsType>::SetUnloadBehaviour(const UnloadBehaviour Behaviour)
{
this->Behaviour = Behaviour;
}
#endif | true |
5a0a07f3878df572f54fc9a9e71208c37fb19c50 | C++ | scrottty/CarND-PID-Control-Project | /src/TWIDDLE.cpp | UTF-8 | 4,157 | 2.71875 | 3 | [] | no_license | #include "TWIDDLE.h"
TWIDDLE::TWIDDLE(double dp[3], double p[3]) :
m_step(0),
m_pNum(0),
m_count(0),
m_bestError(0.0),
m_currentError(0.0),
m_step_initialised(false),
TOL(0.005),
RESTART_VALUE(4000),
ACCUMSTART(100),
MIN_MAX_ERROR(80000),
m_restartSim(false),
m_cte(0.0)
{
for (int i=0; i<3; i++)
{
m_p[i] = p[i];
m_dp[i] = dp[i];
}
}
void TWIDDLE::run(PID &pid, double cte)
{
m_cte = cte;
m_count++;
switch (m_step) {
// At step one, run to get initial error
case 0:
runInitialStep(pid);
break;
case 1:
runPositiveAdjustment(pid);
break;
case 2:
runNegativeAdjustment(pid);
break;
default:
break;
}
}
bool TWIDDLE::getRestartSim()
{
return m_restartSim;
}
bool TWIDDLE::getTunningComplete()
{
return m_tunningComplete;
}
void TWIDDLE::printValues()
{
std::cout << "step: " << m_step << " count: " << m_count << " pNum: " << m_pNum << " BestError: " << m_bestError << " CurrentError: " << m_currentError << std::endl;
std::cout << " Kp,Ki,Kd: " << m_p[0] << "," << m_p[1] << "," << m_p[2] << " dp: " << m_dp[0] << "," << m_dp[1] << "," << m_dp[2] << std::endl;
}
void TWIDDLE::runPID(PID &pid)
{
pid.UpdateError(m_cte);
pid.CalcOutput();
}
void TWIDDLE::runInitialStep(PID &pid)
{
if (!m_step_initialised)
{
pid.Init(m_p[0], m_p[1], m_p[2]);
m_step_initialised = true;
}
runPID(pid);
if (m_count >= ACCUMSTART)
m_bestError += m_cte*m_cte;
if (m_count > RESTART_VALUE)
{
// Restart the sim and move to the next step
m_restartSim = true;
m_step++;
m_step_initialised = false;
m_count = 0;
// Limit bestError to make sure bad results dont accidentally succeed
if(m_bestError > MIN_MAX_ERROR)
m_bestError = MIN_MAX_ERROR;
}
}
void TWIDDLE::runPositiveAdjustment(PID &pid)
{
if (!m_step_initialised)
{
m_restartSim = false;
// increase the coefficient
m_p[m_pNum] += m_dp[m_pNum];
pid.Init(m_p[0], m_p[1], m_p[2]);
m_step_initialised = true;
m_currentError = 0.0;
}
runPID(pid);
if (m_count >= ACCUMSTART)
m_currentError += m_cte*m_cte;
// Restart if timed out or error is already larger than the best error
if (m_count > RESTART_VALUE || m_currentError > m_bestError)
{
m_count = 0;
m_restartSim = true;
if (m_currentError < m_bestError) // If the error has improved increase dp
{
m_bestError = m_currentError;
m_dp[m_pNum] *= 1.1;
if (m_pNum == 2) // If d term
{
checkTunningComplete();
m_pNum = 0; // go back to the P term
}
else
{
m_pNum++;
}
}
else // If worsened move to the negative step
{
m_step++;
}
m_step_initialised = false;
}
}
void TWIDDLE::runNegativeAdjustment(PID &pid)
{
if (!m_step_initialised)
{
m_restartSim = false;
// decrease the coefficient (x2 to remove effect of positive adjustment)
m_p[m_pNum] -= m_dp[m_pNum]*2;
pid.Init(m_p[0], m_p[1], m_p[2]);
m_step_initialised = true;
m_currentError = 0.0;
}
runPID(pid);
if (m_count >= ACCUMSTART)
m_currentError += m_cte*m_cte;
if (m_count > RESTART_VALUE || m_currentError > m_bestError)
{
m_count = 0;
m_restartSim = true;
if (m_currentError < m_bestError) // If the error has improved increase dp
{
m_bestError = m_currentError;
m_dp[m_pNum] *= 1.1;
if (m_pNum == 2) // If d term
{
checkTunningComplete();
m_pNum = 0; // go back to the P term
}
else
{
m_pNum++;
}
}
else // If worsened decrease dp
{
// Remove the changes to p
m_p[m_pNum] += m_dp[m_pNum];
m_dp[m_pNum] *= 0.9;
// move onto the next coefficient
if (m_pNum == 2)
m_pNum = 0;
else
m_pNum++;
}
m_step = 1; // return to step one with the next coefficient
m_step_initialised = false;
}
}
void TWIDDLE::checkTunningComplete()
{
double sum = 0;
for (int i=0; i<3; i++)
{
sum += m_dp[i];
}
if (fabs(sum) < TOL)
m_tunningComplete = true;
}
| true |
926f1c91ba1b557551bee75e606b5ed6e20741ab | C++ | HarshitShirsat/Zilla-HC | /ACC_FR.CPP | UTF-8 | 1,326 | 2.578125 | 3 | [] | no_license | //function which allows the user to either accept or decline the friend request
int accept_friend_request()
{
setfillstyle(SOLID_FILL,LIGHTGRAY);
bar(500,400,600,430);
bar(500,440,600,470);
settextstyle(1,0,1);
setcolor(GREEN);
outtextxy(510,405,"ACCEPT");
setcolor(RED);
outtextxy(510,445,"DECLINE");
restrictmouse(0,0,640,480);
movemouseptr(0,0);
showmouse();
changecursor(cursorhc);
int option=1;
while(1)
{
getmousepos(&button, &x, &y );
if((x>=500 && y>=400 && x<=600 && y<=430) || (x>=500 && y>=440 && x<=600 && y<=470))
{ changecursor(cursorhand); }
else
{changecursor(cursorhc);}
if(x>=500 && y>=400 && x<=600 && y<=430)
{setlinestyle(0,0,3);
setcolor(GREEN);
rectangle(498,398,600,430);
}
else
{
setlinestyle(0,0,3);
setcolor(BLACK);
rectangle(498,398,600,430);
}
if(x>=500 && y>=440 && x<=600 && y<=470)
{
setlinestyle(0,0,3);
setcolor(GREEN);
rectangle(498,438,600,470);
}
else
{setlinestyle(0,0,3);
setcolor(BLACK);
rectangle(498,398,600,470);
}
showmouse();
if( button & 1 == 1 )
{
if(x>=500 && y>=400 && x<=600 && y<=430)
{option=1;
break;}
if(x>=500 && y>=440 && x<=600 && y<=470)
{option=2;
break;}
}
}
return option;
}
| true |
e59d04cc73c71f76b34a254aef0a084f41cbab4a | C++ | athelare/SourceCode-ACM | /2017-2018s_Summer_Acm/July30-AOJ0525-Osenbei.cpp | UTF-8 | 869 | 2.515625 | 3 | [] | no_license | #include<cstdio>
#include<iostream>
using namespace std;
int R,C;
int ColCount[10005];
int situ[11][10002];
void solve()
{
int flip=0,MaxTime=1;
bool flipflag[11];
int MaxCount=0;
for(int i=0;i<R;++i)MaxTime*=2;
for(int flip=0;flip<MaxTime;++flip){
for(int i=0;i<R;++i)
flipflag[i] = (flip & (1<<i));
fill(ColCount,ColCount+C,0);
for(int i=0;i<R;++i)
for(int j=0;j<C;++j){
ColCount[j]+=situ[i][j] ^ flipflag[i];
}
int curCount = 0;
for(int i=0;i<C;++i)curCount+=max(ColCount[i],R-ColCount[i]);
if(curCount>MaxCount)MaxCount = curCount;
}
cout<<MaxCount<<endl;
}
int main(){
while(cin>>R>>C){
if(R+C == 0)break;
for(int i=0;i<R;++i)for(int j=0;j<C;++j)scanf("%d",&situ[i][j]);
solve();
}
return 0;
} | true |
ee3b1f32720ada8eec887e3bbdf3dbaa3e6b8552 | C++ | wangkendy/TiCpp | /ch07/MultiSetWordCount.cpp | UTF-8 | 776 | 3.03125 | 3 | [] | no_license | //: C07:MultiSetWordCount.cpp
//{L} StreamTokenizer
// Count occurrences of words using a multiset
#include "StreamTokenizer.h"
#include "../require.h"
#include <string>
#include <set>
#include <fstream>
#include <iterator>
using namespace std;
int main(int argc, char* argv[])
{
requireArgs(argc, 1);
ifstream in(argv[1]);
assure(in, argv[1]);
StreamTokenizer words(in);
miltiset<string> wordmset;
string word;
while ((word = words.next()).size() != 0)
wordmset.insert(word);
typedef multiset<string>::iterator MSit;
MSit it = wordmset.begin();
while (it != wordmset.end()) {
pair<Msit, MSit> p = wordmset.equal_range(*it);
int count = distance(p.first, p.second);
cout << *it << ": " << count << endl;
it = p.second; // Move to the next word
}
} ///:~
| true |
05956ffc833105c71bcdb1ec684e6cd1ee73712e | C++ | mboydenko/visualization-of-the-prim-algorithm | /Graph/node.cpp | UTF-8 | 2,651 | 2.84375 | 3 | [] | no_license | #include "node.h"
#include "arc.h"
#include <QPainter>
Node::Node(const QSize &sizeNode,
const qint32 &borderWidht,
QFont &fontNode,
qint32 indexNode) :
QGraphicsItem(),
m_index(indexNode),
m_sizeNode(sizeNode),
m_font(fontNode),
m_borderWidth(borderWidht)
{
refreshFont();
}
Node::Node(const Node &node):
QGraphicsItem(),
m_index(node.m_index),
m_sizeNode(node.m_sizeNode),
m_font(node.m_font),
m_borderWidth(node.m_borderWidth),
m_color(node.m_color)
{
setPos(node.pos());
if (m_listArcs.isEmpty()) {m_listArcs = node.listArc();}
const Node * const pItem = &node;
foreach (Arc *line, m_listArcs) {
if (pItem == line->node1())
line->setNode1(this);
else
line->setNode2(this);
}
}
Node::~Node()
{
}
QRectF Node::boundingRect() const
{
return QRectF(0, 0, m_sizeNode.width(), m_sizeNode.height());
}
void Node::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *)
{
p->setRenderHint(QPainter::Antialiasing);
p->setPen(QPen(m_color, m_borderWidth));
p->setBrush(QBrush(QColor(255, 255, 255)));
p->drawRoundRect(boundingRect(), 90, 90);
if (m_index != -1) {
p->setPen(QPen(m_color, 1));
p->setBrush(Qt::NoBrush);
p->setFont(m_font);
p->drawText(boundingRect(),
Qt::AlignHCenter | Qt::AlignCenter,
QString::number(m_index));
}
}
qint32 Node::index() const
{
return m_index;
}
qint32 &Node::atIndex()
{
return m_index;
}
QList<Arc *> Node::listArc() const
{
return m_listArcs;
}
void Node::addArc(Arc *arc)
{
m_listArcs.append(arc);
}
void Node::removeArc(Arc *arc)
{
m_listArcs.removeOne(arc);
}
QColor Node::currentColor() const
{
return m_color;
}
void Node::setColor(QColor newColor)
{
m_color = newColor;
}
Node *Node::adjacentNode(Arc *arc)
{
if(this == arc->node1() || this == arc->node2()){
//Если первая вершина не совпадает с текущей
//то возвращаем первую
if(arc->node1() != this){
return arc->node1();
}
//Иначе возвращаем вторую
else {return arc->node2();}
}
return nullptr;
}
void Node::refreshFont()
{
m_font.setPointSize(1);
QFontMetrics fm(m_font);
int fontSize = -1;
do {
++fontSize;
m_font.setPointSize(fontSize + 1);
fm = QFontMetrics(m_font);
} while(fm.width(QString::number(m_index)) <= m_sizeNode.width() / 2 &&
fm.height() <= m_sizeNode.height() * 0.8);
m_font.setPointSize(fontSize);
}
QPointF Node::center() const
{
return QPointF(pos().x() + m_sizeNode.width() / 2,
pos().y() + m_sizeNode.height() / 2);
}
| true |
f68c388bc572d5dd4466a3f5b40364dc1c6980e7 | C++ | MaSteve/UVA-problems | /UVA12468.cpp | UTF-8 | 276 | 2.578125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a, b;
while (cin >> a >> b && !(a == -1 && b == -1)) {
int c1 = max(a, b) - min(a, b), c2 = min(a, b) + 100 - max(a, b);
printf("%d\n", min(c1, c2));
}
return 0;
}
| true |
9ad10525ae9bc955cf9d3913641b3bf4c39bd964 | C++ | pawelwojtowicz/ecuApp | /Src/UCL/CSemaphore.cpp | UTF-8 | 605 | 2.828125 | 3 | [] | no_license | #include "CSemaphore.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
namespace UCL
{
CSemaphore::CSemaphore()
: m_lockHandle(SEM_FAILED)
{
}
CSemaphore::~CSemaphore()
{
}
bool CSemaphore::Initialize(const std::string& semaphoreName, const UInt32 semaphoreCount)
{
m_lockHandle = sem_open(semaphoreName.c_str(), O_CREAT , ( S_IRWXO | S_IRWXG | S_IRWXU) , 1 );
return ( SEM_FAILED != m_lockHandle );
}
void CSemaphore::Shutdown ()
{
sem_close(m_lockHandle);
}
void CSemaphore::Lock()
{
sem_wait(m_lockHandle);
}
void CSemaphore::Unlock()
{
sem_post(m_lockHandle);
}
}
| true |
d36aaa096f9ec68629e2d78cc7e7a7a707d59e37 | C++ | Back-Log/Competitive-Programming-Algorithms | /Number_of_Subarray_Divisible_by_K.cpp | UTF-8 | 715 | 3.25 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int TotalSubarray(int *arr,int n,int k)
{
int ans=0;
int freq[k]={0};
int sum=0;
for(int i=0;i<n;i++)
{
//we are going to mentain the running sum
//in case of reminder is negative ,we are adding k to it
sum+=((arr[i]%k+k))%k;
freq[sum%k]++;
}
//handle the freq[0] case seprately for their indivisual contribution
ans=freq[0];
for(int i=0;i<k;i++)
{
//adding nC2 to ans for every element
ans+=freq[i]*(freq[i]-1)/2;
}
return ans;
}
int main()
{
//number of element in the array
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)cin>>arr[i];
//value of K
int k;
cin>>k;
cout<<TotalSubarray(arr,n,k)<<endl;
return 0;
} | true |
420adf8756768cf2535309e03e0a452ce0af05bd | C++ | lucabello/kangaroo-docs | /common/MessageQueue.h | UTF-8 | 902 | 3.078125 | 3 | [
"MIT"
] | permissive | #ifndef MESSAGEQUEUE_H
#define MESSAGEQUEUE_H
#include <QQueue>
#include <QMutex>
#include <QWaitCondition>
#include "Message.h"
/*
* Implementation of a thread safe queue.
* NEEDS TESTING!!
*/
class MessageQueue {
QQueue<Message> queue;
QWaitCondition cv;
QMutex mutex;
public:
MessageQueue(){}
/**
* Returns the number of elements in the QQueue<Message> of the class
*/
int count();
/**
* Returns a boolean that says if the QQueue<Message> is empty
*/
bool isEmpty();
/**
* Removes all the elements inside the QQueue<Message>
*/
void clear();
/**
* Pushes the Message passed as a parameter at the end of the FIFO queue of messages
*/
void push(const Message& m);
/**
* Returns the first Message at the head of the FIFO queue of messages
*/
Message pop();
};
#endif // MESSAGEQUEUE_H
| true |
5fe9a981e6eae4ed263a4823923cdcf8b61d9906 | C++ | SolidStateSociety-Src/Introduction-to-CPP-Programming | /Lessons/Lesson 4/Lesson 4.1/BasicArrays/BasicArrays/Main.cpp | UTF-8 | 3,473 | 4.21875 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class BasicArrays
{
public:
/***** Methods for all the arrays *****/
/**** For showing basic array declarations ****/
void basicArrays()
{
/** ways to declare size of array **/
/* while most languages fill in 0s automatically, C and C++ don't, so
* add a "{0}"/"{ }" to initialize all 0s in the array when declaring
*/
int arr1[10] = {0};
/* since since isn't declared, you can just keep adding values
* however, when you call arr2 later, the size will be how many vars declared
* in this example, size = 3
*/
double arr2[] = {0.5, 3454, 32};
/* even though the size is 6 and garbage values/nothing will fill in the rest,
* there's still 4 more spaces to add whatever string value you want
*/
string arr3[6] = {"howdy", "cosine"};
arr1[2] = 5;
// same as arr1[4]
arr1[8 / 2] = 7;
// whatever is at arr[4] will be equal to this index
arr1[5] = arr1[4];
cout << "**BasicArrays()**" << endl;
cout << "*Arr1* \n";
cout << "1st index: " << arr1[0] << endl;
cout << "2nd index: " << arr1[1] << endl;
cout << "3rd index: " << arr1[2] << endl;
cout << "4th index: " << arr1[3] << endl;
cout << "5th index: " << arr1[4] << endl;
cout << "6th index: " << arr1[5] << endl;
cout << "7th index: " << arr1[6] << endl;
cout << "8th index: " << arr1[7] << endl;
cout << "9th index: " << arr1[8] << endl;
cout << "10th index: " << arr1[9] << endl << endl;
cout << "*Arr2* \n";
cout << arr2[0] << "\t\t" << arr2[1] << "\t\t" << arr2[2] << endl << endl;
arr3[4] = "4346 tbs of ass";
cout << "*Arr3* \n";
cout << arr3[4] << endl;
cout << "--------------------------------------- \n\n";
}
/**** For showing basic multidimensional array declarations ****/
void basicMultidimensional()
{
/** you can declare as many dimensions as you'd like, but it gets hard
* to visualize, so if you're going to do so, have a good reason
*
* I'll only show a 2D and 3D array
**/
/** 2D array **/
// 3 * 4 = 12 elements allotted
char arr1[3][4] =
{
{'a', 'b', 'c', 'd'}, // row 0, indices [0, ..]
{'e', 'f', 'g', 'h'}, // row 1, indices [1, ..]
{'i', 'j', 'k', 'l'} // row 2, indices [2, ..]
};
cout << "**BasicMultidimensional()**" << endl;
cout << "*Arr1* \n";
cout << "1st row: " << arr1[0][0] << " " << arr1[0][1] << " " << arr1[0][2] <<
" " << arr1[0][3] << endl;
cout << "2nd row: " << arr1[1][0] << " " << arr1[1][1] << " " << arr1[1][2] <<
" " << arr1[1][3] << endl;
cout << "3rd row: " << arr1[2][0] << " " << arr1[2][1] << " " << arr1[2][2] <<
" " << arr1[2][3] << endl << endl;
/** 3D array **/
// 2 * 3 * 2 = 12 elements allotted
int arr2[2][3][2] =
{
{
{0, 1}, {2, 3}, {4, 5}
},
{
{6, 7}, {8, 9}, {10, 11}
}
};
cout << "*Arr2* \n";
cout << "1st row: " << arr2[0][0][0] << " " << arr2[0][0][1] << " " <<
arr2[0][1][0] << " " << arr2[0][1][1] << " " << arr2[0][2][0] << " " <<
arr2[0][2][1] << " " << arr2[1][0][0] << " " << arr2[1][0][1] << " " <<
arr2[1][1][0] << " " << arr2[1][1][1] << " " << arr2[1][2][0] << " " <<
arr2[1][2][1] << endl;
cout << "--------------------------------------- \n\n";
}
};
int main()
{
BasicArrays bArr;
bArr.basicArrays();
bArr.basicMultidimensional();
return 0;
} | true |
8acb43de5faf8fc87931400f92fa437ddc35bef5 | C++ | Benshakalaka/DataStructure | /数据结构/226_查找/226_查找表(静态查找)/静态查找/顺序查找/顺序表的查找/head.cpp | UTF-8 | 2,524 | 3.53125 | 4 | [] | no_license | #include "head.h"
void Create_Seq(SSTable &ST,int n,Elemtype* r) //构建一个含n个数据元素的静态顺序查找表
{
int i;
ST.elem = (Elemtype *)malloc((n+1)*sizeof(Elemtype));
if(!ST.elem)
exit(1);
for(i=1;i<=n;i++)
ST.elem[i] = r[i-1];
ST.length = n;
}
void Ascend(SSTable &ST) //重建查找表为按关键字的非降序排序
{ //这个算法是选择算法 只不过将其拆解了 选择算法是拿一个和其余剩下的所有进行比较 选出最小的然后swap
int i,j,k;
for(i=1;i<=ST.length;i++) //第一层循环
{
k = i;
ST.elem[0] = ST.elem[i]; //这里借助这个空着的ST.elem[0] 当作temp
for(j=i+1;j<=ST.length;j++)
if(LT(ST.elem[j].key,ST.elem[0].key)) //挑选出比当前数小且是最小的
{
k = j;
ST.elem[0] = ST.elem[j];
}
if(k!=i) //存在这个最小的数 那么交换
{
ST.elem[j] = ST.elem[i];
ST.elem[i] = ST.elem[0];
}
}
}
void Create_Ord(SSTable &ST,int n,Elemtype*r) //构建一个含n个数据元素的静态非降序排序顺序查找表
{
Create_Seq(ST,n,r);
Ascend(ST);
}
void Destroy(SSTable &ST) //销毁
{
free(ST.elem);
ST.elem = NULL;
ST.length = 0;
}
int Search_Seq(SSTable &ST,Keytype key) //算法9.1 在顺序表中查找其关键字等于等于key的数据元素,若找到 则函数值为表中位置 否则为0
{
//**************************ST.elem[0]起到哨兵作用 虽然仅仅是一个程序设计上的小小改进,然而实践证明,在长度大于1000时 查找所需平均时间几乎减少一半*********************************
ST.elem[0].key = key; //0号留空的目的是存储用户要查询的key 方便下面的for循环
for(int i=ST.length;!EQ(ST.elem[i].key,key);i--); //如果找到的话就直接返回位置;否则未找到 i-- 一直到i==0的时候循环停止 因为ST.elem[0] = key;
return i;
}
int Search_Bin(SSTable &ST,Keytype key) //算法9.2 在顺序表中查找其关键字等于等于key的数据元素,若找到 则函数值为表中位置 否则为0
{ //二分查找/折半查找
int mid,start,end;
start = 1;
end = ST.length;
while(start<=end)
{
mid = (start+end)/2;
if(EQ(ST.elem[mid].key,key))
return mid;
else if(LT(key,ST.elem[mid].key))
end = mid-1;
else
start = mid+1;
}
return 0;
}
void Traverse(SSTable ST,void (*visit)(Elemtype))
{
Elemtype *p = ST.elem+1;
for(int i=1;i<=ST.length;i++)
visit(*(p++));
}
| true |