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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
76d679fcaa12ec971bb0d71d1cf628d0594a68e8 | C++ | wenxinz/C-PrimerPlus | /chapter11/stonewt_2.cpp | UTF-8 | 1,129 | 3.3125 | 3 | [] | no_license | //stonewt.cpp -- with all six relational operators reloaded
#include "stonewt_2.h"
#include <iostream>
using std::cout;
Stonewt::Stonewt(double lbs){
stone = int(lbs) / Lbs_per_stn;
pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs);
pounds = lbs;
}
Stonewt::Stonewt(int stn, double lbs){
stone = stn;
pds_left = lbs;
pounds = stn * Lbs_per_stn + lbs;
}
Stonewt::Stonewt(){
stone = pounds = pds_left = 0 ;
}
Stonewt::~Stonewt(){}
void Stonewt::show_stn() const{
cout << stone << " stone, " << pds_left << " pounds\n";
}
void Stonewt::show_lbs() const{
cout << pounds << " pounds\n";
}
// operator overloading
bool Stonewt::operator==(Stonewt & s) const{
return pounds == s.pounds;
}
bool Stonewt::operator!=(Stonewt & s) const{
return pounds != s.pounds;
}
bool Stonewt::operator>(Stonewt & s) const{
return pounds > s.pounds;
}
bool Stonewt::operator>=(Stonewt & s) const{
return pounds >= s.pounds;
}
bool Stonewt::operator<(Stonewt & s) const{
return pounds < s.pounds;
}
bool Stonewt::operator<=(Stonewt & s) const{
return pounds <= s.pounds;
}
| true |
c13ed6b3e39ca7694a0c47281861d4eddf4bc36f | C++ | noahb764/CSC3180 | /closestPoint.h | UTF-8 | 339 | 2.5625 | 3 | [] | no_license | #ifndef CLOSESTPOINT_H
#define CLOSESTPOINT_H
class closestPoint
{
public:
// Default constructor
closestPoint();
//Constructor
closestPoint(double new_x, double new_y);
// Accessors
double getX();
double getY();
//Mutators
void setX();
void setY();
private:
double x_coord;
double y_coord;
};
#endif
| true |
f323d7e720865a831715d845c2e7535725bed9af | C++ | StefanDimeski/Chixel-Engine | /StateManager.cpp | UTF-8 | 1,074 | 3.359375 | 3 | [] | no_license | #include "StateManager.h"
#include <iostream>
StateManager::StateManager()
{
}
StateManager::~StateManager()
{
}
State* StateManager::toInstance(States state)
{
if (state == States::MainMenu)
return new MainMenuState();
}
void StateManager::pushFront(States state)
{
State *s = toInstance(state);
s->changeState = std::bind(&StateManager::changeState, this, std::placeholders::_1); //[&](States state) { this->changeState(state); }; // This is the problem
s->init();
states.push_front(s);
}
void StateManager::popFront()
{
if (states.size() == 0)
return;
states.front()->onChange();
states.pop_front();
}
void StateManager::processInput(char pressed)
{
if (states.size() == 0)
return;
states.front()->processInput(pressed);
}
void StateManager::update()
{
if (states.size() == 0)
return;
states.front()->update();
}
void StateManager::display()
{
if (states.size() == 0)
return;
states.front()->display();
}
void StateManager::changeState(States state)
{
std::cout << "Hello!";
this->popFront();
this->pushFront(state);
} | true |
888bf56cc9b690019db0845a69c57e1fbd922678 | C++ | 956237586/CppExperiments | /CppExperiment3/CppExperiment3/Trapezoid.cpp | UTF-8 | 425 | 3.03125 | 3 | [] | no_license | //Trapezoid.cpp
#include "Trapezoid.h"
Trapezoid::Trapezoid(double top, double height, double bottom) {
this->top = top;
this->height = height;
this->bottom = bottom;
this->area = getArea();
}
double Trapezoid::getArea() {
return (top + bottom) * height / 2.0;
}
int TestTrapezoidMain() {
//int main() {
Shape* trapezoid = new Trapezoid(2, 5, 5);
cout << trapezoid->getArea() << endl;
system("pause");
return 0;
} | true |
72eeba3cb8ee64e8a52eeb27bc3987fdd79f4203 | C++ | KArsen146/kgig2 | /kgig4/transfer.h | UTF-8 | 765 | 2.578125 | 3 | [] | no_license | //
// Created by Арсений Карпов on 30.05.2020.
//
#ifndef KGIG4_TRANSFER_H
#define KGIG4_TRANSFER_H
#include <string>
#include <vector>
#include <algorithm>
class transfer {
private:
double* _first{};
double* _second{};
double* _third{};
int _width;
int _height;
std::vector<std::string> base;
double for_HSL_RGB(double T, double q, double p);
void HSL_RGB();
void RGB_HSL();
void HSV_RGB();
void RGB_HSV();
void YCbCr_RGB(double Kb, double Kr);
void RGB_YCbCr(double Kb, double Kr);
void YCoCg_RGB();
void RGB_YCoCg();
void CMY_RGB();
public:
transfer(int width, int height, double* first, double* second, double* third);
int convert(std::string from, std::string to);
};
#endif //KGIG4_TRANSFER_H
| true |
1a25343b644bb279a05abc7e0093f354e68e6047 | C++ | k119-55524/Old-project | /RedKid3D/RedKid3D Engine/RedKid Engine/LogFile.h | MacCyrillic | 2,086 | 2.75 | 3 | [] | no_license | #pragma once
#include "header.h"
class CLogFile
{
public:
inline void ClearLogFile( void )
{
std::ofstream LogFile;
try
{
//
LogFile.open( LogFileName, std::ios::out | std::ios::trunc );
LogFile << "Log file.\n";
LogFile.close();
}
catch( ... )
{
LogFile.close();
}
};
inline void OutputLogFileErrorString( const wstring &ErrStr, char* file, char* func, UINT line )
{
std::wofstream LogFile;
TCHAR* wFile = GetUniStr( file );
TCHAR* wFunc = GetUniStr( func );
try
{
#if defined( DEBUG ) || defined( _DEBUG )
TCHAR __eRR[512];
wsprintf( __eRR, L"%s\n\nFile: %s.\n\nLine: %d, function: %s.\n", ErrStr.c_str(), wFile, line, wFunc );
OutputDebugString( __eRR );
MessageBox( NULL, __eRR, L"Error!", MB_OK | MB_ICONSTOP | MB_TASKMODAL );
#endif
if ( !fOutErrorMessage )
return;
LogFile.open( LogFileName, std::ios::out | std::ios::app );
LogFile << "ERROR: File - " << wFile << ".\n";
LogFile << " - Error line: " << line << ". Func: " << wFunc << ".\n";
LogFile << " - Error text: " << ErrStr;
LogFile << "\n";
LogFile.close();
}
catch( ... )
{
LogFile.close();
}
};
inline void OutputLogFileString( const wstring &Str )
{
if ( !fOutMessage )
return;
std::wofstream LogFile;
try
{
LogFile.open( LogFileName, std::ios::out | std::ios::app );
LogFile << "Message: " << Str << "\n";
LogFile.close();
#if defined( DEBUG ) || defined( _DEBUG )
OutputDebugString( ( L"-->" + Str + L"\n" ).c_str() );
#endif
}
catch( ... )
{
LogFile.close();
}
}
inline void SetOutMessageFlag( bool f ) { fOutMessage = f; };
inline void SetOutErrorMessageFlag( bool f ) { fOutErrorMessage = f; };
private:
TCHAR* GetUniStr( char* str )
{
TCHAR* wcstring;
size_t newsize = strlen( str ) + 1;
wcstring = new TCHAR[newsize];
size_t convertedChars = 0;
mbstowcs_s( &convertedChars, wcstring, newsize, str, _TRUNCATE );
return wcstring;
};
static bool fOutMessage;
static bool fOutErrorMessage;
};
| true |
f3f08c88d48ee6f168bf77f83f28c71027fc25dd | C++ | SuperVang/example | /cpp/algorithm/ml/ml_lib/logistic_regression.cpp | UTF-8 | 3,811 | 3.21875 | 3 | [] | no_license | //
// Created by books on 19-11-17.
//
#include "logistic_regression.h"
LogisticRegression::LogisticRegression()
{
}
LogisticRegression::~LogisticRegression()
{
}
void LogisticRegression::gradientDescent(const SampleVec &pos, const SampleVec &neg)
{
assert(pos.size() + neg.size() > 1);
const int N = pos.empty() ? neg.front().rows() : pos.front().rows();
m_theta = Eigen::VectorXd::Ones(N);
double cost = calCost(pos, neg);
bool no_change = false;
double alpha = 0.03;
int num = 0;
while (!no_change && num++ < 3000)
{
Eigen::VectorXd delta_theta = Eigen::VectorXd::Zero(N);
for (size_t i = 0; i < pos.size(); i++)
{
delta_theta.noalias() += pos[i] * (logistic(pos[i]) - 1);
}
for (size_t i = 0; i < neg.size(); i++)
{
delta_theta.noalias() += neg[i] * (logistic(neg[i]));
}
delta_theta /= (double) (pos.size() + neg.size());
m_theta = m_theta - alpha * delta_theta;
double update_cost = calCost(pos, neg);
no_change = std::abs(update_cost - cost) < 0.01;
cost = update_cost;
}
std::cout << "Logistic Regression Gradient Descent : " << m_theta.transpose() << std::endl;
}
void LogisticRegression::gradientDescentRegularization(const SampleVec &pos, const SampleVec &neg)
{
assert(pos.size() + neg.size() > 1);
const int N = pos.empty() ? neg.front().rows() : pos.front().rows();
m_theta = Eigen::VectorXd::Ones(N);
double cost = calCostRegularization(pos, neg);
bool no_change = false;
double alpha = 0.03;
Eigen::VectorXd lambda = Eigen::VectorXd::Constant(N, 100.0);
lambda(0) = 0.0;
int num = 0;
while (!no_change && num++ < 3000)
{
Eigen::VectorXd delta_theta = Eigen::VectorXd::Zero(N);
for (size_t i = 0; i < pos.size(); i++)
{
delta_theta.noalias() += (pos[i] * (logistic(pos[i]) - 1) + lambda.cwiseProduct(m_theta));
}
for (size_t i = 0; i < neg.size(); i++)
{
delta_theta.noalias() += (neg[i] * (logistic(neg[i])) + lambda.cwiseProduct(m_theta));
}
delta_theta /= (double) (pos.size() + neg.size());
m_theta = m_theta - alpha * delta_theta;
double update_cost = calCostRegularization(pos, neg);
no_change = std::abs(update_cost - cost) < 0.01;
cost = update_cost;
}
std::cout << "Logistic Regression Gradient Descent : " << m_theta.transpose() << std::endl;
}
int LogisticRegression::predict(const Sample &sample)
{
return logistic(sample) > 0.5 ? 1 : 0;
}
double LogisticRegression::calCost(const SampleVec &pos, const SampleVec &neg)
{
double cost = 0;
for (size_t i = 0; i < pos.size(); i++)
{
cost += std::log(logistic(pos[i]));
}
for (size_t i = 0; i < neg.size(); i++)
{
cost += std::log(1.0 - logistic(neg[i]));
}
return cost / (1.0 * (pos.size() + neg.size()));
}
double LogisticRegression::logistic(const Sample &sample)
{
return 1.0 / (1.0 + std::exp(-m_theta.transpose() * sample));
}
double LogisticRegression::calCostRegularization(const SampleVec &pos, const SampleVec &neg)
{
double cost = 0;
assert(pos.size() + neg.size() > 1);
const int N = pos.empty() ? neg.front().rows() : pos.front().rows();
Eigen::VectorXd lambda = Eigen::VectorXd::Constant(N, 100.0);
lambda(0) = 0.0;
for (int i = 0; i < m_theta.rows(); i++)
{
cost += lambda(i) * m_theta(i) * m_theta(i);
}
for (size_t i = 0; i < pos.size(); i++)
{
cost += std::log(logistic(pos[i]));
}
for (size_t i = 0; i < neg.size(); i++)
{
cost += std::log(1.0 - logistic(neg[i]));
}
return cost / (1.0 * (pos.size() + neg.size()));
}
| true |
40595112411d6bf0f307289aade76f0a342aa037 | C++ | d4vid-4thur69/JPMorgan-SSSM | /SSSMarket/StockMarket.h | UTF-8 | 1,210 | 2.71875 | 3 | [] | no_license | #ifndef D_StockMarket_H
#define D_StockMarket_H
#include <vector>
#include <string>
#include <ctime>
#include "Stocks.h"
using namespace std;
///////////////////////////////////////////////////////////////////////////////
//
// StockMarket is responsible for ...
//
///////////////////////////////////////////////////////////////////////////////
class StockMarket
{
public:
StockMarket();
virtual ~StockMarket();
enum TradeKind {BUY, SELL, LAST};
struct StockTrade
{
string _sym;
time_t _time;
int _quantity;
int _kind;
int _price;
StockTrade(string sym,time_t time,int quantity,int kind,int price)
{
_sym=sym;
_time=time;
_quantity=quantity;
_kind=kind;
_price=price;
}
};
private:
vector<Stocks*> _stock_market_data;
vector<StockTrade*> _market_trading;
bool StockTradeValid(StockTrade* trade);
public:
int CreateStockMarketData(void);
int GetMarketTradingNumber(void);
void RecordTrade(StockTrade* trade);
double CalculateVWSP(string symbol, time_t request_time, int period=300);
double CalculateAllShareIndex(void);
void PrintAllTradesToConsole(void);
void PrintSubsettradesToConsole(vector<StockTrade*>* sub);
};
#endif // D_StockMarket_H
| true |
d4becff354c79cedd2f578f171af54da46308876 | C++ | Redleaf23477/ojcodes | /codeforces/bye2022/C.cpp | UTF-8 | 1,486 | 2.578125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
using LL = long long int;
constexpr LL P = 100 * 100 + 1;
vector<LL> primes;
void make_prime() {
vector<int> sp(P, -1);
iota(sp.begin(), sp.end(), 0);
for (LL i = 2; i < P; i++) {
if (sp[i] == i) {
primes.emplace_back(i);
for (LL j = i * i; j < P; j += i) {
if (sp[j] == j) sp[j] = i;
}
}
}
}
void solve() {
int n; cin >> n;
vector<LL> arr(n);
for (auto &x : arr) cin >> x;
vector<set<LL>> constraints(primes.size());
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
LL big = max(arr[i], arr[j]);
LL small = min(arr[i], arr[j]);
LL sub = big - small;
if (sub == 0) {
cout << "NO\n";
return;
}
for (size_t pi = 0; pi < primes.size(); pi++) {
LL p = primes[pi];
if (sub % p == 0) {
LL r = small % p;
constraints[pi].insert((p - r) % p);
}
}
}
}
for (size_t pi = 0; pi < primes.size(); pi++) {
LL p = primes[pi];
if (constraints[pi].size() == p) {
cout << "NO\n";
return;
}
}
cout << "YES\n";
}
int main() {
ios::sync_with_stdio(false); cin.tie(0);
make_prime();
int T; cin >> T;
while (T--) {
solve();
}
}
| true |
7ad67f538b108fd35c5fc2852910484244be0b61 | C++ | JaredChew/DGT_GP_Ass2 | /DGP2544/src/engine/gameWindow.cpp | UTF-8 | 4,367 | 3.03125 | 3 | [] | no_license | #include "gameWindow.h"
GameWindow::GameWindow(Logger& log) : log(log) {
// ** Initialise variables and objects here ** //
//Initialise controlling variables
gameloop = true;
frameDelay = 1000 / FPS;
avgFPS = 0;
countedFrames = 0;
if (init() == -1) {
gameloop = false;
}
}
GameWindow::~GameWindow() {
// ** Destroy window object here ** //
std::cout << "\nDestroying SDL renderer" << std::endl;
SDL_DestroyRenderer(renderer);
renderer = NULL;
std::cout << "Destroying SDL surface" << std::endl;
SDL_FreeSurface(backbuffer);
backbuffer = NULL;
std::cout << "Destroying SDL window" << std::endl;
SDL_DestroyWindow(window);
window = NULL;
std::cout << "Quitting SDL libraries" << std::endl;
SDL_Quit();
}
int GameWindow::init() {
// ** Initialise window here ** //
std::cout << "\nInitialising SDL..." << std::endl;
log.writeLog("Initialising SDL");
//Initialise SDL drivers
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
SDL_Quit();
std::cerr << "Failed to intialise SDL drivers" << std::endl;
log.writeLog("Failed to intialise SDL drivers");
return -1;
}
std::cout << "SDL drivers initialised" << std::endl;
log.writeLog("SDL drivers initialised");
//Create main window
window = SDL_CreateWindow(WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL) {
SDL_Quit();
std::cerr << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
log.writeLog("Failed to intialise SDL window");
return -1;
}
//Apply window into backbuffer/surface
backbuffer = SDL_GetWindowSurface(window);
std::cout << "SDL window initialised" << std::endl;
log.writeLog("SDL window initialised");
//Initialise renderer
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
if (renderer == NULL) {
SDL_Quit();
std::cerr << "Failed to intialise SDL renderer" << std::endl;
log.writeLog("Failed to intialise SDL renderer");
return -1;
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
std::cout << "SDL renderer initialised" << std::endl;
log.writeLog("SDL renderer initialised");
return 0;
}
void GameWindow::eventHandler() {
// ** Set window event listener here ** //
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) { //Listen to 'X' button of window being clicked
std::cout << "\nPlayer exited game" << std::endl;
gameloop = false;
}
}
}
void GameWindow::fpsCounter() {
// ** Displays average fps ** //
//Count average FPS
avgFPS = countedFrames / (SDL_GetTicks() / 1000.f);
if (avgFPS > 2000000) { avgFPS = 0; }
countedFrames++;
//Display on window
sprintf_s(dynamicWindowTitle, "Assignment 1 | FPS: %d", (int)avgFPS); // Dynamic text
SDL_SetWindowTitle(window, dynamicWindowTitle);
}
void GameWindow::update() {
// ** Set window updating here ** //
//Update the window to display changes (texture)
SDL_RenderPresent(renderer);
//Update the window to display changes (surface)
//SDL_UpdateWindowSurface(window);
//Apply default background colour
SDL_FillRect(backbuffer, NULL, 0);
//Manage frame rate
frameTime = SDL_GetTicks() - frameStart;
if (frameDelay > frameTime) {
SDL_Delay(frameDelay - frameTime);
}
SDL_RenderClear(renderer);
}
void GameWindow::forceQuit() {
std::cerr << "\n\nA critical error has occured, the program will now terminate" << std::endl;
log.writeLog("A critical error has occured, the program will now terminate");
std::cout << "Press ENTER to exit" << std::endl;
std::cin.get();
SDL_Quit();
exit(-1);
}
//Returns gameloop variable status
bool GameWindow::getGameLoop() { return gameloop; }
//Set gameloop variable value
void GameWindow::setGameLoop(bool gameLoop) { this->gameloop = gameLoop; }
// ########### ARCHIVE ########### //
/*
void GameWindow::destroy() {
// ** Destroy window object here ** //
std::cout << "Destroying SDL renderer" << std::endl;
SDL_DestroyRenderer(renderer);
renderer = NULL;
std::cout << "Destroying SDL surface" << std::endl;
SDL_FreeSurface(backbuffer);
backbuffer = NULL;
std::cout << "Destroying SDL window" << std::endl;
SDL_DestroyWindow(window);
window = NULL;
std::cout << "Quitting SDL libraries" << std::endl;
SDL_Quit();
std::cout << "\n\nDone! Press ENTER to exit\n" << std::endl;
std::cin.get();
}
*/ | true |
e77207efa9106d02a125349a93f82c9bcbdc94d5 | C++ | lunakv/henceforth | /Core.cpp | UTF-8 | 6,057 | 2.75 | 3 | [] | no_license | #include <iostream>
#include "Core.hpp"
#include "Exceptions.hpp"
DefDict GetCoreDict() {
DefDict d;
d["+"] = std::make_shared<Add>();
d["-"] = std::make_shared<Sub>();
d["*"] = std::make_shared<Mul>();
d["/"] = std::make_shared<Div>();
d["MOD"] = std::make_shared<Mod>();
d["/MOD"] = std::make_shared<DivMod>();
d["TRUE"] = std::make_shared<Yes>();
d["FALSE"] = std::make_shared<No>();
d["RSHIFT"] = std::make_shared<RShift>();
d["LSHIFT"] = std::make_shared<LShift>();
d["<"] = std::make_shared<Less>();
d[">"] = std::make_shared<More>();
d["="] = std::make_shared<Eq>();
d["<>"] = std::make_shared<NotEq>();
d["AND"] = std::make_shared<And>();
d["OR"] = std::make_shared<Or>();
d["XOR"] = std::make_shared<Xor>();
d["MAX"] = std::make_shared<Max>();
d["MIN"] = std::make_shared<Min>();
d["WITHIN"] = std::make_shared<Within>();
d["1+"] = std::make_shared<AddOne>();
d["1-"] = std::make_shared<SubOne>();
d["2*"] = std::make_shared<Double>();
d["2/"] = std::make_shared<Half>();
d["0="] = std::make_shared<IsZero>();
d["0<"] = std::make_shared<IsNeg>();
d["NEGATE"] = std::make_shared<Negate>();
d["INVERT"] = std::make_shared<Invert>();
d["DUP"] = std::make_shared<Dup>();
d["DROP"] = std::make_shared<Drop>();
d["."] = std::make_shared<Print>();
d["CR"] = std::make_shared<Cr>();
d["SWAP"] = std::make_shared<Swap>();
d["OVER"] = std::make_shared<Over>();
d["ROT"] = std::make_shared<Rot>();
d["DEPTH"] = std::make_shared<Depth>();
return d;
}
// generic binary arithmetic operation
void BinOp(Stack &s, ptrdiff_t(*f)(ptrdiff_t,ptrdiff_t)) {
auto b = s.top(); s.pop();
auto a = s.top(); s.pop();
s.push(f(a, b));
}
void Add::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return a+b; });
}
void Sub::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return a-b; });
}
void Mul::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return a*b; });
}
void Div::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) {
if (!b) throw DivByZero();
return a/b;
});
}
void Mod::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return a%b; });
}
void DivMod::Run(Stack &s, Stack &r, size_t &ip) const {
auto b = s.top(); s.pop();
auto a = s.top(); s.pop();
if (!b) throw DivByZero();
s.push(a % b);
s.push(a / b);
}
void RShift::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return a>>b; });
}
void LShift::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return a<<b; });
}
void Yes::Run(Stack &s, Stack &r, size_t &ip) const {
s.push(1);
}
void No::Run(Stack &s, Stack &r, size_t &ip) const {
s.push(0);
}
Const::Const(ptrdiff_t c) : c(c) {}
void Const::Run(Stack &s, Stack &r, size_t &ip) const {
s.push(c);
}
void More::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return static_cast<ptrdiff_t>(a > b); });
}
void Less::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return static_cast<ptrdiff_t>(a < b); });
}
void Eq::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return static_cast<ptrdiff_t>(a == b); });
}
void NotEq::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return static_cast<ptrdiff_t>(a != b); } );
}
void And::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return a & b; });
}
void Or::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return a | b; });
}
void Xor::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return a^b; });
}
void Max::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return std::max(a, b); });
}
void Min::Run(Stack &s, Stack &r, size_t &ip) const {
BinOp(s, [](auto a, auto b) { return std::min(a, b); });
}
void Within::Run(Stack &s, Stack &r, size_t &ip) const {
auto hi = s.top(); s.pop();
auto lo = s.top(); s.pop();
auto test = s.top(); s.pop();
if (hi >= lo)
s.push(static_cast<ptrdiff_t>(test >= lo && test <= hi));
else
s.push(static_cast<ptrdiff_t>(test >= lo || test <= hi));
}
void AddOne::Run(Stack &s, Stack &r, size_t &ip) const {
++s.top();
}
void SubOne::Run(Stack &s, Stack &r, size_t &ip) const {
--s.top();
}
void Double::Run(Stack &s, Stack &r, size_t &ip) const {
s.top() *= 2;
}
void Half::Run(Stack &s, Stack &r, size_t &ip) const {
s.top() /= 2;
}
void IsZero::Run(Stack &s, Stack &r, size_t &ip) const {
auto t = s.top(); s.pop();
s.push(t == 0);
}
void IsNeg::Run(Stack &s, Stack &r, size_t &ip) const {
auto t = s.top(); s.pop();
s.push(t < 0);
}
void Negate::Run(Stack &s, Stack &r, size_t &ip) const {
s.top() *= -1;
}
void Invert::Run(Stack &s, Stack &r, size_t &ip) const {
s.top() = ~s.top();
}
void Dup::Run(Stack &s, Stack &r, size_t &ip) const {
s.push(s.top());
}
void Drop::Run(Stack &s, Stack &r, size_t &ip) const {
s.pop();
}
void Print::Run(Stack &s, Stack &r, size_t &ip) const {
std::cout << s.top() << ' ';
s.pop();
}
void Cr::Run(Stack &s, Stack &r, size_t &ip) const {
std::cout << std::endl;
}
void Swap::Run(Stack &s, Stack &r, size_t &ip) const {
auto a = s.top(); s.pop();
auto b = s.top(); s.pop();
s.push(a);
s.push(b);
}
void Over::Run(Stack &s, Stack &r, size_t &ip) const {
auto a = s.top(); s.pop();
auto b = s.top();
s.push(a);
s.push(b);
}
void Rot::Run(Stack &s, Stack &r, size_t &ip) const {
auto three = s.top(); s.pop();
auto two = s.top(); s.pop();
auto one = s.top(); s.pop();
s.push(two);
s.push(three);
s.push(one);
}
void Depth::Run(Stack &s, Stack &r, size_t &ip) const {
s.push(s.size());
} | true |
114c9ea3509ab4ceaa929381f80a225eab17125d | C++ | cuhk-gw-suspension/sensactino | /arduino_script/L298N/MyParseNumber.cpp | UTF-8 | 541 | 2.75 | 3 | [
"MIT"
] | permissive | #include "MyParseNumber.h"
/* void myParseInt_(long *pos, char *number, char delimiter){ */
/* *pos = 0; */
/* bool isNegative = (*number=='-'); */
/* if (isNegative) number++; */
/* while (*number != delimiter){ */
/* if (isdigit(*number)) { */
/* *pos = (*pos * 10) + (*number - '0'); */
/* } */
/* number++; */
/* } */
/* if(isNegative) *pos = -(*pos); */
/* } */
void bytesToLong_(long *pos, char *number){
*pos = 0;
for (int i = 0; i < 4; i++)
*pos |= ((long) ((byte)number[i])) << i*8;
}
| true |
f551bb0968ed0b0275c44abcdc7fa21367c5a493 | C++ | Laghitus/sulautetutlabrat | /labra1_2.ino | UTF-8 | 544 | 3.0625 | 3 | [] | no_license |
float voltage = 0;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
pinMode(3, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
if(Serial.available() > 0){
voltage = Serial.parseFloat();
}
analogWrite(3,(voltage/5)*255);
Serial.println((voltage/5)*255);
// print out the value you read:
delay(1); // delay in between reads for stability
}
| true |
50b8be4489cac10f49378aee10f820f9bffd26b3 | C++ | A-KL/the-ray-tracer-challenge | /lib/Core/Shape3D.h | UTF-8 | 773 | 2.6875 | 3 | [] | no_license | #pragma once
#include <list>
#include "Point3D.h"
#include "Vector3D.h"
#include "MatrixOps.hpp"
#include "Material3D.h"
#include "Object3D.h"
class Intersection;
class Ray3D;
class Shape3D : public Object3D
{
public:
Shape3D(const Material3D& material);
Shape3D(const Matrix4d& transform, const Material3D& material);
Shape3D(const Point3D& position, const Matrix4d& transform, const Material3D& material);
const Material3D Material;
const Vector3D NormalAt(const Point3D& point) const;
std::list<Intersection> Intersect(const Ray3D& ray) const;
bool operator==(const Shape3D& other) const;
protected:
virtual const Vector3D LocalNormalAt(const Point3D& point) const = 0;
virtual std::list<Intersection> LocalIntersect(const Ray3D& ray) const = 0;
}; | true |
57ae20f3bf01a292111e072ad6be1a40163caa75 | C++ | RuiMoreira1/CAL-Project-FasterServices | /main.cpp | UTF-8 | 1,406 | 2.546875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include "graph/Graph.h"
#include "GraphMaker.h"
#include "GraphImporter.h"
#include "Solver.h"
int main() {
/*GraphViewer gv; // Instantiate GraphViewer
gv.setCenter(sf::Vector2f(300, 300)); // Set coordinates of window center
GraphViewer::Node &node0 = gv.addNode(0, sf::Vector2f(200, 300)); // Create node
node0.setColor(GraphViewer::BLUE);
GraphViewer::Node &node1 = gv.addNode(1, sf::Vector2f(400, 100));
GraphViewer::Edge &edge1 =
gv.addEdge(0,node0,node1,GraphViewer::Edge::EdgeType::UNDIRECTED);
gv.createWindow(600, 600); // Create window
gv.join(); // Join viewer thread (blocks till window closed)
return 0;*/
GraphMaker g1;
GraphImporter *gM = new GraphImporter();
Graph<unsigned > *graph = gM->importAll("../resources/maps/GridGraphs/8x8/nodes.txt","../resources/maps/GridGraphs/8x8/edges.txt",
"../resources/maps/GridGraphs/workers","../resources/maps/GridGraphs/company_garage");
//graph->addVertex(1,200,200);
//graph->addVertex(2,324,435);
//graph->addEdge(1,2);
Graph<unsigned > graph1 = *graph;
Solver *s1 = new Solver(graph);
vector<unsigned> path = s1->tsp();
for( auto v: path){
cout << v << endl;
}
g1.draw(graph);
//g1.routeDraw(graph,path);
g1.view();
}
| true |
84bb7d83b47ba1fc4b22d88c2c4d2efa72c7d314 | C++ | sparshgoyal2014/cppCodes | /testNull.cpp | UTF-8 | 208 | 2.796875 | 3 | [] | no_license | #include<iostream>
using namespace std;
void display(){
cout << "this is dis[pplay function" << endl;
return ;
}
int main(){
display();
void *p = NULL;
cout << p << endl;
return 0;
} | true |
e48f75563adb851a473a9d59ddfb3e3f2104b657 | C++ | novin997/cs5222-lab-prefetcher | /example_prefetchers/ghbac_setAsso.cc | UTF-8 | 6,843 | 2.515625 | 3 | [] | no_license | //
// Data Prefetching Championship Simulator 2
// Seth Pugsley, seth.h.pugsley@intel.com
//
/*
This file does NOT implement any prefetcher, and is just an outline
*/
#include <stdio.h>
#include <assert.h>
#include "../inc/prefetcher.h"
#include <unordered_map>
#include <deque>
#include <iostream>
#define GHB_SIZE 1024
#define INDEX_SIZE 1024
#define SET_ASSOCIATION 4
#define SET_SIZE INDEX_SIZE/SET_ASSOCIATION
typedef struct GHB
{
// Miss address
unsigned long long int miss_addr;
// Pointer to the previous miss address in GHB
long long int link_pointer;
} GHB_t;
typedef struct index_table
{
// Miss address
unsigned long long int miss_addr;
// Pointer to the GHB
long long int pointer;
} index_table_t;
GHB_t GHB[GHB_SIZE];
index_table_t index_table[INDEX_SIZE];
long long int global_pointer;
std::deque<int> lru[SET_SIZE];
void l2_prefetcher_initialize(int cpu_num)
{
printf("No Prefetching\n");
// you can inspect these knob values from your code to see which configuration you're runnig in
printf("Knobs visible from prefetcher: %d %d %d\n", knob_scramble_loads, knob_small_llc, knob_low_bandwidth);
// Create Global History Buffer table
for(int i = 0; i < GHB_SIZE; i++)
{
GHB[i].miss_addr = 0;
GHB[i].link_pointer = -1;
}
// Create Index table
for(int i = 0; i < INDEX_SIZE; i++)
{
index_table[i].miss_addr = 0;
index_table[i].pointer = -1;
}
// Set head pointer to 0
global_pointer = 0;
}
void l2_prefetcher_operate(int cpu_num, unsigned long long int addr, unsigned long long int ip, int cache_hit)
{
// uncomment this line to see all the information available to make prefetch decisions
unsigned long long int ip_index = ip & (SET_SIZE-1);
long long int current_pointer = 0;
std::unordered_map<unsigned long long int, int> hash_table;
bool add_addr = 0;
bool addr_found = 0;
if(cache_hit == 0)
{
printf("(0x%llx 0x%llx %d %d %d) ", addr, ip, cache_hit, get_l2_read_queue_occupancy(0), get_l2_mshr_occupancy(0));
// printf("%llu\n",global_pointer);
/* Access the index table to check if there is such an address */
for(int j=0; j<SET_ASSOCIATION; j++)
{
if(index_table[ip_index+j*SET_SIZE].miss_addr == addr)
{
printf("test");
/* If there is an address, get pointer to the GHB */
current_pointer = index_table[ip_index+j*SET_SIZE].pointer;
/* Add the miss address to the GHB */
GHB[global_pointer].miss_addr = addr;
GHB[global_pointer].link_pointer = current_pointer;
/* Iterate the linked list of the GHB to get the Markov Prefetching */
/* Iterate until the first pointer or if the address does not match */
/* The Hashmap will count the highest occurance of the next prefetch address */
do
{
long long int next_pointer = (current_pointer+1) % GHB_SIZE;
long long int temp_addr = GHB[next_pointer].miss_addr;
hash_table[temp_addr]++;
current_pointer = GHB[current_pointer].link_pointer;
}while(GHB[current_pointer].link_pointer != current_pointer || addr != GHB[current_pointer].miss_addr);
/* Find the highest number of occurances in the markov prefetch */
int max_count = 0;
unsigned long long int dataAddress = 0;
for(auto i : hash_table)
{
if(max_count < i.second)
{
dataAddress = i.first;
max_count = i.second;
}
}
/* Prefetch the address the highest number of occurances */
l2_prefetch_line(0, addr, dataAddress, FILL_L2);
/* Update index table to the current the pointer */
index_table[ip_index+j*SET_SIZE].pointer = global_pointer;
/* Update the LRU Queue */
for(std::deque<int>::iterator it = lru[ip_index].begin(); it != lru[ip_index].end();)
{
if(*it == j)
it = lru[ip_index].erase(it);
else
it++;
}
lru[ip_index].push_front(j);
// lru[ip_index].push(j-1);
// if(lru[ip_index].size() > SET_ASSOCIATION)
// lru[ip_index].pop() ;
//Exit out the for loop as the block address has been found
global_pointer = (global_pointer+1) % GHB_SIZE;
return;
}
}
/* Look for any empty slots in the index table */
for(int j=0; j<SET_ASSOCIATION; j++)
{
if(index_table[ip_index+j*SET_SIZE].pointer == -1)
{
/* If there is no such address, update the index table and GHB */
index_table[ip_index+j*SET_SIZE].miss_addr = addr;
index_table[ip_index+j*SET_SIZE].pointer = global_pointer;
GHB[global_pointer].miss_addr = addr;
GHB[global_pointer].link_pointer = global_pointer;
lru[ip_index].push_front(j);
global_pointer = (global_pointer+1) % GHB_SIZE;
return;
}
}
/* Look LRU Queue to determine which block of memory to remove */
int j = 0;
j = lru[ip_index].back();
printf("%llu\n",global_pointer);
printf("%d\n",j);
lru[ip_index].push_front(j);
if(lru[ip_index].size() > SET_ASSOCIATION)
lru[ip_index].pop_back();
index_table[ip_index+j*SET_SIZE].miss_addr = addr;
index_table[ip_index+j*SET_SIZE].pointer = global_pointer;
GHB[global_pointer].miss_addr = addr;
GHB[global_pointer].link_pointer = global_pointer;
global_pointer = (global_pointer+1) % GHB_SIZE;
return;
}
else
{
/* code */
}
}
void l2_cache_fill(int cpu_num, unsigned long long int addr, int set, int way, int prefetch, unsigned long long int evicted_addr)
{
// uncomment this line to see the information available to you when there is a cache fill event
// printf("0x%llx %d %d %d 0x%llx\n", addr, set, way, prefetch, evicted_addr);
}
void l2_prefetcher_heartbeat_stats(int cpu_num)
{
printf("Prefetcher heartbeat stats\n");
}
void l2_prefetcher_warmup_stats(int cpu_num)
{
printf("Prefetcher warmup complete stats\n\n");
}
void l2_prefetcher_final_stats(int cpu_num)
{
printf("Prefetcher final stats\n");
}
| true |
0d90a3e4498b8b70b93c89a28a96e4bd631ce323 | C++ | dotnet/runtime | /src/mono/mono/eglib/test/enum.cpp | UTF-8 | 1,099 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "config.h"
#include "glib.h"
typedef enum {
Black = 0,
Red = 1,
Blue = 2,
Purple = Red | Blue, // 3
Green = 4,
Yellow = Red | Green, // 5
White = 7,
} Color;
G_ENUM_FUNCTIONS (Color)
static void
test_enum1 (void)
{
const Color green = Green;
const Color blue = Blue;
const Color red = Red;
const Color white = White;
const Color purple = Purple;
g_assert ((red & blue) == Black);
g_assert ((red | blue | green) == White);
g_assert ((red | blue) == Purple);
g_assert ((white ^ purple) == green);
Color c = Black;
Color c2 = Black;
c |= red;
g_assert (c == Red);
c ^= red;
g_assert (c == Black);
c |= (c2 |= Red) | Blue;
g_assert (c == Purple);
g_assert (c2 == Red);
c = c2 = Black;
c |= (c2 |= Red) |= Blue;
g_assert (c == Purple);
g_assert (c2 == Purple);
c = red;
c &= red;
g_assert (c == Red);
c &= blue;
g_assert (c == Black);
}
#include "test.h"
static RESULT
test_enum (void)
{
test_enum1 ();
return OK;
}
const static Test enum_tests [2] = {{"test_enum", test_enum}};
extern "C"
{
DEFINE_TEST_GROUP_INIT (enum_tests_init, enum_tests)
}
| true |
35f42c8aa4902dd82df2d7abd2cd1b51ad0d3215 | C++ | YuraVasiuk/Custom-Made-Data-Structures | /week12_Hash/hash.h | UTF-8 | 4,295 | 3.84375 | 4 | [] | no_license | #include <list>
#include <string>
#include <assert.h>
using namespace std;
/****************************************
* HASH
* The parent template hash class
****************************************/
template <typename T>
class Hash
{
public:
// the constructors
Hash() : numBuckets(0), numElements(0), buckets(NULL) {}
Hash(int numBuckets) throw (const char *) ;
Hash(const Hash & rhs) throw (const char *) ;
// destructor
~Hash()
{
//if (numBuckets != 0)
//delete[] buckets;
}
// is the hash empty?
bool empty() const
{
if (numElements == 0)
return true;
else
return false;
}
// return the array's capacity
int capacity() const { return numBuckets; }
// how many elements does the hash have?
int size() const { return numElements; }
// clear the content of the hash
void clear();
// is the item in the hash?
bool find(T item) const;
// insert the item into the hash
void insert(T item);
// pure vitual hash function
virtual int hash(T & value) const = 0;
private:
int numBuckets;
int numElements;
list<T> * buckets;
};
/****************************************
* HASH : NON-DEFAULT CONSTRUCTOR
* Allocate the array of the passed number of list, assign the variables
****************************************/
template <typename T>
Hash<T>::Hash(int numBuckets) throw (const char *)
{
this->numBuckets = numBuckets;
numElements = 0;
try
{
buckets = new list<T> [this->numBuckets];
}
catch (bad_alloc)
{
cout << "ERROR: Unable to allocate memory for the hash.";
}
}
/****************************************
* HASH : COPY CONSTRUCTOR
* Make a new hash, the same with the passed one
****************************************/
template <typename T>
Hash<T>::Hash(const Hash & rhs) throw (const char *)
{
// copy the empty hash with no capacity
if ((rhs.empty() == true) && (rhs.capacity() == 0))
{
this->numBuckets = 0;
this->numElements = 0;
buckets = NULL;
}
// copy the empty hash with some capacity
else if (rhs.empty() == true)
{
this->numBuckets = rhs.numBuckets;
this->numElements = 0;
try
{
buckets = new list<T>[numBuckets];
}
catch (bad_alloc)
{
cout << "ERROR: Unable to allocate memory for the hash.";
}
}
// copy the hash with some elements
else
{
this->numBuckets = rhs.numBuckets;
this->numElements = rhs.numElements;
try
{
buckets = new list<T>[numBuckets];
}
catch (bad_alloc)
{
cout << "ERROR: Unable to allocate memory for the hash.";
}
for (int i = 0; i < rhs.numBuckets; i++)
{
if (!rhs.buckets[i].empty())
{
this->buckets = rhs.buckets;
}
}
}
}
/****************************************
* HASH : CLEAR
* Clear the content of the hash
****************************************/
template <typename T>
void Hash<T>::clear()
{
if (!empty())
{
for (int i = 0; i < numBuckets; i++)
{
if (!buckets[i].empty())
{
buckets[i].clear();
}
}
}
}
/****************************************
* HASH : FIND
* Is the element in the hash?
****************************************/
template <typename T>
bool Hash<T>::find(T element) const
{
if (!empty())
{
int index = hash(element);
for (list<T>::iterator it = buckets[index].begin(); it != buckets[index].end(); it++)
{
if (*it == element)
return true;
}
}
return false;
}
/****************************************
* HASH : INSERT
* Insert the element into the hash?
****************************************/
template <typename T>
void Hash<T>::insert(T element)
{
int index = hash(element);
buckets[index].push_back(element);
numElements++;
}
/****************************************
* SHASH
* A hash of strings : It inherits from HASH class
****************************************/
class SHash : public Hash <string>
{
public:
SHash(int numBuckets) throw (const char *) : Hash <string>(numBuckets) {}
SHash(const SHash & rhs) throw (const char *) : Hash <string>(rhs) {}
// hash function for integers is simply to take the modulous
int hash(string & word) const
{
int index = 0;
int sumLetters = 0;
for (string::iterator it = word.begin(); it != word.end(); it++)
{
sumLetters += static_cast<int>(*it);
}
index = sumLetters % capacity();
assert(index >= 0 && index < 232);
return index;
}
};
| true |
54fb92ad27ec884801740085cad6d229563d5dd6 | C++ | walkccc/LeetCode | /solutions/0264. Ugly Number II/0264.cpp | UTF-8 | 535 | 3.25 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int nthUglyNumber(int n) {
vector<int> uglyNums{1};
int i2 = 0;
int i3 = 0;
int i5 = 0;
while (uglyNums.size() < n) {
const int next2 = uglyNums[i2] * 2;
const int next3 = uglyNums[i3] * 3;
const int next5 = uglyNums[i5] * 5;
const int next = min({next2, next3, next5});
if (next == next2)
++i2;
if (next == next3)
++i3;
if (next == next5)
++i5;
uglyNums.push_back(next);
}
return uglyNums.back();
}
};
| true |
7b130098ff4019956ef88cf4c6fd834dda274b93 | C++ | shaylajayde/BowlingAverages | /BowlingAverages.cpp | UTF-8 | 4,576 | 3.6875 | 4 | [] | no_license | // BowlingAverages.cpp : This file contains the 'main' function, along with an int function (GetBowlingData) and 2 void functions
// (GetAverageScore) and (PrettyPrintResults). Program execution begins and ends there.
//
// This program takes in data from a file titled "BowlingScoresModified.txt".
// Uses parallel arrays, arrays as parameters
// including header file
#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
//global constant to store file name as a string
const string inputFile = ("BowlingScoresModified.txt");
//global const for number of rows/columns
const int total_rows = 10;
const int total_cols = 5;
// global consts for setw's
const int nameSet = 24;
const int secondarySet = 10;
const int playerSet = 14;
const int scoreSet = 5;
const int averageSet = 7;
// defining structure
struct scoresData {
//string to hold name of bowler
string playerNames;
//one dimensional array of ints to store bowlers 4 scores
int playerScores[total_cols];
//int to hold average bowling scores
int playerAverage;
};
//function to read and store data into two arrays. takes in file name and empty arrays as input parameters from file BowlingScores.txt; returns
//a status of success or failure (true or false)
int GetBowlingData(string inputFile, scoresData arrScores[])
{
// attempting to use same code from the program to count the letters for file errors
// opening input file
ifstream inFile;
inFile.open(inputFile);
// attempting to use same code from the program to count the letters for file errors - pg 221 in textbook
// error if file fails
if (!inFile) {
cout << "Error with file" << endl;
return 1;
}
// for loop for players names (rows)
for (int r = 0; r < total_rows; r++)
{
inFile >> arrScores[r].playerNames;
// for loop for players scores (columns)
for (int c = 0; c < total_cols; c++)
{
inFile >> arrScores[r].playerScores[c];
}
}
// pausing
system("pause");
// closing out the open file
inFile.close();
return 1;
}
//function to calculate the average bowling score. takes as input arrays from GetBowlingData and returns the average score of each bowler
//in a separate array
void GetAverageScore(scoresData arrScores[])
{
// assigning variable for average score
//int averageScore;
// int to run through rows
for (int r = 0; r < total_rows; r++)
{
// assigning the value of total to 0 - everytime it runs through the loop, it reinitializes to 0 to store new value for next player
int total = 0;
// for loop to add player scores together based on columns
for (int c = 0; c < total_cols; c++)
{
total += arrScores[r].playerScores[c];
}
// taking the total for each value and dividing by 4 (number of columns of scores)
arrScores[r].playerAverage = total / total_cols;
// reassigning averageScore to playerAverage[i]
//arrScores[r].playerAverage = averageScore;
}
}
//function that ouptuts the results: bowler name, scores and average
void PrettyPrintResults(scoresData arrScores[])
{
cout << "" << endl;
cout << setw(nameSet) << left << "Player Name" << setw(secondarySet) << left << "Player Scores " << setw(secondarySet) << " " << left << "Player Average" << endl;
cout << "" << endl;
// for loop for rows
for (int r = 0; r < total_rows; r++)
{
// printing out the player names
cout << setw(playerSet) << left << arrScores[r].playerNames << " ";
cout << setw(scoreSet) << " ";
// for loop for running through columns for scores
for (int c = 0; c < total_cols; c++)
{
// printing out the player scores
cout << setw(scoreSet) << left << arrScores[r].playerScores[c] << " ";
}
// printing out the players average score
cout << setw(averageSet) << " ";
cout << setw(secondarySet) << left << arrScores[r].playerAverage << " " << endl;
}
}
//main function
int main()
{
// assigning values to names, scores, and averages for all players
// 10 players total (rows = r)
// each player has 4 scores listed (columns = c)
//string playerNames[total_rows];
//int playerScores[total_rows][total_cols] = { 0 };
// player average has to run through all 10 players (10 rows)
//float playerAverage[total_rows] = { 0 };
// calling the functions with parameters
//GetBowlingData(scoreData, playerNames, playerScores);
//GetAverageScore(playerScores, playerAverage);
//PrettyPrintResults(playerNames, playerScores, playerAverage);
// struct
scoresData arrScores[total_rows];
GetBowlingData(inputFile, arrScores);
GetAverageScore(arrScores);
PrettyPrintResults(arrScores);
}
| true |
d8096ad79cad4db9211e64e0d42edcfe0b198e4b | C++ | hanzec/Dungeon | /src/Utils/DungeonUtils.cpp | UTF-8 | 3,958 | 2.96875 | 3 | [] | no_license | #include <queue>
#include "../../include/Utils/DungeonUtils.h"
#include "../../include/GameContant/Monster.h"
void DungeonUtils::OrderedList::push(std::list<Monster * > * monsters, Monster * monster){
for ( auto i = monsters->begin(); i != monsters->end(); i++){
if((*i)->nextMoveTime > monster->nextMoveTime){
monsters->insert(i,monster);
return;
}
}
monsters->push_back(monster);
}
Monster * DungeonUtils::OrderedList::pop_min(std::list<Monster * > * monsters){
Monster * result = monsters->front();
monsters->pop_front();
return result;
}
static int32_t corridor_node_cmp(const void *key, const void *with) {
return ((corridor_node_t *) key)->cost - ((corridor_node_t *) with)->cost;
}
void DungeonUtils::Path::dijkstra_no_tunnelling(dungeon_t *dungeon, location_t playerLocation){
heap_t h;
corridor_node_t *prev_node;
for (uint16_t y = 0; y < DUNGEON_Y; y++) {
for (uint16_t x = 0; x < DUNGEON_X; x++) {
dungeon->nontunnel[y][x].pos[curr_y] = y;
dungeon->nontunnel[y][x].pos[curr_x] = x;
dungeon->nontunnel[y][x].cost = INT32_MAX;
}
}
dungeon->nontunnel[playerLocation[curr_y]][playerLocation[curr_x]].cost = 0;
heap_init(&h, corridor_node_cmp, NULL);
heap_insert(&h,&dungeon->nontunnel[playerLocation[curr_y]][playerLocation[curr_x]]);
while (h.size != 0){
prev_node = (corridor_node_t *) heap_remove_min(&h);
for (int8_t i = -1; i < 2; ++i) {
for (int8_t j = -1; j < 2 ; ++j) {
uint16_t x = j + prev_node->pos[curr_x];
uint16_t y = i + prev_node->pos[curr_y];
if (checkLocation(x,y)){
if (dungeon->map[y][x].terrain_type != ter_wall){
if (prev_node->cost + 1 < dungeon->nontunnel[y][x].cost){
dungeon->nontunnel[y][x].prev_node = prev_node;
dungeon->nontunnel[y][x].cost = prev_node->cost + 1;
heap_insert(&h,&dungeon->nontunnel[y][x]);
}
}
}
}
}
}
heap_delete(&h);
}
void DungeonUtils::Path::dijkstra_tunnelling(dungeon_t *dungeon, location_t playerLocation){
heap_t h;
corridor_node_t *prev_node;
for (uint16_t y = 0; y < DUNGEON_Y; y++) {
for (uint16_t x = 0; x < DUNGEON_X; x++) {
dungeon->tunnel[y][x].pos[curr_y] = y;
dungeon->tunnel[y][x].pos[curr_x] = x;
dungeon->tunnel[y][x].cost = INT32_MAX;
}
}
dungeon->tunnel[playerLocation[curr_y]][playerLocation[curr_x]].cost = 0;
heap_init(&h, corridor_node_cmp, NULL);
heap_insert(&h,&dungeon->tunnel[playerLocation[curr_y]][playerLocation[curr_x]]);
while (h.size != 0){
prev_node = (corridor_node_t*) heap_remove_min(&h);
for (int8_t i = -1; i < 2; ++i) {
for (int8_t j = -1; j < 2 ; ++j) {
uint16_t x = j + prev_node->pos[curr_x];
uint16_t y = i + prev_node->pos[curr_y];
if (checkLocation(x,y)){
int weight_tmp = 0;
if (dungeon->map[y][x].terrain_type == ter_wall_immutable)
break;
if (dungeon->map[y][x].hardness == 0){
weight_tmp = 1 + prev_node->cost;
}else{
weight_tmp = 1 + dungeon->map[y][x].hardness/85 + prev_node->cost;
}
if (weight_tmp < dungeon->tunnel[y][x].cost){
dungeon->tunnel[y][x].prev_node = prev_node;
dungeon->tunnel[y][x].cost = weight_tmp;
heap_insert(&h,&dungeon->tunnel[y][x]);
}
}
}
}
}
heap_delete(&h);
}
| true |
c2fcd3da178751a7a99638b8ff57a61ac506fa97 | C++ | mrippa/cpp-list | /listtest.cpp | UTF-8 | 1,053 | 3 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include "list.h"
int main() {
list* mylist = new list();
//char a = 't';
mylist->prepend(10);
mylist->prepend(100);
cout << "Hello World1 " << mylist << endl;
mylist->print();
mylist->rprint(mylist->get_head());
cout << "Hello World\n" << endl;
delete mylist;
list a,b;
a.prepend(-3);
a.prepend(9);
a.prepend(8);
a.prepend(2);
cout << "*******list a********" << endl;
a.print();
cout << "*******list k********" << endl;
list k(a);
k.print();
int data[10] = {3,4,6,7,-3,5};
list d(data, 6);
list e(data, 10);
// for(int i=0; i<40; ++i)
// b.prepend(i * i);
cout << "*******list b********" << endl;
b.print();
cout << "*******list c********" << endl;
list c(b);
c.print();
cout << "*******list e********" << endl;
e.print();
cout << "*******list d********" << endl;
d.print();
cout << endl;
cout << endl;
cout << endl;
//list d(data, 10);
}
| true |
2487704100bffb30b958c16217dde6ce89f724d0 | C++ | affilares/snoopwpf | /Snoop.GenericInjector/Executor.cpp | UTF-8 | 3,060 | 2.84375 | 3 | [
"MS-PL"
] | permissive | #include "pch.h"
#include <array>
#include <string>
#include <vector>
#include <comdef.h>
#include "NetCoreApp3_0Executor.h"
#include "NetFull4_0Executor.h"
bool icase_wchar_cmp(const wchar_t a, const wchar_t b)
{
return std::tolower(a) == std::tolower(b);
}
bool icase_cmp(std::wstring const& s1, std::wstring const& s2)
{
return s1.size() == s2.size()
&& std::equal(s1.begin(), s1.end(), s2.begin(), icase_wchar_cmp);
}
std::vector<std::wstring> split(const std::wstring& input, const std::wstring& delimiter)
{
std::vector<std::wstring> parts;
std::wstring::size_type startIndex = 0;
std::wstring::size_type endIndex;
while ((endIndex = input.find(delimiter, startIndex)) < input.size())
{
auto val = input.substr(startIndex, endIndex - startIndex);
parts.push_back(val);
startIndex = endIndex + delimiter.size();
}
if (startIndex < input.size())
{
const auto val = input.substr(startIndex);
parts.push_back(val);
}
return parts;
}
std::unique_ptr<FrameworkExecutor> GetExecutor(const std::wstring& framework)
{
OutputDebugStringEx(L"Trying to get executor for framework '%s'...", framework.c_str());
if (icase_cmp(framework, L"netcoreapp3.0")
|| icase_cmp(framework, L"netcoreapp3.1"))
{
return std::make_unique<NetCoreApp3_0Executor>();
}
if (icase_cmp(framework, L"net40"))
{
return std::make_unique<NetFull4_0Executor>();
}
OutputDebugStringEx(L"Framework '%s' is not supported.", framework.c_str());
return nullptr;
}
extern "C" __declspec(dllexport) int STDMETHODVCALLTYPE ExecuteInDefaultAppDomain(const LPCWSTR input)
{
try
{
OutputDebugStringEx(input);
const auto parts = split(input, L"<|>");
if (parts.size() != 5)
{
OutputDebugStringEx(L"Not enough parameters.");
return E_INVALIDARG;
}
const auto& framework = parts.at(0);
const auto& assemblyPath = parts.at(1);
const auto& className = parts.at(2);
const auto& method = parts.at(3);
const auto& parameter = parts.at(4);
const auto executor = GetExecutor(framework);
if (!executor)
{
OutputDebugStringEx(L"No executor found.");
return E_NOTIMPL;
}
DWORD* retVal = nullptr;
const auto hr = executor->Execute(assemblyPath.c_str(), className.c_str(), method.c_str(), parameter.c_str(), retVal);
if (FAILED(hr))
{
const _com_error err(hr);
OutputDebugStringEx(L"Error while calling '%s' on '%s' from '%s' with '%s'", method.c_str(), className.c_str(), assemblyPath.c_str(), parameter.c_str());
OutputDebugStringEx(L"HResult: %i", hr);
OutputDebugStringEx(L"Message: %s", err.ErrorMessage());
OutputDebugStringEx(L"Description: %s", std::wstring(err.Description(), SysStringLen(err.Description())).c_str());
}
return hr;
}
catch (std::exception& exception)
{
OutputDebugStringEx(L"ExecuteInDefaultAppDomain failed with exception.");
OutputDebugStringEx(L"Exception:");
OutputDebugStringEx(to_wstring(exception.what()));
}
catch (...)
{
OutputDebugStringEx(L"ExecuteInDefaultAppDomain failed with unknown exception.");
}
return E_FAIL;
}
| true |
31ec5b1f1a8a94ada4520f7119c390a46ff7ca0d | C++ | cpv-project/cpv-cql-driver | /src/LowLevel/RequestMessages/RegisterMessage.hpp | UTF-8 | 887 | 2.734375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "../ProtocolTypes/ProtocolStringList.hpp"
#include "./RequestMessageBase.hpp"
namespace cql {
/**
* Register this connection to receive some types of events
* The response to a REGISTER message will be a READY message.
*/
class RegisterMessage : public RequestMessageBase {
public:
using RequestMessageBase::freeResources;
/** For Reusable */
void reset(MessageHeader&& header);
/** Get description of this message */
std::string toString() const override;
/** Encode message body to binary data */
void encodeBody(const ConnectionInfo& info, std::string& data) const override;
/** Get the event types to register for */
const ProtocolStringList& getEvents() const& { return events_; }
ProtocolStringList& getEvents() & { return events_; }
/** Constructor */
RegisterMessage();
private:
ProtocolStringList events_;
};
}
| true |
cd4d58d92f5bf2035fcc86224cd34e76b5048003 | C++ | BethIovine/BethSTL | /heap.h | UTF-8 | 3,336 | 3.125 | 3 | [] | no_license | //
// Created by Hemingbear on 2021/3/10.
//
#ifndef BETHSTL_HEAP_H
#define BETHSTL_HEAP_H
// heap operation mostly base on vector container.
template<class RandomAccessIterator>
inline void push_heap(RandomAccessIterator first, RandomAccessIterator last) {
push_heap_aux(first, last, size_type(first), value_type(first));
}
template<class RandomAccessIterator, class Distance, class T>
inline void push_heap_aux(RandomAccessIterator first, RandomAccessIterator last, Distance *, T *) {
_push_heap(first, Distance((last - first) - 1), Distance(0), T(*(last - 1)));
}
template<class RandomAccessIterator, class Distance, class T>
void _push_heap(RandomAccessIterator first, Distance holeIndex, Distance topIndex, T value) {
Distance parentIndex = (holeIndex - 1) / 2;
while (parentIndex >= topIndex && *(first + parentIndex) < value) {
*(first + holeIndex) = *(first + parentIndex);
holeIndex = parentIndex;
parentIndex = (holeIndex - 1) / 2;
}
*(first + holeIndex) = value;
}
template<class RandomAccessIterator>
inline void pop_heap(RandomAccessIterator first, RandomAccessIterator last) {
pop_heap_aux(first, last, value_type(first));
}
template<class RandomAccessIterator, class T>
inline void pop_heap(RandomAccessIterator first, RandomAccessIterator last, T *) {
_pop_heap(first, last - 1, last - 1, T(*(last - 1)), size_type(first));
}
template<class RandomAccessIterator, class T, class Distance>
inline void
_pop_heap(RandomAccessIterator first, RandomAccessIterator last, RandomAccessIterator result, T value, Distance *) {
*result = *first; // set back value to back() , so back() is wanted value;
_adjust_heap(first, Distance(0), Distance(last - first), value);
}
template<class RandomAccessIterator, class Distance, class T>
void _adjust_heap(RandomAccessIterator first, Distance holeIndex, Distance len, T value) {
Distance topIndex = holeIndex;
Distance secondChild = holeIndex * 2 + 2;
while (secondChild < len) {
if (*(first + secondChild - 1) > *(first + secondChild)) --secondChild;
*(first + holeIndex) = *(first + secondChild);
holeIndex = secondChild;
secondChild = holeIndex * 2 + 2;
}
// holeIndex has no secondChild, compare with first chi
if (secondChild == len) {
*(first + holeIndex) = *(first + (secondChild - 1));
holeIndex = secondChild - 1;
}
// not remove last biggest node, need do one more vector::pop_back()
}
template<class RandomAccessIterator>
inline void sort_heap(RandomAccessIterator first, RandomAccessIterator last) {
while (last - first > 1) {
pop_heap(first, last--);
}
}
template<class RandomAccessIterator>
inline void make_heap(RandomAccessIterator first, RandomAccessIterator last) {
make_heap_aux(first, last, value_type(first), size_type(first));
}
template<class RandomAccessIterator, class T, class Distance>
void make_heap_aux(RandomAccessIterator first, RandomAccessIterator last, T *, Distance *) {
if (last - first < 2) return;
Distance len = last - first;
Distance parent = (len - 2) / 2; // find first sorted parent node, leaf node don't need adjust
while (true) {
_adjust_heap(first, parent, len, T(*(first + parent)));
parent--;
}
}
#endif //BETHSTL_HEAP_H
| true |
7042f469b43ae6b22245e36cf39f3e75c2932349 | C++ | tomfunkhouser/gaps | /pkgs/R3Surfels/R3SurfelLabelAssignment.cpp | UTF-8 | 2,467 | 2.6875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | /* Source file for the R3 label assignment class */
////////////////////////////////////////////////////////////////////////
// INCLUDE FILES
////////////////////////////////////////////////////////////////////////
#include "R3Surfels.h"
////////////////////////////////////////////////////////////////////////
// Namespace
////////////////////////////////////////////////////////////////////////
namespace gaps {
////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS/DESTRUCTORS
////////////////////////////////////////////////////////////////////////
R3SurfelLabelAssignment::
R3SurfelLabelAssignment(R3SurfelObject *object, R3SurfelLabel* label, RNScalar confidence, int originator)
: scene(NULL),
scene_index(-1),
object(object),
object_index(-1),
label(label),
label_index(-1),
confidence(confidence),
originator(originator),
data(NULL)
{
}
R3SurfelLabelAssignment::
R3SurfelLabelAssignment(const R3SurfelLabelAssignment& assignment)
: scene(NULL),
scene_index(-1),
object(assignment.object),
object_index(-1),
label(assignment.label),
label_index(-1),
confidence(assignment.confidence),
originator(assignment.originator),
data(NULL)
{
}
R3SurfelLabelAssignment::
~R3SurfelLabelAssignment(void)
{
// Remove from scene (removes from everything)
if (scene) scene->RemoveLabelAssignment(this);
}
////////////////////////////////////////////////////////////////////////
// PROPERTY MANIPULATION FUNCTIONS
////////////////////////////////////////////////////////////////////////
R3SurfelLabelAssignment& R3SurfelLabelAssignment::
operator=(const R3SurfelLabelAssignment& assignment)
{
// Copy properties
this->object = assignment.object;
this->object_index = -1;
this->label = assignment.label;
this->label_index = -1;
this->confidence = assignment.confidence;
this->originator = assignment.originator;
// Return this
return *this;
}
void R3SurfelLabelAssignment::
SetConfidence(RNScalar confidence)
{
// Set confidence
this->confidence = confidence;
// Mark scene as dirty
if (scene) scene->SetDirty();
}
void R3SurfelLabelAssignment::
SetOriginator(int originator)
{
// Set originator
this->originator = originator;
// Mark scene as dirty
if (scene) scene->SetDirty();
}
void R3SurfelLabelAssignment::
SetData(void *data)
{
// Set user data
this->data = data;
}
} // namespace gaps
| true |
7b476c46bf3e39eb6576594c6cf63b178f164dc9 | C++ | Faizii992/Online-Solutions-2.2-Algorithm | /SCCShowallcomponentsandshowinputtedcomps.cpp | UTF-8 | 1,814 | 2.765625 | 3 | [] | no_license | #include<bits/stdc++.h>
#define true 1
#define false 0
#define white 0
#define grey 1
using namespace std;
int node,edge;
vector < int > adj[10];
vector < int > revadj[10];
stack < int > stck;
int color[100];
int x;
int mark=-1;
vector < int > scc[100];
int visited[100];
void DFS(int s)
{
color[s]=grey;
for(int i=0;i<adj[s].size();i++)
{
if(color[adj[s][i]]==white)
{
DFS(adj[s][i]);
}
}
stck.push(s);
}
void DFS2(int s)
{
scc[mark].push_back(s);
cout<<s<<endl;
visited[s]=true;
for(int i=0;i<revadj[s].size();i++)
{
if(visited[revadj[s][i]]==false)
{
DFS2(revadj[s][i]);
}
}
//stck.push(s);
}
int main()
{
cout<<"Enter node and edge: "<<endl;
cin>>node>>edge;
for(int i=0;i<edge;i++)
{
adj[i].clear();
revadj[i].clear();
}
cout<<"Enter two vertices: "<<endl;
for(int i=0;i<edge;i++)
{
int a,b;
cin>>a>>b;
adj[a].push_back(b);
revadj[b].push_back(a);
}
for(int i=0;i<node;i++)
{
if(color[i]==white)
{
DFS(i);
}
}
while(!stck.empty())
{
int u=stck.top();
stck.pop();
//cout<<u<<endl;
if(visited[u]==false)
{
mark++;
cout<<"Component no :"<<mark+1<<" has the following components :"<<endl;
x=0;
DFS2(u);
}
}
int x;
cout<<"Enter the comp to find "<<endl;
cin>>x;
for(int i=0;i<scc[x-1].size();i++)
{
cout<<scc[x-1][i]<<" "<<endl;
}
}
| true |
3677fb7763e841c942f9a7c2d771b99d8ed6e31f | C++ | XFone/exapi | /src/concurrent/fifo/FakeQueue.h | UTF-8 | 4,010 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | /*
* $Id: $
*
* Faked FIFO queue (contains only one item) for testing /debuging
*
* Copyright (c) 2014-2015 Zerone.IO (Shanghai). All rights reserved.
*
* $Log: $
*
*/
#pragma once
/** @file FakeQueue.h Faked FIFO/Queue */
#include "Base.h"
#include "Trace.h"
#include "IQueue.h"
#ifdef USE_TBB
#include <tbb/atomic.h>
#else
#include <atomic>
#endif
namespace ATS {
#ifndef USE_TBB
/**
* FIFO queue (contains only one item) for testing /debuging
*/
class FakeQueue : public IQueue {
private:
int m_overload;
std::atomic<void *> m_item;
public:
FakeQueue(void *item = NULL) : m_overload(0) {
TRACE_THREAD(3, "FakeQueue(std) created");
m_item = item;
}
virtual ~FakeQueue() {
if (m_overload) {
TRACE_THREAD(3, "FakeQueue(std) overload hits: %d", m_overload);
}
}
/**
* Check if fifo is empty
*/
virtual bool empty() const {
return (NULL == m_item);
}
/**
* Pop front from fifo
* @param pitem
* return 0 for success, else wise -ERRNO
*/
virtual int pop_front(OUT void **pitem) {
void *saved = NULL;
if (NULL != m_item) {
saved = atomic_exchange(&m_item, (void *)NULL);
}
if (NULL != saved) {
*pitem = saved;
return 0;
} else {
#ifdef UNIT_TEST
usleep(1);
#endif
}
return -EAGAIN;
}
/**
* Push back a new item into fifo
* -EAGAIN: temporary unavailable, push again!
* -ENOMEM: fifo full and no enough memory
* @param item
* return 0 for success, else wise -ERRNO
*/
virtual int push_back(IN const void *item) {
void *expected = NULL;
if (m_item.compare_exchange_weak(expected, (void *)item)) {
return 0;
} else {
m_overload++;
#ifdef UNIT_TEST
usleep(1000);
#endif
}
// res = -ENOMEN;
return -EAGAIN;
}
};
#else /* !USE_TBB */
/**
* FIFO queue (contains only one item) for testing /debuging
* (use intel TBB atomic)
*/
class FakeQueue : public IQueue {
private:
int m_overload;
tbb::atomic<void *> m_item;
public:
FakeQueue(void *item = NULL) : m_overload(0) {
TRACE_THREAD(3, "FakeQueue(tbb) created");
m_item = item;
}
virtual ~FakeQueue() {
if (m_overload) {
TRACE_THREAD(3, "FakeQueue(tbb) overload hits: %d", m_overload);
}
}
/**
* Pop front from fifo
* @param pitem
* return 0 for success, else wise -ERRNO
*/
virtual int pop_front(OUT void **pitem) {
void *saved = NULL;
if (NULL != m_item) {
saved = m_item.fetch_and_store((void *)NULL);
}
if (NULL != saved) {
*pitem = saved;
return 0;
} else {
#ifdef UNIT_TEST
usleep(1);
#endif
}
return -EAGAIN;
}
/**
* Push back a new item into fifo
* -EAGAIN: temporary unavailable, push again!
* -ENOMEM: fifo full and no enough memory
* @param item
* return 0 for success, else wise -ERRNO
*/
virtual int push_back(IN const void *item) {
if (NULL == m_item.compare_and_swap((void *)item, NULL)) {
return 0;
} else {
m_overload++;
#ifdef UNIT_TEST
usleep(1000);
#endif
}
// res = -ENOMEN;
return -EAGAIN;
}
};
#endif /* USE_TBB */
} | true |
c36ef5612ac6bcfd42ad89260c95364313c910b3 | C++ | rforcen/qt-metal | /metal/zcompiler/zCompiler.h | UTF-8 | 10,265 | 2.609375 | 3 | [] | no_license | #ifndef zCompilerH
#define zCompilerH
#include <complex>
#include "zSymbols.h"
using namespace std;
typedef u_char __byte;
class zCompiler {
public:
typedef complex<float> Complex;
string *fname;
int lfname;
constexpr static const float PHI = 1.6180339887;
static const int maxConst = 6000, maxCode = 16000, maxStack = 150;
string s; // expression to evaluate;
int ixs;
int sym; // actual sym
char ch; // actual ch
float nval; // actual numerical value
string ident; // actual id,
Complex Z; // the 'z' value
float consts[maxConst];
int iconsts = 0;
bool err = true;
string errMessage;
// compiler
__byte code[maxCode];
int pc, codeSize;
// run time
Complex stack[maxStack];
int sp;
public:
zCompiler() {
static string fname[] = {"SIN", "COS", "TAN", "EXP", "LOG",
"LOG10", "INT", "SQRT", "ASIN", "ACOS",
"ATAN", "ABS", "C", "PI", "PHI"};
this->fname = fname;
lfname = sizeof(fname) / sizeof(fname[0]);
}
float *getConsts() { return consts; }
int constsLength() { return iconsts; }
int constsBytes(int add = 0) { return (iconsts + add) * sizeof(*consts); }
__byte *getCode() { return code; }
int codeLength() { return pc; }
string *funcNames() { return fname; }
string getErrorMessage() { return errMessage; }
string toUpper(string strToConvert) {
std::transform(strToConvert.begin(), strToConvert.end(),
strToConvert.begin(), ::toupper);
return strToConvert;
}
string toLower(string strToConvert) {
std::transform(strToConvert.begin(), strToConvert.end(),
strToConvert.begin(), ::tolower);
return strToConvert;
}
bool Compile(string expr) {
pc = sp = ixs = iconsts = 0;
ident = "";
s = expr;
getch();
err = false;
getsym();
Ce0();
Gen(END);
codeSize = pc;
return err;
}
Complex Execute(Complex z) {
Z = z;
Complex CI = Complex(0., 1.);
int pc = 0, sp = 0;
bool end = false;
while (!end) {
switch (code[pc]) {
case PUSHC:
pc++;
stack[sp] = Complex(consts[code[pc]], 0.);
sp++;
pc++;
break;
case PUSHZ:
pc++;
stack[sp] = Z;
sp++;
break;
case PUSHI:
pc++;
stack[sp] = CI;
sp++;
break;
case PLUS:
sp--;
stack[sp - 1] += stack[sp];
pc++;
break;
case MINUS:
sp--;
stack[sp - 1] -= stack[sp];
pc++;
break;
case MULT:
sp--;
stack[sp - 1] *= stack[sp];
pc++;
break;
case DIV:
sp--;
stack[sp - 1] /= stack[sp];
pc++;
break;
case POWER:
sp--;
stack[sp - 1] = pow(stack[sp - 1], stack[sp]);
pc++;
break;
case NEG:
stack[sp - 1] = -stack[sp - 1];
pc++;
break;
case FSIN:
stack[sp - 1] = sin(stack[sp - 1]);
pc++;
break;
case FCOS:
stack[sp - 1] = cos(stack[sp - 1]);
pc++;
break;
case FTAN:
stack[sp - 1] = tan(stack[sp - 1]);
pc++;
break;
case FASIN:
stack[sp - 1] = asin(stack[sp - 1]);
pc++;
break;
case FACOS:
stack[sp - 1] = acos(stack[sp - 1]);
pc++;
break;
case FATAN:
stack[sp - 1] = atan(stack[sp - 1]);
pc++;
break;
case FEXP:
stack[sp - 1] = exp(stack[sp - 1]);
pc++;
break;
case FLOG:
stack[sp - 1] = log(stack[sp - 1]);
pc++;
break;
case FLOG10:
stack[sp - 1] = log10(stack[sp - 1]);
pc++;
break;
case FSQRT:
stack[sp - 1] = sqrt(stack[sp - 1]);
pc++;
break;
case FABS:
stack[sp - 1] = abs(stack[sp - 1]);
pc++;
break;
case FINT:
stack[sp - 1] =
Complex((int)stack[sp - 1].real(), (int)stack[sp - 1].imag());
pc++;
break;
case FC:
sp--;
pc++;
stack[sp - 1] = Complex(stack[sp - 1].real(), stack[sp].real());
break;
case END:
end = true;
break;
default:
err = true;
end = true;
break;
}
}
if (sp != 0)
return stack[sp - 1];
else
return Complex(0, 0);
}
private:
bool islower(char c) { return (c >= 'a' && c <= 'z'); }
bool isupper(char c) { return (c >= 'A' && c <= 'Z'); }
bool isalpha(char c) { return (islower(c) || isupper(c)); }
bool isdigit(char c) { return (c >= '0' && c <= '9'); }
bool isalnum(char c) { return (isalpha(c) || isdigit(c)); }
// get next char from *s
char getch() {
ch = 0;
if (ixs < int(s.length())) {
ch = s[ixs];
ixs++;
}
return ch;
}
void ungetch() { ixs--; }
// get next symbol
int getsym() {
int i;
sym = SNULL;
ident = "";
// skip blanks
while (ch != 0 && ch <= ' ') getch();
// detect symbol
if (isalpha(ch)) { // ident
ident = "";
for (i = 0; isalnum(ch) || ch == '_'; i++) {
ident += ch;
getch();
}
sym = IDENT_i;
ident = toUpper(ident); // look up for 'x' or 't'
if (ident == "Z")
sym = IDENT_z;
else if (ident == "I")
sym = IDENT_i;
else {
// is a funct ?
for (i = 0; i < lfname; i++) {
if (ident == fname[i]) {
sym = i + FSIN; // first symbol offset
break;
}
}
if (i >= lfname) {
sym = 0;
error("unknown symbol:" + ident);
}
}
} else {
if (isdigit(ch)) { // number (float) take care of dddd.ddde-dd
for (i = 0; isdigit(ch) || ch == '.' || ch == 'e' || ch == 'E'; i++) {
ident += ch;
getch();
}
sym = NUMBER;
nval = stof(ident);
} else {
switch (ch) {
case '+':
sym = PLUS;
break;
case '-':
sym = MINUS;
break;
case '*':
sym = MULT;
break;
case '/':
sym = DIV;
break;
case '(':
sym = OPAREN;
break;
case ')':
sym = CPAREN;
break;
case '^':
sym = POWER;
break;
case ',':
sym = PERIOD;
break;
case 0:
sym = SNULL;
break;
default:
sym = SNULL;
error(string("character not recognized: ") + to_string(ch));
break;
}
getch();
}
}
return sym;
}
void error(string text) {
errMessage = text;
err = true;
}
void Gen(int token, float f) { // code Generation
code[pc++] = (__byte)token;
code[pc++] = (__byte)iconsts;
consts[iconsts++] = f;
}
void Gen(int token, __byte i) {
code[pc++] = (__byte)token;
code[pc++] = (__byte)i;
}
void Gen(int token) { code[pc++] = (__byte)token; }
void Ce0() {
if (!err) {
Ce1();
do {
switch (sym) {
case PLUS:
getsym();
Ce1();
Gen(PLUS);
break;
case MINUS:
getsym();
Ce1();
Gen(MINUS);
break;
default:
break;
}
} while (sym == PLUS || sym == MINUS);
}
}
void Ce1() {
if (!err) {
Ce2();
do {
switch (sym) {
case MULT:
getsym();
Ce2();
Gen(MULT);
break;
case DIV:
getsym();
Ce2();
Gen(DIV);
break;
}
} while (sym == MULT || sym == DIV);
}
}
void Ce2() {
if (!err) {
Ce3();
do {
if (sym == POWER) {
getsym();
Ce3();
Gen(POWER);
}
} while (sym == POWER);
}
}
void Ce3() {
if (!err) {
switch (sym) {
case OPAREN:
getsym();
Ce0();
getsym();
break;
case NUMBER:
Gen(PUSHC, nval);
getsym();
break;
case IDENT_i:
Gen(PUSHI);
getsym();
break;
case IDENT_z:
Gen(PUSHZ);
getsym();
break;
case MINUS:
getsym();
Ce3();
Gen(NEG);
break;
case PLUS:
getsym();
Ce3();
break;
case FSIN:
case FCOS:
case FTAN:
case FASIN:
case FACOS:
case FATAN:
case FEXP:
case FINT:
case FABS:
case FLOG:
case FLOG10:
case FSQRT: {
int tsym = sym;
getsym();
Ce3();
Gen(tsym);
} break;
case FC:
getsym();
getsym();
Ce3();
getsym();
Ce3();
getsym();
Gen(FC);
break;
case SPI:
getsym();
Gen(PUSHC, (float)M_PI);
break;
case SPHI:
getsym();
Gen(PUSHC, PHI);
break;
case SNULL:
break;
default:
error("unknown symbol: " + ident);
break; // syntax error
}
}
}
};
#endif
| true |
f74d06223beb5878c9b53f5549725365dbdc083e | C++ | XiaoningCui/LeetCodePractice | /108. Convert Sorted Array to Binary Search Tree.cpp | UTF-8 | 3,572 | 4.125 | 4 | [] | no_license | /*
URL: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Author: CUI Xiaoning
Date: 2019-09-05
Difficulty: Easy
Tags: Tree, Depth-first Search
*/
/*
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
*/
# include <iostream>
# include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {}
};
/*
class TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int v, TreeNode* l, TreeNode* r) {
this->val = v;
this->left = l;
this->right = r;
}
};
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
// 如果数组的头和尾相等,说明数组为空,即返回NULL
if (nums.empty()) return NULL;
int middleIndex = (0 + nums.size()) >> 1;
// 创建一棵树root(根节点),值为nums中间位置的值
TreeNode* root = new TreeNode(nums[middleIndex]);
// 提取出用于创建root左子树的新数组
// 新数组的元素:从原数组的首元素,到原数组的中间元素的前一个元素
vector <int> l = vector <int> (nums.begin(), nums.begin() + middleIndex);
// 提取出用于创建root右子树的新数组
// 新数组的元素:从原数组的中间元素的后一个元素,到原数组的末尾元素
vector <int> r = vector <int> (nums.begin() + middleIndex + 1, nums.end());
// 递归创建root的左子树
root->left = sortedArrayToBST(l);
// 递归创建root的右子树
root->right = sortedArrayToBST(r);
// 返回树的根节点
return root;
}
};
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
// 给定数组、起始元素的索引0、数组尺寸,建立树
return _buildTree(nums, 0, nums.size());
}
private:
TreeNode* _buildTree(const std::vector<int>& nums, int begin, int end) {
// 如果数组尺寸,同起始元素索引,即0,相等,说明数组尺寸为0,没有元素,返回NULL
if (begin == end) return NULL;
// 找到数组的中间位置,即要创建的树的根节点(因为题设是根节点在中间)
// 将一个数的二进制表示右移一位,相当于,这个数除以2并向下取整
// middle也就是数组最中间元素的索引
int middle = (begin + end) >> 1;
// 或者写成int middle = (begin + end) / 2;
// 创建一棵树root(根节点),值为nums中间位置元素的值
TreeNode* root = new TreeNode(nums[middle]);
// 从middle处,数组被分开两半
// root的左子树根据数组的左半部分继续递归创建
root->left = _buildTree(nums, begin, middle);
// root的右子树根据数组的右半部分继续递归创建
root->right = _buildTree(nums, middle + 1, end);
// 返回根节点
return root;
}
}; | true |
c43d1f0741f4785d2abc2873fe0f5dbd1d13da90 | C++ | tch123/Algorithm | /Algorithms4Th/LibraryCPP/String.h | GB18030 | 10,132 | 3.046875 | 3 | [] | no_license | #ifndef V_STRING
#define V_STRING
#include <memory.h>
#include "Basic.h"
namespace Vonng
{
template<typename T>
class ObjectString : public Object
{
private:
static const T zero = 0;
mutable T* buffer;
mutable vint* reference;
mutable vint start;
mutable vint length;
mutable vint realLength;
static vint CalculateLength(const T* buffer)
{
vint result = 0;
while (*buffer++)result++;
return result;
}
static vint Compare(const T* bufA, const ObjectString<T>& strB)
{
const T* bufB = strB.buffer + strB.start;
const T* bufAOld = bufA;
vint length = strB.length;
while (length-- && *bufA)
{
vint diff = *bufA++ - *bufB++;
if (diff != 0)
{
return diff;
}
};
return CalculateLength(bufAOld) - strB.length;
}
public:
static vint Compare(const ObjectString<T>& strA, const ObjectString<T>& strB)
{
const T* bufA = strA.buffer + strA.start;
const T* bufB = strB.buffer + strB.start;
vint length = strA.length<strB.length ? strA.length : strB.length;
while (length--)
{
vint diff = *bufA++ - *bufB++;
if (diff != 0)
{
return diff;
}
};
return strA.length - strB.length;
}
private:
void Inc()const
{
if (reference)
{
(*reference)++;
}
}
void Dec()const
{
if (reference)
{
if (--(*reference) == 0)
{
delete[] buffer;
delete reference;
}
}
}
ObjectString(const ObjectString<T>& string, vint _start, vint _length)
{
if (_length == 0)
{
buffer = (T*)&zero;
reference = 0;
start = 0;
length = 0;
realLength = 0;
}
else
{
buffer = string.buffer;
reference = string.reference;
start = string.start + _start;
length = _length;
realLength = string.realLength;
Inc();
}
}
ObjectString(const ObjectString<T>& dest, const ObjectString<T>& source, vint index, vint count)
{
if (index == 0 && count == dest.length && source.length == 0)
{
buffer = (T*)&zero;
reference = 0;
start = 0;
length = 0;
realLength = 0;
}
else
{
reference = new vint(1);
start = 0;
length = dest.length - count + source.length;
realLength = length;
buffer = new T[length + 1];
memcpy(buffer, dest.buffer + dest.start, sizeof(T)*index);
memcpy(buffer + index, source.buffer + source.start, sizeof(T)*source.length);
memcpy(buffer + index + source.length, (dest.buffer + dest.start + index + count), sizeof(T)*(dest.length - index - count));
buffer[length] = 0;
}
}
public:
static ObjectString<T> Empty;
ObjectString()
{
buffer = (T*)&zero;
reference = 0;
start = 0;
length = 0;
realLength = 0;
}
ObjectString(const T& _char)
{
reference = new vint(1);
start = 0;
length = 1;
buffer = new T[2];
buffer[0] = _char;
buffer[1] = 0;
realLength = length;
}
ObjectString(const T* _buffer, vint _length)
{
if (_length == 0)
{
buffer = (T*)&zero;
reference = 0;
start = 0;
length = 0;
realLength = 0;
}
else
{
buffer = new T[_length + 1];
memcpy(buffer, _buffer, _length*sizeof(T));
buffer[_length] = 0;
reference = new vint(1);
start = 0;
length = _length;
realLength = _length;
}
}
ObjectString(const T* _buffer, bool copy = true)
{
CHECK_ERROR(_buffer != 0, L"ObjectString<T>::ObjectString(const T*, bool)#ÿָ빹ַ");
if (copy)
{
reference = new vint(1);
start = 0;
length = CalculateLength(_buffer);
buffer = new T[length + 1];
memcpy(buffer, _buffer, sizeof(T)*(length + 1));
realLength = length;
}
else
{
buffer = (T*)_buffer;
reference = 0;
start = 0;
length = CalculateLength(_buffer);
realLength = length;
}
}
ObjectString(const ObjectString<T>& string)
{
buffer = string.buffer;
reference = string.reference;
start = string.start;
length = string.length;
realLength = string.realLength;
Inc();
}
~ObjectString()
{
Dec();
}
const T* Buffer()const
{
if (start + length != realLength)
{
T* newBuffer = new T[length + 1];
memcpy(newBuffer, buffer + start, sizeof(T)*length);
newBuffer[length] = 0;
Dec();
buffer = newBuffer;
reference = new vint(1);
start = 0;
realLength = length;
}
return buffer + start;
}
ObjectString<T>& operator=(const ObjectString<T>& string)
{
if (this != &string)
{
Dec();
buffer = string.buffer;
reference = string.reference;
start = string.start;
length = string.length;
realLength = string.realLength;
Inc();
}
return *this;
}
ObjectString<T>& operator+=(const ObjectString<T>& string)
{
return *this = *this + string;
}
ObjectString<T> operator+(const ObjectString<T>& string)const
{
return ObjectString<T>(*this, string, length, 0);
}
bool operator==(const ObjectString<T>& string)const
{
return Compare(*this, string) == 0;
}
bool operator!=(const ObjectString<T>& string)const
{
return Compare(*this, string) != 0;
}
bool operator>(const ObjectString<T>& string)const
{
return Compare(*this, string)>0;
}
bool operator>=(const ObjectString<T>& string)const
{
return Compare(*this, string) >= 0;
}
bool operator<(const ObjectString<T>& string)const
{
return Compare(*this, string)<0;
}
bool operator<=(const ObjectString<T>& string)const
{
return Compare(*this, string) <= 0;
}
bool operator==(const T* buffer)const
{
return Compare(buffer, *this) == 0;
}
bool operator!=(const T* buffer)const
{
return Compare(buffer, *this) != 0;
}
bool operator>(const T* buffer)const
{
return Compare(buffer, *this)<0;
}
bool operator>=(const T* buffer)const
{
return Compare(buffer, *this) <= 0;
}
bool operator<(const T* buffer)const
{
return Compare(buffer, *this)>0;
}
bool operator<=(const T* buffer)const
{
return Compare(buffer, *this) >= 0;
}
T operator[](vint index)const
{
CHECK_ERROR(index >= 0 && index<length, L"ObjectString:<T>:operator[](vint)#indexԽ硣");
return buffer[start + index];
}
vint Length()const
{
return length;
}
vint IndexOf(T c)const
{
const T* reading = buffer + start;
for (vint i = 0; i<length; i++)
{
if (reading[i] == c)
return i;
}
return -1;
}
ObjectString<T> Left(vint count)const
{
CHECK_ERROR(count >= 0 && count <= length, L"ObjectString<T>::Left(vint)#countԽ硣");
return ObjectString<T>(*this, 0, count);
}
ObjectString<T> Right(vint count)const
{
CHECK_ERROR(count >= 0 && count <= length, L"ObjectString<T>::Right(vint)#countԽ硣");
return ObjectString<T>(*this, length - count, count);
}
ObjectString<T> Sub(vint index, vint count)const
{
CHECK_ERROR(index >= 0 && index<length, L"ObjectString<T>::Sub(vint, vint)#indexԽ硣");
CHECK_ERROR(index + count >= 0 && index + count <= length, L"ObjectString<T>::Sub(vint, vint)#countԽ硣");
return ObjectString<T>(*this, index, count);
}
ObjectString<T> Remove(vint index, vint count)const
{
CHECK_ERROR(index >= 0 && index<length, L"ObjectString<T>::Remove(vint, vint)#indexԽ硣");
CHECK_ERROR(index + count >= 0 && index + count <= length, L"ObjectString<T>::Remove(vint, vint)#countԽ硣");
return ObjectString<T>(*this, ObjectString<T>(), index, count);
}
ObjectString<T> Insert(vint index, const ObjectString<T>& string)const
{
CHECK_ERROR(index >= 0 && index <= length, L"ObjectString<T>::Insert(vint)#countԽ硣");
return ObjectString<T>(*this, string, index, 0);
}
friend bool operator<(const T* left, const ObjectString<T>& right)
{
return Compare(left, right)<0;
}
friend bool operator<=(const T* left, const ObjectString<T>& right)
{
return Compare(left, right) <= 0;
}
friend bool operator>(const T* left, const ObjectString<T>& right)
{
return Compare(left, right)>0;
}
friend bool operator>=(const T* left, const ObjectString<T>& right)
{
return Compare(left, right) >= 0;
}
friend bool operator==(const T* left, const ObjectString<T>& right)
{
return Compare(left, right) == 0;
}
friend bool operator!=(const T* left, const ObjectString<T>& right)
{
return Compare(left, right) != 0;
}
friend ObjectString<T> operator+(const T* left, const ObjectString<T>& right)
{
return WString(left, false) + right;
}
};
template<typename T>
ObjectString<T> ObjectString<T>::Empty = ObjectString<T>();
typedef ObjectString<char> AString;
typedef ObjectString<wchar_t> WString;
extern vint atoi(const AString& string);
extern vint wtoi(const WString& string);
extern __int64 atoi64(const AString& string);
extern __int64 wtoi64(const WString& string);
extern vuint atou(const AString& string);
extern vuint wtou(const WString& string);
extern unsigned __int64 atou64(const AString& string);
extern unsigned __int64 wtou64(const WString& string);
extern double atof(const AString& string);
extern double wtof(const WString& string);
extern AString itoa(vint number);
extern WString itow(vint number);
extern AString i64toa(__int64 number);
extern WString i64tow(__int64 number);
extern AString utoa(vuint number);
extern WString utow(vuint number);
extern AString u64toa(unsigned __int64 number);
extern WString u64tow(unsigned __int64 number);
extern AString ftoa(double number);
extern WString ftow(double number);
extern vint _wtoa(const wchar_t* w, char* a, vint chars);
extern AString wtoa(const WString& string);
extern vint _atow(const char* a, wchar_t* w, vint chars);
extern WString atow(const AString& string);
extern AString alower(const AString& string);
extern WString wlower(const WString& string);
extern AString aupper(const AString& string);
extern WString wupper(const WString& string);
}
#endif | true |
5acf31f612dd45d96b38a968e6c5e76f3bff820c | C++ | joecatarata/CodeDump | /UVA/895/895.cpp | UTF-8 | 539 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
void split(string str, vector<string> &out, string delim)
{
}
int main(){
ios_base::sync_with_stdio(false);
cout << "gumana" << endl;
vector<string> dict;
string input;
while(cin >> input){
if(input == "#")
break;
dict.push_back(input);
}
string puzzle;
int ctr=0;
while(cin >> puzzle){
if(puzzle == "#")
break;
bool possible = true;
for(auto it=dict.begin(); it != dict.end(); it++){
string word = *it;
}
}
return 0;
} | true |
93e5ae882ca176cb82eae13f38aa5190b1fac1c4 | C++ | rikonek/zut | /semestr_2/zaawansowane_programowanie_obiektowe_c++/11.cpp | UTF-8 | 835 | 3 | 3 | [] | no_license | // zadanie na zaliczenie
// bartek.taczala@gmail.com
// Implement Matrix<N, M, T> (order is random here!)
// N - number of rows
// M - number of columns
// has templated copy ctor ( const Matrix<N1, M1, T1>& )
// N1 < N
// M1 < M
// T1 convertible to T
// has operators:
// operator<<
// operator[]
// template operator+ (const Matrix<N1, M1, T1>)
// is specialized for N = 0 && M = 0 (cannot be created)
// is specialized for bools!! (std::vector<bool> is pure evil!)
#include <iostream>
template<int x, int y, typename T>
class matrix
{
private:
std::vector<std::vector<T>> _vector;
std::vector<T> _vector_y { 0 };
public:
matrix()
{
for(int i=0; i<x; i++)
{
}
}
};
int main()
{
} | true |
f75ad6d21eae762175bd9f8ef91bf4c5df31fe7b | C++ | Jakooboo/lab1_Cwirko_Stasiak | /main.cpp | UTF-8 | 1,072 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include "proces.h"
int load_process(int liczba) {
process process_1("data."+std::to_string(liczba));
std::cout << "Dlugosc procesu " << liczba << " przed sortowaniem: " << process_1.calculate_length_of_process() << std::endl;
process_1.sort_process_first();
std::cout << "Dlugosc procesu " << liczba << " po sortowaniu: " << process_1.calculate_length_of_process() << std::endl;
std::cout << std::endl << "Kolejnosc procesu " << liczba << " po sortowaniu:" << std::endl;
process_1.print_order();
std::cout << std::endl << std::endl;
return 0;
}
int main() {
std::cout << std::endl << "Program do sortowania zadan w procesie" << std::endl;
std::cout << "Laduje plik data.txt i rozpoczynam prace!" << std::endl;
for (int i = 1; i < 5; i++)
{
std::cout << std::endl << "Czas na proces data." << i << std::endl;
load_process(i);
}
std::cout << std::endl << "Koniec programu!" << std::endl;
int a;
std::cout << "Wprowadz dowolny znak i wcisnij klawisz Enter, aby wyjsc z programu." << std::endl;
std::cin >> a;
return 0;
} | true |
606f70863d55a998efb76d73b22d05c419258e11 | C++ | piotrpopiolek/Code | /Szkoła Programowania/Rozdział 14 Listing 14.22 frnd2tmp/Rozdział 14 Listing 14.22 frnd2tmp/frnd2tmp.cpp | UTF-8 | 1,285 | 3.78125 | 4 | [] | no_license | #include<iostream>
using std::cout;
using std::endl;
template<typename T>
class HasFriend
{
T item;
static int ct;
public:
HasFriend(const T & i) :item(i)
{
ct++;
}
~HasFriend()
{
ct--;
}
friend void counts();
friend void reports(HasFriend<T> &); //parametr w postaci szablonu
};
//kazda specjalizacja ma wlasna statyczna dana skladowa
template<typename T>
int HasFriend<T>::ct = 0;
//funkcja (nie szablon) zaprzyjazniona ze wszystkimi klasami HasFriend<T>
void counts()
{
cout << "Konkretyzacja int: " << HasFriend<int>::ct << "; ";
cout << "Konkretyzacja double: " << HasFriend<double>::ct << endl;
}
//funkcja (nie szablon) zaprzyjazniona z klasa HasFriend<int>
void reports(HasFriend<int> & hf)
{
cout << "HasFriend<int>: " << hf.item << endl;
}
//funkcja (nie szablon) zaprzyjazniona z klasa HasFriend<double>
void reports(HasFriend<double> & hf)
{
cout << "HasFriend<double>: " << hf.item << endl;
}
int main()
{
cout << "Brak zadeklarowanych obiektow: ";
counts();
HasFriend<int> hfi1(10);
cout << "Po deklaracji hfi1: ";
counts();
HasFriend<int> hfi2(20);
cout << "Po deklaracji hfi2: ";
counts();
HasFriend<double> hfdb(10.5);
cout << "Po deklaracji hfdb: ";
counts();
reports(hfi1);
reports(hfi2);
reports(hfdb);
system("pause");
return 0;
} | true |
a3bca1984b62627531f5f63802171573af3e1445 | C++ | ElefanteAlbino/FindMyThoughts | /FindMyThoughts.cpp | UTF-8 | 8,398 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <iterator>
#include <vector>
#include <cctype>
#include <algorithm>
#include <map>
using namespace std;
void lowerCase(string &str)
{
for(unsigned int i = 0; i < str.size(); i++){
if(isupper(str[i])){
str[i] = tolower(str[i]);
}
}
}
void filterWords(vector<string> & v){
//preposiciones y pronombres
string blacklist[] = {"i","me","we","us","you","she","her","he","him","it",
"they","them","this","that","these","those","anybody","anyone","each","either",
"everybody","everyone","eveything","neither","nobody","no","one","nothing",
"somebody","someone","something","both","few","many","several","all","any",
"most","none","some","myself","ourselves","yourself","yourselves","himself",
"herself","itself","themselves","what","who","which","whom","whose","my",
"it","his","her","its","our","your","their","mine","yours","his","hers",
"ours","on","theirs","in","at","since","for","ago","before","to","past","till",
"until","by","next","beside","under","below","over","above","across","through",
"into","towards","onto","from","of","off","out","about","character","guy",
"thing","a","when","the","came","around"};
for(unsigned int i = 0; i < v.size(); i++){
if(find(begin(blacklist), end(blacklist), v[i]) != end(blacklist)) {
v.erase(v.begin()+i);
}
}
}
vector<string> separateWords(string keyphrase){
lowerCase(keyphrase);
vector<string> separatedPhrase;
string word = "";
for(auto x : keyphrase){
if(x == ' '){
separatedPhrase.push_back(word);
word = "";
}
else{
word += x;
}
}
separatedPhrase.push_back(word);
filterWords(separatedPhrase);
return separatedPhrase;
}
int main(){
vector<string> separatedPhrase;
string keyphrase;
cout << "What do you remember from the game you wish to find?" << endl;
getline(cin, keyphrase);
separatedPhrase = separateWords(keyphrase);
// for(unsigned int i = 0; i < separatedPhrase.size(); i++){
// cout << separatedPhrase[i] << endl;
// }
multimap<string,string> mmapOfPos = {
{"konami", "Silent Hill"},
{"1999","Silent Hill"},
{"terror", "Silent Hill"},
{"scares","Silent Hill"},
{"silent","Silent Hill"},
{"hill","Silent Hill"},
{"van","Silent Hill"},
{"cherly","Silent Hill"},
{"abandoned","Silent Hill"},
{"village","Silent Hill"},
{"town","Silent Hill"},
{"darkness","Silent Hill"},
{"worship","Silent Hill"},
{"harry","Silent Hill"},
{"cybil","Silent Hill"},
{"demon","Silent Hill"},
{"hell","Silent Hill"},
{"devil","Silent Hill"},
{"girl","Silent Hill"},
{"children","Silent Hill"},
{"follow","Silent Hill"},
{"search","Silent Hill"},
{"fight","Silent Hill"},
{"crash","Silent Hill"},
{"lisa","Silent Hill"},
{"michael","Silent Hill"},
{"alessa","Silent Hill"},
{"alexia","Silent Hill"},
{"dahlia","Silent Hill"},
{"highway","Silent Hill"},
{"lost","Silent Hill"},
{"fps","Doom"},
{"bethesda","Doom"},
{"1993","Doom"},
{"shooter","Doom"},
{"fps","Doom"},
{"marin","Doom"},
{"uac","Doom"},
{"deimos","Doom"},
{"combat","Doom"},
{"demons","Doom"},
{"demon","Doom"},
{"military","Doom"},
{"guns","Doom"},
{"shoots","Doom"},
{"shoot","Doom"},
{"kill","Doom"},
{"strategy","Doom"},
{"doom","Doom"},
{"nintendo", "Mario Kart 64"},
{"1996", "Mario Kart 64"},
{"racing", "Mario Kart 64"},
{"mario","Mario Kart 64"},
{"kart","Mario Kart 64"},
{"64","Mario Kart 64"},
{"red","Mario Kart 64"},
{"races","Mario Kart 64"},
{"race","Mario Kart 64"},
{"powers","Mario Kart 64"},
{"habilitys","Mario Kart 64"},
{"browser","Mario Kart 64"},
{"donkey","Mario Kart 64"},
{"kong","Mario Kart 64"},
{"luigi","Mario Kart 64"},
{"peach","Mario Kart 64"},
{"toad","Mario Kart 64"},
{"wario","Mario Kart 64"},
{"yoshi","Mario Kart 64"},
{"shell","Mario Kart 64"},
{"shells","Mario Kart 64"},
{"boxes","Mario Kart 64"},
{"karts","Mario Kart 64"},
{"magic","Mario Kart 64"},
{"konami", "Contra"},
{"1987", "Contra"},
{"shooter", "Contra"},
{"run","Contra"},
{"gun","Contra"},
{"probotector","Contra"},
{"japanese","Contra"},
{"future","Contra"},
{"corp","Contra"},
{"girl","Contra"},
{"rescue","Contra"},
{"save","Contra"},
{"find","Contra"},
{"escape","Contra"},
{"releasing","Contra"},
{"free","Contra"},
{"island","Contra"},
{"forest","Contra"},
{"aliens","Contra"},
{"capcom", "Street Fighter"},
{"1987", "Street Fighter"},
{"fights", "Street Fighter"},
{"street","Street Fighter"},
{"fighter","Street Fighter"},
{"balrog","Street Fighter"},
{"vega","Street Fighter"},
{"bison","Street Fighter"},
{"akuma","Street Fighter"},
{"charlie","Street Fighter"},
{"cuffs","Street Fighter"},
{"hits","Street Fighter"},
{"habilitys","Street Fighter"},
{"powrs","Street Fighter"},
{"fight","Street Fighter"},
{"arcade","Street Fighter"},
{"Sega", "Sonic the Hedgehog"},
{"1991", "Sonic the Hedgehog"},
{"racing", "Sonic the Hedgehog"},
{"blue","Sonic the Hedgehog"},
{"hedgehog","Sonic the Hedgehog"},
{"rings","Sonic the Hedgehog"},
{"gold","Sonic the Hedgehog"},
{"fast","Sonic the Hedgehog"},
{"light","Sonic the Hedgehog"},
{"velocity","Sonic the Hedgehog"},
{"run","Sonic the Hedgehog"},
{"jumps","Sonic the Hedgehog"},
{"nintendo", "Pokemon"},
{"1996", "Pokemon"},
{"fights", "Pokemon"},
{"pokeballs","Pokemon"},
{"pokedex","Pokemon"},
{"pikachu","Pokemon"},
{"charmander","Pokemon"},
{"ash","Pokemon"},
{"ketchum","Pokemon"},
{"capture","Pokemon"},
{"pokemons","Pokemon"},
{"pokemon","Pokemon"},
{"cap","Pokemon"},
{"yellow","Pokemon"},
{"kanto","Pokemon"},
{"paleta","Pokemon"},
{"master","Pokemon"},
{"snorlax","Pokemon"},
{"bush","Pokemon"},
{"animal","Pokemon"},
{"monster","Pokemon"},
{"animals","Pokemon"},
{"monsters","Pokemon"},
{"fighting","Pokemon"},
{"nintendo","The legend of Zelda: A Link to the Past"},
{"1991","The legend of Zelda: A Link to the Past"},
{"adventure","The legend of Zelda: A Link to the Past"},
{"zelda","The legend of Zelda: A Link to the Past"},
{"legend","The legend of Zelda: A Link to the Past"},
{"link","The legend of Zelda: A Link to the Past"},
{"action","The legend of Zelda: A Link to the Past"},
{"open","The legend of Zelda: A Link to the Past"},
{"world","The legend of Zelda: A Link to the Past"},
{"free","The legend of Zelda: A Link to the Past"},
{"missions","The legend of Zelda: A Link to the Past"},
{"ocarina","The legend of Zelda: A Link to the Past"},
{"sword","The legend of Zelda: A Link to the Past"},
{"shield","The legend of Zelda: A Link to the Past"},
{"japanese","The legend of Zelda: A Link to the Past"},
{"princess","The legend of Zelda: A Link to the Past"},
{"agahnim","The legend of Zelda: A Link to the Past"},
{"castle","The legend of Zelda: A Link to the Past"},
{"hyrule","The legend of Zelda: A Link to the Past"},
{"ganon","The legend of Zelda: A Link to the Past"},
{"triforce","The legend of Zelda: A Link to the Past"},
{"green","The legend of Zelda: A Link to the Past"},
};
typedef multimap<string,string>::iterator MMAPIterator;
map<string,int> results_map;
for(unsigned int i = 0; i < separatedPhrase.size(); i++){
pair<MMAPIterator, MMAPIterator> result = mmapOfPos.equal_range(separatedPhrase[i]);
for (MMAPIterator it = result.first; it != result.second; it++){
string x = it->second;
if (results_map.find(x) == results_map.end()) {
results_map.insert(pair<string, int>(x,1));
} else {
results_map[x] += 1;
}
}
}
string better;
int count = 0;
for (const auto &x : results_map){
if(count == 0){
better = x.first;
count = x.second;
}else if(x.second > count){
better = x.first;
}
}
results_map.erase(better);
cout << "Your perfect match is: "<<better<<endl;
if(not results_map.empty()){
cout << "\nOther possible matches: " <<endl;
for (const auto &x : results_map){
cout<<x.first<<endl;
}
}
return 0;
}
| true |
af58249513e603429bf2df54ca8a7a4d9d5c5dfb | C++ | Vanadianfan/Algorithm | /Co-minimium Spanning Tree (次小生成樹).cpp | UTF-8 | 1,566 | 2.671875 | 3 | [] | no_license | #include<cstdio>
#include<vector>
#include<climits>
#include<cstring>
#include<iostream>
#include<algorithm>
const int N = 123, M = 350;
using namespace std;
int n, m;
bool used[M];
vector<int> MST[N];
int f[N], d[N][N];
template <class T>T MIN(const T &a, const T &b){
return a < b ? a : b;
}
struct YWZ{
int x, y, z;
bool operator < (const YWZ &b) const{
return z < b.z;
}
}edge[M];
inline void read(int &x){
x = 0; char c = 0;
while(!isdigit(c)) c = getchar();
while(isdigit(c)) x = (x << 3) + (x << 1) + c - '0', c = getchar();
}
inline void intialize(void){
memset(d, 0, sizeof(d));
memset(MST, 0, sizeof(MST));
memset(used, false, sizeof(used));
for(int i = 1; i <= n; i++)
f[i] = i, MST[i].push_back(i);
}
int root(int x){
if(f[x] == x) return x;
return f[x] = root(f[x]);
}
int main(){
cin >> n >> m;
for(int i = 0; i < m; i++)
read(edge[i].x), read(edge[i].y), read(edge[i].z);
sort(edge, edge + m);
intialize();
int sum = 0, cosum = INT_MAX;
for(int i = 0; i < m; i++){
int x = root(edge[i].x);
int y = root(edge[i].y);
int &z = edge[i].z;
if(x == y) continue;
sum += z, used[i] = true, f[x] = y;
for(int j = 0; j < MST[x].size(); j++)
for(int k = 0; k < MST[y].size(); k++)
d[MST[x][j]][MST[y][k]] = d[MST[y][k]][MST[x][j]] = z;
for(int j = 0; j < MST[x].size(); j++)
MST[y].push_back(MST[x][j]);
}
for(int i = 0; i < m; i++){
if(used[i]) continue;
int &x = edge[i].x, &y = edge[i].y, &z = edge[i].z;
cosum = MIN(cosum, sum + z - d[x][y]);
}
printf("sum: %d\tcosum: %d", sum, cosum);
return 0;
} | true |
b9f268b0b6623acc06cd71c8784f1ac493021598 | C++ | Thomas-WebDev/CSS503Project2 | /Shop.h | UTF-8 | 2,152 | 3.125 | 3 | [] | no_license | // ---------------------------------- Shop.h -----------------------------------
// By: Dr. Erika Parsons
// Modified by: Kevin Thomas Kehoe
// Course: CSS 503
// Assignment: Program 2
// Date of Last Modification: 05/06/2018
// -----------------------------------------------------------------------------
// Purpose: Declaration of the barber shop and related methods
// -----------------------------------------------------------------------------
#ifndef _SHOP_H_
#define _SHOP_H_
#include <pthread.h>
#include <queue>
#include <map>
#include <iostream>
using namespace std;
#define DEFAULT_CHAIRS 3 // the default number of chairs for waiting = 3
#define DEFAULT_BARBERS 1 // the default number of barbers = 1
class Shop {
public:
// Initializes a Shop object with nBarbers and nChairs.
Shop(int nb, int nc);
// Initializes a Shop object with 1 barber and 3 chairs.
Shop();
// Is called by a customer thread.
int visitShop(int customerId); // return a non-negative number only when a customer got a service
// Is called by a customer thread.
void leaveShop( int customerId, int barberId );
//Is called by a barber thread.
void helloCustomer(int barberId);
//Is called by a barber thread.
void byeCustomer(int barberId);
int nDropsOff = 0; // the number of customers dropped off
private:
int nBarbers; // number of barbers
int nChairs; // number of waiting chairs
enum customerState {WAIT, CHAIR, LEAVING};
struct Barber {
int id;
pthread_cond_t barberCond;
int myCustomer = -1; // no customer
};
struct Customer {
int id;
pthread_cond_t customerCond;
customerState state = WAIT; // initialized as waiting
int myBarber = -1; // no barber
};
Barber *barbers; // array of barber objects
map<int, Customer> customers; // container for customer objects
queue<int> waitingCustomers; // queue of waiting customers
queue<int> sleepingBarbers; // queue of idle barbers
pthread_mutex_t mutex;
Barber* getBarber(int barberId);
};
#endif | true |
d8da05ce526cd87a93e3f86e56b19e507d27feef | C++ | triplekill/C | /thread_class/thread.cpp | UTF-8 | 465 | 3 | 3 | [] | no_license | #include "thread.h"
Thread::Thread()
{
threadPara=NULL;
runFlag=0;
}
int Thread::run(void *Parameter)
{
HANDLE hThread;
if(runFlag) return -1;
this->threadPara=Parameter;
this->runFlag=1;
hThread=CreateThread(NULL,0,start_thread,(LPVOID)this,0,NULL);
CloseHandle(hThread);
return 0;
}
DWORD WINAPI Thread::start_thread(LPVOID Parameter)
{
Thread *_this=(Thread *)Parameter;
return _this->func(_this->threadPara);
}
| true |
f8d026075dfd609b904c42abc608ca409549549a | C++ | SayanDutta001/Cpp-Codes | /Game Theory/TopCoder simpleNim.cpp | UTF-8 | 729 | 2.90625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
const int N=1e5+1;
class LongLongNim{
public:
int dp[N];
int numberOfWins(int maxN, vector<int>ar){
dp[0]=0;
int cnt=0;
for(int i=1;i<N;i++){
dp[i]=0;
for(auto xx: ar) if(xx<=i){
// from a winning position at least one lossing position should be there
if(dp[i-xx]) {
dp[i]=1;
break;
}
}
if(dp[i]) cnt++;
}
int res=(maxN/N)*cnt,rem=maxN%N;
for(int i=0;i<rem;i++) if(dp[i]) res++;
return res;
}
};
int main(){
LongLongNim nn;
cout<<nn.numberOfWins(20,{1,2,3})<<"\n";
} | true |
84931361c4bbdba5be996a1370a3c6524ec38d64 | C++ | xinlianyu/EventCollection | /myqueue.cpp | UTF-8 | 1,821 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include "myqueue.h"
/****************************************************************/
myqueue::myqueue()
{
end=new q_element;
end->next=NULL;
end->pre=NULL;
end->value=-1;
start=end;
}
myqueue::~myqueue(){
q_element *q=start;
q_element *p;
while (q!=NULL) {
p=q;
q=q->next;
delete p;
}
}
void myqueue::enqueue(int value)
{
q_element *temp;
temp=new q_element;
temp->value=value;
temp->next=start;
start->pre=temp;
temp->pre=NULL;
start=temp;
}
int myqueue::dequeue(void)
{
q_element *temp1;
q_element *temp2;
int value;
//cout<<"in dequeue..."<<endl;
if(is_empty()==1) return -1;
else
{
//cout<<"temp1=end->pre"<<endl;
temp1=end->pre;
//cout<<"temp2=temp1->pre"<<endl;
temp2=temp1->pre;
//cout<<"value=temp1->value"<<endl;
value=temp1->value;
//cout<<"value to be dequeued: "<<value<<endl;
//cout<<"temp2->next=end"<<endl;
if(temp2!=NULL)
temp2->next=end;
//cout<<"end->pre=temp2"<<endl;
end->pre=temp2;
if(temp2==NULL) start=end;
//cout<<"delete temp1"<<endl;
//cout<<"temp1: "<<temp1<<endl;
delete temp1;
//cout<<"return value"<<endl;
return value;
}
}
int myqueue::is_empty(void)
{
if(start==end) return 1;
else return 0;
}
int myqueue::have_this(int value)
{
q_element *current;
current=start;
while(current!=NULL)
{
if(current->value==value) return 1;
current=current->next;
}
return 0;
}
void myqueue::clear(void) {
q_element *q=start;
q_element *p;
while (q->next!=NULL) {
p=q;
q=q->next;
delete p;
}
start=end;
}
| true |
6bcf536964942729181e4e85be6e349fa77c5c79 | C++ | FernandaRTenorio/DIMyR_FerRomeroT | /OPENGL TUT7/HELPERS.h | UTF-8 | 421 | 2.90625 | 3 | [] | no_license | #ifndef HELPERS_H
#define HELPERS_H
#include <fstream>
#include <string>
inline
void RemoveQuotes(std::string& input)
{
size_t pos;
while ( (pos = input.find('\"')) != std::string::npos )
{
input.erase(pos, 1);
}
}
inline
void ComputeQuaternionW(float* q)
{
float w2 = 1.0f - q[0] * q[0] - q[1] * q[1] - q[2] * q[2];
if(w2 < 0.0f)
{
q[3] = 0.0f;
}
else
{
q[3] = -sqrtf(w2);
}
}
#endif //HELPERS_H | true |
718f7f34a01411dca5adf5470a122d797e0b4cb8 | C++ | cashinqmar/DSALGO | /practicequestions/assignmenthackrecursion/arithmetic.cpp | UTF-8 | 744 | 3.0625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
bool arithmetic(vector<int>& arr,int vsf,string exp,int idx){
if(idx==arr.size()){
if(vsf%101==0){
cout<<exp<<endl;
return true;
}
else return false;
}
bool res=false;
res=res|arithmetic(arr,vsf+arr[idx],exp+"+"+to_string(arr[idx]),idx+1);
if(res)return true;
res=res|arithmetic(arr,vsf-arr[idx],exp+"-"+to_string(arr[idx]),idx+1);if(res)return true;
res=res|arithmetic(arr,vsf*arr[idx],exp+"*"+to_string(arr[idx]),idx+1);if(res)return true;
return res;
}
void solve(){
int n;
cin>>n;
vector<int> arr(n);
for(int i=0;i<n;i++){
cin>>arr[i];
}
int vsf=arr[0];
string exp=to_string(arr[0])+"";
arithmetic(arr,vsf,exp,1);
}
int main(){
solve();
return 0;
} | true |
c3617dbb6853fafbd9067decb23d86bb8a21fc9b | C++ | atrin-hojjat/CompetetiveProgramingCodes | /CF/EdRound_75/B.cpp | UTF-8 | 462 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main() {
int Q; cin >> Q;
while(Q--) {
int n; cin >> n;
int C = 0;bool X = false;
for(int i = 0; i < n; i++) {
int cnt[2] = {0, 0};
string str; cin >> str;
for(auto x : str)
cnt[x - '0']++;
if(cnt[0] % 2 && cnt[1] % 2) C++;
if(str.size() % 2) X = true;
}
if(X) cout << n << endl;
else cout << n - (C % 2) << endl;
}
return 0;
}
| true |
cb29be7c504cc43ea53593e047ac41f5f151f227 | C++ | nguyminh/CS-161 | /CS 161/fin.cpp | UTF-8 | 15,786 | 3.34375 | 3 | [] | no_license | /*Minh Nguyen
* 3/16/2014
* Final project
* Inputs include very basic conditional statements depending on which requirement you are in.
* output: Displays many different demonstrations of requirement list
*/
#include <iostream>
#include <limits.h>
#include <time.h>
#include <ctime>
#include <cstdlib>
#include <string>
#include <bitset>
#include <cassert>
#include <iomanip>
#include <cstring>
using namespace std;
const int BITS = 8; //global variable to demonstrate twos complement
void intro(); //introduction to my program
void binary(); //req. 1
//*****************************
void twos_complement(); //req. 2
int convert(char binary[]); //function to convert binary numbers into integers
//*****************************
void macro(); //req.3
void output(); //req. 4
void input(); //req. 5
void type_cast(); //req. 6
void conditional(); //req 7
void logical(); // req 8
void loop(); // req 9
void random_gen(); //req 10
void dem_error(); //req 11
void bug_tricks();//req 12
void functions(); //req 13
void functional_decomposition(); //req 14
void scope(); //req 15
//*****************************
void passing(); //req 16
void dub_int(int b); //function to double an integer to demonstrate pass by value
void halved(int &b); //function to halve an integer to demonstrate pass by reference
//*****************************
void overload(); //req 17
void dem_overload(int a); //same function name only used if input is int
void dem_overload(double b); //same function name only used if input is a double
void dem_overload(char c); //same function name only used if input is a character
//******************************************
void simple_string(); //req18
//***************************
void recursion(); //req 19
int factorial(int x); //function to find a factorial to demonstrate recursion
//***************************
void multi_array();//req 20
//*******************************************
void dynamic_array(); //req 21
void example_array(int number[], int size); //function to demonstrate a sample dynamic array by user input
//********************************************
void commandline();// req 22
//***************************************
void structure(); //req 23
struct structure_demo //demonstration of struct. Gives my name, age, height and weight
{
char name[20];
int age;
int height;
int weight;
};
//*****************************************
void classes(); //req 24
class minhsclass // demonstration of class, has 2 different objects that are called sentence and math.
{
public:
void sentence() //sample function to cout in class requirement for objects
{
cout << "This is a sample sentence for a class demonstration." << endl;
}
void math() //sample math function to do to show objects in class
{
int x,y,z;
cout << "Another demonstration of class using a simple addition problem. Enter in an integer: ";
cin >> x;
cout << "Enter in another integer: ";
cin >> y;
cout << x << " + " << y << " = " << x+y;
}
};
//***************************************************************************
void pointer_array(); // req 25
void struct_pointer(); //req 26. Unable to fulfill this requirement
void object_pointer(); //req 27. Unable to fulfill this requirement
int main (int argc, char* argv[]) //sample command line inputs, will print out whatever the inputs are.
{
if(argc==1) //command line input sample. if no arguments given it will start program
intro();
else
{ for(int i=1; i < argc; i++) // else the inputs on command line will be printed out and program starts
cout << "A demonstration of command line. Your command inputs are: " << argv[i] << endl;
}
int choice; //variable to choose what requirement grader wants to see demonstrated
cout << endl << endl << endl << endl << endl << endl;
do //entire program runs on a do while loop to continue choosing for next requirement after one is finished
{ cout << endl;
cout << "Enter requirement number here. To quit the program, enter in 30: ";
cin >> choice; //choice of requirement entered here
cout << endl << endl;
cout << "**********************************************************************************************" << endl;
switch(choice) //switch statement with 27 cases, one for each function of demonstrations.
{
case 1: binary(); break;
case 2: twos_complement(); break;
case 3: macro(); break;
case 4: output(); break;
case 5: input(); break;
case 6: type_cast(); break;
case 7: conditional(); break;
case 8: logical(); break;
case 9: loop(); break;
case 10: random_gen(); break;
case 11: dem_error(); break;
case 12: bug_tricks(); break;
case 13: functions(); break;
case 14: functional_decomposition(); break;
case 15: scope(); break;
case 16: passing(); break;
case 17: overload(); break;
case 18: simple_string(); break;
case 19: recursion(); break;
case 20: multi_array(); break;
case 21: dynamic_array(); break;
case 22: commandline(); break;
case 23: structure(); break;
case 24: classes(); break;
case 25: pointer_array(); break;
case 26: struct_pointer(); break;
case 27: object_pointer(); break;
}
} while (choice!=30); //enter 30 to quit program
cout << endl << endl;
cout << "**************************************************************************************************" << endl;
cout << endl << endl;
cout << "Thank you for taking the time to grade this project!" << endl << endl;
return 0;
}
void intro()
{ cout << endl << endl << endl;
cout << "******************************************************************************************" << endl;
cout << "Welcome to Minh's final project." << endl;
cout << "There are 27 requirements for this project." << endl;
cout << "To ease the grading process, Every requirement is in a seperate function." << endl;
cout << "As the grader, simply enter in the number that corresponds to each requirement" << endl;
cout << "on the final PDF to see my demonstration of that requirement." << endl;
}
void binary()
{
cout << "The binary numbering system represents numeric values using two symbols, 1 and 0." << endl;
cout << "a 2-bit system is represented with 4 possible combinations: 00, 01, 10, 11." << endl;
cout << "Each of these corresponding to the numbers 0, 1, 2, 3." << endl;
cout << "the 0's and 1's simply represents if that numbers digits is being added or not." << endl;
cout << "As you increase in bits, say 3-bit, 4-bit, you get more and more bigger numbers." << endl;
cout << "2-bit has 4 numberse, 3-bit has 8, 4-bit has 16... etc." << endl;
cout << "here is an example of a 4-bit number." << endl;
bitset<4> foo;
foo.set();
cout << foo << " as an integer is: " << foo.to_ulong() << endl;
}
void twos_complement()
{
cout << "demonstration of twos complement." << endl;
char bin1[BITS+1] = "00000011";
cout << "Binary: " << bin1 << endl << "Dec: " << setw(8) << convert(bin1) << endl << endl;
char bin2[BITS+1] = "10000000";
cout << "Binary: " << bin2 << endl << "Dec: " << setw(8) << convert(bin2) << endl << endl;
char bin3[BITS+1] = "01111111";
cout << "Binary: " << bin1 << endl << "Dec: " << setw(8) << convert(bin3) << endl << endl;
}
int convert(char binary[])
{
int power = 128;
int sum = 0;
assert(strlen(binary) == 8);
for (int i=0; i < BITS; ++i)
{
if ( i==0 && binary[i]!='0')
sum = -128;
else
sum += (binary[i]-'0')*power;
power /= 2;
}
return sum;
}
void macro()
{
int number = INT_MAX;
cout << "Using int_max to demonstrate a predefined macro." << endl;
cout << number << endl;
}
void output()
{
cout << "outputting a simple output!" << endl;
}
void input()
{
int choice;
cout << "Demonstrating a simple input. Now enter any integer you'd like: ";
cin >> choice;
cout << "you entered: " << choice << endl;
}
void type_cast()
{
double a;
int b;
cout << "Showing type casting by converting a double into an int. Enter in a double(decimal) here: ";
cin >> a;
b=a;
cout << "the integer it became is " << b << endl;
}
void conditional()
{
int choice;
cout << "demonstrating a conditional. Please enter a number on your keyboard between 1 and 10: ";
cin >> choice;
if (choice < 1 || choice > 10)
cout << "the number " << choice << " is not a number between 1 and 10." << endl;
else
cout << "Good job. " << choice << " is a number between 1 and 10." << endl;
}
void logical()
{
int x=10;
int y=25;
cout << "Demonstrating logical/bitwise operator ^." << endl;
x=x^y;
y=x^y;
x=x^y;
cout << "In this function, x=10, y=25, x=x^y, y=x^y, x=x^y, then printing out x yields: " << x << endl;
}
void loop()
{
cout << "demonstration of a simple for loop. prints out numbers 1-9." << endl;
for (int i=1; i < 10; i++)
cout << i << endl;
}
void random_gen()
{
srand(time(0));
cout << "Demonstration of a random number through a random number generator." << endl;
for (int x=1; x<6; x++)
cout << 1+(rand()%10) << endl;
}
void dem_error()
{
cout << "Demonstration of syntax, logic, and run-time error." << endl << endl;
cout << "A syntax error is an invalid statement written in a way that the language you are working in does not recognize." << endl;
cout << "A very simple example is simply forgettin the semicolon (;) after an endl statement." << endl << endl;
cout << "A logic error is an error in which it causes the program to operate incorrectly, but doesn't terminate by itself." << endl;
cout << "This causes unwanted and unexpected behaviors from the program." << endl;
cout << "an example of a logic error is forgetting a parenthesis in a math equation. such as a + b / 2. It should be (a + b) / 2." << endl << endl;
cout << "A run-time error is an error that occurs during the execution of the program." << endl;
cout << "A simple example would be when a program runs out of memory, it will cause a run-time error." << endl;
}
void bug_tricks()
{
int x;
cout << "Demonstration of a simple debugging trick to make sure that a number entered is indeed an integer." << endl << endl;
cout << "Enter an integer: ";
cin >> x;
while (!cin.good())
{
cout << "Not an integer, try again: ";
cin.clear();
cin.ignore(1000, '\n');
cin >> x;
}
cout << "You entered: " << x << endl;
}
void functions()
{
cout << "This is a function that says HELLO WORLD!" << endl;
}
void functional_decomposition()
{
cout << "This project is essentially decomposed to making 27 functions, one for each of the requirements, no matter how simple it is, and put them all in a switch menu in main." << endl;
}
void scope()
{
int choice;
cout << "In this demonstration of scope, I have declared an int variable called 'choice'." << endl;
cout << "The variable in main is also called 'choice' when you enter in a number, but the 'choice' that is in this function," << endl;
cout << "only exists in this function, or scope." << endl;
cout << "So here, you may enter in an integer that is your 'choice': ";
cin >> choice;
cout << "And the number you entered was: " << choice << ", which has no impact on the main menu." << endl;
}
void passing()
{
int x;
cout << "A simple demonstration on passing by value and passing by reference." << endl;
cout << "For pass by value, I pass in an integer 20. A simple function will double this value." << endl;
dub_int(20);
cout << endl << endl;
cout << "For a pass by reference, Please enter in an integer to be passed into, and it will be halved: ";
cin >> x;
halved(x);
}
void dub_int(int b)
{
cout << "20 doubled is: " << b*2 << endl;
}
void halved(int &b)
{
cout << b << " halved is: " << b/2 << endl;
}
void overload()
{
int x;
double y;
char z;
cout << "In this demonstration of function overloading, I will call a function with 3 overloaded types." << endl;
cout << "Enter in an integer here and the function will double the integer: ";
cin >> x;
dem_overload(x);
cout << "Enter in a double (decimal number) will make the function triple this number: ";
cin >> y;
dem_overload(y);
cout << "Enter in any single character and the function will print it out: ";
cin >> z;
dem_overload(z);
}
void dem_overload(int a)
{
cout << "The integer doubled is : " << a*2 << endl;
}
void dem_overload(double b)
{
cout << "The doubled (decimal) number tripled is : " << b*3 << endl;
}
void dem_overload(char c)
{
cout << "The character you entered is: " << c << endl;
}
void simple_string()
{
string name;
cout << "A simple demonstration on strings. Please enter your first name and it will be printed out: ";
cin >> name;
cout << name << endl;
}
void recursion()
{
int choice;
cout << "Demonstration of recursion by finding the factorial of any integer input." << endl;
cout << "Enter in any integer to get it's factorial: ";
cin >> choice;
cout << factorial(choice) << endl;
}
int factorial(int x)
{
if (x==1)
return 1;
else
return x*factorial(x-1);
}
void multi_array()
{
int x[2][3] = {{0,1,2},{3,4,5}};
cout << "For this multidimentional array demonstration, I have a 2x3 grid, each grid containing a number." << endl;
cout << "The first 3 number is 0,1,2. and the 2nd set of 3 numbers is 3,4,5." << endl;
cout << "To print out the number 0, Simply substitute x[0][0]: " << x[0][0] << endl;
cout << "To print out the number 1, Simply substitute x[0][1]: " << x[0][1] << endl;
cout << "To print out the number 2, Simply substitute x[0][2]: " << x[0][2] << endl;
cout << "To print out the number 3, Simply substitute x[1][0]: " << x[1][0] << endl;
cout << "To print out the number 4, Simply substitute x[1][1]: " << x[1][1] << endl;
cout << "To print out the number 5, Simply substitute x[1][2]: " << x[1][2] << endl;
}
void dynamic_array()
{
cout << "A dynamic array demonstration. Enter in the size of an array of your choice and an array of that size will be created." << endl;
cout << "I would suggest a small integer for the sake of saving time: ";
int *array, array_size;
cin >> array_size;
array= new int[array_size];
example_array(array, array_size);
delete [] array;
}
void example_array(int number[], int size)
{
cout << "Now you will be asked to enter in a number for each array." << endl;
for (int i=1; i <=size; i++)
{cout << "Enter for #" << i << " :";
cin >> number[i];}
for (int i=1; i <=size; i++)
cout << "You entered " << number[i] << " for #" << i << endl;
}
void commandline()
{
cout << "To demonstrate a commandline, Please exit this program and enter in as many argument as you'd like when you run this project." << endl;
cout << "You will see that as part of the demonstration, every word you typed will be printed out." << endl;
}
void structure()
{
cout << "A simple demonstration of using structure to store some data about me." << endl << endl;
structure_demo Minh =
{
"Minh Nguyen",
25,
70,
150
};
cout << "Name: " << Minh.name << endl;
cout << "Age: " << Minh.age << endl;
cout << "Height in inches: " << Minh.height << " in." << endl;
cout << "Weight in pounds: " << Minh.weight << " lbs." << endl;
}
void classes()
{ minhsclass minhsobject;
minhsobject.sentence();
cout << endl << endl;
minhsobject.math();
cout << endl << endl;
}
void pointer_array()
{
cout << "A demonstration for using a pointer to an array." << endl << endl;
cout << "Numbers 0-14 will be printed out, then I will use a pointer and add 1 to the array and numbers 1-15 will be printed out." << endl;
cout << endl << endl;
int *pointer;
int i, a[15];
for (int i = 0; i < 15; i++)
a[i] = i;
pointer = a;
for (int i =0; i < 15; i++)
cout << pointer[i] << " ";
for (int i = 0; i < 15; i++)
pointer[i] = pointer[i] + 1;
cout << endl << endl;
for (int i = 0; i < 15; i++)
cout << a[i] << " ";
cout << endl << endl;
}
void struct_pointer()
{}
void object_pointer(){}
| true |
a586d59ec11047ad23be913c6f185a456552c268 | C++ | CallmeAce/Coding_for_Fun | /workingspace/data_mining/symmetric_string.cpp | UTF-8 | 1,970 | 4.0625 | 4 | [] | no_license | /*
* Interesting Interview Problem
* Given a string, your task is to add alphabets at the end of it, and
* make it symmetric. of course, add a whole string is the most convinent
* way of doing that. But our goal is to make the symmetric string as short
* as possible
*
* It could be solved by dynamic programming!
*
* Author: Xuan Wang
* Input: a string, no space
* Output: a symmetric string
*
*/
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<vector>
using namespace std;
class SymmetricString
{
public:
char input_string[100];
char output_string[100];
vector<int> ind_list;
int length;
/* Methods */
void Sym_Run(int ind);
void init();
void P_Result();
};
void SymmetricString::init()
{
memset(input_string,0,sizeof(char)*100);
cin>>input_string;
for(int i=0;i<100;i++)
{
if(input_string[i]==0)
break;
length=i;
}
}
void SymmetricString::Sym_Run(int ind)
{
int len_ind =0;
for(int i=ind;i<100;i++)
{
if(input_string[i]==0)
break;
len_ind=i;
}
if(!((len_ind-ind)%2)) // if the length is odd, pushback the first alphabet, because the length of the string has to be even. like "ABA, ABCBA"
{
int j =0;
for(int i=ind;i<length;i++)
{
if (i == length-j)
{
return;
}
if(input_string[i]!=input_string[length-j])
{
for(int k =ind;k<=i;k++)
{
ind_list.push_back(k);
}
Sym_Run(i+1);
break;
}
j++;
}
}
else
{
ind_list.push_back(ind);
Sym_Run(ind+1);
}
}
void SymmetricString::P_Result()
{
cout<<"Input String is : "<<endl;
for(int i=0;i<=length;i++)
cout<<input_string[i];
cout<<endl;
cout<<"Output String is : "<<endl;
for(int i=0;i<=length;i++)
cout<<input_string[i];
// cout<<endl;
// cout<<"the string needs to be added: ";
for(int i=ind_list.size();i>0;i--)
cout<<input_string[i-1];
cout<<endl;
}
int main()
{
SymmetricString * a = new SymmetricString();
a->init();
a->Sym_Run(0);
a->P_Result();
}
| true |
141d16e5e8f2c24c00d9673010289b040e9b7c93 | C++ | PraxLannister/Codes | /assignments/MCA-2ndSem/ds/Assign-3/ques7.cpp | UTF-8 | 816 | 3.953125 | 4 | [] | no_license | /*WAP to reverse a Linked List.*/
#include<iostream>
#include<iomanip>
#include<cstdlib>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}node;
node * head=NULL;
//a. Create a linked list.
node * createNode(int data)
{
node *newNode = new node;
if(!newNode)
{
cout<<"\nOVERFLOW!!!\nTerminating!!!!";
exit(0);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
//b. Insert an element at the start of the linked list.
void insertAtBeg(int data)
{
node *newNode = createNode(data);
if(!head)
head = newNode;
else
{
newNode->next = head;
head = newNode;
}
}
void display()
{
node *temp = head;
while(temp)
{
cout<<temp->data<<"->";
temp = temp -> next;
}
cout<<"|\\0|"<<endl;
}
int main(){
cout<<"Enter element for reversing :"<<endl;
} | true |
111f074f0f5f0d70edac63a0d0ea294b8e1daf6d | C++ | albertorobles2000/Ejercicios-de-pilas-y-colas-con-la-stl | /src/ejercicio11.cpp | UTF-8 | 2,362 | 4.03125 | 4 | [] | no_license | /*
13. Implementa una cola con prioridad que contenga strings y de la que salgan primero las cadenas de caracteres
que tengan mas vocales y que en caso de igualdad salgan por orden alfabetico.
*/
#include <iostream>
#include <queue>
#include <string>
using namespace std;
int num_vocales(string s)
{
int contador = 0;
char letra;
for (unsigned i=0; i<s.size(); i++){
letra = s[i];
if ( letra == 'a' || letra == 'A' || letra == 'e' || letra == 'E' || letra == 'i' || letra == 'I' ||
letra == 'o' || letra == 'O' || letra == 'a' || letra == 'U' )
{
contador++;
}
}
return contador;
};
class Cola_prioridad{
private:
queue<string> cola1;
queue<string> cola2;
public:
Cola_prioridad(){}
Cola_prioridad(const Cola_prioridad & cola)
{
cola1 = cola.cola1;
}
void operator = (const Cola_prioridad & otra)
{
cola1 = otra.cola1;
}
void push(string s)
{
int num_vocal = num_vocales(s);
while(!cola1.empty() && num_vocales(cola1.front()) > num_vocal){
cola2.push(cola1.front());
cola1.pop();
}
while(!cola1.empty() && num_vocales(cola1.front()) == num_vocal && s > cola1.front()){
cola2.push(cola1.front());
cola1.pop();
}
cola2.push(s);
while(!cola1.empty()){
cola2.push(cola1.front());
cola1.pop();
}
while(!cola2.empty()){
cola1.push(cola2.front());
cola2.pop();
}
}
void pop()
{
cola1.pop();
}
string & front()
{
return cola1.front();
}
string & back()
{
return cola1.back();
}
bool empty() const
{
return cola1.empty();
}
int size() const
{
return cola1.size();
}
bool operator < (const Cola_prioridad & otra)
{
return cola1 < otra.cola1;
}
bool operator == (const Cola_prioridad & otra)
{
return cola1 == otra.cola1;
}
};
int main(){
Cola_prioridad cola;
string cadena;
cout << "Introduce string separados por enter" << endl;
cout << "Estribe 'fin' para terminar" << endl;
getline(cin,cadena);
while(cadena != "fin"){
cola.push(cadena);
getline(cin,cadena);
}
cout << "\n\nSalida ordenada: " << endl;
while(!cola.empty()){
cout << cola.front() << endl;
cola.pop();
}
}
| true |
4988b946b39f5095777e4c4ddf01eaa8c4a555ba | C++ | Glock123/CsesSolutions | /MinimizingCoins.cpp | UTF-8 | 447 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main() {
int n, target;
cin >> n >> target;
int a[n];
for(int i=0; i<n; i++) cin >> a[i];
vector<int> dp(target + 1, 1e9);
dp[0] = 0;
for(int i=1; i<=target; i++)
for(int j=0; j<n; j++)
if(i - a[j] >= 0) dp[i] = min(dp[i], dp[i-a[j]]+1);
if(dp[target] == 1e9) return printf("-1")*0;
else cout << dp[target];
return 0;
}
| true |
6272079a2328cf067deb4df6754e23897ba9d086 | C++ | ABackerNINI/CRMS_On_VxWorks | /utility/TimeUtil/Duration.h | UTF-8 | 2,383 | 3.078125 | 3 | [] | no_license | #pragma once
#ifndef _ABACKER_DURATION_H_
#define _ABACKER_DURATION_H_
#include "DateTime.h"
class Duration {
friend class DateTime;
public:
unsigned long long ddateTime; //second * 1000
#if (FEATURE_GET_CPU_CYCLE_COUNT)
long long dcpuCycleCount;
#endif
#if (FEATURE_GET_CPU_CYCLE_COUNT)
Duration()
: ddateTime(DEFAULT_DURATION_DDATETIME), dcpuCycleCount(DEFAULT_DURATION_DCPUCYCLECOUNT) {
}
#else
Duration()
: ddateTime(DEFAULT_DURATION_DDATETIME) {
}
#endif
Duration(const char *_Str) {
//TODO construct with string
}
Duration(const DateTime &dateTime1, const DateTime &dateTime2) {
ddateTime = dateTime1.dateTime - dateTime2.dateTime;
#if (FEATURE_GET_CPU_CYCLE_COUNT)
dcpuCycleCount = (long long) dateTime1.cpuCycleCount - (long long) dateTime2.cpuCycleCount;
#endif
}
bool isUninitialized() const {
#if (FEATURE_GET_CPU_CYCLE_COUNT)
return ddateTime == DEFAULT_DURATION_DDATETIME && dcpuCycleCount == DEFAULT_DURATION_DCPUCYCLECOUNT;
#else
return ddateTime == DEFAULT_DURATION_DDATETIME;
#endif
}
std::string toString_in_micro_sec() const {
char duration[20];
sprintf(duration, "%lld", ddateTime);
return std::string(duration);
}
std::string toString_in_milli_sec() const {
char duration[20];
sprintf(duration, "%lld", ddateTime / 1000);
return std::string(duration);
}
std::string toString_in_sec() const {
if (isUninitialized())return std::string();
char duration[20];
sprintf(duration, "%lld", ddateTime / 1000);
return std::string(duration);
}
std::string toString_in_minute() const {
char duration[20];
sprintf(duration, "%lld", ddateTime / (1000LL * 60LL));
return std::string(duration);
}
std::string toString_in_hour() const {
char duration[20];
sprintf(duration, "%lld", ddateTime / (1000LL * 3600LL));
return std::string(duration);
}
std::string toString_in_day() const {
char duration[20];
sprintf(duration, "%lld", ddateTime / (1000LL * 3600LL * 24LL));
return std::string(duration);
}
};
#endif//_ABACKER_DURATION_H_ | true |
83b46ce01c5bdb888d161f66084d1324e7249d66 | C++ | thomaswohlfahrt/oiram_repus_jumpnrun | /source/Logic.h | UTF-8 | 4,085 | 3.234375 | 3 | [] | no_license | #ifndef LOGIC_H
#define LOGIC_H
#include "SDL/SDL.h"
#include <string>
#include "movingItem.h"
#include "player.h"
#include <iterator>
class map;
using namespace std;
/**
* @brief A class responsible for moving Item objects, detecting collisions and resolving them.
* Various methods for handling collisions between different objects exist. Depending on
* the type of objects which collide it might be important to know wether the collision took place
* in X or in Y direction.
*
*/
class Logic
{
public:
Logic();
/**
* @brief Method that encapsulates the hands on game logic such as movement.
* In order to move an Item object its position is first changed preliminarily.
* Then collisions are checked. In case there are no collisions the Item is not moved back.
* Incase the object shows a collision either in x or y direction, appropriate action is then
* taken by specialized methods.
*/
void run(vector<Item*> &items,map *tmap);
private:
map* mapPointer;
vector<Item*> *itemPointer;
bool standing;
/**
* @brief Convenience function to move an item by its delta
*/
void moveX(MovingItem *myitem);
/**
* @brief Convenience function to move an item by its delta
*/
void moveY(MovingItem *myitem);
/**
* @brief Convenience function to move an item back by its delta
*/
void moveXBack(MovingItem *myitem);
/**
* @brief Convenience function to move an item back by its delta
*/
void moveYBack(MovingItem *myitem);
/**
* @brief Convenience function to check if two bounding rectangles are overlapping
* @returns wether a collision has happened
*/
int checkCollision(Item *myitem1, Item *myitem2 );
/**
* @brief Move a crab object and check for collisions
*/
void handleCrab(int pos,vector<Item*> &items);
/**
* @brief Move a grr object and check for collisions
*/
void handleGrrr(int pos,vector<Item*> &items);
/**
* @brief Move a Cloud object and check for collisions
*/
void handleFightCloud(int pos,vector<Item *> &items);
/**
* @brief Move a bullet object and check for collisions
*/
void handleBullet(int pos,vector<Item*> &items);
/**
* @brief Move a bullet object check for timeouts and handle collisions
*/
void handlePrincessBullet(int pos,vector<Item*> &items);
/**
* @brief Move a bullet object and check for collisions
*/
void handleGhost(int pos,vector<Item*> &items);
/**
* @brief Move a bullet object and check for collisions
*/
void handleTrapStone(int pos,vector<Item*> &items);
/**
* @brief Move the player and handle collisions appropriately
*/
void handlePlayer(Item *tmp,vector<Item*> &items);
/**
* @brief Handle a specific type of collision
*/
void collisionPlayerMapX(Player *tmp, int pos, vector<Item *> &items);
/**
* @brief Handle a specific type of collision
*/
void collisionPlayerMapY(Player *tmp, int pos, vector<Item *> &items);
/**
* @brief Handle a specific type of collision
*/
void collisionPlayerGhostXY(Player *tmp,int pos,vector<Item*> &items);
/**
* @brief Handle a specific type of collision
*/
void collisionPlayerCrabX(Player *tmp, int pos,vector<Item*> &items);
/**
* @brief Handle a specific type of collision
*/
void collisionPlayerCrabY(Player *tmp,int pos,vector<Item*> &items);
/**
* @brief Handle a specific type of collision
*/
void collisionPlayerCoinXY(Player *tmp,int pos,vector<Item*> &items);
/**
* @brief Handle a specific type of collision
*/
void collisionHeartXY(Player *tmp,int pos,vector<Item*> &items);
/**
* @brief Handle a specific type of collision
*/
void collisionStarXY(Player *tmp,int pos,vector<Item*> &items);
/**
* @brief Handle a specific type of collision
*/
void collisionPrincesBulletXY(Player *tmp,int pos,vector<Item*> &items);
/**
* @brief Handle a specific type of collision
*/
void collisionWaterYX(Player *tmp);
/**
* @brief Handle a specific type of collision
*/
void collisionGoalXY();
/**
* @brief Handle a specific type of collision
*/
void collisionGrrrXY(Player* tmp);
};
#endif // LOGIC_H
| true |
615c319f51a5fbfeb6e44b86cea8dac70998f59f | C++ | Justocodes/C-Projects | /PROJECTS/THE PAINTING PROJECT.cpp | UTF-8 | 6,209 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
int bedroom1, bedroom2, basement;
int window1, window2, window3, window4;
int length;
int width;
int height;
int total_area_room1, total_area_room2, total_area_basement;
int total_area;
int count, counter, rooms;
double gallons_needed = 50;
float company1_price_per_gallon, company2_price_per_gallon, company3_price_per_gallon;
float total_expenses_paint_company1, total_expenses_paint_company2, total_expenses_paint_company3;
float labor1, labor2, labor3;
float grand_total_expenses_company1, grand_total_expenses_company2, grand_total_expenses_company3;
float min;
string firstname, lastname;
system("mode 150");
cout << " BUILDERS QUALITY INC" << endl;
cout << " 1011 AVE QUEENS NY, 70333" << endl;
cout << " BUILDERSINC@YOURMAIL.com" << endl;
cout << " TEL: (233)-633-366" << endl << endl << endl;
cout << fixed << setprecision(2) << endl;
cout << "Date: " << __DATE__ ;
cout << endl;
cout << "Please enter first name : ";
cin >> firstname;
cout << "Please enter last name: ";
cin >> lastname;
cout << endl;
{
cout << "Please enter the length, width, and height for bedroom 1: " << endl;
cin >> length >> width >> height;
bedroom1 = 2 * height*(length + width);
cout << "Bedroom 1 = " << bedroom1 << endl;
cout << endl;
cout << "Please enter the length and width for window 1: " << endl;
cin >> length >> width;
window1 = length * width;
cout << "Window 2 = " << window1 << endl;
cout << endl;
total_area_room1 = bedroom1 - window1;
cout << "The total area for bedroom 1 is equal to " << total_area_room1 << endl;
cout << endl;
}
//Bedroom 2
cout << "Please enter the length, width, and height for bedroom2: " << endl;
cin >> length >> width >> height;
bedroom2 = 2 * height*(length + width);
cout << "Bedroom 2 = " << bedroom2 << endl;
cout << endl;
cout << endl;
cout << "Please enter the length and width for window2: " << endl;
cin >> length >> width;
window2 = length * width;
cout << "Window 2 = " << window2 << endl;
cout << endl;
cout << "Please enter the length and width for window3: " << endl;
cin >> length >> width;
window3 = length * width;
cout << "Window 3 = " << window3 << endl;
cout << endl;
total_area_room2 = bedroom2 - window2 - window3;
cout << "The total area for bedroom 2 is equal to " << total_area_room2 << endl;
cout << endl;
//Basement
cout << "Please enter the length, width, and height for basement: " << endl;
cin >> length >> width >> height;
basement = 2 * height*(length + width);
cout << "Basement = " << basement << endl;
cout << endl;
//window 4
cout << "Please enter the length and width for window4: " << endl;
cin >> length >> width;
window4 = length * width;
cout << "Window 4 = " << window4 << endl;
cout << endl;
//Total Area fot Basement
total_area_basement = basement - window4;
cout << "The total area for basement is equal to " << total_area_basement << endl;
cout << endl;
//Total area all 3 rooms
total_area = total_area_room1 + total_area_room2 + total_area_basement;
cout << "The Total Area for all rooms is equal to " << total_area << endl;
cout << endl;
//Galons needed
gallons_needed = total_area / gallons_needed;
cout << "Total amount of gallons to be used to paint the three rooms are " << gallons_needed << endl;
cout << endl;
//companies price per gallon
cout << "What is Company 1's price per gallon?" << endl;
cin >> company1_price_per_gallon;
cout << "What is Company 2's price per gallon?" << endl;
cin >> company2_price_per_gallon;
cout << "What is Company 3's price per gallon?" << endl;
cin >> company3_price_per_gallon;
cout << endl;
//total paint expenses
total_expenses_paint_company1 = company1_price_per_gallon * gallons_needed;
cout << "The total paint expenses for company 1 are " << total_expenses_paint_company1 << endl;
cout << endl;
total_expenses_paint_company2 = company2_price_per_gallon * gallons_needed;
cout << "The total paint expenses for company 2 are " << total_expenses_paint_company2 << endl;
cout << endl;
total_expenses_paint_company3 = company3_price_per_gallon * gallons_needed;
cout << " The total paint expenses for company 3 are " << total_expenses_paint_company3 << endl;
cout << endl;
cout << "Please enter the cost of Labor for company 1: " << endl;
cin >> labor1;
cout << "Please enter the cost of Labor for company 2: " << endl;
cin >> labor2;
cout << "Please enter the cost of Labor for company 3: " << endl;
cin >> labor3;
cout << endl;
grand_total_expenses_company1 = total_expenses_paint_company1 + labor1;
cout << "Company 1's grand total of expenses is equal to " << grand_total_expenses_company1 << endl;
grand_total_expenses_company2 = total_expenses_paint_company2 + labor2;
cout << "Company 2's grand total of expenses is equal to " << grand_total_expenses_company2 << endl;
grand_total_expenses_company3 = total_expenses_paint_company3 + labor3;
cout << "Company 3's grand total of expenses is equal to " << grand_total_expenses_company3 << endl;
if (grand_total_expenses_company1 < grand_total_expenses_company2 && grand_total_expenses_company1 < grand_total_expenses_company3){
min = grand_total_expenses_company1;
cout << "The minimum offer is made by Company 1 for a grand total of " << grand_total_expenses_company1 << endl;
}
else if (grand_total_expenses_company2 < grand_total_expenses_company1 && grand_total_expenses_company2 < grand_total_expenses_company3){
min = grand_total_expenses_company2;
cout << "The minimum offer is made by Company 2 for a grand total of " << grand_total_expenses_company2 << endl;
}
else {
min = grand_total_expenses_company3;
cout << "The minimum offer is made by Company 3 for a grand total of " << grand_total_expenses_company3 << endl;
}
system("pause");
return 0;
} | true |
72d7e4de0437d6ecd39458065b859086fddbd719 | C++ | eriser/SynthTest | /Arduino/_03_Low_Pass_Filter_Tester/_03_Low_Pass_Filter_Tester.ino | UTF-8 | 1,642 | 2.765625 | 3 | [] | no_license | /** Outputs a constant analog value to the piezo element.
* This is to test the effectiveness of an attached low-pass
* filter (sim.okawa-denshi.jp/en/PWMtool.php, provideyourown.com/2011/analogwrite-convert-pwm-to-voltage/).
* Silence is good.
*/
const int speakerPin = 9;
/** From: playground.arduino.cc/Code/PwmFrequency
* forum.arduino.cc/index.php/topic,16612.0.html#4
*/
void setPwmFrequency(int pin, int divisor)
{
byte mode;
if(pin == 5 || pin == 6 || pin == 9 || pin == 10)
{
switch(divisor)
{
case 1: mode = 0x01; break;
case 8: mode = 0x02; break;
case 64: mode = 0x03; break;
case 256: mode = 0x04; break;
case 1024: mode = 0x05; break;
default: return;
}
if(pin == 5 || pin == 6)
{
TCCR0B = TCCR0B & 0b11111000 | mode;
}
else
{
TCCR1B = TCCR1B & 0b11111000 | mode;
}
}
else if(pin == 3 || pin == 11)
{
switch(divisor)
{
case 1: mode = 0x01; break;
case 8: mode = 0x02; break;
case 32: mode = 0x03; break;
case 64: mode = 0x04; break;
case 128: mode = 0x05; break;
case 256: mode = 0x06; break;
case 1024: mode = 0x7; break;
default: return;
}
TCCR2B = TCCR2B & 0b11111000 | mode;
}
}
void setup()
{
pinMode(speakerPin, OUTPUT);
// Set PWM frequency
setPwmFrequency(speakerPin, 8); // 31250 Hz divide 8 = 3906.25 Hz
}
void loop()
{
analogWrite(speakerPin, 128);
}
| true |
10320f2d8856fa8c32291faefc729938c7c8edc2 | C++ | CmosZhang/Code_Practice | /LintCode/背包问题IV.cpp | GB18030 | 1,513 | 3.4375 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
//һЩƷһĿֵжֿĿ
//Ʒ [2,3,6,7] Ŀֵ 7, ô2ֿܣ[7] [2, 2, 3]Է2
//Ҳ12510Ӳʴ80Ԫķ
//Ӳҿظѡ
//״̬תƷ̣
//dp[i][j]ǰiӲҴճjԪķ
//dp[i][j]=dp[i-1][j]+dp[i-1][j-A[i]*1]+dp[i-1][j-A[i]*2]+...+
int backpack(vector<int>&item, int target) {
int len = item.size();
vector<vector<int>> dp(len + 1, vector<int>(target, 0));
dp[0][0] = 1;
for (int i = 1; i <= len; i++) {
for (int j = 0; j <= target; j++) {
int k = 0;
while (k*item[i - 1] < j) {
dp[i][j] += dp[i - 1][j - item[i - 1] * k];
k++;
}
}
}
return dp[len][target];
}
//ӲҲظѡÿӲֻʹһ
//dp[i][j]ʾǰiӲҴճjԪķ
//dp[i][j] = dp[i-1][j]+dp[i-1][j-A[i]]
//dp[0][0] = 1
int backpack2(vector<int>&item, int target) {
int len = item.size();
vector<vector<int>> dp(len + 1, vector<int>(target, 0));
dp[0][0] = 1;
for (int i = 1; i <= len; i++) {
for (int j = 0; j <= target; j++) {
dp[i][j] = dp[i - 1][j];
if (item[i - 1] <= j) {
dp[i][j] += dp[i - 1][j - item[i - 1]];
}
}
}
return dp[len][target];
} | true |
4ecfc7ca65b4591417bd45c4027074012e112645 | C++ | ghbenjamin/quarantania2 | /src/systems/AnimationSystem.cpp | UTF-8 | 1,648 | 2.578125 | 3 | [] | no_license | #include <systems/AnimationSystem.h>
#include <game/Level.h>
#include <graphics/RenderInterface.h>
#include <components/RenderComponent.h>
#include <components/AnimationComponent.h>
#include <utils/Memory.h>
AnimationSystem::AnimationSystem(Level *parent)
: System(parent)
{
m_level->events().subscribe<GameEvents::EntityMove>(this);
m_level->events().subscribe<GameEvents::EntityDamage>(this);
}
void AnimationSystem::operator()( GameEvents::EntityMove &evt )
{
auto animC = m_level->ecs().getComponents<AnimationComponent>( evt.ent );
std::vector<Vector2i> path;
if ( evt.path.has_value() )
{
path = *evt.path;
}
else
{
path.push_back( evt.oldPos );
path.push_back( evt.newPos );
}
std::vector<Vector2f> worldPath;
worldPath.reserve( path.size() + 1 );
worldPath.push_back( m_level->tileCoordsToWorld( evt.oldPos ).convert<float>() );
for ( Vector2i tile : path )
{
worldPath.push_back( m_level->tileCoordsToWorld( tile ).convert<float>() );
}
m_level->animation().pushAnimation(utils::make_unique_with_type<Animation, AnimTilePath>(m_level, evt.ent, worldPath, 0.2f) );
}
void AnimationSystem::operator()( GameEvents::EntityDamage &evt )
{
if ( m_level->ecs().entityHas<AnimationComponent>( evt.target ) )
{
auto [renderC, animC] = m_level->ecs().getComponents<RenderComponent, AnimationComponent>(evt.target);
m_level->animation().pushAnimation(utils::make_unique_with_type<Animation, AnimColourMod>(
m_level, evt.target, Colour::Red, renderC->sprite.getColour(), 0.5f) );
}
}
| true |
f02a4af8c62a5ef4b3004642877ef356d7d2a6f2 | C++ | Gummybearr/PS | /leetcode/Remove Duplicates from Sorted Array.cpp | UTF-8 | 265 | 2.671875 | 3 | [] | no_license | class Solution {
public:
int removeDuplicates(vector<int>& nums) {
set<int> s;
for(int i = 0;i<nums.size();i++){s.insert(nums[i]);}
vector<int> v;
for(auto i:s){v.push_back(i);}
nums = v;
return s.size();
}
}; | true |
2fb4e85c6a9ce873deb089a2a24145ca49cf3e88 | C++ | WhiZTiM/coliru | /Archive2/39/5ab7884091af2f/main.cpp | UTF-8 | 2,038 | 2.703125 | 3 | [] | no_license | #include <boost/icl/split_interval_set.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <iostream>
#include <map>
namespace icl = boost::icl;
using boost::adaptors::map_values;
typedef icl::split_interval_set<int> iset;
typedef std::map<int, iset> iset_map;
template <typename C>
iset_map transpose_input(C const& raw_input)
{
iset_map trans;
for(typename C::const_iterator it = raw_input.begin(); it != raw_input.end(); ++it)
for (size_t i = 0; i<it->size(); ++i)
trans[i].insert(it->at(i));
return trans;
}
int main()
{
typedef iset::interval_type ival;
typedef std::vector<ival> ival_vec;
// for parsing
typedef boost::spirit::istream_iterator input;
std::vector<ival_vec> raw_input;
{
using namespace boost::spirit::qi;
using boost::phoenix::construct;
input f(std::cin >> std::noskipws), l;
rule<input, iset::interval_type(), blank_type> ival_
= ('[' >> int_ >> '-' >> int_ >> ']') [ _val = construct<ival>(_1, _2) ]
| eps;
bool ok = phrase_parse(f, l, ival_ % '|' % eol, blank, raw_input);
if (!ok || f!=l) {
std::cout << "unparsed: '" << std::string(f,l) << "'\n";
return 255;
}
}
iset_map const transposed = transpose_input(raw_input);
iset unioned;
for (iset_map::const_iterator it = transposed.begin(); it != transposed.end(); ++it)
boost::copy(it->second, std::inserter(unioned, unioned.end()));
for (iset::const_iterator iv = unioned.begin(); iv != unioned.end(); ++iv) {
for (iset_map::const_iterator pair = transposed.begin(); pair != transposed.end(); ++pair)
{
iset const& set = pair->second;
size_t idx = distance(set.begin(), set.lower_bound(*iv));
std::cout << *iv << " (" << (idx+1) << ")\t|";
}
std::cout << "\n";
}
}
| true |
0853c174af26cb958c468f8980c4848ab6024862 | C++ | xiongfj/Backup | /0-----C#/弱引用.cpp | UTF-8 | 488 | 2.9375 | 3 | [] | no_license |
* 弱引用数据在垃圾回收的时候会被系统回收, 有一定的风险,
* 所以在使用前需要判断是否已经被回收
public void func()
{
WeakReference mathReference = new WeakReference(new xxClass() );
xxClass obj;
if (mathReference.IsAlive)
{
obj = mathReference.Target as xxClass;
...
}
else
;// 对象已经被回收,无法使用.
GC.Collect(); // 垃圾收回
if (mathReference.IsAlive) // 此时得到 false
{
// f
}
}
| true |
25c19de46c8a7cb163cb7b138fe8ba67503ddeaa | C++ | gitkobaya/rcga | /cmd_check.cpp | SHIFT_JIS | 11,365 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstdarg>
#include<cstdlib>
#include<cstring>
#include "cmd_check.h"
CCmdCheck::CCmdCheck()
{
iGenerationNumber = 0;
iGenDataNum = 0;
iGenVectorDimNum = 0;
iCrossOverNum = 0;
iGaMethod = 0; // lf`̎@ݒ
iOutputFlag = 0;
pcFuncName = NULL;
lfAlpha = 0.0;
lfBeta = 0.0;
lfRangeMin = 0.0;
lfRangeMax = 0.0;
}
CCmdCheck::~CCmdCheck()
{
}
/**
*<PRE>
* ͂ꂽR}h`FbN
* ver 0.1
* ver 0.2 IvV̒ljAт̂ق̏CB
* ver 0.3 lHm\pOtc[쐬̂ߐVɏCB
*</PRE>
* @param argc R}h͍̓ڐ
* @param argv ͂R}h̏ڍ
* @return CCMD_SUCCESS
* CCMD_ERROR_INVALID_FORMAT
* CCMD_ERROR_INVALID_DATA
* CCMD_ERROR_MEMORY_ALLOCATE
* CCMD_ERROR_MEMORY_RELEASE
* @author kobayashi
* @since 0.1 2014/05/02
* @version 0.1
*/
long CCmdCheck::lCommandCheck( int argc, char* argv[] )
{
int i;
long lRet = 0;
CCmdCheckException cce;
/* R}h̃`FbN */
if( argc <= 1 )
{
return CCMD_ERROR_INVALID_FORMAT;
}
if( argv == NULL )
{
cce.SetErrorInfo( CCMD_ERROR_INVALID_FORMAT, "lCommandCheck", "CCmdCheck", "sȃR}hłB", __LINE__ );
throw( cce );
}
for( i=1; i<argc ;i++ )
{
/* vZ */
if( strcmp( argv[i], "-gn" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
iGenerationNumber = atoi( argv[i+1] );
i++;
}
/* `q */
else if( strcmp( argv[i], "-n" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
iGenDataNum = atoi( argv[i+1] );
i++;
}
/* `q̃xNg */
else if( strcmp( argv[i], "-gv" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
iGenVectorDimNum = atoi( argv[i+1] );
i++;
}
/* 1eƑ2e̕U̍LɊւp[^[ */
else if( strcmp( argv[i], "-alpha" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
lfAlpha = atof( argv[i+1] );
i++;
}
/* eƑ3̐e̕U̍LɊւp[^[ */
else if( strcmp( argv[i], "-beta" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
lfBeta = atof( argv[i+1] );
i++;
}
/* */
else if( strcmp( argv[i], "-con" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
iCrossOverNum = atoi( argv[i+1] );
i++;
}
/* ]{ړI */
else if( strcmp( argv[i], "-f" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
pcFuncName = new char[strlen(argv[i+1])+1];
memset( pcFuncName, '\0', sizeof(pcFuncName) );
strcpy( pcFuncName, argv[i+1] );
i++;
}
/* lGA̎@ */
else if( strcmp( argv[i], "-gm" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
iGaMethod = atoi( argv[i+1] );
i++;
}
/* ʏo */
else if( strcmp( argv[i], "-out" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
iOutputFlag = atoi( argv[i+1] );
i++;
}
/* ]̒`̍ŏl */
else if( strcmp( argv[i], "-dmin" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
lfRangeMin = atof( argv[i+1] );
i++;
}
/* ]̒`̍őn */
else if( strcmp( argv[i], "-dmax" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
lfRangeMax = atof( argv[i+1] );
i++;
}
/* e̐ݒ */
else if( strcmp( argv[i], "-pn" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
iParentNumber = atoi( argv[i+1] );
i++;
}
/* q̌ݒ */
else if( strcmp( argv[i], "-cn" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
iChildrenNumber = atoi( argv[i+1] );
i++;
}
/* ]lʂ̎q̌ */
else if( strcmp( argv[i], "-uecn" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
iUpperEvalChildrenNumber = atoi( argv[i+1] );
i++;
}
/* wK */
else if( strcmp( argv[i], "-lr" ) == 0 )
{
lRet = lCommandErrorCheck( argv[i] );
if( lRet != 0 ) return lRet;
lfLearningRate = atoi( argv[i+1] );
i++;
}
/* wv̕\ */
else if( strcmp( argv[i], "-h" ) == 0 )
{
vHelp();
}
else
{
lRet = CCMD_ERROR_INVALID_DATA;
break;
}
}
return lRet;
}
/**
*<PRE>
* ̓IvVǂ`FbN
* ver 0.1 VK쐬
* ver 0.2 lHm\pOtc[쐬pɏCB
*</PRE>
* @param argc
* @param argv
* @return 0
* -1
* -2
* @author kobayashi
* @since 2013/1/1
* @version 0.2
*/
long CCmdCheck::lCommandErrorCheck( char *argv )
{
long lRet = 0L;
if( ( strcmp( argv, "-gn" ) == 0 ) ||
( strcmp( argv, "-n" ) == 0 ) ||
( strcmp( argv, "-gv" ) == 0 ) ||
( strcmp( argv, "-alpha" ) == 0 ) ||
( strcmp( argv, "-beta" ) == 0 ) ||
( strcmp( argv, "-con" ) == 0 ) ||
( strcmp( argv, "-gm" ) == 0 ) ||
( strcmp( argv, "-f" ) == 0 ) ||
( strcmp( argv, "-dmin" ) == 0 ) ||
( strcmp( argv, "-dmax" ) == 0 ) ||
( strcmp( argv, "-pn" ) == 0 ) ||
( strcmp( argv, "-cn" ) == 0 ) ||
( strcmp( argv, "-out" ) == 0 ) ||
( strcmp( argv, "-lr" ) == 0 ) ||
( strcmp( argv, "-uecn" ) == 0 ) ||
( strcmp( argv, "-h" ) == 0 ))
{
lRet = 0;
}
else
{
lRet = -2;
}
return lRet;
}
/**
*<PRE>
* gp@\B
*</PRE>
* @author kobayashi
* @since 2015/6/10
* @version 0.2
*/
void CCmdCheck::vHelp()
{
printf("lf`vZ\n");
printf("gp@\n");
printf("rga [-f]\n");
printf("-gn XV\n");
printf("-n `q̐\n");
printf("-gv `q̃xNg\n");
printf("-alpha eƑe̕Ulp[^\n");
printf("-beta eeƑOe̕Ulp[^\n");
printf("-con \n");
printf("-pn ěiREXŎgpj\n");
printf("-cn iREXŎgpj\n");
printf("-gm lf`̎@ݒ\n");
printf("-f p\n");
printf("-dmin ]̒`̍ŏl\n");
printf("-dmax ]̒`̍ől\n");
printf("-out ʏo\n");
}
double CCmdCheck::lfGetAlpha()
{
return lfAlpha;
}
double CCmdCheck::lfGetBeta()
{
return lfBeta;
}
int CCmdCheck::iGetCrossOverNum()
{
return iCrossOverNum;
}
char* CCmdCheck::pcGetFuncName()
{
return pcFuncName;
}
int CCmdCheck::iGetGenerationNumber()
{
return iGenerationNumber;
}
int CCmdCheck::iGetGenDataNum()
{
return iGenDataNum;
}
int CCmdCheck::iGetGenVectorDimNum()
{
return iGenVectorDimNum;
}
int CCmdCheck::iGetGaMethod()
{
return iGaMethod;
}
int CCmdCheck::iGetOutputFlag()
{
return iOutputFlag;
}
double CCmdCheck::lfGetRangeMin()
{
return lfRangeMin;
}
double CCmdCheck::lfGetRangeMax()
{
return lfRangeMax;
}
int CCmdCheck::iGetChildrenNumber()
{
return iChildrenNumber;
}
int CCmdCheck::iGetParentNumber()
{
return iParentNumber;
}
int CCmdCheck::iGetUpperEvalChildrenNumber()
{
return iUpperEvalChildrenNumber;
}
double CCmdCheck::lfGetLearningRate()
{
return lfLearningRate;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////CCmdCheckExceptionNX
/**
* <PRE>
* RXgN^(G[ݒ肷)
* </PRE>
* @author kobayashi
* @since 2015/6/10
* @version 1.0
*/
CCmdCheckException::CCmdCheckException()
{
iErrCode = 0;
strMethodName = "";
strClassName = "";
strErrDetail = "";
}
/**
* RXgN^(G[ݒ肷)
* @param iCode G[R[h
* @param sMethodName
* @param sClassName NX
* @param sDetail G[ڍ
* @author kobayashi
* @since 2009/6/14
* @version 1.0
*/
CCmdCheckException::CCmdCheckException(int iCode, std::string sMethodName, std::string sClassName, std::string sDetail)
{
iErrCode = iCode;
strMethodName = sMethodName;
strClassName = sClassName;
strErrDetail = sDetail;
}
/**
* RXgN^(G[ݒ肷)
* @param iCode G[R[h
* @param iLine s
* @param sMethodName
* @param sClassName NX
* @param sDetail G[ڍ
* @author kobayashi
* @since 2009/6/14
* @version 1.0
*/
CCmdCheckException::CCmdCheckException(int iCode, std::string sMethodName, std::string sClassName, std::string sDetail, int iLine)
{
iErrCode = iCode;
iErrLine = iLine;
strMethodName = sMethodName;
strClassName = sClassName;
strErrDetail = sDetail;
}
/**
* <PRE>
* fXgN^
* </PRE>
* @author kobayashi
* @since 2015/6/10
* @version 1.0
*/
CCmdCheckException::~CCmdCheckException()
{
iErrCode = 0;
strMethodName = "";
strClassName = "";
strErrDetail = "";
}
/**
* RXgN^(G[ݒ肷)
* @param iCode G[R[h
* @param sMethodName
* @param sClassName NX
* @param sDetail G[ڍ
* @author kobayashi
* @since 2009/6/14
* @version 1.0
*/
void CCmdCheckException::SetErrorInfo(int iCode, std::string sMethodName, std::string sClassName, std::string sDetail)
{
iErrCode = iCode;
strMethodName = sMethodName;
strClassName = sClassName;
strErrDetail = sDetail;
}
/**
* RXgN^(G[ݒ肷)
* @param iCode G[R[h
* @param iLine s
* @param sMethodName
* @param sClassName NX
* @param sDetail G[ڍ
* @author kobayashi
* @since 2009/6/14
* @version 1.0
*/
void CCmdCheckException::SetErrorInfo(int iCode, std::string sMethodName, std::string sClassName, std::string sDetail, int iLine)
{
iErrCode = iCode;
iErrLine = iLine;
strMethodName = sMethodName;
strClassName = sClassName;
strErrDetail = sDetail;
}
/**
* G[ԍo͂
* @author kobayashi
* @since 2009/6/14
* @version 1.0
*/
int CCmdCheckException::iGetErrCode()
{
return iErrCode;
}
/**
* G[Nso͂
* @author kobayashi
* @since 2009/6/14
* @version 1.0
*/
int CCmdCheckException::iGetErrLine()
{
return iErrLine;
}
/**
* G[No͂
* @author kobayashi
* @since 2009/6/14
* @version 1.0
*/
std::string CCmdCheckException::strGetMethodName()
{
return strMethodName;
}
/**
* G[NNXo͂
* @author kobayashi
* @since 2009/6/14
* @version 1.0
*/
std::string CCmdCheckException::strGetClassName()
{
return strClassName;
}
/**
* G[̏ڍo͂
* @author kobayashi
* @since 2009/6/14
* @version 1.0
*/
std::string CCmdCheckException::strGetErrDetail()
{
return strErrDetail;
}
| true |
76189aea15a5a90ed5a355627e7d328f2ae5df57 | C++ | Rosta6/chess | /functions.cpp | UTF-8 | 5,381 | 2.96875 | 3 | [] | no_license | #include "header.h"
HANDLE color = GetStdHandle(STD_OUTPUT_HANDLE);
#define X 48
#define Y 24
void menu(){
cout << " 2 - Zadej tah. " << endl;
}
struct Round //data structure for storing rounds
{
string white_move;
string black_move;
};
class chessBoardClass
{
public:
bool inRange(unsigned low, unsigned high, unsigned x)
{
return ((x-low) <= (high-low));
}
void initBoard(){
for (int i = 0; i < Y; i++)
{
for (int j = 0; j < X; j++)
{
board[i][j] = box;
}
}
char arrayPiecesWhite[] = {'R', 'N', 'B', 'Q', 'K', 'B','N','R'}; //array of Pieces
char arrayPiecesBlack[] = {'r', 'n', 'b', 'q', 'k', 'b','n','r'}; //array of Pieces
int help[2] = {1,2};
for (int i = 0; i<8;i++){
help[1] = 2 + i*6;
placePiece(help, arrayPiecesWhite[i]);
}
help[0] = 4;
for (int i = 0; i<8;i++){
help[1] = 2 + i*6;
placePiece(help, 'P');
}
help[0] = 22;
for (int i = 0; i<8;i++){
help[1] = 2 + i*6;
placePiece(help, arrayPiecesBlack[i]);
}
help[0] = 19;
for (int i = 0; i<8;i++){
help[1] = 2 + i*6;
placePiece(help, 'p');
}
}
void printBoard(){
int prepinacRow = 0;
int n = 8;
cout << endl;
cout << " A B C D E F G H " << endl;
cout << endl;
SetConsoleTextAttribute(color, 8); //border up
cout <<" ";
for (int a = 0; a < X + 4; a++)
cout << box ;
cout << endl;
for (int i = 0; i < Y; i++)
{
if( i%3 == 1){
cout <<" " << n << " ";
}else{
cout << " ";
}
SetConsoleTextAttribute(color, 8);
cout << box << box;
for (int j = 0; j < X; j++)
{
if(prepinacRow == 0){
if(inRange(0,5,j) || inRange(12,17,j) || inRange(24,29,j) || inRange(36,41,j))
{
SetConsoleTextAttribute(color, 0);
}else if(inRange(6,11,j) || inRange(18,23,j) || inRange(30,35,j) || inRange(42,47,j)){
SetConsoleTextAttribute(color, 15);
}
}else{
if(prepinacRow == 1){
if(inRange(0,5,j) || inRange(12,17,j) || inRange(24,29,j) || inRange(36,41,j))
{
SetConsoleTextAttribute(color, 15);
}else if(inRange(6,11,j) || inRange(18,23,j) || inRange(30,35,j) || inRange(42,47,j)){
SetConsoleTextAttribute(color, 0);
}
}
}
if((j == 2 || j == 8 || j == 14 || j == 20 || j == 26 || j == 32 || j == 38 || j == 44) && 1 == i%3){
SetConsoleTextAttribute(color, 9);
cout << board[i][j];
}else{
cout << board[i][j];
}
}
if(inRange(0,1,i) || inRange(5,7,i) || inRange(11,13,i) || inRange(17,19,i)){
prepinacRow = 0;
}else {
prepinacRow = 1;
}
SetConsoleTextAttribute(color, 8);
cout << box << box;
SetConsoleTextAttribute(color, 15);
if( i%3 == 1){
cout << " " << n;
n--;
}else{
cout << " ";
}
cout << endl;
}
SetConsoleTextAttribute(color, 8); //border down
cout <<" ";
for (int a = 0; a < X + 4 ; a++)
cout << box;
cout << endl;
SetConsoleTextAttribute(color, 15);
cout << endl;
cout << " A B C D E F G H " << endl;
}
void placePiece(int position[2], char chessType)
{
board[position[0]][position[1]] = chessType;
}
void removePiece(int position[2])
{
board[position[0]][position[1]] = box;
}
private:
char board[Y][X]; //radek - sloupec
char box = (char)219; // bile pole
};
class chessPiece
{
public:
void getPositionfromInput(string userInput)
{
string delimiter = "-"; //splitting string with user input
size_t pos = 0;
string oldPosotionString;
while ((pos = userInput.find(delimiter)) != string::npos)
{
oldPosotionString = userInput.substr(0, pos);
cout << oldPosotionString << endl;
userInput.erase(0, pos + delimiter.length());
}
string newPositionString = userInput;
cout << newPositionString << endl;
}
void convertPositionToIndex(string position){
if(position == "A8"){
}
}
private:
int oldPosition[2]; // first position is X and second is Y value of chess piece
int newPosition[2];
};
| true |
1171b954047724f24219a387b906359b72cda476 | C++ | daboytim/cse560 | /lab1/outputStream.h | UTF-8 | 1,201 | 3.109375 | 3 | [] | no_license | /*
* resultOutputStream.h
*
* Created on: Nov 25, 2009
* Author: Derek Boytim
*/
#ifndef _OutputStream
#define _OutputStream
#include <iostream>
#include <fstream>
class OutputStream {
private:
ofstream outputStream;
string outputFile;
bool isOpen;
public:
OutputStream(string);
~OutputStream();
bool isOpen();
void write(int);
void write(char);
void wirte(string);
OutputStream operator<<(int);
OutputStream operator<<(char);
OutputStream operator<<(string);
};
OutputStream::OutputStream(string fileName) {
outputFile = fileName;
outputStream.open(fileName);
if(outputStream.is_open()) {
isOpen = true;
}
}
bool OutputStream::isOpen() {
return isOpen;
}
void OutputStream::write(int i) {
outputStream << i;
}
void OutputStream::write(char c) {
outputStream << c;
}
void OutputStream::write(string s) {
outputStream << s;
}
OutputStream OutputStream::operator<<(int i) {
outputStream << i;
return this;
}
OutputStream OutputStream::operator<<(char c) {
outputStream << c;
return this;
}
OutputStream OutputStream::operator<<(string s) {
outputStream << s;
return this;
}
#endif
| true |
71fd626ef104e7ce42983c7acfe5b103a938b9cc | C++ | codfish92/dataStructures | /CS262/Lab06/LinkedListIter/LinkedListIter.h | UTF-8 | 2,855 | 3.875 | 4 | [] | no_license | // FORWARD ITERATORS to step through the nodes of a linked list
// A node_iterator of can change the underlying linked list through the
// * operator, so it may not be used with a const node. The
// node_const_iterator cannot change the underlying linked list
// through the * operator, so it may be used with a const node.
// WARNING:
// This classes use std::iterator as its base class;
// Older compilers that do not support the std::iterator class can
// delete everything after the word iterator in the second line:
/************************************************************/
// Drew Koelling
// 2/28/2012
// b
//
// to recieve a crash course on iterators through linked lists to use later in a game created that uses iterators
/************************************************************/
//namespace macs262_labs{
class node_iterator{
public:
node_iterator(node* initial = NULL)
{ current = initial; }
Item& operator *( ) const
{ return current->data; }
// creates a node_iterator set to the begining of the list
node_iterator& operator ++( ) // Prefix ++
{
current = current->next;
return *this;
}
node_iterator operator ++(int) // Postfix ++
{
node_iterator original(current);
current = current->next;
return original;
}
node_iterator& operator --( ) // Prefix --
{
current = current->prev;
return *this;
}
node_iterator operator --(int) // Postfix --
{
node_iterator original(current);
current = current->prev;
return original;
}
bool hasNext() const
{
return current->next != NULL;
}
bool hasPrev() const
{
return current->prev != NULL;
}
bool operator ==(const node_iterator other) const
{ return current == other.current; }
bool operator !=(const node_iterator other) const
{ return current != other.current; }
private:
node* current;
};
class const_node_iterator{
public:
const_node_iterator(const node* initial = NULL)
{ current = initial; }
// creates a const_node_iterator set to the beginning of the list.
const Item& operator *( ) const
{ return current->data; }
const_node_iterator& operator ++( ) // Prefix ++
{
current = current->next;
return *this;
}
const_node_iterator operator ++(int) // Postfix ++
{
const_node_iterator original(current);
current = current->next;
return original;
}
const_node_iterator& operator --( ) // Prefix ++
{
current = current->prev;
return *this;
}
const_node_iterator operator --(int) // Postfix ++
{
const_node_iterator original(current);
current = current->prev;
return original;
}
bool operator ==(const const_node_iterator other) const
{ return current == other.current; }
bool operator !=(const const_node_iterator other) const
{ return current != other.current; }
private:
const node* current;
};
//} // for namespace
| true |
539e928db1919ee80c25728acadf8331b9c9b40b | C++ | ajb042487/cpp-distributed-text-system | /embedded/distributed-text/include/config/ReadOnlyConfiguration.h | UTF-8 | 2,033 | 2.828125 | 3 | [
"MIT"
] | permissive | #ifndef CONFIG_READONLYCONFIGURATION_H
#define CONFIG_READONLYCONFIGURATION_H
#include <cstdint>
#include <string>
#include <vector>
#include "rapidjson/document.h" //#TODO: Forward-declare
namespace Config
{
using rapidjson::Document;
class ReadOnlyConfiguration
{
public:
ReadOnlyConfiguration();
virtual ~ReadOnlyConfiguration();
bool readConfiguration(std::string configurationFile);
// Only shown function signatures are supported!
bool getValue(const std::string path, uint8_t& value);
bool getValue(const std::string path, uint16_t& value);
bool getValue(const std::string path, uint32_t& value);
bool getValue(const std::string path, uint64_t& value);
bool getValue(const std::string path, int8_t& value);
bool getValue(const std::string path, int16_t& value);
bool getValue(const std::string path, int32_t& value);
bool getValue(const std::string path, int64_t& value);
bool getValue(const std::string path, double& value);
bool getValue(const std::string path, std::string& value);
bool getValue(const std::string path, std::vector<uint8_t>& value);
bool getValue(const std::string path, std::vector<uint16_t>& value);
bool getValue(const std::string path, std::vector<uint32_t>& value);
bool getValue(const std::string path, std::vector<uint64_t>& value);
bool getValue(const std::string path, std::vector<int8_t>& value);
bool getValue(const std::string path, std::vector<int16_t>& value);
bool getValue(const std::string path, std::vector<int32_t>& value);
bool getValue(const std::string path, std::vector<int64_t>& value);
bool getValue(const std::string path, std::vector<double>& value);
bool getValue(const std::string path, std::vector<std::string>& value);
private:
//Disallow Copy and Assign
ReadOnlyConfiguration(ReadOnlyConfiguration const&); // Don't Implement
void operator=(ReadOnlyConfiguration const&); // Don't implement
rapidjson::Document* _json;
};
}
#endif /* CONFIG_READONLYCONFIGURATION_H */
| true |
01c6503c80b1dc6ae2e74ee571c83c4c56fc50ad | C++ | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | /answers/harshpreet0508/day18/q2.cpp | UTF-8 | 617 | 3.421875 | 3 | [
"MIT"
] | permissive | // Given an array, sort in decending order of set bits
#include<bits/stdc++.h>
using namespace std;
int sbc(int n)
{
int c=0;
while(n)
{
if(n & 1 == 1)
c++;
n = n>>1;
}
return c;
}
int func(int n1,int n2)
{
int c1 = sbc(n1);
int c2 = sbc(n2);
if(c1<=c2)
return 0;
return 1;
}
int main()
{
int n,i;
cin>>n;
int a[n];
for(i=0;i<n;i++)
{
cin>>a[i];
}
sort(a,a+n,func);
cout<<"\nDescending order of set bits ";
for(i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
return 0;
}
| true |
efc3c6ece945229fdb7a14a1e471ba2d4393b694 | C++ | iloveooz/podbelsky2008 | /05/p05_05.cpp | UTF-8 | 445 | 3.375 | 3 | [] | no_license | //p05_05.cpp - увеличение указателя
#include <iostream>
using namespace std;
int main()
{
float zero = 0.0, pi = 3.141593, Euler = 2.718282;
float *ptr = &Euler;
cout << "\n ptr = " << ptr << " &ptr = " << &ptr << " *ptr = " << *ptr;
cout << "\n(ptr + 1) = " << (ptr + 1) << " *(ptr + 1) = " << *(ptr + 1);
cout << "\n(ptr + 2) = " << (ptr + 2) << " *(ptr + 2) = " << *(ptr + 2) << endl;
return 0;
}
| true |
dffd932afa6c8b56f7600e868a183987f44dbd65 | C++ | sadisticaudio/SDKs | /AAX_SDK_2p3p2/ExamplePlugIns/Common/ProcessingClasses/CSimpleSynth.cpp | UTF-8 | 3,900 | 2.6875 | 3 | [] | no_license | /*================================================================================================*/
/*
* Copyright 2015 by Avid Technology, Inc.
* All rights reserved.
*
* CONFIDENTIAL: This document contains confidential information. Do not
* read or examine this document unless you are an Avid Technology employee
* or have signed a non-disclosure agreement with Avid Technology which protects
* the confidentiality of this document. DO NOT DISCLOSE ANY INFORMATION
* CONTAINED IN THIS DOCUMENT TO ANY THIRD-PARTY WITHOUT THE PRIOR WRITTEN CONSENT
* OF Avid Technology, INC.
*/
/*================================================================================================*/
// Self Include
#include "CSimpleSynth.h"
// Standard Includes
#include <cstddef>
CSimpleSynth::CSimpleSynth()
: mVoices()
, mBypassed(false)
, mGain(1.f)
, mToneGenerator(NULL)
{
}
void CSimpleSynth::SetBypass(bool inBypass) { mBypassed = inBypass; }
void CSimpleSynth::SetGain(float inGain) { mGain = inGain; }
void CSimpleSynth::SetWaveType(EWaveType inWaveType) { mToneGenerator = GetToneGenerator(inWaveType); }
void CSimpleSynth::SetTuning(float inAHz)
{
for (size_t voiceNum = MaxNumVoices(); voiceNum > 0; --voiceNum)
{
mVoices[voiceNum-1].SetTuning(inAHz);
}
}
void CSimpleSynth::InitializeVoices(float inSampleRate, float inAHz)
{
for (size_t voiceNum = MaxNumVoices(); voiceNum > 0; --voiceNum)
{
mVoices[voiceNum-1] = CSimpleTone((int32_t)inSampleRate, inAHz);
}
}
int32_t CSimpleSynth::MaxNumVoices() const
{
// size of mVoices will always be the same
static const int32_t sVoices = static_cast<int32_t>(sizeof(mVoices) / sizeof(CSimpleTone));
return sVoices;
}
/* static */ const char* CSimpleSynth::GetWaveTypeName(EWaveType inWaveType)
{
switch (inWaveType)
{
case eWaveType_Saw: return "Saw";
case eWaveType_Tri: return "Tri";
case eWaveType_Square: return "Square";
default: return "<unknown>";
}
}
void CSimpleSynth::GetSamples(float* outBuffer, int32_t outBufferSize)
{
// Count the active voices
size_t numActiveVoices = 0;
for (size_t voiceNum = MaxNumVoices(); voiceNum > 0; --voiceNum)
{
if (mVoices[voiceNum-1].IsEnabled())
{
++numActiveVoices;
}
}
// Generate samples using a simple sample-by-sample procedure
for (int32_t i = 0; i < outBufferSize; ++i)
{
float sample = 0.f;
for (size_t voiceNum = MaxNumVoices(); voiceNum > 0; --voiceNum)
{
ISimpleTone& curVoice = mVoices[voiceNum-1];
if (curVoice.IsEnabled())
{
const float curNormalizedSample = (curVoice.ProcessOneSample(*mToneGenerator));
sample += curNormalizedSample;
}
}
// Scale output by the number of active voices to avoid overload
sample = (mBypassed || 0 == numActiveVoices) ? 0.f : mGain * (sample / numActiveVoices);
outBuffer[i] = sample;
}
}
void CSimpleSynth::HandleNoteOn(unsigned char inNote, unsigned char inVelocity)
{
if (inNote < MaxNumVoices())
{
// Use inNote as the key into the mVoices array
mVoices[inNote].SetMIDINote(inNote, inVelocity);
}
}
void CSimpleSynth::HandleNoteOff(unsigned char inNote, unsigned char inVelocity)
{
if (inNote < MaxNumVoices())
{
// Use inNote as the key into the mVoices array
mVoices[inNote].SetMIDINote(0, 0);
}
}
void CSimpleSynth::HandleAllNotesOff()
{
for (unsigned char note = 0; note < MaxNumVoices(); ++note)
{
HandleNoteOff(note, 0);
}
}
/* static */
const IToneGeneratorDelegate* CSimpleSynth::GetToneGenerator(EWaveType inWaveType)
{
static const CSawToneGeneratorDelegate sSawToneGenerator;
static const CTriangleToneGeneratorDelegate sTriangeToneGenerator;
static const CSquareToneGeneratorDelegate sSquareToneGenerator;
switch (inWaveType)
{
case eWaveType_Saw: return &sSawToneGenerator;
case eWaveType_Tri: return &sTriangeToneGenerator;
case eWaveType_Square: return &sSquareToneGenerator;
default: return NULL;
}
}
| true |
4ac38f0fe045eb60bfd5aa62a8977b164c0631c8 | C++ | aixi/blaze | /blaze/net/Acceptor.cc | UTF-8 | 2,139 | 2.515625 | 3 | [] | no_license | //
// Created by xi on 19-2-3.
//
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <blaze/log/Logging.h>
#include <blaze/net/EventLoop.h>
#include <blaze/net/InetAddress.h>
#include <blaze/net/SocketsOps.h>
#include <blaze/net/Acceptor.h>
namespace blaze
{
namespace net
{
Acceptor::Acceptor(EventLoop* loop, const InetAddress& listen_addr, bool reuse_port) :
loop_(loop),
listen_socket_(sockets::CreateNonBlockingOrDie(listen_addr.family())),
listen_channel_(loop_, listen_socket_.fd()),
listening_(false),
idle_fd_(::open("/dev/null", O_RDONLY | O_CLOEXEC))
{
assert(idle_fd_ >= 0);
listen_socket_.SetReuseAddr(true);
listen_socket_.SetReusePort(reuse_port);
listen_socket_.bindAddress(listen_addr);
// FIXME: where is the Timestamp receive_time parameter ?
listen_channel_.SetReadCallback(std::bind(&Acceptor::HandleRead, this));
}
Acceptor::~Acceptor()
{
listen_channel_.DisableAll();
::close(idle_fd_);
}
void Acceptor::Listen()
{
loop_->AssertInLoopThread();
listening_ = true;
listen_socket_.listen();
listen_channel_.EnableReading();
}
void Acceptor::HandleRead()
{
loop_->AssertInLoopThread();
InetAddress peer_addr;
int connfd = listen_socket_.accept(&peer_addr);
if (connfd >= 0)
{
LOG_TRACE << "Accepts of " << peer_addr.ToIpPort().c_str();
if (new_connection_callback_)
{
new_connection_callback_(connfd, peer_addr);
}
else
{
::close(connfd);
}
}
else
{
LOG_SYSERR << "in Acceptor::HandleRead";
if (errno == EMFILE) // too many opened file, use ulimit -n to change a process's maximum open files number
{
// FIXME: race condition in multi-thread environment
::close(idle_fd_);
// FIXME: how about anther thread open a file hold idle_fd_'s number, before accept(2)
idle_fd_ = ::accept(listen_socket_.fd(), nullptr, nullptr);
::close(idle_fd_);
idle_fd_ = ::open("/dev/null", O_RDONLY | O_CLOEXEC);
}
}
}
}
}
| true |
4948f33e0c9a3b96dfd27fb3c077aa3880cb7f2b | C++ | vishnuRND/Programs | /spiralform.cpp | UTF-8 | 890 | 3.0625 | 3 | [] | no_license | // spiralform.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdlib.h>
int a[10][10];
void spiral(int row,int column)
{
for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
{
if(!(i==j||j==((column-1)-i)))
printf("%d",a[i][j]);
printf("\t");
}
printf("\n");
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int row,column;
printf("enter num of rows\n");
scanf("%d",&row);
printf("enter num of columns\n");
scanf("%d",&column);
if(row!=column)
{
printf("enter same row and column value\n");
exit(0);
}
for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
{
printf("enter value\n");
scanf("%d",&a[i][j]);
}
}
printf("the matrix is\n");
for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
{
printf("%d",a[i][j]);
printf("\t");
}
printf("\n");
}
spiral(row,column);
return 0;
}
| true |
4a0f8136ade47a2e8701849a5452c3f7af9282a9 | C++ | CSE-560-GPU-Computing-2021/project_-team_4 | /rrt_cpu/main_single_rrt.cpp | UTF-8 | 2,173 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <chrono>
#include "Canvas.h"
#include "Utils.h"
#include "Tree.h"
#include "config.h"
#include "random"
int build_tree(Tree *tree1){
std::ofstream myfile;
myfile.open ("path_raw.txt", std::ios_base::app);
std::default_random_engine generator;
generator.seed(SEED);
std::uniform_real_distribution<> sample_dir_x(BB.first.first, BB.second.first);
std::uniform_real_distribution<> sample_dir_y(BB.first.second, BB.second.second);
int iterations = 0;
Tree* tree = tree1;
while (iterations++<MAX_ITERATIONS){
Node sampled_dir = std::make_tuple(sample_dir_x(generator), sample_dir_y(generator));
Node parent = Utils::nearest_neighbour(sampled_dir, tree->nodes);
Node new_node = Utils::extend(parent, sampled_dir, STEP_SIZE);
if (tree->add_node(parent, new_node)){
if(print_file) {
myfile << std::get<0>(parent) << " " << std::get<1>(parent) << " " << std::get<0>(new_node) << " " << std::get<1>(new_node) << " " << tree->id << "\n";
}
if (Utils::eul_dist(new_node, tree->end)<0.2){
myfile.close();
return iterations;
}
}
if(iterations%1000==0){std::cout<< iterations << std::endl;}
}
myfile.close();
return -1;
}
int main_() {
if(print_file){ std::ofstream myfile; myfile.open ("path_raw.txt", std::ios_base::trunc | std::ios_base::out); myfile.close();}
Canvas canvas;
canvas.add_obs_from_file(path_to_obs);
canvas.init_obs_tree(BB.first, BB.second, canvas.obstacles);
// canvas1.obs_tree->print_all_points();
Tree tree1(&canvas, start_node, end_node, STEP_SIZE, 0);
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
int iterations = build_tree(&tree1);
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> time_span = t2 - t1;
std::cout << "Time spent: " << time_span.count() << " ms" << std::endl;
std::cout << iterations << std::endl;
return 0;
}
| true |
a8df66d66676de931f95c119ddde71da46c8d2c3 | C++ | aselalee/ArduinoBluetoothRemoteCar | /SumoBot/MicroServo.h | UTF-8 | 545 | 2.671875 | 3 | [] | no_license |
#ifndef _MICROSERVO_H_
#define _MICROSERVO_H_
#include <Arduino.h>
#include <Servo.h>
class MicroServo
{
public:
MicroServo(uint8_t const pin,
uint16_t const rangeMin,
uint16_t const rangeMax,
uint16_t const moveOffest);
~MicroServo();
void Begin();
void Rotate();
void MoveTo(uint16_t const pos);
private:
uint8_t m_Pin;
uint16_t m_RangeMin;
uint16_t m_RangeMax;
uint16_t m_MoveOffset;
uint16_t m_CurServoPos;
Servo m_Servo;
};
#endif //_MICROSERVO_H_
| true |
ae05df072e2189fd1a71c6b6f9ef35f628400677 | C++ | tonyeko/Polinom | /BruteForce.hpp | UTF-8 | 463 | 2.625 | 3 | [] | no_license | // bruteforce.cpp
// Nama : Tony Eko Yuwono
// NIM : 13518030
#include "Polinom.hpp"
Polinom multiplicationBruteForce(Polinom P1, Polinom P2) {
Polinom result(P1.getDerajat()+P2.getDerajat(), true);
for (int i = 0; i <= P1.getDerajat(); i++) {
for (int j = 0; j <= P2.getDerajat(); j++) {
int newKoef = result.getKoefAt(i+j) + P1.getKoefAt(i) * P2.getKoefAt(j);
result.setKoefAt(i+j, newKoef);
}
}
return result;
} | true |
2cb4cf26ffaff37c9f3db79bff468f48d4b7c953 | C++ | yazevnul/teaching | /hse/2016/1/cpp/2016_10_19/main.cpp | UTF-8 | 3,483 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cassert>
#include <cstdint>
// http://en.cppreference.com/w/cpp/language/operator_precedence
// http://en.cppreference.com/w/cpp/language/integer_literal
static constexpr uint32_t SetBit(const uint32_t value, const uint8_t index) noexcept {
assert(index <= sizeof(uint32_t) * 8);
return value | (uint32_t{1} << index);
}
static constexpr bool GetBit(const uint32_t value, const uint8_t index) noexcept {
assert(index <= sizeof(uint32_t) * 8);
return value & (uint32_t{1} << index);
}
static constexpr uint32_t ResetBit(const uint32_t value, const uint8_t index) noexcept {
assert(index <= sizeof(uint32_t) * 8);
return value & ~(uint32_t{1} << index);
}
// Should be reduced to exactly one assembly instruction.
//
// There is also a lot of compiler specific builtins [1].
//
// [1] https://gcc.gnu.org/onlinedocs/gcc-6.1.0/gcc/Other-Builtins.html
static constexpr uint32_t RotateLeft(const uint32_t value, const uint8_t index) noexcept {
assert(index <= sizeof(uint32_t) * 8);
return (value << index) | (value >> (sizeof(uint32_t) * 8 - index));
}
static constexpr uint32_t RotateRight(const uint32_t value, const uint8_t index) noexcept {
assert(index <= sizeof(uint32_t) * 8);
return RotateLeft(value, (sizeof(uint32_t) * 8 - index));
}
static std::string GetBitRepresentation(const uint32_t value) {
std::string str;
str.reserve(sizeof(uint32_t) * 8);
for (ssize_t i = sizeof(uint32_t) * 8 - 1; i >= 0; --i) {
str += GetBit(value, static_cast<uint8_t>(i)) ? '1' : '0';
}
return str;
}
static std::ostream& Pad(std::ostream& out) {
return out << "\t\t";
}
int main() {
{
uint32_t x = 1;
Pad(std::cout) << x << std::endl;
Pad(std::cout) << SetBit(x, 8) << std::endl;
std::cout << std::endl;
}
{
uint32_t x = 1;
Pad(std::cout) << GetBit(x, 0) << std::endl;
Pad(std::cout) << GetBit(x, 1) << std::endl;
Pad(std::cout) << GetBit(SetBit(x, 8), 8) << std::endl;
std::cout << std::endl;
}
{
uint32_t x = 1;
Pad(std::cout) << GetBitRepresentation(x) << std::endl;
Pad(std::cout) << GetBitRepresentation(SetBit(x, 8)) << std::endl;
std::cout << std::endl;
}
{
uint32_t x = 1;
Pad(std::cout) << GetBitRepresentation(x) << std::endl;
Pad(std::cout) << GetBitRepresentation(ResetBit(SetBit(SetBit(x, 8), 3), 8)) << std::endl;
std::cout << std::endl;
}
{
uint32_t x = 1;
Pad(std::cout) << x << std::endl;
// Pad(std::cout) << SetBit(x, 255) << std::endl; // assert failure
std::cout << std::endl;
}
{
uint32_t x = 100500;
Pad(std::cout) << GetBitRepresentation(x) << std::endl;
Pad(std::cout) << GetBitRepresentation(RotateLeft(x, 7)) << std::endl;
Pad(std::cout) << GetBitRepresentation(RotateLeft(x, 27)) << std::endl;
Pad(std::cout) << GetBitRepresentation(RotateLeft(x, 32)) << std::endl;
std::cout << std::endl;
}
{
uint32_t x = 100500;
Pad(std::cout) << GetBitRepresentation(x) << std::endl;
Pad(std::cout) << GetBitRepresentation(RotateRight(x, 7)) << std::endl;
Pad(std::cout) << GetBitRepresentation(RotateRight(x, 27)) << std::endl;
Pad(std::cout) << GetBitRepresentation(RotateRight(x, 0)) << std::endl;
std::cout << std::endl;
}
}
| true |
2fc771fded2e3cb15262ce9686148c731ab623ba | C++ | bq-wang/mainStream | /cpp/cppprimer/src/exceptionhandlings/src/exceptionhandlings/stackExcp.cpp | UTF-8 | 3,870 | 3.453125 | 3 | [] | no_license | #include "stdafx.h"
#include "stackExcp.h"
#include <iostream>
#include <string>
using std::cout;
using std::endl;
//void iStack::pop(int &top_value)
//{
// if (empty())
// {
// throw popOnEmpty();
// }
// top_value = _stack[--_top];
// cout << "istack::pop(): " << top_value << endl;
//}
//
//
//void iStack::push(int value)
//{
// cout << "istack::push( " << value << " ) \n";
// if (full())
// {
// throw pushOnFull();
// }
// _stack[_top++] = value;
//
//}
/**
* @ version 2
* this version contains the function declaration contains the function exception specification
*/
void iStack::pop(int &top_value) throw (popOnEmpty)
{
if (empty())
{
throw popOnEmpty();
}
top_value = _stack[--_top];
cout << "istack::pop(): " << top_value << endl;
}
void iStack::push(int value) throw (pushOnFull)
{
cout << "istack::push( " << value << " ) \n";
if (full())
{
throw pushOnFull();
}
_stack[_top++] = value;
}
bool iStack::empty()
{
return _top <= 0;
}
bool iStack::full()
{
return _top > _stack.capacity(); // a common pitfall is tha the use _stack.size();
}
void iStack::display()
{
cout << "display: ( ";
for (int i = 0; i < _top; ++i)
{
// a common case of error is that if you write as follow
// the code will be like this:
// cout << _stack[i} << ( i == _top - 1) ? ")" : "";
// it will output some wierd output , guess the compiler try to output the value of the condition test part of the the ternary expression
// that is because of the order of the execution ,
// where the ?: has a lower precedence than the << operator
// so it will first output the evalution value of the condition expression and then if depends on the return resutlt, which is a
cout << _stack[i] << " " << ((i == _top - 1) ? " )" : "") ;
if (i != 0 && i % 8 == 0 || i == _top - 1 ) cout << endl;
}
}
void intermixedTryClause()
{
iStack stack(32);
for (int ix = 0;ix < 51; ++ix)
{
try
{
if (ix % 3 == 0) {
stack.push(ix);
}
}
catch (pushOnFull)
{
//cout << "caught error on pushOnFull" << endl;
}
if (ix % 4 == 0)
{
stack.display();
}
try
{
if (ix % 10 == 0)
{
int dummy;
stack.pop(dummy);
stack.display();
}
}
catch (popOnEmpty)
{
//cout << "caught error on popOnEmpty" << endl;
}
}
}
/**
* Below test the function try body techniques where you can put the try clause with the catch clauses right after the function body without
* the function opening body '{' or the function closing body '}'
*/
void functionTryBody() try
{
iStack stack(32);
for (int i = 0; i < 51; ++i ) {
int val;
if (i % 3 == 0) stack.push(i);
if (i % 4 == 0) stack.display();
if (i % 10 == 0) { stack.pop(val); stack.display(); }
}
}
catch (popOnEmpty) { /* */ }
catch (pushOnFull) { /* */ }
void (* pf) (int) throw (std::string);
/**
* exception declaration is part of the function interface.
*/
typedef int exceptionType;
void no_problem() throw ()
{}
void doit(int, int) throw (std::string, exceptionType)
{}
void recoup(int , int ) throw (exceptionType) {}
int exception_specification()
{
// ok, recoup is as restrictive as pf1
void (*pf1)(int, int) throw (exceptionType) = &recoup;
// OK, no_problem is more restrictive than pf2
void (*pf2)() throw (std::string) = &no_problem;
// it is error as according to the book, however, it does work
// on VC++, it does not throw out errors?
void (*pf3)(int , int) throw (std::string) = &doit;
return 0;
}
/** an empty exception specification guaranttees that the function does not throw any exception .for example
* the function no_problem guarantee not to throw any exception
*/
extern void no_problem() throw(); | true |
4d444303c104af6caf0c4eb50edd21efb583b70c | C++ | deepank1728/workspace | /cpp/new/mergesort.cpp | UTF-8 | 706 | 3.265625 | 3 | [] | no_license | #include<iostream>
using namespace std;
void merge_sort(int a[],int low,int mid,int up)
{
int c[up-low+1];
int i=low,j=mid+1,k=0;
while(i<=mid && j<=up)
{
if(a[i]<a[j])
c[k++]=a[i++];
else
c[k++]=a[j++];
}
while(i<=mid)
c[k++]=a[i++];
while(j<=up)
c[k++]=a[j++];
k=0;
for(int p=low;p<=up;p++)
a[p]=c[k++];
}
void partition(int a[],int low,int up)
{
if(low==up)
return;
int mid=(low+up)/2;
partition(a,low,mid);
partition(a,mid+1,up);
merge_sort(a,low,mid,up);
}
void print(int a[],int size)
{
for(int i=0;i<size;i++)
cout<<a[i]<<" ";
cout<<endl;
}
int main()
{
int a[]={1,0,2,9,3,8,4,7,5,6},size=10;
print(a,size);
partition(a,0,size-1);
print(a,size);
}
| true |
a2b6bcba093cd008c763063265a4431d6bb06e7b | C++ | cc-catch/cppcourse | /course01/project01/fran/food.cc | UTF-8 | 1,959 | 2.875 | 3 | [] | no_license | #include "food.h"
#include "cinder/Rand.h"
Food::Food(float radius):
mRadius(radius)
{}
void Food::Update(double elapsedSeconds)
{
mAnimateOffset = cinder::vec2(cos(elapsedSeconds) * mRadius, sin(elapsedSeconds) * mRadius);
}
void Food::Draw()
{
// A Tasty Flower for a very hungry caterpillar
cinder::gl::color(cinder::Color(0.0f, 1.0f, 0.0f));
cinder::gl::drawLine(mPosition + mAnimateOffset, mPosition + cinder::vec2(0, 20));
cinder::gl::color(cinder::Color(0.0f, 0.0f, 1.0f));
cinder::gl::drawSolidCircle(mPosition + mAnimateOffset + cinder::vec2(10 - mRadius / 2, 0.0f - mRadius / 2), mRadius / PETAL_SIZE);
cinder::gl::drawSolidCircle(mPosition + mAnimateOffset + cinder::vec2(0 - mRadius / 2, 10 - (mRadius / 2)), mRadius / PETAL_SIZE);
cinder::gl::drawSolidCircle(mPosition + mAnimateOffset + cinder::vec2(10 - mRadius / 2, 10 - (mRadius / 2)), mRadius / PETAL_SIZE);
cinder::gl::drawSolidCircle(mPosition + mAnimateOffset + cinder::vec2(0 - mRadius / 2, 0 - (mRadius / 2)), mRadius / PETAL_SIZE);
cinder::gl::color(cinder::Color(0.9f, 1.0f, 1.0f));
cinder::gl::drawStrokedCircle(mPosition + mAnimateOffset + cinder::vec2(10 - mRadius / 2, 0.0f - mRadius / 2), mRadius / PETAL_SIZE);
cinder::gl::drawStrokedCircle(mPosition + mAnimateOffset + cinder::vec2(0 - mRadius / 2, 10 - (mRadius / 2)), mRadius / PETAL_SIZE);
cinder::gl::drawStrokedCircle(mPosition + mAnimateOffset + cinder::vec2(10 - mRadius / 2, 10 - (mRadius / 2)), mRadius / PETAL_SIZE);
cinder::gl::drawStrokedCircle(mPosition + mAnimateOffset + cinder::vec2(0 - mRadius / 2, 0 - (mRadius / 2)), mRadius / PETAL_SIZE);
cinder::gl::drawSolidCircle(mPosition + mAnimateOffset, mRadius / 2);
}
cinder::vec2 Food::GetPosition()
{
return mPosition + mAnimateOffset;
}
void Food::Respawn(float width, float height)
{
mPosition = cinder::vec2(cinder::Rand::randFloat( mRadius, width - mRadius * 2 ),
cinder::Rand::randFloat( mRadius, height - mRadius * 2 ));
}
| true |
f37145dbd5905232fd1a89259566692f3c2f64f5 | C++ | ligewei/hodgepodge | /bailian/2683.cpp | UTF-8 | 225 | 2.75 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
double a = 2;
double b = 1;
double sum = 0;
for(int i=1;i<=n;i++)
{
sum += a/b;
a = a+b;
b = a-b;
}
printf("%.4lf\n",sum);
return 0;
} | true |
7d417c0b4d174a8c20106c9113d4f7757f74bf7e | C++ | shouzo/Data-Structure-Learning_pages | /Data_Structures_6th_Edition/example/5第五章/5-5節Dijkstra++.cpp | BIG5 | 2,046 | 3.515625 | 4 | [] | no_license | /*=========================================================
5-5` qY@IlUI̵u|
Dijkstra() Dijkstratk
find_min() XDecided[]=0BDist̤p
Cost[V][V] ϧΪ[vFx}
Dist[V] q_IUI̵uZ
Prior[V] UI̵u|e@ӳI
Decided[V] ̵uwO_wMw
=========================================================
*/
#include <cstdlib>
#include <iostream>
using namespace std;
#define V 7
int Cost[V][V]={{0,1,4,5,15000,15000,15000},
{1,0,15000,2,15000,15000,15000},
{4,15000,0,4,15000,3,15000},
{5,2,4,0,5,2,15000},
{15000,15000,15000,5,0,15000,6},
{15000,15000,3,2,15000,0,4},
{15000,15000,15000,15000,6,4,0}};
int Dist[V],Prior[V],Decided[V];
void Dijstra(int);
void find_min(int *);
void PrintPath(int, int);
int main(int argc, char *argv[])
{
int i,V0;
cout << "пJ_I: ";
cin >> V0;
Dijstra(V0);
for(i=0;i < V;i++)
{
if(i == V0)
continue;
cout << endl << "V" << V0 << " --> V" << i << " Cost == " << Dist[i] << endl;
PrintPath(V0,i);
}
system("PAUSE");
return EXIT_SUCCESS;
}
void Dijstra(int V0)
{
int Vx;
int i,w;
for(i=0;i<V;i++)
{
Dist[i]=Cost[V0][i];
Prior[i]=0;
Decided[i]=0;
}
Decided[0]=1;
for(i=1;i<V;i++)
{
find_min(&Vx);
Decided[Vx]=1;
for(w=0;w<V;w++)
{
if(!Decided[w] && (Dist[w] > (Dist[Vx]+Cost[Vx][w])))
{
Dist[w]=Dist[Vx]+Cost[Vx][w];
Prior[w]=Vx;
}
}
}
}
void find_min(int *Vx)
{
int i;
int l=0,lowest=32767;
for(i=0;i<V;i++)
if (!Decided[i] && Dist[i]<lowest)
{
lowest=Dist[i];
l=i;
}
*Vx=l;
}
void PrintPath(int V0,int Vx)
{
int i;
cout << "V" << Vx << " e@O ";
for (i=Prior[Vx]; i!= V0 ; i=Prior[i])
cout << "V" << i << ", V" << i << "e@O ";
cout << "V" << V0 << endl;
}
| true |
5f08e3f976a02c056064f2983b6c3f96bb0ea3dd | C++ | SashaFlaska/ucd-csci2312-pa2 | /Point.cpp | UTF-8 | 7,627 | 3.46875 | 3 | [] | no_license | //
// Point.cpp
// PA2
//
// Created by Alexander Flaska on 2/24/16.
// Copyright © 2016 Alexander Flaska. All rights reserved.
//
#include "Point.h"
#include <cmath>
#include <algorithm> //min, max
#include <string>
#include <sstream>
#include <iostream>
#include "Point.h"
using namespace std;
using namespace Clustering;
namespace Clustering
{
unsigned int Point::__idGen = 0;
Point::Point(int dimensions)// default constructor; creates id, increments, and makes a new array.
{
__id = ++__idGen;
__dim = dimensions;
__values = new double[__dim];
for (int pos = 0; pos < __dim; ++pos)
{
__values[pos] = 0.0;
}
}
Point::Point(int i, double *array)// construtor that already has an array passed, so it just assigns and inrements.
{
__dim = i;
__values = array;
__id = __idGen++;
}
Point::Point(const Point &point) // copy constructor. Does everything the default does.
{
__dim = point.__dim;
__values = new double[__dim];
__id = point.__id;
for (int pos = 0; pos < __dim; ++pos)
__values[pos] = point.__values[pos];
}
Point &Point::operator=(const Point &point)// overloaded equals operator
{
if (&point == this)// returns if it's the thing it's equal to.
{
return *this;
}
else
{
for (int pos = 0; pos < __dim; ++pos)// loops and assigns all pointers in array to the array
{
this->__values[pos] = point.getValue(pos);
}
return *this;
}
}
double Point::distanceTo(const Point &point) const// distance to function. pythagorean theorem.
{
double totalDistance = 0.0;
for (int pos = 0; pos < __dim; ++pos)
{
totalDistance += pow((__values[pos] - point.__values[pos]), 2);
}
totalDistance = sqrt(totalDistance);
return totalDistance;
}
Point &Point::operator*=(double d)// overloaded *= operator.
{
for (int pos = 0; pos < __dim; ++pos)// loops, and *='s everything, and then returns pointer.
__values[pos] *= d;
return *this;
}
Point &Point::operator/=(double d)// overloaded /= operators.
{
for (int pos = 0; pos < __dim; ++pos)// same as above, except / instead of *
__values[pos] /= d;
return *this;
}
const Point Point::operator*(double d) const // overloaded * operator
{
Point newPoint(*this);// makes a new point, multiplies it, and returns, using overloaded *=
newPoint *= d;
return newPoint;
}
const Point Point::operator/(double d) const // overloaded / operator
{
Point newPoint(*this); // new point, divides, and returns using overloaded /=
newPoint /= d;
return newPoint;
}
double &Point::operator[](int index)// just returns the array at indices.
{
return __values[index];
}
Point &operator+=(Point &leftPoint, const Point &rightPoint)// overloaded +=
{
for (int pos = 0; pos < leftPoint.__dim; ++pos)// loops, and +='s left to right, returns left.
leftPoint.__values[pos] += rightPoint.__values[pos];
return leftPoint;
}
Point &operator-=(Point &leftPoint, const Point &rightPoint)// overloaded-=
{
for (int pos = 0; pos < leftPoint.__dim; ++pos)// loops, and -='s left to right, returns left.
leftPoint.__values[pos] -= rightPoint.__values[pos];
return leftPoint;
}
const Point operator+(const Point &leftPoint, const Point &rightPoint)// overloaded +
{
Point newPoint(leftPoint);// new point, returns newpoint+= rightpoint using overloaded +=
return newPoint+=rightPoint;
}
const Point operator-(const Point &leftPoint, const Point &rightPoint)// overloaded -
{
Point newPoint(leftPoint);// new point using leftpoing, returns it -=right point using overloaded-=
return newPoint -= rightPoint;
}
bool operator==(const Point &leftPoint, const Point &rightPoint)// overloaded ==
{
if (leftPoint.__id != rightPoint.__id)// if not the same, false.
return false;
for (int i = 0; i < std::max(leftPoint.__dim, rightPoint.__dim); ++i)// loop through to make the same check.
{
if (leftPoint.getValue(i) != rightPoint.getValue(i))
return false;
}
// ID's are the same, values are the same
return true;// if not false, must be true.
}
bool operator!=(const Point &leftPoint, const Point &rightPoint)
{
return(!(leftPoint == rightPoint));// returns if not = to each other.
}
bool operator<(const Point &leftPoint, const Point &rightPoint)// overloaded <
{
if (leftPoint != rightPoint)// if they're not equal
{
if (leftPoint.__dim == rightPoint.__dim)// check if they're equal
{
for (int i = 0; i < leftPoint.__dim; ++i)// loop and return the appropriate bool based on what's greater
{
if (leftPoint.__values[i] > rightPoint.__values[i])
return false;
else if (leftPoint.__values[i] < rightPoint.__values[i])
return true;
}
}
}
return false;
}
bool operator>(const Point &leftPoint, const Point &rightPoint)// overloaded >
{
return operator<(rightPoint, leftPoint);// using overloaded < just return
}
bool operator<=(const Point &leftPoint, const Point &rightPoint)// overloaded <= using overloaded operators
{
return !(leftPoint > rightPoint);
}
bool operator>=(const Point &leftPoint, const Point &rightPoint)// overloaded >= using overloaded operators
{
return !(leftPoint<rightPoint);
}
std::ostream &operator<<(ostream &outputStream, const Point &point)// overloaded << operator
{
int pos;
for (pos = 0; pos < point.__dim-1; ++pos)// loops
outputStream << point.__values[pos] << ", ";// opens ostream with the values in __values
outputStream << point.__values[pos];// makes sure there are commas
return outputStream;
}
std::istream &operator>>(std::istream &inputStream, Point &point)// overloaded >> operator, code taken from lecture, tweaked for function
{
string tempstring;
string buffer;
double d;
int index = -1;
while (getline(inputStream, tempstring))
{
stringstream lineStream(tempstring);
while (getline(lineStream, buffer, ','))
{
d = stod(buffer);
point.setValue(++index, d);
}
}
return inputStream;
}
}
// destructor, and getters/ setters. Pretty obvious as to what they do.
Point::~Point()
{
delete [] __values;
}
int Point::getId() const
{
return __id;
}
int Point::getDims() const
{
return __dim;
}
void Point::setValue(int i, double d)
{
__values[i] = d;
}
double Point::getValue(int i) const
{
return __values[i];
}
| true |
21403041b6b9e7b2c6a04082ecd0b6b16a28db54 | C++ | bradleymckenzie/McKenzie-Bradley-CIS-17a-48969 | /Hmwk/Assignment 4/Gaddis_8thEd_Chapter13_Probl6_InventoryClass/main.cpp | UTF-8 | 1,839 | 3.859375 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Bradley McKenzie
* Created on October 20, 2017
* Purpose: Inventory Class:
*/
//System Libraries
#include <iostream>
#include <iomanip>
using namespace std;
//User Libraries
#include "Inventory.h"
//Global Constants
//Such as PI, Vc, -> Math/Science Values
//as well as conversions from system of units to another
//Function Prototypes
void print(class Inventory *show);
//Executable code begins here!!!
int main(int argc, char** argv) {
//Declare Variables
Inventory inventorY;
int itemN = 0;
int quantity = 0;
float cost = 0;
float totalCost = 0;
//Input Values
cout<<"\t============================"<<endl;
cout<<"\t Inventory Class"<<endl;
cout<<"\t============================"<<endl;
cout<<"\tEnter Item Number: ";
cin>>itemN;
while (itemN < 0){
cout<<"Only enter positive values for the Item Number: ";
cin>>itemN;
}
cout<<"\tEnter Item Quantity: ";
cin>>quantity;
while (quantity < 0){
cout<<"Only enter positive values for the Item Quantity: ";
cin>>quantity;
}
cout<<"\tEnter Item Cost: $";
cin>>cost;
while (cost < 0){
cout<<"Only enter positive values for the Item Cost: ";
cin>>cost;
}
//Process by mapping inputs to outputs
inventorY.setItemN(itemN);
inventorY.setQuantity(quantity);
inventorY.setCost(cost);
inventorY.setTotalCost(totalCost);
//Output Values
cout<<"\t============================"<<endl;
print(&inventorY);
cout<<"\t============================"<<endl;
//Exit stage right!
return 0;
}
void print(Inventory *item)
{
cout<<setw(21)<<"Item Number: "<<item->getItemN()<< endl;
cout<<setw(23)<<"Item Quantity: "<<item->getQuantity()<<endl;
cout<<setw(20)<<"Item Cost: $"<<item->getCost()<<endl;
cout<<setw(21)<<"Total Cost: $"<<item->getTotalCost()<<endl;
} | true |
fc0f8a34a2be54e385a8a32266237bbd223bdab8 | C++ | YifatYank/advencedPrograming2018 | /ex1/src/ClassicLogic.h | UTF-8 | 2,241 | 3.265625 | 3 | [] | no_license | /**
* Name : Yifat Yankocivh
* ID : 204709224
* User Name : yankovy
*/
#ifndef CLASSICLOGIC_H_
#define CLASSICLOGIC_H_
#include "GameLogic.h"
#include "Player.h"
#include "GameDisplay.h"
#include "ConsuleDisplay.h"
#include <iostream>
using namespace std;
/*The class represents the classical logic of reversy game */
class ClassicLogic : public GameLogic {
private:
Board * gameBoard_;
Player * white_;
Player * black_;
CellValue winner_;
GameDisplay * display;
bool playDirection(int x,int y,int xMove,int yMove, CellValue value, bool checkMode);
public:
/** Function name : ClassicLogic
* Parameters : size, and two players.
* Return value : The ClassicLogic created.
* General flow : Assignment of members, creation of the board and initialization of the board .
*/
ClassicLogic(int board_size, Player * first, Player * second);
/** Function name : getLegalMoves
* Parameters : A player's value - a player's color.
* Return value : A vector contains all the legal moves the player can do.
* General flow : Check all the cells in the game board - if they are legal moves.
* If the cell is a legal move - the function adds the cell's location to the vector.
*/
virtual vector<Point *> * getLegalMoves(CellValue value);
/** Function name : playMove
* Parameters : The player's value - a player's color, and the player's move.
* Return value : If the move is legal or not.
* General flow : Check if the move is legal - if the move is legal the function plays the move.
*/
virtual bool playMove(Point move, CellValue value);
/** Function name : getWinner
* Parameters : None.
* Return value : The game's winner.
* General flow : Returns the game's winner - if the game has not over yet, the functions returns EMPTY.
*/
virtual CellValue getWinner();
/** Function name : playLogic
* Parameters : None.
* Return value : None.
* General flow : Plays the game, until it ends.
*/
virtual void playLogic();
/** Function name : ~ClassicLogic
* Parameters : None.
* Return value : None.
* General flow : The classicLogic destractor. Frees the board was allocated in the constractor.
*/
virtual ~ClassicLogic();
};
#endif /* CLASSICLOGIC_H_ */
| true |
5a5351918228d56b87d790b38fb6baff64aa5543 | C++ | DusanInfinity/ooprojektovanje-lab | /Lab. vezba 3 - SkiSanta/SkiSport/skisanta.cpp | UTF-8 | 1,526 | 2.9375 | 3 | [] | no_license | #include "skisanta.h"
#include <QDebug>
SkiSanta::SkiSanta(int w, int h, QObject *parent) : QObject(parent)
{
x = w/4;
y = h/4;
this->h = h;
this->w = w;
currentState = 1; // 0 - levo, 1 - pravo, 2 - desno
imageState = 0;
QImage imageL1, imageL2, imageS1, imageS2, imageR1, imageR2;
imageL1.load(":/images/images/santa-left1.png");
imageL2.load(":/images/images/santa-left2.png");
imageS1.load(":/images/images/santa1.png");
imageS2.load(":/images/images/santa2.png");
imageR1.load(":/images/images/santa-right1.png");
imageR2.load(":/images/images/santa-right2.png");
images = {imageL1, imageL2, imageS1, imageS2, imageR1, imageR2};
}
void SkiSanta::changeSantaPos(int value)
{
if(x+value < 0 || x + value > w-w/7) return;
if(value < 0)
currentState = 0;
else if(value > 0)
currentState = 2;
else
currentState = 1;
//qDebug() << "changeSantaPos:" << value;
x += value;
}
void SkiSanta::resize(QSize newSize)
{
if(w == newSize.width() || h == newSize.height()) return;
qDebug() << "resize";
x = (int)(((float)newSize.width()/w)*x);
y = (int)(((float)newSize.height()/h)*y);
this->w = newSize.width();
this->h = newSize.height();
}
int SkiSanta::getX() const
{
return x;
}
int SkiSanta::getY() const
{
return y;
}
void SkiSanta::changeImage()
{
imageState = (imageState + 1) % 2;
}
QImage SkiSanta::getCurrentStateImage()
{
return images[2*currentState + imageState];
}
| true |
3ea8c80ddaab006aa18b7b92e2fd7cc657789b04 | C++ | c437yuyang/Test_Cpps | /21_0_构造函数析构函数执行顺序/21_0_构造函数析构函数执行顺序.cpp | GB18030 | 762 | 3.3125 | 3 | [] | no_license | // 21_0_캯ִ˳.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class B {
public:
B(void)
{
cout << "B\t";
}
~B(void)
{
cout << "~B\t";
}
};
struct C {
C(void)
{
cout << "C\t";
}
~C(void)
{
cout << "~C\t";
}
};
struct D : B {
D() { cout << "D\t"; }
~D() { cout << "~D\t"; }
private: C c;
};
int main()
{
D d; //B C D ~D ~ C ~B
///
// D̳B, Ĺ캯ִУûʡ
// CDijԱDĹ캯ʼǰгʼִCĹ캯
// ִDĹ캯
// ִе˳빹෴
system("pause");
return 0;
}
| true |
d4ed1dc82d32a9929fd84f6f1470e7cbeb0a6f90 | C++ | mikechen66/CPP-Programming | /CPP-Programming-Principles/chapter06-programming/ex10_permutations.cpp | UTF-8 | 2,004 | 3.53125 | 4 | [] | no_license | #include "../text_lib/std_lib_facilities.h"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
int get_fac(int num)
{
// Check for negative num
if (num < 0) error("Cannot find factorials of negative numbers.");
int fac = num;
if (fac == 0)
fac = 1;
else
for (int i = num - 1; i > 0; --i)
fac *= i;
cout << fac << '\n';
return fac;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
int find_perms(int a, int b)
{
// Calculate the number of permutations of (a,b)
if (a == 0 || b == 0) error("No permutations found for 0");
if (a < b) error("Not enough numbers for set size");
int answer = get_fac(a) / get_fac(a - b);
return answer;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
int find_combs(int a, int b)
{
// Calculate the number of combinations of (a,b)
int answer = find_perms(a, b) / get_fac(b);
return answer;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
int main()
try {
// Program
cout << "Please enter two numbers representing the number of possibles\n"
<< " and the size of the sets. Then indicate whether you want the\n"
<< " number of permutations ('p') or combinations ('c').\n";
int a;
int b;
char f;
cin >> a >> b >> f;
string func;
int answer;
switch (f) {
case 'p':
func = "permutations";
answer = find_perms(a, b);
break;
case 'c':
func = "combinations";
answer = find_combs(a, b);
break;
default:
error("Invalid function request\n");
}
cout << "The number of " << func << " of " << a << " & " << b
<< " are " << answer << ".\n";
}
catch(exception& e) {
cerr << "Error: " << e.what() << '\n';
return 1;
}
catch(...) {
cerr << "undefined thing, yo!\n";
return 2;
}
| true |
d2273d98496367de03079241fcb88b937f96baf0 | C++ | dakeryas/CosmogenicAnalyser | /src/TimeDivision.cpp | UTF-8 | 2,429 | 3.1875 | 3 | [] | no_license | #include "TimeDivision.hpp"
#include <cmath>
namespace CosmogenicAnalyser{
TimeDivision::TimeDivision(double timeBinWidth, TimeWindow onTimeWindow, TimeWindow offTimeWindow)
:timeBinWidth(timeBinWidth),onTimeWindow(std::move(onTimeWindow)),offTimeWindow(std::move(offTimeWindow)){
if(timeBinWidth < 0) throw std::invalid_argument(std::to_string(timeBinWidth)+"is not valid time bin width");
else if(getAnalysisGapLength() < 0) throw std::invalid_argument("On-time and off-time windows should not overalp.");
else if(4 * timeBinWidth > getAnalysisTime()) throw std::invalid_argument("The time bin width must be smaller than a fourth of the analysis time.");
}
double TimeDivision::getTimeBinWidth() const{
return timeBinWidth;
}
const TimeWindow& TimeDivision::getOnTimeWindow() const{
return onTimeWindow;
}
const TimeWindow& TimeDivision::getOffTimeWindow() const{
return offTimeWindow;
}
double TimeDivision::getOnTimeWindowLength() const{
return onTimeWindow.getLength();
}
double TimeDivision::getOffTimeWindowLength() const{
return offTimeWindow.getLength();
}
double TimeDivision::getAnalysisTime() const{
return getOnTimeWindowLength() + getOffTimeWindowLength();
}
double TimeDivision::getSpannedAnalysisTime() const{
return offTimeWindow.getEndTime() - onTimeWindow.getStartTime();
}
double TimeDivision::getAnalysisGapLength() const{
return offTimeWindow.getStartTime() - onTimeWindow.getEndTime();
}
unsigned TimeDivision::getNumberOfBins() const{
return std::round(getAnalysisTime() / timeBinWidth);
}
unsigned TimeDivision::getSpannedNumberOfBins() const{
return std::round(getSpannedAnalysisTime() / timeBinWidth);
}
double TimeDivision::getWindowsLengthsRatio() const{
return getOffTimeWindowLength() / getOnTimeWindowLength();
}
std::ostream& operator<<(std::ostream& output, const TimeDivision& timeDivision){
output<<std::setw(12)<<std::left<<"Bin width: "<<std::setw(5)<<std::left<<timeDivision.getTimeBinWidth()<<"\n"
<<std::setw(12)<<std::left<<"On-time: "<<std::setw(7)<<std::right<<timeDivision.getOnTimeWindowLength()<<"\n"
<<std::setw(12)<<std::left<<"Off-time: "<<std::setw(7)<<std::right<<timeDivision.getOffTimeWindowLength();
return output;
}
}
| true |
191677f9e6b4da19c1106c4e887f4ec05ecb8f03 | C++ | SenaYora/NanotekSpice | /include/components/Input.hpp | UTF-8 | 864 | 2.78125 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2020
** OOP_nanotekspice_2019
** File description:
** Input
*/
#ifndef INPUT_HPP_
#define INPUT_HPP_
#include "IComponent.hpp"
class Input : public nts::IComponent {
public:
Input(std::string);
~Input();
nts::Tristate compute(__attribute__((unused)) std::size_t pin = 1) { return (_value); };
void setLink(std::size_t pin, nts::IComponent &other, std::size_t otherPin);
void dump() const { std::cout << "It's an " << _type << " component named: " << _name << " (" << _value << ")" << std::endl; }
virtual void setValue(nts::Tristate value) { _value = value; };
std::string const &getName() const { return _name; };
protected:
std::string _name;
std::string _type;
nts::IComponent *_pin[1];
nts::Tristate _value;
};
#endif /* !INPUT_HPP_ */ | true |
f262867ffecd24c9f58e1e7a45c49b0fccc70812 | C++ | wsnk/concur | /concurrency_queue/tests/concur-test/src/thread_master.cpp | UTF-8 | 1,947 | 2.53125 | 3 | [] | no_license | # include "thread_master.h"
# include <boost/test/test_tools.hpp>
//--------------------------------------------------------------------------------
# ifdef _WIN32
# include <Windows.h>
# include <WinBase.h>
# else
# include <sched.h>
# endif
//--------------------------------------------------------------------------------
namespace {
//--------------------------------------------------------------------------------
# ifdef _WIN32
void set_thread_affinity( unsigned cpu )
{
if( !SetThreadAffinityMask( GetCurrentThread( ), DWORD_PTR( 1 ) << cpu ) ) {
DWORD dwError = GetLastError( );
BOOST_TEST_MESSAGE( "failed to set affinity; error code: " << dwError );
}
}
# else
void set_thread_affinity( unsigned cpu )
{
cpu_set_t cpu_set;
CPU_ZERO( &cpu_set );
CPU_SET( cpu, &cpu_set );
if( sched_setaffinity( 0, sizeof( cpu_set_t ), &cpu_set ) ) {
BOOST_TEST_MESSAGE( "failed to set affinity; error code: " << errno );
}
}
# endif
//--------------------------------------------------------------------------------
} // anonymous namespace
//--------------------------------------------------------------------------------
void ThreadMaster::initialize( const Config& cfg )
{
cfg_ = cfg;
threads_.reserve( cfg.count );
for( unsigned i( 0 ); i < cfg.count; ++i ) {
threads_.emplace_back( std::thread( [ this, i ]( ) {
run( i );
} ) );
}
}
void ThreadMaster::run( unsigned num ) const
{
if( cfg_.affinity >= 0 )
set_thread_affinity( static_cast< unsigned >( cfg_.affinity ) + num );
{
std::unique_lock< std::mutex > lock( mtx_ );
while( !started_ )
cv_.wait( lock );
}
cfg_.func( num );
}
void ThreadMaster::launch( )
{
{
std::lock_guard< std::mutex > lock( mtx_ );
started_ = true;
}
cv_.notify_all( );
}
void ThreadMaster::stop( )
{
for( std::thread& t : threads_ ) {
try { if( t.joinable( ) ) t.join( ); }
catch( ... ) { }
}
}
| true |
c22577deed70f81c81fd7933a9ce1d9d1611c909 | C++ | Fihiz/42-final_CPP | /CPP_08/ex02/mutantstack.hpp | UTF-8 | 3,440 | 3.359375 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* mutantstack.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: salome <salome@student.42lyon.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/21 17:36:00 by salome #+# #+# */
/* Updated: 2021/04/21 21:16:37 by salome ### ########lyon.fr */
/* */
/* ************************************************************************** */
#ifndef MUTANTSTACK_HPP
# define MUTANTSTACK_HPP
#include <iostream>
#include <stack>
#include <list>
/* The std::stack class is a container adapter that gives the programmer
** the functionality of a stack - specifically, a LIFO (last-in, first-out) data structure. */
/* Remember that there are iterators, dedicated for list, vector, map...
** but not for stack ! */
/* C++ iterators are used for sequential access or random access to elements within the data structure.
** Thus, iterators would have no meaning for data structures that, by definition, don’t allow for sequential or random access.
** That’s why there are no iterators for stacks and queues.
** On the other hand, vectors and lists allow sequential and/or random access to elements, so iterators
** make sense for navigating these data structures. */
# define T_N "\033[00m"
# define T_Y "\033[00;33m"
# define T_GN "\033[00;32m"
# define T_GYB "\033[01;90m"
# define T_GYI "\033[03;90m"
# define T_GYHID "\033[2;90m"
# define T_BB "\033[01;34m"
template< typename T >
class MutantStack : public std::stack<T> // MutantStack has the std::stack behavior
{
private:
public:
MutantStack<T>( void ) : std::stack<T>()
{
std::cout << T_GYHID "Default constructor called" T_N << std::endl;
};
MutantStack<T>( MutantStack const &src ) : std::stack<T>(src) {};
MutantStack<T> &operator=( MutantStack const &rhs )
{
std::stack<T>::operator=(rhs);
};
virtual ~MutantStack<T>( void )
{
std::cout << T_GYHID "Destructor called" T_N << std::endl;
};
typedef typename std::stack<T>::container_type::iterator iterator;
typedef typename std::stack<T>::container_type::const_iterator const_iterator;
typedef typename std::stack<T>::container_type::reverse_iterator reverse_iterator;
typedef typename std::stack<T>::container_type::const_reverse_iterator const_reverse_iterator;
iterator begin()
{
return ( std::stack<T>::c.begin() );
}
const_iterator begin() const
{
return ( std::stack<T>::c.begin() );
}
iterator end()
{
return ( std::stack<T>::c.end() );
}
const_iterator end() const
{
return ( std::stack<T>::c.end() );
}
reverse_iterator rbegin()
{
return ( std::stack<T>::c.rbegin() );
}
const_reverse_iterator rbegin() const
{
return ( std::stack<T>::c.rbegin() );
}
reverse_iterator rend()
{
return ( std::stack<T>::c.rend() );
}
const_reverse_iterator rend() const
{
return ( std::stack<T>::c.rend() );
}
};
#endif | true |
6eeb132e4dc1bca2e5f077953cf3ec51bc80e3e6 | C++ | TopKekstar/RVR | /practica3.1/GameServer.h | UTF-8 | 1,654 | 2.671875 | 3 | [
"Unlicense"
] | permissive | #include <pthread.h>
#include <map>
#include "UDPServer.h"
#include "Game.h"
/**
* La clase GameServer representa el servidor dedicado del juego. La
* funcionalidad de red se implmenta mediante el interfaz de UDPServer (Prác-
* tica 2.3).
*
* Esta clase se encarga de realizar además la simulación del juego.
*
*/
class GameServer : public UDPServer
{
private:
/**
* Estado del juego. Se actualiza en cada tick y se envía a los clientes
* de forma completa.
*/
GameWorld gw;
public:
/**
* Constructor:
* @param s, nombre del servidor (e.g. "localhost" o "192.168.0.1")
* @param p, puerto en el que escucha (e.g. "8080")
*/
GameServer(const char * s, const char * p):UDPServer(s, p){};
virtual ~GameServer(){};
/**
* Tratamiento del mensaje. Los clientes envían las ordénes del tanque
* (girar, disparar, avanzar):
* 1. Crear un clase Player (Client Proxy)
* 2. Deserializar el mensaje en la clase
* 3. Actualiza el proxy de cliente para el jugador
*/
void do_message(char * buffer)
{
}
/**
* Función envoltorio para ejecutar un paso de simulación
*/
void simulate()
{
gw.simulate();
}
/**
* Esta función recorre la lista de conexiones (gestionada por la clase
* UDPServer) y envía el mundo del juego serializado después de cada paso
* de simulación
* 1. Serializar el mundo
* 2. Para cada conexión, enviar mundo actualizado. En caso de error
* eliminar conexión de la lista
*/
void broadcast();
};
| true |
479cc5278ccb2da6a1c8e8a2f0d95261bea050da | C++ | BFH1122/TCP_VIEW | /Service/MFCMyDialog/RandomEntry.cpp | GB18030 | 901 | 3.078125 | 3 | [] | no_license |
#include <iostream>
#include "random.h"
#include<cstdlib>
#include<ctime>
//ľʵ
int* randomNums::getNums() {
return nums;
}
//ĺ
void randomNums::randomN() {
//
nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = rand() % 20 - 10;
}
}
randomNums::randomNums() {
}
//캯
randomNums::randomNums(int nn) {
n = nn;
srand((unsigned)time(NULL));
}
//
randomNums::~randomNums() {
//delete nums;
//ڴ˴ͷռ
}
//---------------------------------------
//캯
NumArrays::NumArrays() {
}
NumArrays::~NumArrays() {
for (int i = 0; i < n; i++) {
delete array[i];
}
}
int** NumArrays::getArray(int n, int len) {
array = new int*[n];
randomNums *num = new randomNums(len);
for (int i = 0; i < n; i++) {
(*num).randomN();
array[i] = (*num).getNums();
}
return array;
}
| true |
01137f06c6e6c8a1b6eb13eae22943c37e7243cf | C++ | bozhink/Code-Chunks | /Ada/livro-ds/gfilac.h | ISO-8859-1 | 1,248 | 3.5625 | 4 | [] | no_license | // (C) 1999, Arthur Vargas Lopes
// Arquivo fonte GFilaC.h
#ifndef FILAC
#define FILAC
#include <stdio.h>
#include <iostream.h>
#include <process.h>
#include <malloc.h>
template <class Tipo_Dado,int N> class FilaC
{
public:
Filac(); // Construtor
void Queue(Tipo_Dado D);
void DeQueue(Tipo_Dado *R);
int Tamanho();
private:
Tipo_Dado Q[N];
int Inicio;
int Fim;
int tamanho;
};
// Algoritmo 4.4
template <class Tipo_Dado, int N>
FilaC<Tipo_Dado,N>::Filac() // Substitui procedimento de inicializao
{
Inicio = 0;
Fim = -1;
tamanho = 0;
}; // Inicializa
// Algoritmo 4.5
template <class Tipo_Dado, int N>
void FilaC<Tipo_Dado,N>::Queue(Tipo_Dado D)
{
if (N == tamanho) {
cout << "*** Overflow na fila ***" << '\n';
exit(1);
}
else {
Q[Fim] = D;
Fim = (Fim + 1) % N;
tamanho += 1;
}
}; // Queue
// Algoritmo 4.6
template <class Tipo_Dado, int N>
void FilaC<Tipo_Dado,N>::DeQueue(Tipo_Dado *R)
{
if (tamanho == 0) {
cout << "*** Underflow na fila ***\n";
exit(1);
}
else {
*R = Q[Inicio];
Inicio = (Inicio + 1) % N;
tamanho -= 1;
}
}; // DeQueue
template <class Tipo_Dado, int N>
int FilaC<Tipo_Dado,N>::Tamanho()
{
return tamanho;
}; // Tamanho
#endif
| true |
2599779e0f51e90a883aff8f0033df0b87cae679 | C++ | germix/germix-games | /code/game-aisland/src/EntityParameters.h | WINDOWS-1250 | 628 | 2.53125 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// EntityParameters
//
// Germn Martnez
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef ___EntityParameters_h___
#define ___EntityParameters_h___
#include <map>
#include <mach/String.h>
class EntityParameters
{
public:
std::map<String,String> map;
public:
EntityParameters()
{
}
~EntityParameters()
{
}
public:
String get(const char* key, const char* defaultValue) const;
void insert(const char* key, const char* value)
{
map[key] = value;
}
};
#endif
| true |
b9190c756a20c17662777de14ea3010b58380382 | C++ | BillXu/TestLua | /TestLua/testClass2.h | UTF-8 | 1,292 | 2.625 | 3 | [] | no_license | #pragma once
#include "mytestClass.h"
#define PKG_NUM 2
struct stTestBase
{
stTestBase(){ x = y = 0 ;nType = 0 ; }
int nType ;
int x ;
int y ;
};
struct stChild
:public stTestBase
{
stChild(){ z = 0 ;nType = 1 ;}
int z ;
};
class COthreBase
{
public:
COthreBase(){};
void Print(){ printf("multi ji cheng\n");}
};
void FreeFunction( int a );
enum eGlobalEnum
{
eGolal ,
eGolal2,
};
class CSubClass
:public CBaseClass,
public COthreBase
{
public:
enum eGlobalEnum
{
eGolal = 3,
eGolal2,
};
public:
CSubClass(){m_nNum = 0 ;m_pParent = NULL ;}
CSubClass( int a ,CBaseClass* pParent ){ m_nNum = a ;m_pParent = pParent ;}
~CSubClass(){}
void PrintVirtual(){ printf("this is Child \n");};
void FuncSub();
static void StaticFunc(){ printf("this is static func\n");}
void FuncInline(){ printf("this is inline function\n");}
void PrintStruct(stTestBase* pS );
void TestOverload(int a ){ printf("this is test over load one argument\n");}
void TestOverload(int a, int b ){ printf("this is test over load 2 argument\n");}
CBaseClass* get_m_pParent(){ return m_pParent ; }
void set_m_nNum(int n ) { m_nNum = n ; };
int get_m_nNum(){ return m_nNum ; }
void Swap(int*a , int* b, int add );
public:
int m_nPN ;
protected:
int m_nNum ;
CBaseClass* m_pParent ;
}; | true |
4d4a0f57236e4963ddb80b95307acb98c19e7a74 | C++ | bmvskii/DataStructuresAndAlgorithms | /Sort, search algorithms/Вариант у-2/priority_queue_ordered_vector_impl.cpp | UTF-8 | 2,149 | 3.0625 | 3 | [] | no_license | #include "priority_queue.hpp"
#include "vector.hpp"
#include <cassert>
struct PriorityQueue
{
Vector m_orderedItems;
int fixedSize;
};
PriorityQueue * PriorityQueueCreate (int _fixedSize)
{
PriorityQueue * pPQ = new PriorityQueue;
VectorInit( pPQ->m_orderedItems );
pPQ->fixedSize = _fixedSize;
return pPQ;
}
void PriorityQueueDestroy ( PriorityQueue * _pPQ )
{
VectorDestroy( _pPQ->m_orderedItems );
delete _pPQ;
}
void PriorityQueueClear ( PriorityQueue & _pq )
{
VectorClear( _pq.m_orderedItems );
}
bool PriorityQueueIsEmpty ( const PriorityQueue & _pq )
{
return _pq.m_orderedItems.m_nUsed == 0;
}
void PriorityQueueInsertInternal(PriorityQueue & _pq, Payment _key, int _position = -1)
{
if (_position == -1)
VectorPushBack(_pq.m_orderedItems, _key);
else
VectorInsertAt(_pq.m_orderedItems, _position, _key);
if (_pq.fixedSize + 1 == _pq.m_orderedItems.m_nUsed)
PriorityQueueDeleteMin(_pq);
}
void PriorityQueueInsert ( PriorityQueue & _pq, Payment _key)
{
for ( int i = 0; i < _pq.m_orderedItems.m_nUsed; i++ )
if ( _key.m_summary < _pq.m_orderedItems.m_pData[ i ].m_summary )
{
PriorityQueueInsertInternal(_pq, _key, i);
return;
}
else if (_key.m_summary == _pq.m_orderedItems.m_pData[i].m_summary)
{
if (difftime(mktime(&_key.m_time),mktime(&_pq.m_orderedItems.m_pData[i].m_time)) <= 0)
{
PriorityQueueInsertInternal(_pq, _key, i);
return;
}
}
PriorityQueueInsertInternal(_pq, _key);
}
void showData(std::ostream & _s, Payment _p) {
_s << _p.m_time.tm_mday << "/" << _p.m_time.tm_mon << "/" << _p.m_time.tm_year << " $"
<< _p.m_summary << " " << _p.m_fstCompany << " " << _p.m_sndCompany << std::endl;
}
void PriorityQueuePrint(const PriorityQueue &_pq, std::ostream & _s)
{
for (int i = _pq.m_orderedItems.m_nUsed - 1; i >= 0; i--)
showData(_s, _pq.m_orderedItems.m_pData[i]);
}
Payment PriorityQueueMin ( const PriorityQueue & _pq )
{
assert( ! PriorityQueueIsEmpty( _pq ) );
return _pq.m_orderedItems.m_pData[ 0 ];
}
void PriorityQueueDeleteMin ( PriorityQueue & _pq )
{
assert( !PriorityQueueIsEmpty( _pq ) );
VectorDeleteAt( _pq.m_orderedItems, 0 );
} | true |
010d4f27cb32342e2dbf78c773e828dfea3e7742 | C++ | markygriff/Mr.Engine | /MrEngineLib/MrEngine/Camera2D.hpp | UTF-8 | 1,552 | 2.859375 | 3 | [] | no_license | #ifndef Camera2D_hpp
#define Camera2D_hpp
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <stdio.h>
namespace MrEngine
{
class Camera2D
{
public:
Camera2D();
~Camera2D();
void init(int screenWidth, int screenHeight);
void update();
/// Converts screen coordinates to World corordinates
glm::vec2 convertScreenToWorld(glm::vec2 screenCoords);
/// Returns true if box is on the visible screen
bool isBoxInView(const glm::vec2 &position, const glm::vec2 &dimensions);
void offsetPosition(const glm::vec2& offset) { m_position += offset; m_needsMatrixUpdate = true; }
void offsetScale(float offset) { m_scale += offset; if (m_scale < 0.001f) m_scale = 0.001f; m_needsMatrixUpdate = true; }
//setters
void setPosition(const glm::vec2& newPosition) { m_position = newPosition; m_needsMatrixUpdate = true; }
void setScale(const float newScale) { m_scale = newScale; m_needsMatrixUpdate = true; }
//getters
glm::vec2 getPosition() const { return m_position; }
float getScale() const { return m_scale; }
glm::mat4 getCameraMatrix() const { return m_cameraMatrix; }
float getDimRatio() const { return (float) m_screenWidth / (float) m_screenHeight; }
private:
int m_screenWidth = 500;
int m_screenHeight = 500;
bool m_needsMatrixUpdate = true;
float m_scale = 1.0f;
glm::vec2 m_position;
glm::mat4 m_cameraMatrix; // 4x4 matrix
glm::mat4 m_orthoMatrix;
};
}
#endif /* Camera2D_hpp */
| true |
18ace9e085940ec5cf18207792b00ed0049ae0b4 | C++ | kgandhi09/C-Cpp | /fopen/src/fopenForClass.cpp | UTF-8 | 768 | 2.671875 | 3 | [] | no_license | //============================================================================
// Name : fopen.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
#include "Tests.h"
#include "Production.h"
int main(int argc, char* argv[]) {
Tests* ts = new Tests();
if(ts->tests())
{
Production* p = new Production();
p->production(argc, argv);
delete p;
int retVal;
FILE *fp;
char buffer[] = "Hello World.";
fp = fopen("GoL1.txt","w");
retVal = fwrite(buffer,sizeof(buffer),1,fp);
}
cout << "!!!Let's do fopen for read!!!" << endl;
delete ts;
return 0;
}
| true |
35b1f6c0cbf29594ad6c73f8ef072e9be630f680 | C++ | YuWan1117/StudyServer | /r_l.cpp | UTF-8 | 751 | 2.796875 | 3 | [] | no_license | /*
* (C) 2007-2015 Alibaba Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* r_l.cpp --
*
* Version: 1.0 2015年07月28日 14时36分25秒
*
* Authors:
* Sweetheart502 (liyingxiao), liyingxiao502@gmail.com
*
*/
#include <iostream>
void PrintValue ( int & i )
{
std::cout << "lvalue : " << i << std::endl ;
}
void PrintValue ( int && i )
{
std::cout << "rvalue : " << i << std::endl ;
}
void Forward ( int && i )
{
PrintValue ( i ) ;
}
int main ( void )
{
int i =0 ;
PrintValue ( i ) ;
PrintValue ( 1 ) ;
Forward ( 2 ) ;
/*
* p68 the last line.
*/
return 0 ;
}
| true |
b3cb39c05a15730817a8c83a3dfb8848f56af36b | C++ | GainAw/Calculator-Test | /Project1/Calculator.h | UTF-8 | 502 | 2.875 | 3 | [] | no_license | #pragma once
#include<string>
#include<iostream>
#include<conio.h>
using namespace std;
namespace Calculator
{
double add(double left, double right);
double sub(double left, double right);
double mult(double left, double right);
double div(double left, double right);
double car(double left, double right);
double invert();
double square(double left);
double logarithm(double left);
double sine(double left);
double cosine(double left);
double tangent(double left);
}
| true |
fa74ae3b134cf3681feea9f5cbf21b21f91b90d7 | C++ | GustavoECM/CodigoC- | /Estudo_Funcao_C++_Livro/Estudo_Funcao_C++_Livro/FuncaoMatematica.cpp | ISO-8859-1 | 984 | 3.5 | 4 | [] | no_license | #include "stdafx.h"
#include "FuncaoMatematica.h"
#include<iostream>
using namespace std;
FuncaoMatematica::FuncaoMatematica()
{
}
void FuncaoMatematica::exemplosFuncao() {
int x = 9.2 , y = 8;
cout << ceil(x)<< endl; //arrendonda x para o menor inteiro no menor que x
cout << cos<int>(x) << endl; //co_seno trigonometrico de x (x em radianos)
cout << exp(x) << endl; //funcao exponencial E
cout << fabs(x) << endl; //valor absoluto de x
cout << floor(x) << endl; //arredonda x para o maior inteiro nao maior que x
cout << fmod(x, y) << endl; //resto de x/y como numro de ponto flutuante
cout << log(x) << endl; //logaritmo de x (base e)
cout << log10(x) << endl; //logaritmo de x (base 10)
cout << pow(x, y) << endl; // x elevado potencia de y;
cout << sin(x) << endl; //seno trigonametrico de x (x em radianos)
cout << sqrt(y) << endl;//raiz quadeada de y
cout << tan<int>(x) << endl; // tangente trigonometrico de x (x radiano)
} | true |
3e0e2f02432166ffd21c3745ef70023d8e9e8181 | C++ | JonyOliva/GameSFML | /animation.cpp | UTF-8 | 4,152 | 2.828125 | 3 | [] | no_license | #include "animation.h"
#include <iostream>
Animation::Animation(sf::Texture* texture, int initRow, sf::Vector2u _imgCount, float _frameTime, bool ppMode){
currentImage = {0, initRow};
frameTime = _frameTime;
totalTime = 0;
imgCount = _imgCount;
pingpong = ppMode;
tRect.width = texture->getSize().x/imgCount.x;
tRect.height = texture->getSize().y/imgCount.y;
}
void Animation::Update(float deltaTime){
totalTime+=deltaTime;
if(totalTime >= frameTime){
totalTime = 0;
if(pingpong){
if(endloop){
if(currentImage.x == 0){
endloop = 0;
currentImage.x++;
}
else
currentImage.x--;
}
else{
if(currentImage.x == imgCount.x-1){
endloop = 1;
currentImage.x--;
}
else
currentImage.x++;
}
}else{
currentImage.x++;
if(currentImage.x >= imgCount.x){
currentImage.x = 0;
}
}
}
tRect.left = currentImage.x*tRect.width;
tRect.top = currentImage.y*tRect.height;
}
void Animation::setRow(int row){
currentImage.y = row;
}
void Animation::setFrameTime(float _frameTime){
totalTime = 0;
frameTime = _frameTime;
}
void Animation::setPPMode(bool mode){
pingpong = mode;
}
GuiDialog::GuiDialog(char* text, sf::Font& f, sf::Vector2f position, sf::Color color, unsigned int csize, float time){
enable = true;
dialog.setFont(f);
dialog.setPosition(position);
dialog.setFillColor(color);
dialog.setString(text);
if(csize != 0)
dialog.setCharacterSize(csize);
showTime = time;
}
void GuiDialog::Update(float deltaTime){
if(showTime != 0){
totalTime+=deltaTime;
if(totalTime >= showTime)
enable = false;
}
}
void GuiDialog::Draw(sf::RenderWindow* window){
if(enable)
window->draw(dialog);
}
sf::Vector2f GuiDialog::getPos(){
return dialog.getPosition();
}
void GuiDialog::setEnable(bool state){
enable = state;
}
bool GuiDialog::getEnable(){
return enable;
}
AnimationProp::AnimationProp(sf::Sprite* _spr, float _duration){
spr = _spr;
end = false;
totalTime = 0;
duration = _duration;
}
bool AnimationProp::isEnd(){
return this->end;
}
AnimationPos::AnimationPos(sf::Sprite* _spr, sf::Vector2f startPos, sf::Vector2f endPos, float _duration) : AnimationProp(_spr, _duration){
movePos = {endPos.x - startPos.x, endPos.y - startPos.y};
velX = (1.f/60.f)*(movePos.x/duration);
velY = (1.f/60.f)*(movePos.y/duration);
}
AnimationRot::AnimationRot(sf::Sprite* _spr, float startPos, float endPos, float _duration) : AnimationProp(_spr, _duration){
rotation = endPos - startPos;
vel = (1.f/60.f)*(rotation/duration);
}
AnimationSiz::AnimationSiz(sf::Sprite* _spr, sf::Vector2f startPos, sf::Vector2f endPos, float _duration) : AnimationProp(_spr, _duration){
size = endPos - startPos;
vel = (1.f/60.f)*(size/duration);
}
void AnimationProp::Update(float time){
totalTime+=time;
if(totalTime >= duration){
end = true;
}
}
void AnimationProp::Reset(){
end = false;
totalTime = 0;
}
void AnimationPos::Update(float time){
if(!end)
spr->move(velX, velY);
AnimationProp::Update(time);
}
void AnimationRot::Update(float time){
if(!end)
spr->rotate(vel);
AnimationProp::Update(time);
}
void AnimationSiz::Update(float time){
if(!end)
spr->setScale(spr->getScale()+vel);
AnimationProp::Update(time);
}
void AnimationPlayer::AddAnimation(AnimationProp* anim){
anims.push_back(anim);
}
void AnimationPlayer::Update(float deltaTime){
if(anims[currentAnim]->isEnd()){
currentAnim++;
if(currentAnim == anims.size()){
currentAnim = 0;
Reset();
}
}
anims[currentAnim]->Update(deltaTime);
}
void AnimationPlayer::Reset(){
for(int i=0;i<anims.size();i++){
anims[i]->Reset();
}
}
| true |