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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e273ae14f46a8538a05b780a4564e6da810addf0 | C++ | kevinbyrom/FootballPoC | /src/Gamelib Source/Actions.cpp | UTF-8 | 2,270 | 3.125 | 3 | [] | no_license | #include <windows.h>
#include "Gamelib.h"
void ACTIONS::Pop()
{
/////////////////////////////////////////////////
// //
// Used to POP the top action off of the stack //
// //
/////////////////////////////////////////////////
// Return if there are no actions
if (NumActions == 0)
return;
// Remove the first action by coping the others over it
memcpy(Action, &Action[1], sizeof(ACTION) * NumActions - 1);
// Decrement the amount of actions
NumActions--;
}
void ACTIONS::Push(int type, int time, float param1, float param2, float param3)
{
//////////////////////////////////////////////
// //
// Used to PUSH a new action onto the stack //
// //
//////////////////////////////////////////////
// If there are existing actions, move then forward one space
if (NumActions > 0)
{
if (NumActions == MAX_ACTIONS) NumActions--;
memcpy(&Action[1], Action, sizeof(ACTION) * NumActions);
}
// Set the first action's attributes
Action[0].Type = type;
Action[0].Time = time;
Action[0].Param[0] = param1;
Action[0].Param[1] = param2;
Action[0].Param[2] = param3;
// Increment the amount of actions
NumActions++;
}
void ACTIONS::PushEnd(int type, int time, float param1, float param2, float param3)
{
/////////////////////////////////////////////////////////
// //
// Used to PUSH a new action onto the end of the stack //
// //
/////////////////////////////////////////////////////////
// If all actions are full, just return
if (NumActions == MAX_ACTIONS)
return;
// Set the last action's attributes
Action[NumActions].Type = type;
Action[NumActions].Time = time;
Action[NumActions].Param[0] = param1;
Action[NumActions].Param[1] = param2;
Action[NumActions].Param[2] = param3;
// Increment the amount of actions
NumActions++;
}
void ACTIONS::SetTime(int time)
{
////////////////////////////////////////////////
// //
// Used to set the time of the current action //
// //
////////////////////////////////////////////////
// If there are no actions, just return
if (NumActions == 0)
return;
// Set the current action's time
Action[0].Time = time;
} | true |
0101e313fc8c69d28c5395e080774e9c09c761e2 | C++ | DoDoENT/jtorch | /TorchLib/Source/Linear.cpp | UTF-8 | 2,690 | 2.734375 | 3 | [] | permissive | #include <math.h> // for fabsf, floor, log10, pow
#include <stddef.h> // for NULL
#include <stdexcept> // for runtime_error
#include "Linear.hpp"
#include "Tensor.hpp" // for Tensor, TO_TENSOR_PTR
#include "TorchData.hpp" // for TorchData, TorchDataType
#define SAFE_DELETE(x) if (x != NULL) { delete x; x = NULL; }
#define SAFE_DELETE_ARR(x) if (x != NULL) { delete[] x; x = NULL; }
namespace mtorch {
Linear::Linear(const uint32_t n_inputs, const uint32_t n_outputs)
: TorchStage() {
n_inputs_ = n_inputs;
n_outputs_ = n_outputs;
// NOTE: For efficiency we store the weight matrix transposed!
// (we want the matrix vector multiply to be strided properly)
uint32_t size_[2] = {n_outputs_, n_inputs_};
weights_ = new Tensor<float>(2, size_);
biases_ = new Tensor<float>(1, &n_outputs_);
}
Linear::~Linear() {
SAFE_DELETE(weights_);
SAFE_DELETE(biases_);
}
void Linear::setWeights(const float* weights) {
weights_->setData(weights);
}
void Linear::setWeightsFromStream( InputStream & stream )
{
weights_->setDataFromStream( stream );
}
void Linear::setBiases(const float* biases) {
biases_->setData(biases);
}
void Linear::setBiasesFromStream( InputStream & stream )
{
biases_->setDataFromStream( stream );
}
void Linear::init(TorchData& input, TorchData **output) {
if (input.type() != TorchDataType::TENSOR_DATA) {
throw std::runtime_error("Linear::init() - "
"FloatTensor expected!");
}
Tensor<float>& in = (Tensor<float>&)input;
if (in.dim() != 1 || in.size()[0] != n_inputs_) {
throw std::runtime_error("Linear::init() - ERROR: input size mismatch!");
}
*output = new Tensor<float>(1, &n_outputs_);
}
void Linear::forwardProp(TorchData& input, TorchData** output) {
init(input, output);
float* A = weights_->getData();
float* X = ((Tensor<float>&)input).getData();
Tensor<float>* Y = TO_TENSOR_PTR(*output);
uint32_t M = (uint32_t)n_outputs_;
uint32_t N = (uint32_t)n_inputs_;
// Perform the linear accumulation
for (uint32_t i = 0; i < M; i++) {
float sum = 0;
for (uint32_t k = 0; k < N; k++) {
sum += A[i + M * k] * X[k];
}
Y->setDataAt(sum, i);
}
// Now add in the bias
Tensor<float>::accumulate(*Y, *biases_);
}
TorchStage * Linear::loadFromStream( InputStream & stream ) noexcept
{
int32_t n_outputs = stream.read< int32_t >();
int32_t n_inputs = stream.read< int32_t >();
Linear* ret = new Linear(n_inputs, n_outputs);
ret->setWeightsFromStream( stream );
ret->setBiasesFromStream( stream );
return ret;
}
} // namespace mtorch
| true |
4cfeca5d3df95c5a9cea5e43a83020acb17448c4 | C++ | Young-Murloc/1day1quiz | /1일1문제/0414땅따먹기.cpp | UHC | 1,897 | 3.5625 | 4 | [] | no_license | /*
Ա Ϸ մϴ. Ա (land) N 4 ̷ ְ, ĭ ֽϴ. 1 ྿ , 4ĭ ĭ 鼭 ; մϴ. , Ա ӿ ྿ , ؼ Ư Ģ ֽϴ.
,
| 1 | 2 | 3 | 5 |
| 5 | 6 | 7 | 8 |
| 4 | 3 | 2 | 1 |
־ٸ, 1 ° ĭ (5) , 2 ° ĭ (8) ϴ.
, ִ ִ밪 returnϴ solution Լ ϼ ּ. , 1 ° ĭ (5), 2 ° ĭ (7), 3 ù° ĭ (4) 16 ְ ǹǷ 16 return ϸ ˴ϴ.
̳ α / bottom to top / memorization
top to bottom Ѱ?
*/
#include <vector>
#include <algorithm>
using namespace std;
int dp[100000][4];
void DP(vector<vector<int>> land) {
for (int i = 0; i < land.size() - 1; i++) {
dp[i + 1][0] = max(max(dp[i][1], dp[i][2]), dp[i][3]) + land[i + 1][0];
dp[i + 1][1] = max(max(dp[i][0], dp[i][2]), dp[i][3]) + land[i + 1][1];
dp[i + 1][2] = max(max(dp[i][0], dp[i][1]), dp[i][3]) + land[i + 1][2];
dp[i + 1][3] = max(max(dp[i][0], dp[i][1]), dp[i][2]) + land[i + 1][3];
}
return;
}
int solution(vector<vector<int> > land)
{
int answer = 0;
dp[0][0] = land[0][0];
dp[0][1] = land[0][1];
dp[0][2] = land[0][2];
dp[0][3] = land[0][3];
DP(land);
for (int i = 0; i < 4; i++) {
if (answer < dp[land.size() - 1][i]) {
answer = dp[land.size() - 1][i];
}
}
return answer;
} | true |
fe6527714a33151cc65b44fd9f5d6c0a2b37868e | C++ | HanLab-BME-MTU/extern | /mex/include/wildmagic-5.7/include/Wm5TriangleKey.inl | UTF-8 | 1,732 | 2.578125 | 3 | [
"BSD-2-Clause"
] | permissive | // Geometric Tools, LLC
// Copyright (c) 1998-2011
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.0 (2010/01/01)
//----------------------------------------------------------------------------
inline TriangleKey::TriangleKey (int v0, int v1, int v2)
{
if (v0 < v1)
{
if (v0 < v2)
{
// v0 is minimum
V[0] = v0;
V[1] = v1;
V[2] = v2;
}
else
{
// v2 is minimum
V[0] = v2;
V[1] = v0;
V[2] = v1;
}
}
else
{
if (v1 < v2)
{
// v1 is minimum
V[0] = v1;
V[1] = v2;
V[2] = v0;
}
else
{
// v2 is minimum
V[0] = v2;
V[1] = v0;
V[2] = v1;
}
}
}
//----------------------------------------------------------------------------
inline bool TriangleKey::operator< (const TriangleKey& key) const
{
if (V[2] < key.V[2])
{
return true;
}
if (V[2] > key.V[2])
{
return false;
}
if (V[1] < key.V[1])
{
return true;
}
if (V[1] > key.V[1])
{
return false;
}
return V[0] < key.V[0];
}
//----------------------------------------------------------------------------
inline TriangleKey::operator size_t () const
{
return V[0] | (V[1] << 10) | (V[2] << 20);
}
//----------------------------------------------------------------------------
| true |
b542e81164272a40ac552d58300cb80087e5d88c | C++ | fruitbox12/WorldSimulator | /actorlevel.h | UTF-8 | 558 | 2.953125 | 3 | [] | no_license | #pragma once
#include "actor.h"
#include "level.h"
// OOP: Multiple Inheritance: ActorLevel "IS A(N)" Actor and "IS A" Level
class ActorLevel : public Actor, public Level {
private:
public:
ActorLevel();
ActorLevel(int id, string name, string description, int rows, int cols, bool moveable);
~ActorLevel();
// Getters
Level* getLevel();
Actor* findActor(string name);
// Add Actor randomly
bool addActor(Actor* actor);
// Add Actor at a specified location
bool addActor(Actor* actor, int row, int col);
};
| true |
d2ccc3e4ec173cd5eacc1c73748e7724bb2179db | C++ | Mukki/Soccer-Simulator | /Class/Joueur.h | UTF-8 | 598 | 2.75 | 3 | [] | no_license | #pragma once
#ifndef JOUEUR_H_
#define JOUEUR_H_
#include <string>
#include "Parcours.h"
#include "Sportif.h"
#include <vector>
using namespace std;
class Joueur : public Sportif
{
protected:
float taille;
float poids;
string villeNaissance;
vector<Parcours> vect_parcours;
public:
Joueur();
Joueur(string nom, string prenom, float taille, float poids, string villeNaissance);
~Joueur();
string leNom();
string lePrenom();
float laTaille();
float lePoids();
string laVilleNaissance();
void ajoutParcours(string nomCub, Date datePassage);
virtual float briserContrat();
};
#endif | true |
44c25b9375a0e408e61ac174e28864592be6f633 | C++ | cies96035/CPP_programs | /Kattis/AC/npuzzle.cpp | UTF-8 | 436 | 2.9375 | 3 | [] | no_license | #include<iostream>
using namespace std;
char puzzle;
int sum;
int main()
{
cin.tie(0);
ios_base::sync_with_stdio(0);
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
cin >> puzzle;
if(puzzle != '.'){
puzzle -= 'A';
sum += std::abs(i - puzzle / 4) + std::abs(j - puzzle % 4);
}
}
}
cout << sum << '\n';
return 0;
} | true |
d1a55345f8cb77a408a30d591e0d85e8fa500fd7 | C++ | ayushkhanduri/dsa-algo | /Platforms/LeetCode/implement-strStr.cpp | UTF-8 | 774 | 3.3125 | 3 | [] | no_license | //https://leetcode.com/problems/implement-strstr/
// 100%
#include "iostream"
#include "string"
using namespace std;
int strStr(string haystack, string needle) {
int hayStackSize = haystack.size(), needleSize = needle.size(), index = -1;
if ( !needleSize ) {
return 0;
}
for (int i = 0 ; i < hayStackSize ; i ++) {
if (haystack.at(i) == needle.at(0) && (hayStackSize - i ) >= needleSize ) {
int j = i , k = 0, matchingChars = 0;
while (j < hayStackSize && k < needleSize) {
if (haystack.at(j) == needle.at(k)) {
j++;
k++;
matchingChars++;
} else {
break;
}
}
if (matchingChars == needleSize) {
index = i;
break;
}
}
}
return index;
}
int main() {
int position = strStr("hello", "o");
cout << position;
} | true |
5281be892d373d735e0808168bc46b44d507d896 | C++ | Sverda/Prosterno | /Prosterno/Game.h | WINDOWS-1250 | 1,741 | 3.375 | 3 | [] | no_license | #pragma once
#include"GameBase.h"
#include"Board.h"
#include"Player.h"
#include"AI.h"
#include<ctime>
#include<iostream>
using namespace std;
// Zarzdza oglnym przebiegiem gry i jest porednikiem pomidzy main a systemem gry.
template <typename P, typename E> // P - player, E - enemy
class Game: public GameBase
{
private:
Board board;
Person* player;
Person* enemy;
bool endgame; // Okrela, czy nastpi koniec gry
void printStartInstruction();
public:
Game();
~Game();
void PlayRound();
bool CheckEndgame();
void LoadBoard();
};
template <typename P, typename E>
Game<P, E>::Game()
{
player = new P(Field::Friend, board);
enemy = new E(Field::Enemy, board);
srand((int)time(NULL)); // Losowanie dla AI
printStartInstruction();
//board.PrintBoard();
endgame = false;
}
template <typename P, typename E>
Game<P, E>::~Game()
{
delete player;
delete enemy;
}
template <typename P, typename E>
void Game<P, E>::printStartInstruction()
{
cout << "\nTwoje pionki (lub I gracza) sa oznaczone jako: P" << endl;
cout << "Pionki przeciwnika (lub II gracza) natomiast jako: W" << endl;
cout << "Ruszanie pionka: RzadKolumna Rzad2Kolumna2" << endl;
cout << "Aby zapisac wprowadz: ss ss, zamiast ruchu. \n" << endl;
}
template <typename P, typename E>
void Game<P, E>::PlayRound()
{
board.PrintBoard();
cout << "Ruch I gracza" << endl;
player->MakeMove();
board.PrintBoard();
endgame = board.CheckEndgame();
if (endgame)
{
return;
}
cout << "Ruch II gracza" << endl;
enemy->MakeMove();
endgame = board.CheckEndgame();
}
template <typename P, typename E>
bool Game<P, E>::CheckEndgame()
{
return endgame;
}
template<typename P, typename E>
void Game<P, E>::LoadBoard()
{
board.Load(SAVEFILE);
}
| true |
3a497b88efad8e928216322bece5b413a0428912 | C++ | Gouldian0120/serverclienttcp | /cpp_libraries/utilities/compressing.h | UTF-8 | 466 | 2.75 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | #pragma once
#include <vector>
namespace compressing
{
class compressor
{
public:
static std::vector<unsigned char> compression(const std::vector<unsigned char>& original_data);
static std::vector<unsigned char> decompression(const std::vector<unsigned char>& compressed_data);
public:
static void set_block_bytes(const unsigned short& block_bytes);
static unsigned short get_block_bytes(void);
private:
static unsigned short _block_bytes;
};
}
| true |
bc6a7d86dbc2f59bb76e968de27cfeb051a94193 | C++ | huynguyenqc/AI-LogicalAgent-Project | /2_1/Source/CNF.h | UTF-8 | 1,628 | 2.875 | 3 | [] | no_license | #ifndef CNF_INCLUDED
#define CNF_INCLUDED
#include <vector>
#include <set>
#include <string>
#include <map>
#include <fstream>
#include <iterator>
#include "Proposition.h"
#define OR_OP '|'
#define AND_OP '&'
#define NOT_OP '~'
#define BEGIN_KB "KB"
#define END_KB "ENDKB"
struct PComp {
bool operator () (const Proposition* x, const Proposition* y) const {
return (*x) < (*y);
}
};
class Element {
friend class ListProposition;;
private:
Proposition* p;
int prio;
public:
Element();
Element& operator += (int literal);
Element operator & (const Element &other) const;
bool operator < (const Element &other) const;
bool isTrue() const;
bool isFalse() const;
void assignPriority(int pr);
void printOut(std::ofstream &fo, const std::vector< std::string > &mpStr) const;
};
class ListProposition {
private:
typedef std::set< Proposition*, PComp> TStatList;
typedef TStatList::iterator StatIt;
TStatList staticList;
public:
void addProp(Element &e);
bool propExist(const Element &e);
~ListProposition();
};
class CNF {
private:
ListProposition LP;
typedef std::set< Element >::iterator SIter;
std::string inferred;
std::set< Element > propList;
std::map< std::string, int > mpLiteral;
std::vector< std::string > mpStr;
void addProp(const Element &e);
bool propExist(const Element &e);
Element splitIntoLiterals(const std::string &prop, char delim);
public:
CNF(const std::string &FILE_NAME);
void printOut(std::ofstream &fo) const;
int resolve(unsigned int prio);
friend void RobinsonResolution(CNF &cnf, const std::string &FILE_NAME);
};
#endif
| true |
13c593390152a5ea2258146165a6df2487b8c807 | C++ | Pekkari/cpp-samples | /Module_1/vector_strings/src/vector_strings.cpp | UTF-8 | 1,557 | 3.59375 | 4 | [] | no_license | #include "vector_strings.hpp"
#include <iostream>
#include <vector>
enum command {
ADD,
PRINT,
REMOVE,
QUIT,
};
command str2cmd(std::string input_cmd){
if (input_cmd == "PRINT")
return PRINT;
else if (input_cmd == "ADD")
return ADD;
else if (input_cmd == "REMOVE")
return REMOVE;
else
return QUIT;
}
void Adder(std::vector<std::string>& names) {
std::string name;
std:: cout << "Enter a name:" << std::endl;
std::cin >> name;
names.push_back(name);
std::cout << "Number of names in the vector:" << std::endl;
std::cout << names.size() << std::endl;
}
void Remover(std::vector<std::string>& names) {
std::cout << "Removing the last element:" << std::endl;
std::cout << names.back() << std::endl;
names.pop_back();
}
void Printer(std::vector<std::string>& names) {
for (std::string name : names)
std::cout << name << std::endl;
}
void CMDReader() {
std::vector<std::string> name_list;
std::string input_cmd;
command cmd;
std::cout << "Commands: ADD, PRINT, REMOVE, QUIT" << std::endl;
while (cmd != QUIT) {
std::cout << "Enter a command:" << std::endl;
std::cin >> input_cmd;
cmd = str2cmd(input_cmd);
switch (cmd) {
case ADD:
Adder(name_list);
break;
case REMOVE:
Remover(name_list);
break;
case PRINT:
Printer(name_list);
break;
case QUIT:
return;
}
}
}
| true |
43fa9b1b37cda844517ab6703101692f5049908b | C++ | CodeShark/CryptoLedger | /src/LevelDBModel.cpp | UTF-8 | 2,493 | 2.8125 | 3 | [] | no_license | #include "LevelDBModel.h"
using namespace leveldb;
using namespace std;
using namespace CryptoLedger;
LevelDBModel::~LevelDBModel()
{
close();
}
void LevelDBModel::open(const string& dbname)
{
if (db_) throw runtime_error("DB is already open.");
Options options;
options.create_if_missing = true;
Status status = DB::Open(options, dbname, &db_);
if (!status.ok()) throw runtime_error(status.ToString());
}
void LevelDBModel::close()
{
if (db_)
{
delete db_;
db_ = nullptr;
}
}
void LevelDBModel::insert(const bytes_t& key, const bytes_t& value)
{
if (!db_) throw runtime_error("DB is not open.");
Status status = db_->Put(WriteOptions(), Slice(string(reinterpret_cast<const char*>(&key[0]), key.size())), Slice(string(reinterpret_cast<const char*>(&value[0]), value.size())));
if (!status.ok()) throw runtime_error(status.ToString());
}
void LevelDBModel::remove(const bytes_t& key)
{
if (!db_) throw runtime_error("DB is not open.");
Status status = db_->Delete(WriteOptions(), Slice(string(reinterpret_cast<const char*>(&key[0]), key.size())));
if (!status.ok()) throw runtime_error(status.ToString());
}
void LevelDBModel::get(const bytes_t& key, bytes_t& value) const
{
if (!db_) throw runtime_error("DB is not open.");
auto it = insertionMap_.find(key);
if (it == insertionMap_.end())
{
string strvalue;
Status status = db_->Get(ReadOptions(), Slice(string(reinterpret_cast<const char*>(&key[0]), key.size())), &strvalue);
if (!status.ok()) throw runtime_error(status.ToString());
value.assign(strvalue.begin(), strvalue.end());
}
else
{
value = it->second;
}
}
void LevelDBModel::batchInsert(const bytes_t& key, const bytes_t& value)
{
insertionMap_[key] = value;
updates_.Put(Slice(string(reinterpret_cast<const char*>(&key[0]), key.size())), Slice(string(reinterpret_cast<const char*>(&value[0]), value.size())));
}
void LevelDBModel::batchRemove(const bytes_t& key)
{
insertionMap_.erase(key);
updates_.Delete(Slice(string(reinterpret_cast<const char*>(&key[0]), key.size())));
}
void LevelDBModel::commit()
{
if (!db_) throw runtime_error("DB is not open.");
Status status = db_->Write(WriteOptions(), &updates_);
if (!status.ok()) throw runtime_error(status.ToString());
insertionMap_.clear();
}
void LevelDBModel::rollback()
{
insertionMap_.clear();
updates_.Clear();
}
| true |
b64e1d67df940ebcb2928d68af6b875a8bc2fc40 | C++ | yixinx/Go-Game | /computer go 2.0/computer go 2.0/stone.cpp | UTF-8 | 2,623 | 2.8125 | 3 | [] | no_license | #include "new_board.h"
#include <cstdio>
#include <time.h>
#include <cstdlib>
#include <cstring>
#include <process.h>
#include <windows.h>
#include <iostream>
#include <shellapi.h>
#include <math.h>
using namespace std;
stone::stone(int r, int c, board_t * new_board)
{
row = r;
col = c;
color = EMPTY;
type = EMPTY_P;
s_influence = 0;
stone_board = new_board;
}
stone::stone(stone * old_stone, board_t * new_board)
{
row = old_stone->row;
col = old_stone->col;
stone_block = NULL;
stone_chain = NULL;
stone_board = new_board;
color = old_stone->color;
s_influence = old_stone->s_influence;
type = old_stone->type;
}
stone::~stone()
{
color = EMPTY;
stone_block = NULL;
stone_chain = NULL;
}
// TODO: add to block
void stone::add_to_chain(board_t &curr_board)
{
int ai = 0, aj = 0;
int flag = 0;
chain * last_chain = NULL;
for (int k = 0; k < 4; k++)
{
ai = row + deltai[k];
aj = col + deltaj[k];
if (!stone_board->on_board(ai, aj)) continue;
chain * temp_chain = stone_board->main_board[POS(ai, aj)]->stone_chain;
if (temp_chain != NULL && (*(temp_chain->stones.begin()))->color == color)
if (flag == 0)
{
temp_chain->absorb_a_stone(this);
flag = 1;
last_chain = this->stone_chain;
}
else
{
if (temp_chain != this->stone_chain)
{
temp_chain->combine_chain(last_chain);
last_chain = this->stone_chain;
}
}
}
if (flag == 0)
{
block * new_block = new block(*this, curr_board);
}
}
/* remove itself means change the stone_block, stone_chain,color, type, but will not destroy the object. It is called in the destructor for the chain */
void
stone::remove_itself()
{
/*
// update the chain,
stone_chain->stones.remove(this);
// TODO: if the chain becomes empty, and then maybe the block becomes empty, we should delete the chain or even the block
if (stone_chain->stones.empty())
{
stone_block->chains.remove(stone_chain);
delete stone_chain;
if (stone_block->chains.empty())
{
stone_block->stones.remove(this);
stone_block->block_board->blocks.remove(stone_block);
delete stone_block;
}
else stone_block->stones.remove(this);
}
else
{
// update the block that the chain belongs to
stone_block->stones.remove(this);
stone_block->block_board->blocks.remove(stone_block);
delete stone_block;
}
*/
stone_block = NULL;
stone_chain = NULL;
color = EMPTY;
type = EMPTY_P;
}
stone_type stone::change_type(stone_type the_type)
{
return type = the_type;
} | true |
d8c9e20b2c1bcb8a386a61f59fd62ff2af5cb33e | C++ | Zebsi235/RemoteControl | /Command.h | UTF-8 | 441 | 2.796875 | 3 | [] | no_license | //////////////////////////////////////////
// Workfile : Command.h
// Author : Michael Enzelsberger
// Date : 09.01.2021
// Description : Interface for commands.
//////////////////////////////////////////
#ifndef COMMAND_H
#define COMMAND_H
#include <memory>
class Command
{
public:
//pure virtual interface
virtual void Execute() = 0;
virtual void Undo() const = 0;
virtual ~Command() = default;
using SPtr = std::shared_ptr<Command>;
};
#endif | true |
7f56f1697ed5675ff4d974f6eb8cdbfb58900417 | C++ | BirgandLab/flowProportionalSampler | /Chronodot_time_adjust/Chronodot_time_adjust.ino | UTF-8 | 1,147 | 3.0625 | 3 | [] | no_license | // Date, time and temperature functions using
// a Chronodot RTC connected via I2C and Wire lib
#include <Wire.h>
#include "Chronodot.h"
Chronodot RTC;
void setup () {
Serial.begin(9600);
Serial.println("Initializing Chronodot.");
Wire.begin();
RTC.begin();
RTC.adjust(DateTime(__DATE__, __TIME__));
}
void loop () {
DateTime now = RTC.now();
Serial.print(now.year(), DEC);
Serial.print('/');
if(now.month() < 10) Serial.print("0");
Serial.print(now.month(), DEC);
Serial.print('/');
if(now.day() < 10) Serial.print("0");
Serial.print(now.day(), DEC);
Serial.print(' ');
if(now.hour() < 10) Serial.print("0");
Serial.print(now.hour(), DEC);
Serial.print(':');
if(now.minute() < 10) Serial.print("0");
Serial.print(now.minute(), DEC);
Serial.print(':');
if(now.second() < 10) Serial.print("0");
Serial.print(now.second(), DEC);
Serial.println();
Serial.print(now.tempC(), 1);
Serial.println(" degrees Celcius");
Serial.print(now.tempF(), DEC);
Serial.println(" degrees Farenheit");
Serial.println();
delay(3000);
}
| true |
fcec244466867dabd8a0f61a4d38c024cce6cc8e | C++ | yangdechuan/algo-notebook | /数据结构/Trie.cpp | UTF-8 | 1,639 | 4.03125 | 4 | [] | no_license | /*
Trie(we pronounce 'try'),也叫前缀树。
参考:LeetCode 208. Implement Trie (Prefix Tree)
*/
#include<cstring>
#include<string>
using namespace std;
struct TrieNode {
int isEnd;
TrieNode* links[26];
TrieNode() {
isEnd = 0;
memset(links, NULL, sizeof(links));
}
};
class Trie {
public:
TrieNode* root;
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* cur = root;
for(char ch : word){
int idx = ch - 'a';
if((cur->links)[idx] == NULL){
(cur->links)[idx] = new TrieNode();
}
cur = (cur->links)[idx];
}
cur->isEnd = 1;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode* cur = root;
for(char ch : word){
int idx = ch - 'a';
cur = (cur->links)[idx];
if(cur == NULL) return false;
}
return cur->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode* cur = root;
for(char ch : prefix){
int idx = ch - 'a';
cur = (cur->links)[idx];
if(cur == NULL) return false;
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/ | true |
0e3f5e314b2e6819b33f564b1196e37935721b2a | C++ | rabaugart/biptest | /test-boost/tprocess/tprocess.cpp | UTF-8 | 1,686 | 2.625 | 3 | [] | no_license | //
// Starts mercurial (hg summary) and reads the revision number
//
#include <iostream>
#include <regex>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/process.hpp>
namespace po = boost::program_options;
namespace bfs = boost::filesystem;
namespace pr = boost::process;
int main( int argc, char** argv )
{
std::string svn;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("svn", po::value<std::string>(&svn)->default_value(""), "path to svn directory")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << "\n";
return 1;
}
bfs::current_path( svn );
const std::vector<bfs::path> addPaths{"/usr/local/bin"};
const std::vector<bfs::path> allPaths{ [&addPaths]() {
std::vector<bfs::path> ret = boost::this_process::path();
ret.insert( ret.end(), addPaths.begin(), addPaths.end() );
return ret;
}() };
bfs::path hg = pr::search_path("hg",addPaths);
if ( hg.empty() )
throw std::runtime_error( "hg executable not found ");
std::future<std::string> fdata;
const int ret = pr::system( hg, "summary", pr::std_out > fdata );
const std::string data = fdata.get();
// parent: 791:28a023ad9c5c
const std::regex re( "parent: [0-9]+:([0-9a-z]+)");
std::smatch ma;
const bool found = std::regex_search( data, ma, re );
if ( ! found )
throw std::runtime_error("Version pattern not found in hg output");
const std::string rev = ma[1].str();
std::cout << "Ok " << svn << " " << ret << std::endl << data << std::endl << rev << std::endl;
return 0;
}
| true |
04042379a0cc38b97bdb0d9d96d6a1e0dd507154 | C++ | aosipov91/rawEngine | /src/renderer/shader.cpp | UTF-8 | 4,925 | 2.65625 | 3 | [] | no_license | #include "shader.h"
namespace renderer {
GLuint load_program(const char *path1, const char *path2, const char *path3)
{
GLuint shader1 = load_shader(GL_VERTEX_SHADER, path1);
GLuint shader2 = load_shader(GL_FRAGMENT_SHADER, path2);
GLuint shader3 = load_shader(GL_GEOMETRY_SHADER, path3);
GLuint program = make_program(shader1, shader2, shader3);
return program;
}
GLuint load_program(const char *path1, const char *path2)
{
GLuint shader1 = load_shader(GL_VERTEX_SHADER, path1);
GLuint shader2 = load_shader(GL_FRAGMENT_SHADER, path2);
GLuint program = make_program(shader1, shader2);
return program;
}
void unload_shader_program(GLuint* id)
{
glDeleteProgram(*id);
}
char *load_file(const char *path) {
#if defined(_WIN32)
FILE *file;
fopen_s(&file, path, "rb");
#elif defined(__linux__)
FILE *file = fopen(path, "rb");
#endif
if (!file) {
fprintf(stderr, "fopen %s failed: %d %s\n", path, errno, strerror(errno));
exit(1);
}
fseek(file, 0, SEEK_END);
int length = ftell(file);
rewind(file);
char *data = (char*)calloc(length + 1, sizeof(char));
fread(data, 1, length, file);
fclose(file);
return data;
}
GLuint make_shader(GLenum type, const char *source) {
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &source, NULL);
glCompileShader(shader);
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
GLint length;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
GLchar *info = (GLchar*)calloc(length, sizeof(GLchar));
glGetShaderInfoLog(shader, length, NULL, info);
fprintf(stderr, "glCompileShader failed:\n%s\n %s", info, source);
free(info);
}
return shader;
}
GLuint load_shader(GLenum type, const char *path) {
char *data = load_file(path);
GLuint result = make_shader(type, data);
free(data);
return result;
}
GLuint make_program(GLuint shader1, GLuint shader2, GLuint shader3) {
GLuint program = glCreateProgram();
glAttachShader(program, shader1);
glAttachShader(program, shader2);
glAttachShader(program, shader3);
glLinkProgram(program);
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status == GL_FALSE) {
GLint length;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length);
GLchar *info = (GLchar*)calloc(length, sizeof(GLchar));
glGetProgramInfoLog(program, length, NULL, info);
fprintf(stderr, "glLinkProgram failed: %s\n", info);
free(info);
}
glDetachShader(program, shader1);
glDetachShader(program, shader2);
glDetachShader(program, shader3);
glDeleteShader(shader1);
glDeleteShader(shader2);
glDeleteShader(shader3);
return program;
}
GLuint make_program(GLuint shader1, GLuint shader2) {
GLuint program = glCreateProgram();
glAttachShader(program, shader1);
glAttachShader(program, shader2);
glLinkProgram(program);
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status == GL_FALSE) {
GLint length;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length);
GLchar *info = (GLchar*)calloc(length, sizeof(GLchar));
glGetProgramInfoLog(program, length, NULL, info);
fprintf(stderr, "glLinkProgram failed: %s\n", info);
free(info);
}
glDetachShader(program, shader1);
glDetachShader(program, shader2);
glDeleteShader(shader1);
glDeleteShader(shader2);
return program;
}
void shader_uniform_1i(GLuint program, const char* name, const int value)
{
// glUseProgram(program);
glUniform1i(glGetUniformLocation(program, name), value);
// glUseProgram(0);
}
void shader_uniform_1f(GLuint program, const char* name, const int value)
{
// glUseProgram(program);
glUniform1f(glGetUniformLocation(program, name), value);
// glUseProgram(0);
}
void shader_uniform_3f(GLuint program, const char* name, float x, float y, float z)
{
const float data[3] = {x, y, z};
GLint loc = glGetUniformLocation(program, name);
if (loc == -1) {
fprintf(stderr, "glGetUniformLocation failed, programId = %u, uniforName = %s\n", program, name);
}
glUniform3fv(loc, 1, (GLfloat*)data);
}
void shader_uniform_mat4(GLuint program, const char* name, const float* data)
{
// glUseProgram(program);
glUniformMatrix4fv(glGetUniformLocation(program, name), 1, GL_FALSE, (GLfloat*)data);
// glUseProgram(0);
}
Shader::Shader()
: mHandle(0)
{
}
Shader::~Shader()
{
}
Shader::Shader(const char *path1, const char *path2)
{
mHandle = load_program(path1, path2);
}
Shader::Shader(const char *path1, const char *path2, const char *path3)
{
mHandle = load_program(path1, path2, path3);
}
}
| true |
b6161bcf9df713c7afea418e8520f6d745d6a4b0 | C++ | maidahahmed/Algorithmic-Toolbox-San-Diego | /Go in depth with each topic/_0_1_KnapSack/_0_1_KnapSack.cpp | UTF-8 | 2,227 | 3.359375 | 3 | [
"MIT"
] | permissive |
//___________________________________________________________________
// 0-1 Knapsack Problem
// Given weights and values of n items,
// we need to put these items in a knapsack of capacity W
// to get the maximum total value in the knapsack Without Breaking any item(whole OR Nothing)
// 1- the Naive Solution (Recursion) Which Will Try All The items To Get The Optimal Solution
// Which Will Be Exponential(2^n)
// wt[] = {1, 1, 1}, W = 2, val[] = {10, 20, 30}
// K(3, 2) ---------> K(n, W)
// / \
// / \
// K(2,2) K(2,1)
// / \ / \
// / \ / \
// K(1,2) K(1,1) K(1,1) K(1,0)
// / \ / \ / \
// / \ / \ / \
// K(0,2) K(0,1) K(0,1) K(0,0) K(0,1) K(0,0)
// But,There are a Lot of OverLabing
// So We'll Go With Another approach(DP)
/*Author : Abdallah Hemdan */
/***********************************************/
/*
___ __
* |\ \|\ \
* \ \ \_\ \
* \ \ ___ \emdan
* \ \ \\ \ \
* \ \__\\ \_\
* \|__| \|__|
*/
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <functional>
#define all(v) v.begin(), v.end()
#define mp make_pair
#define pb push_back
#define endl '\n'
typedef long long int ll;
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
using namespace std;
int _0_1_KnapSack(int W, int val[], int wt[], int n) {
int K[n + 1][W + 1];
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= W; w++) {
if (i == 0 || w == 0)
K[i][w] = 0;
else if (wt[i - 1] <= w)
K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);
else
K[i][w] = K[i - 1][w];
}
}
return K[n][W];
}
int main() {
int n, Capas;
cin >> n >> Capas;
int Values[n];
int Weights[n];
for (size_t i = 0; i < n; i++) cin >> Values[i];
for (size_t i = 0; i < n; i++) cin >> Weights[i];
cout << _0_1_KnapSack(Capas, Values, Weights, n) << endl;
}
| true |
c04870fee0342b99844833dcc02732a5182e0dd6 | C++ | MitkoConev/FMI-notes-for-programming | /Object-oriented-programming/week8/main.cpp | UTF-8 | 1,082 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include "FMIPerson.h"
#include "Asistant.h"
#include "Lector.h"
#include "Student.h"
#include "task.cpp"
int main()
{
/*
std::vector<FMIPerson*> fmiList;
fmiList.push_back(new Asistant());
fmiList.push_back(new Lector());
fmiList.push_back(new Student());
for(int i = 0; i < fmiList.size(); i++)
{
std::cout << fmiList[i]->getIdentificator() << std::endl;
} */
std::vector<Employee*> employees;
employees.push_back(new Programmer("Ivan", 18, true, true));
employees.push_back(new Programmer("Peter", 30, false, true));
employees.push_back(new Manager("John", 2, 5));
employees.push_back(new Programmer("George", 3, false, false));
employees.push_back(new Manager("Svetlin", 40, 120));
employees.push_back(new Programmer("Yoan", 15, true, false));
for(int i = 0; i < employees.size(); i++)
{
if(employees[i]->getType() == Manage)
{
employees[i]->printInfo();
std::cout << std::endl;
}
}
return 0;
} | true |
e3bc78117a28646ac692f30940c7d1a7489b06bd | C++ | adamjoniec/splitscreen | /main.cpp | UTF-8 | 3,020 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include "arguments.h"
#include "windowmanager.h"
using namespace std;
void printConfiguration(Arguments arguments) {
cout << "\n " << MINIMIZE_AT_START_LONG << ", " << MINIMIZE_AT_START_SHORT << " (" <<
(arguments.minimizeAtStart ? "true" : "false") << ")";
/*cout << "\n " << VERTICAL_LONG << ", " << VERTICAL_SHORT << " (" <<
(arguments.vertical ? "true" : "false") << ")";
cout << "\n " << HORIZONTAL_LONG << ", " << HORIZONTAL_SHORT << " (" <<
(!arguments.vertical ? "true" : "false") << ")";*/
cout << "\n " << ALWAYS_ON_TOP_LONG << ", " << ALWAYS_ON_TOP_SHORT << " (" <<
(arguments.alwaysOnTop ? "true" : "false") << ")";
cout << "\n " << TIMEOUT_SECONDS_LONG << ", " << TIMEOUT_SECONDS_SHORT << " seconds ("
<< arguments.timeoutSeconds << ")";
cout << "\n " << WINDOW_TITLE_LONG << ", " << WINDOW_TITLE_SHORT << " title (" << arguments.windowTitle << ")";
cout << "\n";
}
int main(int argc, char** argv)
{
SetWindowText(GetConsoleWindow(), "splitscreen");
cout << "Split screen / couch co-op window adjuster. By default works with Minecraft (just launch "
<< " up to four instances of Minecraft and run this app for magic to happen). "
<< "For any other game/program use " << WINDOW_TITLE_LONG << ", " << WINDOW_TITLE_SHORT << " argument i.e."
<< "\n > splitscreen.exe " << WINDOW_TITLE_LONG << " GameTitle"
<< "\n\nUsing arguments (with defaults):";
Arguments arguments = parseArguments(argc, argv);
printConfiguration(arguments);
if (arguments.minimizeAtStart) {
ShowWindow(GetConsoleWindow(), SW_MINIMIZE);
}
cout << "\nWaiting for " << arguments.windowTitle << " window(s) ...";
unsigned long foundWindowsCount = 0;
for (int seconds = 0; seconds < arguments.timeoutSeconds; ++seconds) {
const list<HWND> foundWindows = findWindows(arguments.windowTitle);
const bool noNewWindow = (foundWindowsCount == foundWindows.size()) || foundWindows.size() == 0;
const bool exitAfterClosing = (foundWindowsCount > 0 && foundWindows.size() == 0);
foundWindowsCount = foundWindows.size();
if (exitAfterClosing) {
cout << "\n\nAll " << arguments.windowTitle << "(s) windows/instances were closed. Closing splitscreen!";
exit(0);
}
if (noNewWindow) {
cout << '.';
sleepSecond();
continue;
}
cout << "\n\n : found " << foundWindowsCount << " " << arguments.windowTitle << " window"
<< (foundWindowsCount > 1 ? "s" : "") << ", adjusting ... ";
adjustWindows(foundWindows, arguments.alwaysOnTop);
cout << "done \n";
cout << "\n ... waiting for more " << arguments.windowTitle << " windows ...";
sleepSecond();
}
cout << "\n\nTimeout! Closing splitscreen!\n";
return 0;
}
| true |
30e0ff0d7ed0180c250476e9b83dc226ce994fb7 | C++ | gkovaig/MedGP | /medgpc/src/mean/c_meanfunc.cpp | UTF-8 | 1,652 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | /*
-------------------------------------------------------------------------
This is the function file for top mean function class.
All other mean functions can inherit these functions.
-------------------------------------------------------------------------
*/
#include <iostream>
#include <vector>
#include <math.h>
#include <stdlib.h>
#include <mkl.h>
// #include <omp.h>
#include "mean/c_meanfunc.h"
#include "util/global_settings.h"
using namespace std;
c_meanfunc::c_meanfunc(){
meanfunc_name = "c_meanfunc";
meanfunc_hyp_num = 0;
}
c_meanfunc::c_meanfunc(vector<int> input_param){
meanfunc_name = "c_meanfunc";
meanfunc_hyp_num = 0;
set_meanfunc_param(input_param);
}
c_meanfunc::c_meanfunc(vector<int> input_param, vector<double> input_hyp){
meanfunc_name = "c_meanfunc";
meanfunc_hyp_num = 0;
set_meanfunc_param(input_param);
set_meanfunc_hyp(input_hyp);
}
void c_meanfunc::print_meanfunc(){
cout << "current mean function object: " << meanfunc_name << endl;
}
void c_meanfunc::set_meanfunc_hyp(vector<double> input_hyp){
meanfunc_hyp = input_hyp;
for(int i = 0; i < int(input_hyp.size()); i++){
meanfunc_hyp[i] = meanfunc_hyp[i];
}
}
void c_meanfunc::set_meanfunc_param(vector<int> input_param){
meanfunc_param = input_param;
}
vector<int> c_meanfunc::get_meanfunc_param(){
vector<int> meanfunc_param_copy(meanfunc_param);
return meanfunc_param_copy;
}
vector<double> c_meanfunc::get_meanfunc_hyp(){
vector<double> meanfunc_hyp_copy(meanfunc_hyp);
return meanfunc_hyp_copy;
}
int c_meanfunc::get_meanfunc_hyp_num(){
return meanfunc_hyp_num;
} | true |
768f30b90c714e3c20ea73b6c09239a3da3253a6 | C++ | kimsj0302/algorithm_study | /BOJ/2446.cpp | UTF-8 | 418 | 3.328125 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
void print_n(int n) {
for (int i = 0; i < n; i++) {
printf("*");
}
}
void print_b(int n) {
for (int i = 0; i < n; i++) {
printf(" ");
}
}
int main() {
int n;
cin >> n;
for (int i = n; i > 0; i--) {
print_b(n - i);
print_n(i*2-1);
printf("\n");
}
for (int i = 2; i <=n; i++) {
print_b(n - i);
print_n(i * 2 - 1);
printf("\n");
}
} | true |
86a741ec57e6e628aac54974d0f8a1355a857a83 | C++ | LeFiz/Fizplex | /src/rhs_scaler_test.cc | UTF-8 | 984 | 2.703125 | 3 | [] | no_license | #include "rhs_scaler.h"
#include "gtest/gtest.h"
namespace fizplex {
TEST(RhsScalerTest, AlreadyScaledVectorIsUnchanged) {
DVector v = {1.0, -1.0, 0.5, -0.5};
RhsScaler rs(v.max_abs());
rs.scale(v);
EXPECT_EQ(v, DVector({1.0, -1.0, 0.5, -0.5}));
rs.unscale(v);
EXPECT_EQ(v, DVector({1.0, -1.0, 0.5, -0.5}));
}
TEST(RhsScalerTest, LargerVectorIsChanged) {
DVector v = {6.0, -3.0};
RhsScaler rs(v.max_abs());
rs.scale(v);
EXPECT_EQ(v, DVector({1.0, -0.5}));
rs.unscale(v);
EXPECT_EQ(v, DVector({6.0, -3.0}));
}
TEST(RhsScalerTest, VectorNearZeroIsChanged) {
DVector v = {0.5, -0.01};
RhsScaler rs(v.max_abs());
rs.scale(v);
EXPECT_EQ(v, DVector({1.0, -0.02}));
rs.unscale(v);
EXPECT_EQ(v, DVector({0.5, -0.01}));
}
TEST(RhsScalerTest, ScalarScaling) {
DVector v = {6.0, -3.0};
RhsScaler rs(v.max_abs());
double d = -18.6;
rs.scale(d);
EXPECT_DOUBLE_EQ(-3.1, d);
rs.unscale(d);
EXPECT_DOUBLE_EQ(-18.6, d);
}
} // namespace fizplex
| true |
b0027eef65aa450bf156e7620ccb066c26ac7411 | C++ | igokul95/country_state_city_selection | /country_state_citiy_selection/country.h | UTF-8 | 840 | 2.859375 | 3 | [] | no_license | #ifndef COUNTRY_H
#define COUNTRY_H
#include <QObject>
#include <QVector>
#include "state.h"
#include "city.h"
struct CountryItem {
QString name;
States* states;
City* cities;
};
class Countries : public QObject
{
Q_OBJECT
Q_PROPERTY(int activeCountry READ activeCountry WRITE activeCountry)
Q_PROPERTY(States* statesOfActiveCountry READ statesOfActiveCountry)
Q_PROPERTY(City* citiesOfActiveCountry READ citiesOfActiveCountry)
public:
explicit Countries(QObject *parent = nullptr);
QList<CountryItem*> items() const;
int activeCountry() const;
void activeCountry(int currentCountry);
States* statesOfActiveCountry() const;
City* citiesOfActiveCountry() const;
signals:
public slots:
private:
QList<CountryItem*> _countries;
int _activeCountry;
};
#endif // COUNTRY_H
| true |
f9a6f1ab80d93e4cad7ea4825f59642def94d3b8 | C++ | Oscarntnz/IG | /P2/malla.cc | UTF-8 | 10,384 | 2.8125 | 3 | [] | no_license | #include "aux.h"
#include "malla.h"
// *****************************************************************************
//
// Clase Malla3D
//
// *****************************************************************************
Malla3D::~Malla3D(){
v.clear();
f.clear();
a.clear();
a_2.clear();
c_i.clear();
c_d.clear();
c_p.clear();
c_l.clear();
c_a.clear();
c_a_2.clear();
}
// Visualización en modo inmediato con 'glDrawElements'
void Malla3D::draw_ModoInmediato()
{
// visualizar la malla usando glDrawElements,
// habilitar uso de un array de vértices y de colores
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
// indicar el formato y la dirección de memoria del array de vértices
// (son tuplas de 3 valores float, sin espacio entre ellas)
glVertexPointer(3, GL_FLOAT, 0, v.data());
glColorPointer(3, GL_FLOAT, 0, c_i.data());
glPointSize(5.0);
// visualizar, indicando: tipo de primitiva, número de índices,
// tipo de los índices, y dirección de la tabla de índices
if(modos_visualizacion[ModoVisualizacion::SOLIDO]){
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
dibuja(f);
}
if(modos_visualizacion[ModoVisualizacion::PUNTOS]){
glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
glColorPointer(3, GL_FLOAT, 0, c_p.data());
dibuja(f);
}
if(modos_visualizacion[ModoVisualizacion::LINEAS]){
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glColorPointer(3, GL_FLOAT, 0, c_l.data());
dibuja(f);
}
if(modos_visualizacion[ModoVisualizacion::AJEDREZ]){
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glColorPointer(3, GL_FLOAT, 0, c_a.data());
dibuja(a);
glColorPointer(3, GL_FLOAT, 0, c_a_2.data());
dibuja(a_2);
}
// deshabilitar array de vértices
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
}
// -----------------------------------------------------------------------------
// Visualización en modo diferido con 'glDrawElements' (usando VBOs)
void Malla3D::draw_ModoDiferido()
{
if(id_vbo_ver == 0)
id_vbo_ver = CrearVBO(GL_ARRAY_BUFFER, v.size()*3*sizeof(Tupla3f), v.data());
if(id_vbo_tri == 0)
id_vbo_tri = CrearVBO(GL_ELEMENT_ARRAY_BUFFER, f.size()*sizeof(Tupla3i), f.data());
if(id_vbo_aj1 == 0)
id_vbo_aj1 = CrearVBO(GL_ELEMENT_ARRAY_BUFFER, a.size()*sizeof(Tupla3i), a.data());
if(id_vbo_aj2 == 0)
id_vbo_aj2 = CrearVBO(GL_ELEMENT_ARRAY_BUFFER, a_2.size()*sizeof(Tupla3i), a_2.data());
if(id_vbo_col == 0)
id_vbo_col = CrearVBO(GL_ARRAY_BUFFER, c_d.size()*sizeof(Tupla3f), c_d.data());
if(id_vbo_pun == 0)
id_vbo_pun = CrearVBO(GL_ARRAY_BUFFER, c_p.size()*sizeof(Tupla3f), c_p.data());
if(id_vbo_lin == 0)
id_vbo_lin = CrearVBO(GL_ARRAY_BUFFER, c_l.size()*sizeof(Tupla3f), c_l.data());
if(id_vbo_ca1 == 0)
id_vbo_ca1 = CrearVBO(GL_ARRAY_BUFFER, c_a.size()*sizeof(Tupla3f), c_a.data());
if(id_vbo_ca2 == 0)
id_vbo_ca2 = CrearVBO(GL_ARRAY_BUFFER, c_a_2.size()*sizeof(Tupla3f), c_a_2.data());
// especificar localización y formato de la tabla de vértices, habilitar tabla
glBindBuffer(GL_ARRAY_BUFFER, id_vbo_ver); // activar VBO de vértices
glVertexPointer(3, GL_FLOAT, 0, 0); // especifica formato y offset (=0)
glBindBuffer(GL_ARRAY_BUFFER , 0); // desactivar VBO de vértices.
glEnableClientState(GL_VERTEX_ARRAY); // habilitar tabla de vértices
glPointSize(5.0);
// especificar localización y formato de la tabla de colores, habilitar tabla
if(modos_visualizacion[ModoVisualizacion::SOLIDO]){
glBindBuffer(GL_ARRAY_BUFFER, id_vbo_col); // activar VBO de colores
glColorPointer(3, GL_FLOAT, 0, 0); // especifica formato y offset (=0)
glBindBuffer(GL_ARRAY_BUFFER , 0); // desactivar VBO de colores.
glEnableClientState(GL_COLOR_ARRAY); // activar tabla de colores
// visualizar triángulos con glDrawElements (puntero a tabla == 0)
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
dibuja_dif(f, id_vbo_tri);
}
if(modos_visualizacion[ModoVisualizacion::PUNTOS]){
glBindBuffer(GL_ARRAY_BUFFER, id_vbo_pun); // activar VBO de colores
glColorPointer(3, GL_FLOAT, 0, 0); // especifica formato y offset (=0)
glBindBuffer(GL_ARRAY_BUFFER , 0); // desactivar VBO de colores.
glEnableClientState(GL_COLOR_ARRAY); // activar tabla de colores
// visualizar triángulos con glDrawElements (puntero a tabla == 0)
glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
dibuja_dif(f, id_vbo_tri);
}
if(modos_visualizacion[ModoVisualizacion::LINEAS]){
glBindBuffer(GL_ARRAY_BUFFER, id_vbo_lin); // activar VBO de colores
glColorPointer(3, GL_FLOAT, 0, 0); // especifica formato y offset (=0)
glBindBuffer(GL_ARRAY_BUFFER , 0); // desactivar VBO de colores.
glEnableClientState(GL_COLOR_ARRAY); // activar tabla de colores
// visualizar triángulos con glDrawElements (puntero a tabla == 0)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
dibuja_dif(f, id_vbo_tri);
}
if(modos_visualizacion[ModoVisualizacion::AJEDREZ]){
glBindBuffer(GL_ARRAY_BUFFER, id_vbo_ca1); // activar VBO de colores
glColorPointer(3, GL_FLOAT, 0, 0); // especifica formato y offset (=0)
glBindBuffer(GL_ARRAY_BUFFER , 0); // desactivar VBO de colores.
glEnableClientState(GL_COLOR_ARRAY); // activar tabla de colores
// visualizar triángulos con glDrawElements (puntero a tabla == 0)
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
dibuja_dif(f, id_vbo_aj1);
glBindBuffer(GL_ARRAY_BUFFER, id_vbo_ca2); // activar VBO de colores
glColorPointer(3, GL_FLOAT, 0, 0); // especifica formato y offset (=0)
glBindBuffer(GL_ARRAY_BUFFER , 0); // desactivar VBO de colores.
// visualizar triángulos con glDrawElements (puntero a tabla == 0)
dibuja_dif(f, id_vbo_aj2);
}
// desactivar uso de array de vértices
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
}
// -----------------------------------------------------------------------------
// Función de visualización de la malla,
// puede llamar a draw_ModoInmediato o bien a draw_ModoDiferido
void Malla3D::draw()
{
if(visible){
if(modo_dibujo == ModoDibujado::INMEDIATO)
draw_ModoInmediato();
else if(modo_dibujo == ModoDibujado::DIFERIDO)
draw_ModoDiferido();
}
}
GLuint Malla3D::CrearVBO(GLuint tipo_vbo, GLuint tamanio_bytes, GLvoid * puntero_ram)
{
GLuint id_vbo; // resultado: identificador de VBO
glGenBuffers(1, & id_vbo); // crear nuevo VBO, obtener identificador (nunca 0)
glBindBuffer(tipo_vbo , id_vbo ); // activar el VBO usando su identificador
// esta instrucción hace la transferencia de datos desde RAM hacia GPU
glBufferData(tipo_vbo, tamanio_bytes, puntero_ram, GL_STATIC_DRAW);
glBindBuffer (tipo_vbo, 0); // desactivación del VBO (activar 0)
return id_vbo ; // devolver el identificador resultado
}
void Malla3D::dibuja(std::vector<Tupla3i> v){
glDrawElements(GL_TRIANGLES, v.size()*3, GL_UNSIGNED_INT, v.data());
}
void Malla3D::dibuja_dif(std::vector<Tupla3i> v, GLuint id){
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); // activar VBO de triángulos
glDrawElements(GL_TRIANGLES, 3*f.size (), GL_UNSIGNED_INT, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER , 0);
}
void Malla3D::cambiar_visualizacion(ModoVisualizacion modo){
if(modo != ModoVisualizacion::AJEDREZ){
modos_visualizacion[ModoVisualizacion::AJEDREZ] = false;
modos_visualizacion[modo] = !modos_visualizacion[modo];
}
else{
modos_visualizacion[ModoVisualizacion::PUNTOS] = false;
modos_visualizacion[ModoVisualizacion::LINEAS] = false;
modos_visualizacion[ModoVisualizacion::SOLIDO] = false;
modos_visualizacion[modo] = !modos_visualizacion[modo];
}
}
void Malla3D::mover(Tupla3f vector_despl){
for(auto it = v.begin(); it != v.end(); ++it)
*it = *it + vector_despl;
}
void Malla3D::escalar(float factor){
for(auto it = v.begin(); it != v.end(); ++it)
*it = *it * factor;
}
void Malla3D::rellenar_v_colores(){
reserva_espacio();
std::fill(c_i.begin(), c_i.end(), color_i);
std::fill(c_d.begin(), c_d.end(), color_d);
std::fill(c_p.begin(), c_p.end(), color_lineas);
std::fill(c_l.begin(), c_l.end(), color_puntos);
std::fill(c_a.begin(), c_a.end(), color_ajedrez_1);
std::fill(c_a_2.begin(), c_a_2.end(), color_ajedrez_2);
}
void Malla3D::reserva_espacio(){
c_i.clear(); c_d.clear(); c_p.clear();
c_l.clear(); c_a.clear(); c_a_2.clear();
c_i.resize(v.size()); c_d.resize(v.size());
c_p.resize(v.size()); c_l.resize(v.size());
c_a.resize(f.size()); c_a_2.resize(f.size());
}
void Malla3D::rellenar_v_ajedrez(){
a.clear();
a_2.clear();
//Inicializacion de las tablas para el modo ajedrez
unsigned int i;
auto it = f.begin();
for(i = 0; it != f.end(); ++i, ++it){
if(i%2 == 0)
a.push_back(*it);
else
a_2.push_back(*it);
}
}
void Malla3D::elimina_vbo(){
// Si existen los buffer, los elimina pasa actualizar las nuevas caras, vertices o colores
if(id_vbo_ver != 0 && id_vbo_tri != 0 && id_vbo_col != 0 && id_vbo_aj1 != 0 &&
id_vbo_aj2 != 0 && id_vbo_pun != 0 && id_vbo_lin != 0 && id_vbo_ca1 != 0 && id_vbo_ca2 != 0){
glDeleteBuffers(N_VBO, &id_vbo_ver);
id_vbo_ver = 0, // id de VBO de vertices
id_vbo_tri = 0, // id de VBO de triangulos
id_vbo_col = 0, // id de VBO de colores
id_vbo_aj1 = 0, // id de VBO de mitad de los triangulos ajedrez
id_vbo_aj2 = 0, // id de VBO de otra mitad de los triangulos ajedrez
id_vbo_pun = 0, // id de VBO de color de puntos
id_vbo_lin = 0, // id de VBO de color de lineas
id_vbo_ca1 = 0, // id de VBO de color de ajedrez 1
id_vbo_ca2 = 0; // id de VBO de color de ajedrez 2
}
} | true |
f00e312ac4d7683dee44b30e8d43e85b27bc714e | C++ | asdlei99/public-note | /c&cpp/qt/learnQt2/16/mySelection/spinbxdelegate.h | UTF-8 | 1,694 | 2.734375 | 3 | [] | no_license | #ifndef SPINBXDELEGATE_H
#define SPINBXDELEGATE_H
#include <QItemDelegate>
#include <QSpinBox>
class SpinBxDelegate : public QItemDelegate
{
public:
SpinBxDelegate(QWidget *parent=0):QItemDelegate(parent){}
//view利用该委托函数进行编辑器的创建, view会自动销毁编辑器的指针
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const{
QSpinBox *editor = new QSpinBox(parent);
editor->setMinimum(0);
editor->setMaximum(100);
return editor;
}
//为编辑器设置数据
void setEditorData(QWidget *editor, const QModelIndex &index) const{
int value = index.model()->data(index, Qt::EditRole).toInt(); //获取当前的数据
QSpinBox *spinBox = static_cast<QSpinBox*>(editor); //获取编辑器指针,且强制转换为已知的类型.
spinBox->setValue(value); //为编辑器设置数据
}
//将数据写入到模型, 标准的QItemDelegate在完成编辑后会发射closeEditor信号来告知视图,视图确保编辑器部件被关闭和销毁
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const{
QSpinBox *spinBox = static_cast<QSpinBox*>(editor); //获取编辑器指针,且强制转换为已知的类型.
spinBox->interpretText();
int value = spinBox->value();
model->setData(index, value, Qt::EditRole);
}
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index){
editor->setGeometry(option.rect);
}
};
#endif // SPINBXDELEGATE_H
| true |
7d361d7f0018d95309de4cfa68ece5ef27cd9f9b | C++ | antonskvortsov10/Adventure-game | /Adv Proj/AdvProj/hero.cpp | UTF-8 | 1,950 | 2.859375 | 3 | [] | no_license | #include "hero.h"
void Hero::setMoney(int num)
{
money += num;
emit moneyChanged(money);
}
void Hero::setHealth(int num)
{
health += num;
if (health <= 0)
{
this->healthChanged(0);
emit heroDead();
emit hero_dead();
}
else
emit healthChanged(health);
}
void Hero::move(Directions direction)
{
currentRoom = (*maze)[currentRoom].neighbourRooms[direction];
emit hero_moved(currentRoom);
}
void Hero::addItem(shared_ptr<Item> items)
{
beginResetModel();
inventory.append(items);
endResetModel();
//emit inventory_changed(inventory);
}
QVariant Hero::data(const QModelIndex &index, int role) const
{
if(role == Qt::DisplayRole)
return inventory[index.row()]->name;
if(role == Qt::ToolTipRole)
return inventory[index.row()]->description;
return QVariant();
}
int Hero::rowCount(const QModelIndex &parent) const
{
return inventory.size();
}
void Hero::useItem(const QModelIndex index)
{
this->inventory[index.row()]->consume(this);
beginResetModel();
if (this->inventory[index.row()]->useOnce() == true)
inventory.removeAt(index.row());
endResetModel();
}
bool Hero::checkMoney(int num)
{
if (money-num<0) return false;
return true;
}
int Hero::getDamage()
{
int damage=0;
QList<shared_ptr<Item>> items=this->getItems();
for (int i=0; i<items.size(); i++)
if (items[i]->type=="weapon")
if (damage<items[i]->getDamage())
damage=items[i]->getDamage();
return damage;
}
int Hero::getShield()
{
int shield=0;
QList<shared_ptr<Item>> items=this->getItems();
for (int i=0; i<items.size(); i++)
if (items[i]->type=="shield")
if (shield<items[i]->getShield())
shield=items[i]->getShield();
return shield;
}
| true |
53a2f9aa27434277c75a084de443c60ae5267e86 | C++ | liangzelang/CPP_Primer_Plus | /chapter_7/ex7.8b/ex7.8b/main.cpp | UTF-8 | 713 | 3.765625 | 4 | [] | no_license | #include <iostream>
const int Seasons = 4;
const char * Sname[4] = {"Spring", "Summer", "Fall", "Winter"};
void fill(double *);
void show(const double *);
struct Expense
{
double ar[Seasons];
};
int main()
{
using namespace std;
Expense expense;
fill(expense.ar);
show(expense.ar);
system("pause");
return 0;
}
void fill(double * ar)
{
using namespace std;
for(int i = 0; i <Seasons; i++)
{
cout << Sname[i] << " expense : " << endl;
cin >> ar[i];
if(!cin)
{
cin.clear();
cout << "Please input right number" << endl;
break;
}
}
}
void show(const double * ar)
{
using namespace std;
for(int i = 0; i< Seasons; i++)
{
cout << Sname[i] << " expense : " << ar[i] << ". \n";
}
} | true |
e459b142b7ae857bc5a21bd1143a052f5676265f | C++ | Scrumplesplunge/kano | /src/kano/code.cc | UTF-8 | 1,709 | 2.734375 | 3 | [] | no_license | export module kano.code;
export import <variant>;
export import <vector>;
export namespace kano::code {
enum class builtin_type {
boolean,
int32,
};
struct pointer_type;
struct function_type;
using type_type = std::variant<builtin_type, pointer_type, function_type>;
struct type {
template <typename T> type(T&& value);
std::unique_ptr<type_type> value;
};
struct pointer_type { type pointee; };
struct function_type {
type return_type;
std::vector<type> parameters;
};
template <typename T>
type::type(T&& value) : value(new type_type{std::forward<T>(value)}) {}
enum class symbol {};
using literal = std::variant<bool, std::byte, std::int32_t>;
struct global { symbol symbol; };
struct local { int offset; };
struct dereference;
struct add;
struct sub;
using expression_type =
std::variant<literal, global, local, dereference, add, sub>;
struct expression {
template <typename T> expression(type* type, T&& value);
type* type;
std::unique_ptr<expression_type> value;
};
struct unop {
unop(expression inner) : inner(std::move(inner)) {}
expression inner;
};
struct dereference : unop { using unop::unop; };
struct binop {
binop(expression left, expression right)
: left(std::move(left)), right(std::move(right)) {}
expression left, right;
};
struct add : binop { using binop::binop; };
struct sub : binop { using binop::binop; };
template <typename T>
expression::expression(struct type* type, T&& value)
: type(type), value(new expression_type{std::forward<T>(value)}) {}
struct label { symbol symbol; };
struct jump { symbol symbol; };
struct jumpc { expression cond; symbol symbol; };
struct retw { expression value; };
} // namespace kano::code
| true |
f0d4704500aac5c1c155b6af450769fd32768bff | C++ | andyspb/cpp-test | /src/lge/antipattern.h | UTF-8 | 559 | 2.65625 | 3 | [] | no_license | /*
* test_antipattern.h
*
* Created on: Jan 15, 2016
* Author: andy
*/
#ifndef SRC_LGE_ANTIPATTERN_H_
#define SRC_LGE_ANTIPATTERN_H_
#include <stdio.h>
namespace anti_pattern {
class Base {
public:
int* pointer_to_data_;
};
class Derived : public Base {
public:
Derived() {
data_ = 10;
pointer_to_data_ = &data_;
}
private:
int data_;
};
TEST_RESULT test() {
Derived d;
*d.pointer_to_data_ = 20;
printf("%d\n", *d.pointer_to_data_);
RETURN_OK();
}
} // namespace anti_pattern
#endif /* SRC_LGE_ANTIPATTERN_H_ */
| true |
51415160f69c882957e68debb61e72a26534c02c | C++ | dotkt/aDLL | /dlldiscovery/loadintomemory.cpp | UTF-8 | 1,399 | 2.921875 | 3 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | #include "adll.h"
/*
** LoadIntoMemory() is the function that loads the image of the executable or DLL
** that is going to be analyzed in the search of imported DLLs. This function returns
** the pointer that is pointing to the begining of the image.
*/
LPVOID LoadIntoMemory(LPCWSTR EPath)
{
HANDLE hFile;
PVOID virtualptr;
DWORD byteread, size;
PIMAGE_DOS_HEADER dosHeader;
// Open the file
hFile = CreateFile(
EPath,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if (hFile == INVALID_HANDLE_VALUE)
{
PrintError("LoadIntoMemory - CreateFile()");
return NULL;
}
// Load the image
size = GetFileSize(hFile, NULL);
virtualptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
if (!ReadFile(hFile, virtualptr, size, &byteread, NULL))
{
PrintError("LoadIntoMemory - ReadFile()");
CloseHandle(hFile);
return NULL;
}
// First bytes of PE belongs to the MS_DOS section
dosHeader = (PIMAGE_DOS_HEADER)virtualptr;
// Check if loaded file is an executable
if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
{
printf("[!] ERROR: Selected file is not a windows executable\n");
CloseHandle(hFile);
return NULL;
}
CloseHandle(hFile);
return virtualptr;
} | true |
a762e0e5211bf1cba9744fc7b29fa5915f0bb8c9 | C++ | biafrag/Sistemas-Reativos---INF1350 | /Tarefa3_2/app/event_driven.ino | UTF-8 | 1,337 | 2.515625 | 3 | [] | no_license | #include "event_driven.h"
#include "app.h"
#include "pindefs.h"
bool debounce[3] = {true,true,true};
bool lastState[3] = {HIGH,HIGH,HIGH};
float timeDebounce[3] = {600,600,600};
bool buttonsUsed[3]= {false,false,false};
bool stateButton = false;
int buttons[3] = {BUT1,BUT2,BUT3};
unsigned long old = 0;
void button_listen (int pin)
{
if(pin == BUT1)
{
buttonsUsed[0] = true;
}
else if (pin == BUT2)
{
buttonsUsed[1] = true;
}
else
{
buttonsUsed[2] = true;
}
}
void timer_set (int ms)
{
}
void setup()
{
pinMode(BUT1,INPUT_PULLUP);
pinMode(BUT2,INPUT_PULLUP);
pinMode(BUT3,INPUT_PULLUP);
pinMode(LED1,OUTPUT);
button_changed(BUT1,HIGH) ;
Serial.begin(9600);
appinit();
}
bool bouncing(float timeDebounce)
{
if(millis() - timeDebounce >= 500)
{
return true;
}
return false;
}
void loop()
{
for(int i = 0; i < 3; i++)
{
debounce[i] = bouncing(timeDebounce[i]);
if(debounce[i])
{
stateButton = digitalRead(buttons[i]);
if(buttonsUsed[i] && stateButton != lastState[i])
{
button_changed(buttons[i],stateButton) ;
timeDebounce[i] = millis();
debounce[i] = false;
}
}
}
unsigned long now = millis();
if(now >= old+timee)
{
old = now;
timer_expired();
}
}
| true |
cadc336c7b605d4eb9236363d8004266e70301a4 | C++ | C6H8O7/DirectX-animation | /DirectXAnim/Sprite.h | UTF-8 | 1,007 | 2.609375 | 3 | [] | no_license | /**
* Header Sprite
*
* @author Fabsther
* @since 03/05/2010
* @version 1.0
*/
#ifndef SPRITE__H
#define SPRITE__H
#include <d3dx9.h>
#include <d3dx9tex.h>
#include "helper.h"
class Sprite
{
public:
LPD3DXSPRITE m_pSprite;
LPDIRECT3DTEXTURE9 m_pTexture;
RECT *m_pRect;
D3DXVECTOR2 *m_pCenter;
float m_fRotation;
D3DXVECTOR2 *m_pScaleCenter;
float m_fScaleRotation;
D3DXVECTOR2 *m_pScale;
D3DXVECTOR2 m_Position;
D3DCOLOR m_Color;
LPDIRECT3DDEVICE9 m_pD3DDevice;
public:
Sprite( LPDIRECT3DDEVICE9 _Device );
~Sprite();
void Display();
void SetPosition(float _x, float _y);
void SetTexture(LPDIRECT3DTEXTURE9 _pTexture);
void SetRectangle(LONG _x, LONG _y, LONG _w, LONG _h);
void SetCenter(float _x, float _y);
void SetRotation(float _rotation);
void SetScaleCenter(float _x, float _y);
void SetScale(float _x, float _y);
void SetColor(UCHAR _r, UCHAR _g, UCHAR _b, UCHAR _a);
void GetPosition(float *_x, float *_y);
};
#endif //SPRITE__H | true |
5706d22b7e485247c242ef744a86d46160fa093b | C++ | ms303956362/myexercise | /Cpp/cppprimer/1/test.cpp | UTF-8 | 483 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <functional>
class Defer {
// func
std::function<void(void)> f_;
public:
Defer(std::function<void(void)>& f): f_(f) {}
~Defer() {
f_();
}
};
void test() {
int a = 0;
std::function<void(void)> f = [&]() {
std::cout << "[end]: a=" << a << std::endl;
};
Defer d{f};
std::cout << "[begin] a=" << a << std::endl;
a = a + 1;
}
int main(int argc, char const *argv[])
{
test();
return 0;
}
| true |
5170cb09e9c3c001dd08cbd2582d894aec9bc24f | C++ | Hrishikesh-Thakkar/Competitive-Programming | /108A.cpp | UTF-8 | 714 | 2.640625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
if(s[0]=='0' && (s[1]>='6' && s[1]<='9'))
cout<<"10:01"<<endl;
else if(s[0]=='1' && (s[1]>='6' && s[1]<='9'))
cout<<"20:02"<<endl;
else
{
int sec=s[1]-'0';
int first=(s[1]-s[3]);
int second=(s[0]-s[4]);
sec++;
if(s[0]=='0' && s[1]=='5' && s[3]=='5')
cout<<"10:01"<<endl;
else if(s[0]=='1' && s[1]=='5' && s[3]=='5')
cout<<"20:02"<<endl;
else if(s[0]=='2' && s[1]=='3' && s[3]=='3' &&s[4]=='2')
cout<<"00:00"<<endl;
else if(first==0 && second)
cout<<s[0]<<s[1]<<":"<<s[1]<<s[0];
else cout<<s[0]<<sec<<":"<<sec<<s[0];
//cout<<s[3]-s[1]<<" "<<s[4]-s[0];
}
return 0;
} | true |
5bea059cdd5c78dffa71d79cee3afb9035491e05 | C++ | Augusto-Salda/Algoritmos_y_Estructura_de_datos | /Pila_Dinámica.cpp | UTF-8 | 2,493 | 3.703125 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct Puntero{
int Dato;
Puntero *Sig;
};
class CPila{
private:
Puntero *Temp;
Puntero *X;
public:
void ingresar(int);
void sacar();
bool vacia();
void imprimir();
int etope();
CPila();
~CPila();
};
CPila::CPila(){
Temp=NULL;
X=NULL;
}
void CPila::ingresar(int Dato){
int Dat;
X = new Puntero;
cout<<"Dato: ";
cin>>Dat;
X -> Dato=Dat;
X -> Sig=Temp;
Temp = X;
cout<<"El dato se guardo correctamente: ";
cout<<Temp->Dato<<endl<<endl;
}
void CPila::sacar(){
if(vacia()==true){
cout<<"La pila esta vacia"<<endl<<endl;
}
else{
int Dat;
Puntero *AUX;
AUX=Temp->Sig;
Dat=Temp->Dato;
delete Temp;
Temp=AUX;
cout<<"El elemento que se saco es: "<<Dat<<endl<<endl;
}
}
bool CPila::vacia(){
if(Temp==NULL)
return true;
else
return false;
}
void CPila::imprimir(){
Puntero *AUX;
AUX=Temp;
if (vacia()==true){
cout<<"La pila esta vacia"<<endl;
}
else{
while(Temp!=NULL){
cout<<"| "<< Temp->Dato <<" |"<<endl;
cout<<"_"<<endl;
Temp=Temp->Sig;
}
}
Temp=AUX;
cout<<endl;
}
int CPila::etope(){
if (vacia()==true){
cout<<"La pila esta vacia"<<endl<<endl;
return NULL;
}
else{
return Temp->Dato;
}
}
CPila::~CPila(){
}
int main(){
int Opc,Dat;
CPila Obj1;
do{
cout<<"Ingresar pila ---------> 1"<<endl;
cout<<"Sacar pila ------------> 2"<<endl;
cout<<"Imprimir pila ---------> 3"<<endl;
cout<<"Elemento tope ---------> 4"<<endl;
cout<<"Salir -----------------> 5"<<endl;
cout<<"Elige un opcion: ";
cin>>Opc;
switch (Opc)
{
case 1:
{
Obj1.ingresar(Dat);
}
break;
case 2:
{
Obj1.sacar();
}
break;
case 3:
{
Obj1.imprimir();
}
break;
case 4:
{
int cima;
cima=Obj1.etope();
if(cima!=NULL)
cout<<"El elemento en la cima es: "<<cima<<endl<<endl;
}
break;
case 5:
{
cout<<"Adios"<<endl;
}
break;
default:
{
cout<<"No es una opcion valida"<<endl;
}
}
}
while (Opc!=5);
return 0;
} | true |
4984911e597d423d62b89a9d80b16b61cc4ff543 | C++ | shpp-ekondratyev/cs-b-fractals | /Sierpinski/src/sierpinski.cpp | UTF-8 | 1,389 | 3.453125 | 3 | [] | no_license | /*
* File: sierpinski.cpp
* ---------------------------
*
*/
#include <iostream>
#include "gwindow.h"
#include <cmath>
using namespace std;
/* Function prototypes */
void drawTriangle(GWindow window, GPoint top, double EDGE_LENGTH, int cycleCount);
/* Global variables/constants */
const double EDGE_LENGTH = 314; // size of the triangle side at start
int cycleCount = 0; //start number of triangles in triangle
/* Main program*/
int main() {
GWindow window (800, 600);
GPoint top(window.getWidth() / 2,window.getHeight() / 2-((sqrt(3) * EDGE_LENGTH) / 2) / 2);
drawTriangle (window,top,EDGE_LENGTH,cycleCount);
return 0;
}
void drawTriangle(GWindow window, GPoint top, double EDGE_LENGTH, int cycleCount){
double height = sqrt(3) * EDGE_LENGTH / 2;
double topX = top.getX();
double topY = top.getY();
GPoint left(topX - height,topY + height);
GPoint right(topX + height,topY + height);
window.drawLine(top,left);
window.drawLine(left,right);
window.drawLine(top,right);
if(cycleCount != 10){
GPoint left(topX - height / 2,topY + height / 2);
GPoint right(topX + height / 2,topY + height / 2);
drawTriangle(window,top,EDGE_LENGTH / 2,cycleCount + 1);
drawTriangle(window,left,EDGE_LENGTH / 2,cycleCount + 1);
drawTriangle(window,right,EDGE_LENGTH / 2,cycleCount + 1);
}
}
| true |
de07f3ff1f882e12eb00a4e31343dfca4876b509 | C++ | nazarov-yuriy/contests | /gvzhf/p18/p1889.cpp | UTF-8 | 1,354 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <unordered_map>
#include <set>
using namespace std;
int main() {
int n, id = 0;
cin >> n;
unordered_map<string, int> ids;
int langs[1001];
ids["unknown"] = id++;
for (int i = 0; i < n; i++) {
string str;
cin >> str;
if (!ids.count(str)) ids[str] = id++;
langs[i] = ids[str];
}
int answers = 0;
for (int i = 1; i <= n; i++) {
if (0 == n % i) {
set<int> used;
bool ok = true;
for (int j = 0; j < i; j++) {
int lang = 0;
for (int k = 0; k < n / i; k++) {
if (langs[k + j * n / i]) {
if (lang && lang != langs[k + j * n / i]) {
ok = false;
break;
} else {
lang = langs[k + j * n / i];
}
}
}
if (lang && used.count(lang)) {
ok = false;
} else {
used.insert(lang);
}
if (!ok) break;
}
if (ok) {
answers++;
cout << i << ' ';
}
}
}
if (!answers) cout << "Igor is wrong.";
return 0;
} | true |
66528de09ec0d3cff4e39ed75cc391642dea02cb | C++ | qkrwjdtn1236/C-Language-Algorithm | /소수/4/main.cpp | UHC | 419 | 3.640625 | 4 | [] | no_license | #include <iostream>
//2 100 Ҽ ϰ Ҽ Ȯ ϱ;
using namespace std;
int main() {
int i,j;
int num = 0;
for(i = 2;i<=100;i++)
{
for(j = 2;j<i;j++)
{
if(i%j == 0)
break;
}
if(i == j)
num++;
}
cout<<"2 100 Ҽ : "<<num<<endl;
cout<<"Ҽ Ȯ : "<<(num/99.0)*100<<'%'<<endl;
return 0;
}
| true |
ab460f19ca189fb54d2c5e0506b353710802fa01 | C++ | saswatsk/Comprehensive-C | /STL And DS & Algo/Arrays/Programs/Program to add two numbers stored in a 2 arrays/main.cpp | UTF-8 | 1,452 | 3.71875 | 4 | [] | no_license | // program to add 2 numbers in 2 arrays
#include<iostream>
using namespace std;
// main function to add the arrays
void addArrays(int arr1[], int arr2[], int arr3[], int n1, int n2, int n3)
{
int carry = 0;
int count = 0;
int temp = 0;
// for the entire len of arr3 which is always one more than max(n1, n2)
for(int i = n3 - 1; i >= 0; i--)
{
// cal the value of temp i.e sum of those particular digits
if( n1 <= 0 && n2 <= 0)
temp = carry;
else if(n1<=0 && n2 > 0)
temp = arr2[n2-1]+carry;
else if (n2 <= 0 && n1 > 0)
temp = arr1[n1-1]+carry;
else
temp = (arr1[n1-1]+arr2[n2-1])+carry;
arr3[i] = temp%10;
carry = temp/10;
n1--;
n2--;
}
}
int main() {
// input the both arrays
int n1, n2;
cin >> n1;
int arr1[n1];
for (int i = 0; i < n1; i++)
cin >> arr1[i];
cin >> n2;
int arr2[n2];
for (int i = 0; i < n2; i++)
cin >> arr2[i];
// make a third array w length one greater than the length of bigger array
int n3 = n1 >= n2 ? n1 + 1 : n2 + 1;
int arr3[n3];
addArrays(arr1, arr2, arr3, n1, n2, n3);
// print the arr3 i.e the sum arrays
bool flag = false;
for (int i = 0; i < n3; i++) {
if (arr3[i] != 0)
flag = true;
if (flag)
cout << arr3[i] << ", ";
}
cout << "END" << endl;
} | true |
52c9190d0bfba63448d725f626d1da78777d7df5 | C++ | VictorBusk/E3PRJ3-Gruppe1 | /DevKit/Semesterprojekt3/plannerdialog.cpp | UTF-8 | 1,570 | 2.75 | 3 | [] | no_license | /*!
* @file light.cpp
* @brief Displaying and managing dialog-UI input
* @author Victor Busk (201409557@post.au.dk)
*/
#include "plannerdialog.h"
#include "ui_plannerdialog.h"
#include <QWidget>
/*!
* @brief Sets up dialog startup
* @param[in] parent QWidget UI setup.
* @author Victor Busk (201409557@post.au.dk)
*/
PlannerDialog::PlannerDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::PlannerDialog)
{
ui->setupUi(this);
connect(ui->planLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(lineEdit_textChanged()));
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
ui->planLineEdit->setFocus();
}
/*!
* @brief Set restrictions of textinput and ok-button visibility
* @author Victor Busk (201409557@post.au.dk)
*/
void PlannerDialog::lineEdit_textChanged()
{
ui->planLineEdit->setMaxLength(8);
QString planString = ui->planLineEdit->text();
if (planString.isEmpty()) // If the user has typed enable OK
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
else
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
}
/*!
* @brief Return textinput for futher usage
* @author Victor Busk (201409557@post.au.dk)
*/
QString PlannerDialog::getLineEditText() const
{
QString plan = ui->planLineEdit->text();
return plan;
}
/*!
* @brief Destroys dialog-UI when called
* @author Victor Busk (201409557@post.au.dk)
*/
PlannerDialog::~PlannerDialog()
{
delete ui;
}
/* [] END OF FILE */
| true |
67427d74644f934ea4b0e086e1460234f90a63e8 | C++ | VoyakinH/OOP | /Lab_01/operations.cpp | UTF-8 | 2,447 | 3.09375 | 3 | [] | no_license | #include "operations.h"
//#include <math.h>
//#include "defines.h"
//#include "object.h"
static void move_point(point_t &point, const struct move &mo)
{
point.x += mo.dx;
point.y += mo.dy;
point.z += mo.dz;
return;
}
int move_object(object_t &object, const struct move &mo)
{
int err = check_object(object);
if (err != OK)
return err;
for (int i = 0; i < object.nodes_num; i++)
move_point(object.nodes[i], mo);
return err;
}
static void scale_point(point_t &point, const struct scale &sc)
{
point.x = sc.kx * point.x + sc.xm * (1 - sc.kx);
point.y = sc.ky * point.y + sc.ym * (1 - sc.ky);
point.z = sc.kz * point.z + sc.zm * (1 - sc.kz);
return;
}
int scale_object(object_t &object, const struct scale &sc)
{
int err = check_object(object);
if (err != OK)
return err;
for (int i = 0; i < object.nodes_num; i++)
scale_point(object.nodes[i], sc);
return err;
}
static struct trig count_trig(const struct rotate &ro)
{
struct trig tg;
tg.cos_x = cos(ro.dgx * PI / 180);
tg.cos_y = cos(ro.dgy * PI / 180);
tg.cos_z = cos(ro.dgz * PI / 180);
tg.sin_x = sin(ro.dgx * PI / 180);
tg.sin_y = sin(ro.dgy * PI / 180);
tg.sin_z = sin(ro.dgz * PI / 180);
return tg;
}
// Тут ошибка в логике. Надо создать буферы и работать с ними. тк если поменять в первой строчке
// point.x то потом будет учитываться оно а не начальное.
static void rotate_point(point_t &point, const struct trig &tg, const struct rotate &ro)
{
point.x = ro.xc + (point.x - ro.xc) * tg.cos_z - (point.y - ro.yc) * tg.sin_z;
point.y = ro.yc + (point.x - ro.xc) * tg.sin_z + (point.y - ro.yc) * tg.cos_z;
point.y = ro.yc + (point.y - ro.yc) * tg.cos_x - (point.z - ro.zc) * tg.sin_x;
point.z = ro.zc + (point.z - ro.zc) * tg.cos_x + (point.y - ro.yc) * tg.sin_x;
point.x = ro.xc + (point.x - ro.xc) * tg.cos_y + (point.z - ro.zc) * tg.sin_y;
point.z = ro.zc + (point.z - ro.zc) * tg.cos_y - (point.x - ro.xc) * tg.sin_y;
return;
}
int rotate_object(object_t &object, const struct rotate &ro)
{
int err = check_object(object);
if (err != OK)
return err;
struct trig tg = count_trig(ro);
for (int i = 0; i < object.nodes_num; i++)
rotate_point(object.nodes[i], tg, ro);
return err;
}
| true |
323c716ebf24baec511f311678b1bcebc86431bd | C++ | shtanriverdi/Full-Time-Interviews-Preparation-Process | /Weekly Questions/173. Binary Search Tree Iterator.cpp | UTF-8 | 1,329 | 3.6875 | 4 | [] | no_license | // Question Link ---> https://leetcode.com/problems/binary-search-tree-iterator/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class BSTIterator {
vector<int> sorted;
int iterator, size;
public:
BSTIterator(TreeNode* root) {
iterator = 0;
fillSortedVector(root);
size = sorted.size();
}
void fillSortedVector(TreeNode *cur) {
if (!cur) {
return;
}
fillSortedVector(cur->left);
sorted.push_back(cur->val);
fillSortedVector(cur->right);
}
/** @return the next smallest number */
int next() {
if (hasNext()) {
return sorted[iterator++];
}
return -1;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return iterator < size;
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/ | true |
ca23bd791b7846ed59b54a1ffeed6fa8fc5fd857 | C++ | rafaelacruzmarques/SIN-142---Projeto---Final | /main.cpp | UTF-8 | 586 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include<stdio.h>
#include "funcoes.h"
//define o número de linhas e colunas da matriz de vetores
#define LINHAS 6
#define COLUNAS 1000000
int main()
{
//alocacao das linhas da matriz
int** matriz = (int**) malloc(LINHAS*sizeof(int*));
//alocacao das colunas da matriz
for(int n = 0; n < LINHAS; n++)
matriz[n] = (int*) malloc(COLUNAS*sizeof(int));
if(matriz==NULL)
{
cout<<"Erro ao alocar matriz";
exit(1);
}
executaOrdenacao(matriz);
cout<<"---------------Ordenação Sequencial------------------";
free(matriz);
return 0;
}
| true |
c340b556f24e2f11f7c5236d4c8c797bcb5fd295 | C++ | x4nemi/proyecto_videojuego | /civilizacion.h | UTF-8 | 1,846 | 3.484375 | 3 | [] | no_license | #ifndef CIVILIZACION_H
#define CIVILIZACION_H
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
class Civilizacion{
private:
string nombre;
int x;
int y;
float puntuacion;
public:
Civilizacion();
Civilizacion(const string&, const int&, const int&, const float&);
void setNombre(const string&);
void setX(const int&);
void setY(const int&);
void setPuntuacion(const float&);
string getNombre();
int getX();
int getY();
float getPuntuacion();
friend ostream& operator<<(ostream &out, const Civilizacion &c){
out << left;
out << setw(20) << c.nombre;
out << setw(5) << c.x;
out << setw(5) << c.y;
out << setw(10) << c.puntuacion;
out << endl;
return out;
}
friend istream& operator>>(istream &in, Civilizacion &c){
cout << "Nombre de la Civ: ";
getline(cin, c.nombre);
//cin.ignore();
cout << "Posicion en X: ";
cin >>c.x;
//cin.ignore();
cout << "Posicion en Y: ";
cin >> c.y;
//cin.ignore();
cout << "Puntuacion: ";
cin >> c.puntuacion;
return in;
}
bool operator == (const Civilizacion& c){
return nombre == c.nombre;
}
bool operator == (const Civilizacion& c) const{
return nombre == c.nombre;
}
/*
bool operator > (const Civilizacion& c){
return nombre > c.nombre;
}
bool operator<(const Civilizacion& c) const{
return nombre < c.nombre;
}*/
};
#endif | true |
5a8b26fd1b37c72bf358f341b7814e168211a364 | C++ | alexswin/IntegerRiddleSolver | /main.cpp | UTF-8 | 3,068 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <set>
#include <map>
#include <vector>
#include <cmath>
using namespace std;
/*
Paul and steve are two perfect logicians. They have been told there are two integers x and y such that 1 < x < 1 and x + y < 100, but have not been told what x and y are exactly. Steve is given the value of x + y and Paul is given the value of xy. They then have the following conversation.
Paul: I can't determine the two numbers.
Steve: I knew that.
Paul: Now I can determine them.
Steve: So can I.
What are the two numbers?
*/
set<int> makePrimes(int upToWhat);
int main() {
set<int> primes = makePrimes(2500);
map<int, set<int>> sumsWithProducts;
for (int i = 5; i <= 99; ++i) {
sumsWithProducts[i];
}
//Remove all sums of two primes
for (set<int>::iterator i = primes.begin(); i != primes.end() && *i <= 97; ++i) {
set<int>::iterator j = i;
++j;
while (j != primes.end() && *i + *j < 100) {
sumsWithProducts.erase(*i + *j);
++j;
}
}
//Remove 6
sumsWithProducts.erase(6);
/*for (map<int, set<int>>::iterator i = sumsWithProducts.begin(); i != sumsWithProducts.end(); ++i) {
cout << i->first << " ";
}*/
//Populate vector of possible products for each sum in sumsWithProducts
for (map<int, set<int>>::iterator i = sumsWithProducts.begin(); i != sumsWithProducts.end(); ++i) {
for (int j = 2; j <= (i->first / 2); ++j) {
if (j != (i->first - j)) {
i->second.insert(j * (i->first - j));
}
}
}
map<int, set<int>> productsWithSums;
for (int i = 6; i <= 2352; ++i) {
productsWithSums[i];
}
for (set<int>::iterator i = primes.begin(); i != primes.end(); ++i) {
//Remove all primes
productsWithSums.erase(*i);
//Remove all products of 2 primes, including primes squared
for (set<int>::iterator j = i; j != primes.end(); j++) {
productsWithSums.erase(*i * *j);
}
}
//Remove powers of 2
for (int i = 1; i <= 14; ++i) {
productsWithSums.erase(pow(2,i));
}
//Remove odd numbers
vector<int> removeThese;
for (map<int, set<int>>::iterator i = productsWithSums.begin(); i != productsWithSums.end(); ++i) {
if (i->first % 2 == 1) {
removeThese.push_back(i->first);
}
}
for (int i = 0; i < removeThese.size(); ++i) {
productsWithSums.erase(removeThese[i]);
}
/*for (map<int, set<int>>::iterator i = productsWithSums.begin(); i != productsWithSums.end(); ++i) {
cout << i->first << " ";
}*/
removeThese.clear();
for (map<int, set<int>>::iterator i = productsWithSums.begin(); i != productsWithSums.end(); ++i) {
//If product doesn't have factors that sum to a sum in sums, remove
}
}
set<int> makePrimes(int upToWhat) {
vector<int> primesVector;
primesVector.push_back(2);
for (int i = 3; i <= upToWhat; i += 2) {
int j = 0;
bool isPrime = true;
while (primesVector[j] <= sqrt(i)) {
if (i % primesVector[j] == 0) {
isPrime = false;
break;
}
++j;
}
if (isPrime) {
primesVector.push_back(i);
}
}
set<int> primes;
for (int i = 0; i < primesVector.size(); ++i) {
primes.insert(primesVector[i]);
}
return primes;
} | true |
4171a355a16f32d9d65dc75262cb35ae0e13817a | C++ | liquidmetal/dwa-hacks | /MapLoader.h | UTF-8 | 826 | 2.609375 | 3 | [] | no_license | #pragma once
#include <vector>
#include "Vector.h"
using namespace math;
class MapLoader
{
public:
bool** loadMap(char* filename);
bool** loadVDBMap(char* filename);
Vec2f getStartPosition();
Vec2f getEndPosition();
unsigned int getNumRows();
unsigned int getNumCols();
float** getSDF(); // call this only if loadVDBMap() was called
MapLoader();
std::vector<math::Vec2d> getFishesFromMap();
unsigned int getStartRadius();
unsigned int getEndRadius();
private:
bool** mapData; // Stores the passibility of each block
Vec2f posStart; // The starting point
Vec2f posEnd; // The ending point
float startRadius,endRadius;
bool loaded;
unsigned int numRows, numCols;
float** grid_array;
std::vector<math::Vec2d> mFishPositions;
};
| true |
c99c946069d97a7abb3faa2e93ebc5caae9e6ff9 | C++ | 0xc0dec/solo | /src/solo/lua/SoloLuaMathApi.cpp | UTF-8 | 11,580 | 2.546875 | 3 | [
"Zlib"
] | permissive | /*
* Copyright (c) Aleksey Fedotov
* MIT license
*/
#include "math/SoloRadians.h"
#include "math/SoloDegrees.h"
#include "math/SoloVector2.h"
#include "math/SoloVector3.h"
#include "math/SoloVector4.h"
#include "math/SoloQuaternion.h"
#include "math/SoloMatrix.h"
#include "math/SoloRay.h"
#include "SoloLuaCommon.h"
using namespace solo;
static void registerVector2(CppBindModule<LuaBinding> &module) {
auto binding = BEGIN_CLASS(module, Vector2);
REG_CTOR(binding, float, float);
binding.addProperty("x",
static_cast<float(Vector2::*)()const>(&Vector2::x),
[](Vector2 * v, float val) {
v->x() = val;
});
binding.addProperty("y",
static_cast<float(Vector2::*)()const>(&Vector2::y),
[](Vector2 * v, float val) {
v->y() = val;
});
REG_METHOD(binding, Vector2, isUnit);
REG_METHOD(binding, Vector2, isZero);
REG_METHOD(binding, Vector2, distance);
REG_METHOD(binding, Vector2, length);
REG_METHOD(binding, Vector2, normalized);
REG_METHOD(binding, Vector2, normalize);
REG_METHOD(binding, Vector2, angle);
REG_METHOD(binding, Vector2, clamp);
REG_METHOD(binding, Vector2, dot);
REG_META_METHOD(binding, "__add", [](const Vector2 & v1, const Vector2 & v2) {
return v1 + v2;
});
REG_META_METHOD(binding, "__sub", [](const Vector2 & v1, const Vector2 & v2) {
return v1 - v2;
});
REG_META_METHOD(binding, "__mul", [](const Vector2 & v, float f) {
return v * f;
});
REG_META_METHOD(binding, "__div", [](const Vector2 & v, float f) {
return v / f;
});
REG_META_METHOD(binding, "__unm", [](const Vector2 & v) {
return -v;
});
binding.endClass();
}
static void registerVector3(CppBindModule<LuaBinding> &module) {
auto binding = BEGIN_CLASS(module, Vector3);
REG_CTOR(binding, float, float, float);
binding.addProperty("x",
static_cast<float(Vector3::*)()const>(&Vector3::x),
[](Vector3 * v, float val) {
v->x() = val;
});
binding.addProperty("y",
static_cast<float(Vector3::*)()const>(&Vector3::y),
[](Vector3 * v, float val) {
v->y() = val;
});
binding.addProperty("z",
static_cast<float(Vector3::*)()const>(&Vector3::z),
[](Vector3 * v, float val) {
v->z() = val;
});
REG_METHOD(binding, Vector3, isUnit);
REG_METHOD(binding, Vector3, isZero);
REG_METHOD(binding, Vector3, distance);
REG_METHOD(binding, Vector3, length);
REG_METHOD(binding, Vector3, normalized);
REG_METHOD(binding, Vector3, normalize);
REG_METHOD(binding, Vector3, angle);
REG_METHOD(binding, Vector3, clamp);
REG_METHOD(binding, Vector3, dot);
REG_METHOD(binding, Vector3, cross);
REG_META_METHOD(binding, "__add", [](const Vector3 & v1, const Vector3 & v2) {
return v1 + v2;
});
REG_META_METHOD(binding, "__sub", [](const Vector3 & v1, const Vector3 & v2) {
return v1 - v2;
});
REG_META_METHOD(binding, "__mul", [](const Vector3 & v, float f) {
return v * f;
});
REG_META_METHOD(binding, "__div", [](const Vector3 & v, float f) {
return v / f;
});
REG_META_METHOD(binding, "__unm", [](const Vector3 & v) {
return -v;
});
binding.endClass();
}
static void registerVector4(CppBindModule<LuaBinding> &module) {
auto binding = BEGIN_CLASS(module, Vector4);
REG_CTOR(binding, float, float, float, float);
binding.addProperty("x",
static_cast<float(Vector4::*)()const>(&Vector4::x),
[](Vector4 * v, float val) {
v->x() = val;
});
binding.addProperty("y",
static_cast<float(Vector4::*)()const>(&Vector4::y),
[](Vector4 * v, float val) {
v->y() = val;
});
binding.addProperty("z",
static_cast<float(Vector4::*)()const>(&Vector4::z),
[](Vector4 * v, float val) {
v->z() = val;
});
binding.addProperty("w",
static_cast<float(Vector4::*)()const>(&Vector4::w),
[](Vector4 * v, float val) {
v->w() = val;
});
REG_METHOD(binding, Vector4, isUnit);
REG_METHOD(binding, Vector4, isZero);
REG_METHOD(binding, Vector4, distance);
REG_METHOD(binding, Vector4, length);
REG_METHOD(binding, Vector4, normalized);
REG_METHOD(binding, Vector4, normalize);
REG_METHOD(binding, Vector4, angle);
REG_METHOD(binding, Vector4, clamp);
REG_METHOD(binding, Vector4, dot);
REG_META_METHOD(binding, "__add", [](const Vector4 & v1, const Vector4 & v2) {
return v1 + v2;
});
REG_META_METHOD(binding, "__sub", [](const Vector4 & v1, const Vector4 & v2) {
return v1 - v2;
});
REG_META_METHOD(binding, "__mul", [](const Vector4 & v, float f) {
return v * f;
});
REG_META_METHOD(binding, "__div", [](const Vector4 & v, float f) {
return v / f;
});
REG_META_METHOD(binding, "__unm", [](const Vector4 & v) {
return -v;
});
binding.endClass();
}
static void registerQuaternion(CppBindModule<LuaBinding> &module) {
auto binding = BEGIN_CLASS(module, Quaternion);
REG_CTOR(binding);
binding.addProperty("x",
static_cast<float(Quaternion::*)()const>(&Quaternion::x),
[](Quaternion * v, float val) {
v->x() = val;
});
binding.addProperty("y",
static_cast<float(Quaternion::*)()const>(&Quaternion::y),
[](Quaternion * v, float val) {
v->y() = val;
});
binding.addProperty("z",
static_cast<float(Quaternion::*)()const>(&Quaternion::z),
[](Quaternion * v, float val) {
v->z() = val;
});
binding.addProperty("w",
static_cast<float(Quaternion::*)()const>(&Quaternion::w),
[](Quaternion * v, float val) {
v->w() = val;
});
REG_STATIC_METHOD(binding, Quaternion, fromAxisAngle);
REG_STATIC_METHOD(binding, Quaternion, lerp);
REG_STATIC_METHOD(binding, Quaternion, slerp);
REG_METHOD(binding, Quaternion, isIdentity);
REG_METHOD(binding, Quaternion, isZero);
REG_METHOD(binding, Quaternion, conjugate);
REG_METHOD(binding, Quaternion, invert);
REG_METHOD(binding, Quaternion, inverted);
REG_METHOD(binding, Quaternion, normalize);
REG_METHOD(binding, Quaternion, normalized);
REG_METHOD(binding, Quaternion, toAxisAngle);
REG_META_METHOD(binding, "__mul", [](const Quaternion & q1, const Quaternion & q2) {
return q1 * q2;
});
binding.endClass();
}
static void registerRadians(CppBindModule<LuaBinding> &module) {
auto binding = BEGIN_CLASS(module, Radians);
REG_CTOR(binding, float);
REG_METHOD(binding, Radians, toRawDegrees);
REG_METHOD(binding, Radians, toRawRadians);
REG_FREE_FUNC_AS_STATIC_FUNC_RENAMED(binding, [](const Degrees & d) {
return Radians(d);
}, "fromDegrees");
REG_FREE_FUNC_AS_STATIC_FUNC_RENAMED(binding, [](float d) {
return Radians(Degrees(d));
}, "fromRawDegrees");
REG_META_METHOD(binding, "__unm", [](const Radians & r) {
return -r;
});
REG_META_METHOD(binding, "__add", [](const Radians & r1, const Radians & r2) {
return r1 + r2;
});
REG_META_METHOD(binding, "__sub", [](const Radians & r1, const Radians & r2) {
return r1 - r2;
});
REG_META_METHOD(binding, "__mul", [](const Radians & r, float f) {
return r * f;
});
REG_META_METHOD(binding, "__div", [](const Radians & r, float f) {
return r * f;
});
binding.endClass();
}
static void registerDegrees(CppBindModule<LuaBinding> &module) {
auto binding = BEGIN_CLASS(module, Degrees);
REG_CTOR(binding, float);
REG_METHOD(binding, Degrees, toRawDegrees);
REG_METHOD(binding, Degrees, toRawRadians);
REG_FREE_FUNC_AS_STATIC_FUNC_RENAMED(binding, [](const Radians & d) {
return Degrees(d);
}, "fromRadians");
REG_FREE_FUNC_AS_STATIC_FUNC_RENAMED(binding, [](float r) {
return Degrees(Radians(r));
}, "fromRawRadians");
REG_META_METHOD(binding, "__unm", [](const Degrees & d) {
return -d;
});
REG_META_METHOD(binding, "__add", [](const Degrees & d1, const Degrees & d2) {
return d1 + d2;
});
REG_META_METHOD(binding, "__sub", [](const Degrees & d1, const Degrees & d2) {
return d1 - d2;
});
REG_META_METHOD(binding, "__mul", [](const Degrees & d, float f) {
return d * f;
});
REG_META_METHOD(binding, "__div", [](const Degrees & d, float f) {
return d * f;
});
binding.endClass();
}
static void registerMatrix(CppBindModule<LuaBinding> &module) {
auto binding = BEGIN_CLASS(module, Matrix);
REG_CTOR(binding);
REG_STATIC_METHOD(binding, Matrix, identity);
REG_METHOD(binding, Matrix, isIdentity);
REG_METHOD(binding, Matrix, getDeterminant);
REG_METHOD(binding, Matrix, invert);
REG_METHOD(binding, Matrix, inverted);
REG_METHOD(binding, Matrix, transpose);
REG_METHOD(binding, Matrix, transposed);
REG_STATIC_METHOD(binding, Matrix, createLookAt);
REG_STATIC_METHOD(binding, Matrix, createPerspective);
REG_STATIC_METHOD(binding, Matrix, createOrthographic);
REG_STATIC_METHOD(binding, Matrix, createScale);
REG_STATIC_METHOD(binding, Matrix, createRotationFromQuaternion);
REG_STATIC_METHOD(binding, Matrix, createRotationFromAxisAngle);
REG_STATIC_METHOD(binding, Matrix, createTranslation);
REG_METHOD(binding, Matrix, scale);
REG_METHOD(binding, Matrix, translation);
REG_METHOD(binding, Matrix, rotation);
REG_METHOD(binding, Matrix, upVector);
REG_METHOD(binding, Matrix, downVector);
REG_METHOD(binding, Matrix, leftVector);
REG_METHOD(binding, Matrix, rightVector);
REG_METHOD(binding, Matrix, forwardVector);
REG_METHOD(binding, Matrix, backVector);
REG_METHOD(binding, Matrix, rotateByQuaternion);
REG_METHOD(binding, Matrix, rotateByAxisAngle);
REG_METHOD(binding, Matrix, scaleByScalar);
REG_METHOD(binding, Matrix, scaleByVector);
REG_METHOD(binding, Matrix, translate);
REG_METHOD(binding, Matrix, transformPoint);
REG_METHOD(binding, Matrix, transformDirection);
REG_METHOD(binding, Matrix, transformRay);
REG_METHOD(binding, Matrix, decompose);
REG_META_METHOD(binding, "__mul", [](const Matrix & m1, const Matrix & m2) {
return m1 * m2;
});
binding.endClass();
}
static void registerRay(CppBindModule<LuaBinding> &module) {
auto binding = BEGIN_CLASS(module, Ray);
REG_CTOR(binding, const Vector3 &, const Vector3 &);
REG_METHOD(binding, Ray, origin);
REG_METHOD(binding, Ray, setOrigin);
REG_METHOD(binding, Ray, direction);
REG_METHOD(binding, Ray, setDirection);
binding.endClass();
}
void registerMathApi(CppBindModule<LuaBinding> &module) {
registerRadians(module);
registerDegrees(module);
registerVector2(module);
registerVector3(module);
registerVector4(module);
registerQuaternion(module);
registerMatrix(module);
registerRay(module);
}
| true |
32c0cc639275d214f7914f1cf2163ae91d578c64 | C++ | benjaminulmer/subdivision-framework | /skeleton/InputHandler.cpp | UTF-8 | 2,889 | 2.8125 | 3 | [] | no_license | #include "InputHandler.h"
Camera* InputHandler::camera;
RenderEngine* InputHandler::renderEngine;
Program* InputHandler::program;
int InputHandler::mouseOldX;
int InputHandler::mouseOldY;
bool InputHandler::moved;
// Must be called before processing any SDL2 events
void InputHandler::setUp(Camera* camera, RenderEngine* renderEngine, Program* program) {
InputHandler::camera = camera;
InputHandler::renderEngine = renderEngine;
InputHandler::program = program;
}
void InputHandler::pollEvent(SDL_Event& e) {
if (e.type == SDL_KEYDOWN || e.type == SDL_KEYUP) {
InputHandler::key(e.key);
}
else if (e.type == SDL_MOUSEBUTTONDOWN) {
moved = false;
}
else if (e.type == SDL_MOUSEBUTTONUP) {
InputHandler::mouse(e.button);
}
else if (e.type == SDL_MOUSEMOTION) {
InputHandler::motion(e.motion);
}
else if (e.type == SDL_MOUSEWHEEL) {
InputHandler::scroll(e.wheel);
}
else if (e.type == SDL_WINDOWEVENT) {
InputHandler::reshape(e.window);
}
else if (e.type == SDL_QUIT) {
SDL_Quit();
exit(0);
}
}
// Callback for key presses
void InputHandler::key(SDL_KeyboardEvent& e) {
auto key = e.keysym.sym;
if (e.state == SDL_PRESSED) {
if (key == SDLK_f) {
renderEngine->toggleFade();
}
else if (key == SDLK_ESCAPE) {
SDL_Quit();
exit(0);
}
}
}
// Callback for mouse button presses
void InputHandler::mouse(SDL_MouseButtonEvent& e) {
mouseOldX = e.x;
mouseOldY = e.y;
}
// Callback for mouse motion
void InputHandler::motion(SDL_MouseMotionEvent& e) {
int dx, dy;
dx = e.x - mouseOldX;
dy = e.y - mouseOldY;
// left mouse button moves camera
if (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT)) {
program->updateRotation(mouseOldX, e.x, mouseOldY, e.y, false);
}
else if (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_MIDDLE)) {
program->updateRotation(mouseOldX, e.x, mouseOldY, e.y, true);
}
// Update current position of the mouse
int width, height;
SDL_Window* window = SDL_GetWindowFromID(e.windowID);
SDL_GetWindowSize(window, &width, &height);
int iX = e.x;
int iY = height - e.y;
//program->setMousePos(iX, iY);
mouseOldX = e.x;
mouseOldY = e.y;
}
// Callback for mouse scroll
void InputHandler::scroll(SDL_MouseWheelEvent& e) {
int dy;
dy = e.x - e.y;
const Uint8 *state = SDL_GetKeyboardState(0);
if (state[SDL_SCANCODE_U]) {
//program->updateRadialBounds(RadialBound::MAX, -dy);
}
else if (state[SDL_SCANCODE_J]) {
//program->updateRadialBounds(RadialBound::MIN, -dy);
}
else if (state[SDL_SCANCODE_M]) {
//program->updateRadialBounds(RadialBound::BOTH, -dy);
}
else {
program->updateCameraDist(-dy);
//camera->updateZoom(dy);
}
}
// Callback for window reshape/resize
void InputHandler::reshape(SDL_WindowEvent& e) {
if (e.event == SDL_WINDOWEVENT_RESIZED) {
renderEngine->setWindowSize(e.data1, e.data2);
program->setWindowSize(e.data1, e.data2);
}
}
| true |
31e358677fe37c9e80f634e26299eaf51c693e59 | C++ | ashish1500616/Programming | /4.Interview-Bit/Searching/kth_smallest_element_in_an_array.cpp | UTF-8 | 687 | 3.34375 | 3 | [] | no_license |
// Unsorted Read Only Array Find the Kth Minimum.
bool helper(const vector<int> &A, int v, int B)
{
int cnt = 0;
for (auto x : A)
{
if (x <= v)
{
cnt++;
}
}
if (cnt >= B)
{
return 1;
}
return 0;
}
int Solution::kthsmallest(const vector<int> &A, int B)
{
int mine = *min_element(A.begin(), A.end());
int maxe = *max_element(A.begin(), A.end());
int l = mine - 1;
int h = maxe;
while (h - l > 1)
{
int mid = l + ((h - l) >> 1);
if (helper(A, mid, B) == 1)
{
h = mid;
}
else
{
l = mid;
}
}
return h;
} | true |
122745d6a48b3a40633d09451151e6e9a19122ea | C++ | MicrosoftDocs/cpp-docs | /docs/atl/codesnippet/CPP/programming-with-ccombstr-atl_3.cpp | UTF-8 | 648 | 3.609375 | 4 | [
"CC-BY-4.0",
"MIT"
] | permissive | // The wrong way to do it
BSTR * MyBadFunction()
{
// Create the CComBSTR object
CComBSTR bstrString(L"Hello World");
// Convert the string to uppercase
HRESULT hr;
hr = bstrString.ToUpper();
// Return a pointer to the BSTR. ** Bad thing to do **
return &bstrString;
}
// The correct way to do it
HRESULT MyGoodFunction(/*[out]*/ BSTR* bstrStringPtr)
{
// Create the CComBSTR object
CComBSTR bstrString(L"Hello World");
// Convert the string to uppercase
HRESULT hr;
hr = bstrString.ToUpper();
if (hr != S_OK)
return hr;
// Return a copy of the string.
return bstrString.CopyTo(bstrStringPtr);
} | true |
850b868da8b917b7181d29cbd2c1f1152f48c569 | C++ | monowireless/Act_samples | /act2/act2.cpp | UTF-8 | 596 | 2.765625 | 3 | [] | no_license | #include <TWELITE>
const uint8_t PIN_DO1 = 18;
int iLedCounter = 0;
/*** the setup procedure (called on boot) */
void setup() {
pinMode(PIN_DO1, OUTPUT);
digitalWrite(PIN_DO1, LOW); // TURN DO1 ON
Timer0.begin(10); // 10Hz Timer
Serial << "--- act2 (using a timer) ---" << crlf;
}
/*** loop procedure (called every event) */
void loop() {
if (Timer0.available()) {
if (iLedCounter == 0) {
digitalWrite(PIN_DO1, HIGH);
iLedCounter = 1;
} else {
digitalWrite(PIN_DO1, LOW);
iLedCounter = 0;
}
}
} | true |
1ee3e234c2fb47e6ff65b67f5d0ea6e4f4aa8d3c | C++ | ajinkyakulkarni/CommodityADS2016Code | /Utils/Utils.h | UTF-8 | 5,277 | 3.15625 | 3 | [] | no_license | #ifndef UTILS_H
#define UTILS_H
#include <new>
#include <cassert>
#include <limits>
#include <utility>
#include "Debug.h"
using namespace std;
namespace igmdk{
struct EMPTY{};
template<typename ITEM> ITEM* rawMemory(int n = 1)
{return (ITEM*)::operator new(sizeof(ITEM) * n);}
void rawDelete(void* array){::operator delete(array);}
template<typename ITEM> void rawDestruct(ITEM* array, int size)
{
for(int i = 0; i < size; ++i) array[i].~ITEM();
rawDelete(array);
}
long long ceiling(unsigned long long n, long long divisor)
{return n/divisor + bool(n % divisor);}
template<typename TYPE> TYPE& genericAssign(TYPE& to, TYPE const& rhs)
{
if(&to != &rhs)
{
to.~TYPE();
new(&to)TYPE(rhs);
}
return to;
}
template<typename KEY, typename VALUE> struct KVPair
{
KEY key;
VALUE value;
KVPair(KEY const& theKey = KEY(), VALUE const& theValue = VALUE()):
key(theKey), value(theValue) {}
};
template<typename ITEM>bool operator<=(ITEM const& lhs, ITEM const& rhs)
{return !(rhs < lhs);}
template<typename ITEM>bool operator>(ITEM const& lhs, ITEM const& rhs)
{return rhs < lhs;}
template<typename ITEM>bool operator>=(ITEM const& lhs, ITEM const& rhs)
{return !(lhs < rhs);}
template<typename ITEM>bool operator==(ITEM const& lhs, ITEM const& rhs)
{return lhs <= rhs && lhs >= rhs;}
template<typename ITEM>bool operator!=(ITEM const& lhs, ITEM const& rhs)
{return !(lhs == rhs);}
template<typename ITEM> struct DefaultComparator
{
bool isLess(ITEM const& lhs, ITEM const& rhs)const{return lhs < rhs;}
bool isEqual(ITEM const& lhs, ITEM const& rhs)const{return lhs == rhs;}
};
template<typename ITEM> struct ReverseComparator
{
bool isLess(ITEM const& lhs, ITEM const& rhs)const{return rhs < lhs;}
bool isEqual(ITEM const& lhs, ITEM const& rhs)const{return lhs == rhs;}
};
template<typename ITEM> struct PointerComparator
{
bool isLess(ITEM const& lhs, ITEM const& rhs)const{return *lhs < *rhs;}
bool isEqual(ITEM const& lhs, ITEM const& rhs)const{return *lhs == *rhs;}
};
template<typename ITEM> struct IndexComparator
{
ITEM* array;
IndexComparator(ITEM* theArray): array(theArray){}
bool isLess(int lhs, int rhs)const{return array[lhs] < array[rhs];}
bool isEqual(int lhs, int rhs)const{return array[lhs] == array[rhs];}
};
template<typename KEY, typename VALUE, typename COMPARATOR =
DefaultComparator<KEY> > struct KVComparator
{
COMPARATOR comparator;
KVComparator(COMPARATOR const& theComparator = COMPARATOR()):
comparator(theComparator) {}
bool isLess(KVPair<KEY, VALUE> const& lhs, KVPair<KEY, VALUE>const& rhs)
const{return comparator.isLess(lhs.key, rhs.key);}
bool isEqual(KVPair<KEY, VALUE> const& lhs, KVPair<KEY, VALUE>const& rhs)
const{return comparator.isEqual(lhs.key, rhs.key);}
};
template<typename VECTOR> struct LexicographicComparator
{
bool isLess(VECTOR const& lhs, VECTOR const& rhs, int i)const
{
return i < lhs.getSize() ? i < rhs.getSize() && lhs[i] < rhs[i] :
i < rhs.getSize();
}
bool isEqual(VECTOR const& lhs, VECTOR const& rhs, int i)const
{
return i < lhs.getSize() ? i < rhs.getSize() && lhs[i] == rhs[i] :
i >= rhs.getSize();
}
bool isEqual(VECTOR const& lhs, VECTOR const& rhs)const
{
for(int i = 0; i < min(lhs.getSize(), rhs.getSize()); ++i)
if(lhs[i] != rhs[i]) return false;
return lhs.getSize() == rhs.getSize();
}
bool isLess(VECTOR const& lhs, VECTOR const& rhs)const
{
for(int i = 0; i < min(lhs.getSize(), rhs.getSize()); ++i)
{
if(lhs[i] < rhs[i]) return true;
if(rhs[i] < lhs[i]) return false;
}
return lhs.getSize() < rhs.getSize();
}
int getSize(VECTOR const& value){return value.getSize();}
};
template<typename ITEM, typename COMPARATOR> int argMin(ITEM* array,
int size, COMPARATOR const& c)
{
assert(size > 0);
int best = 0;
for(int i = 1; i < size; ++i)
if(c.isLess(array[i], array[best])) best = i;
return best;
}
template<typename ITEM> int argMin(ITEM* array, int size)
{return argMin(array, size, DefaultComparator<ITEM>());}
template<typename ITEM> int argMax(ITEM* array, int size)
{return argMin(array, size, ReverseComparator<ITEM>());}
template<typename ITEM> int valMin(ITEM* array, int size)
{
int index = argMin(array, size);
assert(index > -1);
return array[index];
}
template<typename ITEM> int valMax(ITEM* array, int size)
{
int index = argMax(array, size);
assert(index > -1);
return array[index];
}
template<typename ITEM, typename FUNCTION> int argMinFunc(ITEM* array,
int size, FUNCTION const& f)
{
assert(size > 0);
int best = -1;
double bestScore;
for(int i = 0; i < size; ++i)
{
double score = f(array[i]);
if(best == -1 || score < bestScore)
{
best = i;
bestScore = score;
}
}
return best;
}
template<typename ITEM, typename FUNCTION> ITEM valMinFunc(ITEM* array,
int size, FUNCTION const& f)
{
int index = argMinFunc(array, size, f);
assert(index > -1);
return array[index];
}
}
#endif
| true |
a72d96fd126c8fc9a2b94dc90e0334f6d4c1e0c6 | C++ | Crawping/fishjam-template-library | /Temp/STL/STLTester/STLMemoryTester.h | GB18030 | 2,452 | 2.875 | 3 | [] | no_license | #pragma once
#include <cppunit/extensions/HelperMacros.h>
/*********************************************************************************************************
* C++üԷΪ
* ʽ( CComPtr) -- ҪԴάüͬʱṩüĹӿ
* ʽ( shared_ptr) -- ԴûκҪ,ȫʽüָԴⲿάü
*
* STLṩָauto_ptrԽ׳쳣ʱڴй©
* auto_ptr ڿʱָȨתƣָᱻΪNULLͨ const auto_ptr ֹ
* auto_ptr ӵָĶָ롣auto_ptrʱָĶҲ
* ƣ
* auto_ptrܹȨ
* auto_ptrΪijԱ
* auto_ptrָ顣
* ֵͨʼauto_ptr
*
* std::tr1::shared_ptr -- °汾мSharePtrüӿ˽еģshared_ptr֮ٿ
* ŵ:
* 1.Զ deleter/allocator
* ƣ
* 1.һʼԴʹshared_ptrͱһֱʹ
* 2.ʹshared_ptrʵάϵԴ
* 3.ԴijԱҪȡһָԼshared_ptr
* Ҫ enable_shared_from_this<CMyClass> ̳(Ϊʽˡ) + shared_from_this() ָ shared_ptr
* ָת
* std::tr1::static_pointer_cast
* std::tr1::dynamic_pointer_cast
*
* thisʹ shared_ptr --
* TODO: weak_ptr
*********************************************************************************************************/
class CSTLMemoryTester : public CPPUNIT_NS::TestFixture
{
public:
CPPUNIT_TEST_SUITE( CSTLMemoryTester );
CPPUNIT_TEST( test_auto_ptr );
CPPUNIT_TEST( test_contain_assign );
CPPUNIT_TEST( test_shared_ptr );
CPPUNIT_TEST_SUITE_END();
void test_auto_ptr();
//ֱӸֵ(=)assigncopy ַʽͬ
void test_contain_assign();
void test_shared_ptr();
DECLARE_DEFAULT_TEST_CLASS(CSTLMemoryTester);
};
| true |
c55b69108261954b60dee860ce40c085b8fb3c7a | C++ | antmicro/verible | /common/util/range.h | UTF-8 | 3,825 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | // Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This library contains generic range-based utilities for which I could
// not find equivalents in the STL or absl or gtl.
#ifndef VERIBLE_COMMON_UTIL_RANGE_H_
#define VERIBLE_COMMON_UTIL_RANGE_H_
#include <algorithm>
#include <utility>
#include "common/util/logging.h"
namespace verible {
// Return true if sub is a substring inside super.
// SubRange and SuperRange types just need to support begin() and end().
// The SuperRange type could be a container or range.
// The iterator categories need to be RandomAccessIterator for less-comparison.
// This can be used to check string_view ranges and their invariants.
template <class SubRange, class SuperRange>
bool IsSubRange(const SubRange& sub, const SuperRange& super) {
return sub.begin() >= super.begin() && sub.end() <= super.end();
}
// Returns true if the end points of the two ranges are equal, i.e. they point
// to the same slice.
// Suitable for string/string_view like objects.
// Left and right types need not be identical as long as their begin/end
// iterators are compatible.
// This allows mixed comparison of (element-owning) containers and ranges.
// Did not want to name this EqualRange to avoid confusion with
// std::equal_range (and other STL uses of that name).
// Could have also been named IntervalEqual.
template <class LRange, class RRange>
bool BoundsEqual(const LRange& l, const RRange& r) {
return l.begin() == r.begin() && l.end() == r.end();
}
// TODO(fangism): bool RangesOverlap(l, r);
// Returns offsets [x,y] where the sub-slice of 'superrange' from
// x to y == 'subrange'.
// Both Range types just needs to support begin(), end(), and std::distance
// between those iterators. SuperRange could be a container or range.
// Precondition: 'subrange' must be a sub-range of 'superrange'.
//
// Tip: This is highly useful in tests that compare ranges because
// the iterators of ranges themselves are often un-printable, however,
// pairs of integer indices or distances are printable and meaningful.
//
// Example:
// instead of:
// EXPECT_TRUE(BoundsEqual(range1, range2));
//
// write:
// EXPECT_EQ(SubRangeIndices(range1, common_base),
// SubRangeIndices(range2, common_base));
//
// If you don't have a common_base in the current context, you could use
// range1 if both range types are the same. Any differences reported will
// be relative to range1's bounds.
//
// To avoid passing common_base repeatedly, you could also provide:
// auto indices = [&](const auto& range) {
// return SubRangeIndices(range, common_base);
// };
// EXPECT_EQ(indices(range1), indices(range2));
//
template <class SubRange, class SuperRange>
std::pair<int, int> SubRangeIndices(const SubRange& subrange,
const SuperRange& superrange) {
const int max = std::distance(superrange.begin(), superrange.end());
const int begin = std::distance(superrange.begin(), subrange.begin());
const int end = std::distance(superrange.begin(), subrange.end());
CHECK(IsSubRange(subrange, superrange))
<< "got: (" << begin << ',' << end << "), max: " << max;
return {begin, end};
}
} // namespace verible
#endif // VERIBLE_COMMON_UTIL_RANGE_H_
| true |
ab6f2402420300a6f1e3794eaceff5975c4b9733 | C++ | motis-project/net | /example/https_example.cc | UTF-8 | 2,971 | 2.578125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include "net/http/client/https_client.h"
using namespace net::http::client;
// CMakeLists.txt example (i.e. for GCC/Clang)
/*
cmake_minimum_required(VERSION 2.6)
project(request)
add_subdirectory(net EXCLUDE_FROM_ALL)
include_directories(net/include)
add_executable(request main.cc)
target_link_libraries(request net-https_client)
set_target_properties(request PROPERTIES COMPILE_FLAGS "-std=c++11")
*/
// Turn off decompression support (eliminates zlib dependency):
// cmake -DNO_ZLIB:bool=true ..
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cout << "usage: " << argv[0] << " URL\n";
return 0;
}
// Boost Asio IO Service object
// Represents an 'event loop' for asynchronous Input/Output operations
// (such as networking or timers)
boost::asio::io_service ios;
// Request:
// URL [mandatory, i.e. "http://www.google.de"]
// method [optional, default = HTTP GET],
// headers [optional, default = empty],
// body [optional, default = empty, does only make sense for POST/PUT/...]
request req{
argv[1],
request::method::GET,
{// Sample headers:
// Mircorsoft Windows 7 using Internet Explorer 8
// (omit the headers if not needed)
{"Accept",
"application/x-ms-application, image/jpeg, application/xaml+xml, "
"image/gif, image/pjpeg, application/x-ms-xbap, */*"},
{"Accept-Language", "de-DE"},
{"User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; "
"Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR "
"3.0.30729; Media Center PC 6.0)"},
{"Accept-Encoding", "gzip, deflate"},
{"Connection", "Keep-Alive"}}};
// Create a HTTP(S) connection and send a query:
// Reply will be available in the supplied callback function.
//
// Callback parameters:
// std::shared_ptr<net::ssl> [shared pointer to the connection object]
// response [response object: contains headers and body]
// error_code [the error code, if (ec) {error} else {ok}]
//
// make_https -> creates a TLS secured HTTPS connection (using OpenSSL)
// make_http -> creates a plain TCP HTTP connection
//
// Change 1st callback parameter to std::shared_ptr<net::tcp> for HTTP.
make_https(ios, req.address)
->query(req, [](std::shared_ptr<net::ssl> const&, response const& res,
boost::system::error_code ec) {
if (ec) {
std::cout << "error: " << ec.message() << "\n";
} else {
std::cout << "HEADER:\n";
for (auto const& header : res.headers) {
std::cout << header.first << ": " << header.second << "\n";
}
std::cout << "\nCONTENT:\n";
std::cout << "response: " << res.body << "\n";
}
});
// Start asynchronous event loop.
// This is required in order to start the request!
ios.run();
} | true |
700df545385522d6c581a66aec561f78347187db | C++ | JohnLonginotto/ACGTrie | /acgtrie/c_mikhail_acgtrie/DnaBase.cpp | UTF-8 | 6,716 | 2.6875 | 3 | [] | no_license | #include "StdAfx.h"
#include "DnaTrieBuilder.h"
int CSequenceUp2Bit::GetLength() const
{
int zeroBitCount = 0;
unsigned int curBlock;
assert(sizeof(TSequenceUp2BitStorage) == 8); // This method implemented for 8-byte codes
assert((up2BitCode >> 32) == ((int *)&up2BitCode)[1]); // Sometimes >> 32 works incorrectly
// We imply that machine architecture is Little Endian
if ((up2BitCode >> 32) == 0)
{
zeroBitCount = 32;
curBlock = (unsigned int)(up2BitCode);
}
else
curBlock = up2BitCode >> 32;
for (int mid = 16; mid != 1; mid /= 2)
{
if ((curBlock >> mid) == 0)
{
zeroBitCount += mid;
// curBlock &= (1U << mid) - 1;
}
else
curBlock >>= mid;
}
assert(curBlock == 1);
assert((up2BitCode >> (sizeof(TSequenceUp2BitStorage) * 8 - zeroBitCount)) == 0);
assert((up2BitCode >> (sizeof(TSequenceUp2BitStorage) * 8 - zeroBitCount - 2)) == 1);
return (sizeof(TSequenceUp2BitStorage) * 8 - zeroBitCount) / 2 - 1;
}
CSequenceUp2Bit CSequenceUp2Bit::GetSubsequence(int startCharInd, int charCount) const
{
CSequenceUp2Bit newSeq;
assert(startCharInd >= 0 && charCount >= 0);
assert(startCharInd + charCount <= GetLength());
newSeq.up2BitCode = ((up2BitCode >> (startCharInd * 2)) &
((c_one << (charCount * 2)) - 1)) |
(c_one << (charCount * 2));
return newSeq;
}
void CDna2Bits::AssignFromString(const std::string &dnaStr)
{
m_len = int(dnaStr.length());
int portionCount = (m_len - 1) / c_dnaCharsInPortion + 1;
if (portionCount > int(m_bits.size()))
m_bits.resize(portionCount);
for (int portionInd = 0; portionInd < portionCount; portionInd++)
{
TDna2BitsPortion curPortion = 0;
int curCharCount = c_dnaCharsInPortion;
if (portionInd == portionCount - 1)
curCharCount = (m_len - 1) % c_dnaCharsInPortion + 1;
for (int i = 0; i < curCharCount; i++)
{
char ch = dnaStr[portionInd * c_dnaCharsInPortion + i];
switch (ch)
{
case 'A':
case 'C':
case 'T':
case 'G':
break;
default:
THROW_EXCEPTION("Invalid input character");
}
curPortion |= TDna2BitsPortion((ch >> 1) & 3) << (i * 2);
}
m_bits[portionInd] = curPortion;
}
}
void CDna2Bits::GetSubsequenceUp2Bit(CSequenceUp2Bit &seqUp2Bit, int startCharInd, int charCount) const
{
// TODO? to process empty sequences separately and to return assert(charCount > 0
assert(charCount >= 0 && charCount <= CSequenceUp2Bit::c_maxLen);
assert(sizeof(CSequenceUp2Bit::TSequenceUp2BitStorage) <= 8); // This method implemented for up to 8-byte codes
assert(sizeof(TDna2BitsPortion) == 8); // and 4-byte processing portions
// Subsequence will touch at maximum 2 portions: ... <8-byte portion N> <8-byte portion N + 1>...
// ^<subsequence>^
int startPortionInd = startCharInd / c_dnaCharsInPortion;
TDna2BitsPortion finalPortion = m_bits[startPortionInd] >> (startCharInd % c_dnaCharsInPortion * 2);
int lastPortionInd = (startCharInd + charCount - 1) / c_dnaCharsInPortion;
if (lastPortionInd > startPortionInd) // TODO? to remove this conditional check by adding one more m_bits cell with value 0
{
int startPortionCharCount = c_dnaCharsInPortion - startCharInd % c_dnaCharsInPortion;
finalPortion |= (m_bits[lastPortionInd] &
((c_one << ((charCount - startPortionCharCount) * 2)) - 1)) <<
(startPortionCharCount * 2);
}
// TODO: to test by means of assert(GetSubsequenceUp2Bit_Slow( ),
// seqUp2Bit.up2BitCode == finalPortion | (c_one << (charCount * 2)));
seqUp2Bit.up2BitCode = finalPortion | (c_one << (charCount * 2));
}
int CDna2Bits::GetEqualCharCount(CSequenceUp2Bit &seqUp2Bit, int startCharInd) const
{
assert(sizeof(CSequenceUp2Bit::TSequenceUp2BitStorage) == sizeof(TDna2BitsPortion));
//assert(startCharInd >= 0 && startCharInd < GetLength());
assert(startCharInd >= 0 && startCharInd <= GetLength());
int seqLen = seqUp2Bit.GetLength();
int restCharCount = GetLength() - startCharInd;
CSequenceUp2Bit subseqUp2Bit;
if (restCharCount > CSequenceUp2Bit::c_maxLen)
restCharCount = CSequenceUp2Bit::c_maxLen;
//assert(restCharCount * 4 <= sizeof(TDna2BitsPortion));
GetSubsequenceUp2Bit(subseqUp2Bit, startCharInd, restCharCount);
// Leading 01s will not disturb
CSequenceUp2Bit::TSequenceUp2BitStorage code1 = subseqUp2Bit.up2BitCode;
CSequenceUp2Bit::TSequenceUp2BitStorage code2 = seqUp2Bit.up2BitCode;
//// Removing leading 01s and getting pure 2-bit arrays of DNA characters
//CSequenceUp2Bit::TSequenceUp2BitStorage code1 = subseqUp2Bit.up2BitCode ^
// (c_one << (restCharCount * 2));
//CSequenceUp2Bit::TSequenceUp2BitStorage code2 = seqUp2Bit.up2BitCode ^
// (c_one << (seqLen * 2));
// XOR between 2-bit arrays will reveal differences
CSequenceUp2Bit::TSequenceUp2BitStorage codesDiff = code1 ^ code2;
int diffCharInd = GetFirstNonZeroCharacter(codesDiff);
return std::min(diffCharInd, std::min(restCharCount, seqLen));
}
int CDna2Bits::GetFirstNonZeroCharacter(TDna2BitsPortion codesDiff)
{
int zeroBitCount = 0;
unsigned int curBlock;
assert(sizeof(TDna2BitsPortion) == 8); // This method implemented for 8-byte codes
if ((codesDiff & 0xFFFFFFFF) == 0)
{
zeroBitCount = 32;
curBlock = (unsigned int)(codesDiff >> 32);
}
else
curBlock = (unsigned int)(codesDiff);
if (curBlock == 0)
return (zeroBitCount + 32) / 2; // I suppose this is very typical case
for (int mid = 16; mid != 1; mid /= 2)
{
if ((curBlock & ((1 << mid) - 1)) == 0)
{
zeroBitCount += mid;
curBlock >>= mid;
}
}
return zeroBitCount / 2;
}
//bool CDna2Bits::AreSubsequencesEqual(const CSequenceUp2Bit &seqUp2Bit,
// int thisStartCharInd, int charCount) const
//{
// assert(sizeof(CSequenceUp2Bit::TSequenceUp2BitStorage) == sizeof(TDna2BitsPortion));
//
//
//
// return false;
//}
//
void CDna2Bits::RunUnitTests()
{
if (GetFirstNonZeroCharacter(0) != sizeof(TDna2BitsPortion) * 4)
THROW_EXCEPTION("CDna2Bits unit test failed");
assert(sizeof(TDna2BitsPortion) == 8);
for (int i = 0; i < 64; i++)
{
if (GetFirstNonZeroCharacter(c_one << i) != i / 2)
THROW_EXCEPTION("CDna2Bits unit test failed");
if (GetFirstNonZeroCharacter((c_one << i) | (c_one << 62)) != i / 2)
THROW_EXCEPTION("CDna2Bits unit test failed");
}
}
void DnaBase_RunUnitTests()
{
CDna2Bits::RunUnitTests();
} | true |
5dac27fe2b883c9cd5eda71eab0fb1d0311d587b | C++ | kmgumienny/Systems-Programming | /Event Driven Simulation/Banking Simulation Files/event.cpp | UTF-8 | 944 | 3.5 | 4 | [] | no_license | //event.cpp - kmgumienny
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <queue>
#include "event.h"
/*
* getEvent creates an event and takes the first thing from the
* queue an assigns it to the new event, running it through the action
* method. The queue then gets rid of that event. Used in single line.
*/
void EventQueue::getEvent(){
Event *eTop=aQueue.top();
aQueue.pop();
eTop->Action();
}
/*
* works exactly as getEvent but runs the item on top of the queue
* in Action2. This is used in multiple lines.
*/
void EventQueue::getEvent2(){
Event *eTop=aQueue.top();
aQueue.pop();
eTop->Action2();
}
/*
* take the first event in the queue and returns it.
*/
Event* EventQueue::getTop(){
return aQueue.top();
}
/*
* removes the first Event in the queue
*/
void EventQueue::remove(){
aQueue.pop();
}
/*
* pushes an Event into the queue.
*/
void EventQueue::addEvent(Event *a){
aQueue.push(a);
}
| true |
b493ca6b40c2c85cf93c07ea098c8d94094c58ee | C++ | king7282/algorithm | /boj/Others/1267.cpp | UTF-8 | 325 | 2.921875 | 3 | [] | no_license | #include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
int M = 0, Y = 0;
for (int i = 1; i <= n; i++) {
int input;
scanf("%d", &input);
Y += (input / 30 + 1) * 10;
M += (input / 60 + 1) * 15;
}
if (Y < M)
printf("Y %d\n", Y);
else if (Y > M)
printf("M %d\n", M);
else
printf("Y M %d\n", Y);
} | true |
94fa0c56ed9725ddfcbb6c07f8c5849c8aa55143 | C++ | kailasspawar/DS-ALGO-PROGRAMS | /Trees/BinTree/ConvertGivenBTtoItsSumTree.cpp | UTF-8 | 577 | 3.1875 | 3 | [] | no_license | #include<iostream>
#include"Bintree.h"
using namespace std;
int toSumTree(bnode root)
{
if(root==NULL)
return 0;
int old_val = root->data;
root->data = toSumTree(root->left) + toSumTree(root->right);
return root->data + old_val;
}
int main()
{
bnode root = NULL;
root = newNode(10);
root->left = newNode(-2);
root->right = newNode(6);
root->left->left = newNode(8);
root->left->right = newNode(-4);
root->right->left = newNode(7);
root->right->right = newNode(5);
toSumTree(root);
inorder(root);
return 0;
}
| true |
247c3687f6d9dbbb54775934ffce6e2b3845f318 | C++ | Erecorn/Brasseur_Corentin_Test_Technique | /Bronze(versionAvecAideDuGitPresentDansLeRapport).cpp | UTF-8 | 5,916 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
/***** Var global *****/
/**********************/
/*******fonction*******/
void addCP(int nextCheckpointX, int nextCheckpointY, vector<vector<int>>* vectorCP, vector<int>* actualCP,
bool* listeFini,int* lapSize, int* lap);
void vitesseAI(int nextCheckpointAngle, int nextCheckpointDist, int* vitesse);
/**********************/
void addCP(int nextCheckpointX, int nextCheckpointY, vector<vector<int>>* vectorCP, vector<int>* actualCP,
bool* listeFini,int* lapSize, int* lap)
{
if(vectorCP->empty())
{
vectorCP->push_back(*actualCP);
}else
{
if (nextCheckpointX != (vectorCP->back().front()) && nextCheckpointY != (vectorCP->back().back()))
{
for (auto cp = vectorCP->begin(); cp != vectorCP->end(); ++cp)
{
if ( (*(cp->begin()) == nextCheckpointX) && (*(--cp->end()) == nextCheckpointY ))
{
*listeFini = true;
*lapSize = vectorCP->size();
*lap = 2;
} }
if (! *listeFini)
{
vectorCP->push_back(*actualCP);
}
}
}
}
void vitesseAI(int nextCheckpointAngle, int nextCheckpointDist, int* vitesse)
{
if( nextCheckpointAngle >= 1 || nextCheckpointAngle <= -1)
{
if( nextCheckpointAngle >= 90 || nextCheckpointAngle <= -90 )
{
*vitesse = 0;
}else if( nextCheckpointDist < 2400 )
{
*vitesse *= ((90 - abs(nextCheckpointAngle)) / (float)90);
}
}else
{
if( nextCheckpointDist < 2400 ) *vitesse *= nextCheckpointDist / 2400;
}
}
int main()
{
bool boost = true;
vector<vector<int>>* vectorCP = new vector<vector<int>>();
vector<int>* actualCP = new vector<int>(2);
bool listeFini = false;
int lap = 1;
int lapSize;
float pi = 3.14159265;
// game loop
while (1) {
int dirX, dirY, vitesse, dirXdesi, dirYdesi;
int distNextCheckX, distNextCheckY;
int x;
int y;
int nextCheckpointX; // x position of the next check point
int nextCheckpointY; // y position of the next check point
int nextCheckpointDist; // distance to the next checkpoint
int nextCheckpointAngle; // angle between your pod orientation and the direction of the next checkpoint
cin >> x >> y >> nextCheckpointX >> nextCheckpointY >> nextCheckpointDist >> nextCheckpointAngle; cin.ignore();
int opponentX;
int opponentY;
cin >> opponentX >> opponentY; cin.ignore();
// actualCP = new vector<int>();
actualCP->at(0) = nextCheckpointX;
actualCP->at(1) = nextCheckpointY;
if(!listeFini)
{
addCP(nextCheckpointX, nextCheckpointY, vectorCP, actualCP, &listeFini, &lapSize, &lap);
}
vitesse = 100;
if( nextCheckpointAngle <= -1 || nextCheckpointAngle >= 1)
{
vector<float>* dirDesi = new vector<float>(2);
vector<float>* dir = new vector<float>(2);
dirDesi->at(0) = (nextCheckpointX - x);
dirDesi->at(1) = (nextCheckpointY - y);
float sqrtVal = dirDesi->at(0)*dirDesi->at(0) + dirDesi->at(1) * dirDesi->at(1);
dirDesi->at(0) = dirDesi->at(0) * (1 / std::sqrt(sqrtVal));
dirDesi->at(1) = dirDesi->at(1) * (1 / std::sqrt(sqrtVal));
dir->at(0) = ((dirDesi->at(0) * cos(-nextCheckpointAngle * pi / 180) ) - (dirDesi->at(1) * sin(-nextCheckpointAngle * pi / 180) ));
dir->at(1) = ((dirDesi->at(1) * cos(-nextCheckpointAngle * pi / 180) ) - (dirDesi->at(0) * sin(-nextCheckpointAngle * pi / 180) ));
sqrtVal = dir->at(0)*dir->at(0) + dir->at(1) * dir->at(1);
dir->at(0) = dir->at(0) / std::sqrt(sqrtVal);
dir->at(1) = dir->at(1) / std::sqrt(sqrtVal);
dirDesi->at(0) = (dirDesi->at(0) - dir->at(0));
dirDesi->at(1) = (dirDesi->at(1) - dir->at(1));
sqrtVal = dirDesi->at(0)*dirDesi->at(0) + dirDesi->at(1) * dirDesi->at(1);
dirDesi->at(0) = (dirDesi->at(0) * (1 / std::sqrt(sqrtVal)))*100;
dirDesi->at(1) = (dirDesi->at(1) * (1 / std::sqrt(sqrtVal)))*100;
dirX = nextCheckpointX + dirDesi->at(0);
dirY = nextCheckpointY + dirDesi->at(1);
}else
{
dirX = nextCheckpointX;
dirY = nextCheckpointY;
}
a
vitesseAI(nextCheckpointAngle, nextCheckpointDist, &vitesse);
cout << dirX << " " << dirY << " ";
if( boost && lap >= 2 && nextCheckpointDist > 5000 && nextCheckpointAngle < 1 && nextCheckpointAngle > -1 )
{
cout << "BOOST" << endl;
boost = false;
}
else
{
cout << vitesse << endl;
}
int i = 0;
for (auto checkpoint = vectorCP->begin(); checkpoint != vectorCP->end(); ++checkpoint)
{
cerr << "DEBUG: ARRAY[" << i << "], X=" << *(checkpoint->begin()) << ", Y=" << *(--checkpoint->end()) << endl;
i++;
}
cerr << "vitesse : " << vitesse << endl;
cerr << "dirX : " << dirX << " dirY : " << dirY << endl;
cerr << "nextCheckpointDist : " << nextCheckpointDist << endl;
cerr << "boost : " << boost << endl;
cerr << "lap : " << lap << " lapSize : " << nextCheckpointAngle << endl;
cerr << "distNextCheckX : " << distNextCheckX << " distNextCheckY : " << distNextCheckY << endl;
}
} | true |
9007b28d889a50e1a29333908ec2acdd4b3eae67 | C++ | samkit993/competitve_prog | /codechef/COOLING.cpp | UTF-8 | 952 | 2.65625 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<stack>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
int tCases;
scanf("%d",&tCases);
for(int p=0;p<tCases;++p){
int n;
scanf("%d",&n);
vector<int> pies(n,0);
vector<int> racks(n,0);
for(int i=0;i<n;++i){
scanf("%d",&pies[i]);
}
for(int i=0;i<n;++i){
scanf("%d",&racks[i]);
}
sort(pies.begin(),pies.end());
sort(racks.begin(),racks.end());
int count=0;
for(int i=0,j=0;i<n && j<n;){
//cout << racks[i] << " " << pies[j] << endl;
//cout << "i = " << i << "j = " << j << "count = " << count << endl << endl;
if(racks[i] >= pies[j]){
++i;
++j;
++count;
}else{
++i;
}
}
printf("%d\n",count);
}
return 0;
}
| true |
a51426b40e3590d629c4d7859cbc3be6b27a25fd | C++ | ETLang/Sharpish | /Build/include/Rational.h | UTF-8 | 2,131 | 3.140625 | 3 | [
"MIT"
] | permissive | #pragma once
namespace CS
{
struct Rational
{
int32_t Num;
uint32_t Den;
Rational() { }
Rational(const Rational& copy) : Num(copy.Num), Den(copy.Den) { }
Rational(int32_t x) : Num(x), Den(1) { }
Rational(int32_t num, uint32_t den) : Num(num), Den(den) { }
template<int Precision = 8>
static Rational FromFloat(float value)
{
int factor = CompileTimePow<Precision>::Of10;
return Rational((int)(value * factor), factor);
}
Rational Simplify() const;
inline Rational operator +(const Rational& rhs) const
{
if (Den == rhs.Den) return Rational(Num + rhs.Num, Den);
return Rational(Num * rhs.Den + rhs.Num * Den, Num * Den).Simplify();
}
inline Rational operator -(const Rational& rhs) const
{
if (Den == rhs.Den) return Rational(Num - rhs.Num, Den);
return Rational(Num * rhs.Den - rhs.Num * Den, Num * Den).Simplify();
}
inline Rational operator *(const Rational& rhs) const
{
return Rational(Num * rhs.Num, Den * rhs.Den);
}
inline Rational operator /(const Rational& rhs) const
{
return Rational(Num * rhs.Den, Den * rhs.Num);
}
inline bool operator ==(const Rational& rhs) const
{
auto a = Simplify();
auto b = rhs.Simplify();
return a.Num == b.Num && a.Den == b.Den;
}
inline bool operator !=(const Rational& rhs) const
{
return !(*this == rhs);
}
inline bool operator <(const Rational& rhs) const
{
return Num * rhs.Den < Den * rhs.Num;
}
inline bool operator >(const Rational& rhs) const
{
return Num * rhs.Den > Den * rhs.Num;
}
inline bool operator <=(const Rational& rhs) const
{
return Num * rhs.Den <= Den * rhs.Num;
}
inline bool operator >=(const Rational& rhs) const
{
return Num * rhs.Den >= Den * rhs.Num;
}
inline operator bool() const { return Num != 0; }
private:
template<int Power> struct CompileTimePow
{ static const int Of10 = 10 * CompileTimePow<Power - 1>::Of10; };
template<> struct CompileTimePow<0>
{ static const int Of10 = 1; };
};
}
IS_VALUETYPE(::CS::Rational, "60B9DC9A-BBEE-469B-8027-F7EE76B129C4");
DECLARE_HASHABLE(::CS::Rational);
| true |
c66545326c3f6f8667054c8bc3c19d12deb77a7e | C++ | nervmaster/Graphs | /grafo.cpp | UTF-8 | 10,709 | 3.03125 | 3 | [] | no_license | #include "grafo.h"
// PUBLICOS
Grafo::Grafo(int nvertice)
{
this->nvertice = nvertice;
this->nvertice_atual = nvertice;
listaVertice = new Vertice*[nvertice];
//Cria um array com os todos os objetos vertice
}//Construtor
int Grafo::novoVertice(int id, string nome)
{
//Cria um novo vertice com seu nome
if(listaVertice[id] = new Vertice(nome))
return 1;
return 0;
}
int Grafo::novaAresta(int id1, int id2, int peso)
{
if(listaVertice[id1]->novaAresta(id2, peso))
{
listaVertice[id2]->incrementaGrauEntrada();
//Incrementa o grau de entrada do alvo
return 1;
}
return 0;
}
string Grafo::get(int id)
{
if(listaVertice[id])
return listaVertice[id]->getNome();
return NULL;
}
int Grafo::deleteid(int id)
{
int i;
int *vizinho;
if(listaVertice[id]!=NULL)
{
vizinho = listaVertice[id]->getVizinho();
//Pega uma lista de vertices que ele é origem
//vizinhos
//Decrementa o grau de entrada de seus vizinhos;
for(i=1;i<vizinho[0];i++)
{
listaVertice[vizinho[i]]->decrementaGrauEntrada();
}
delete vizinho;
for(i=0;i<nvertice;i++) //Deletar todas as referencias ao vertice deletado
{ //Percorre N deletando
if(listaVertice[i]) //se existe o vertice
{
listaVertice[i]->removeAresta(id); //Deleta todos as arestas de id
}
}
delete listaVertice[id];
nvertice_atual--;
listaVertice[id] = NULL;
return 1;
}
return 0;
}
int * Grafo::vizinhos(int id)
{
int * lista;
if(listaVertice[id]) //Verificar se o vertice existe
{
lista = listaVertice[id]->getVizinho();
//Pega a lista de vertice que ele é origem
return lista;
}
lista = new int;
*lista = 0;
return lista;
}
int Grafo::conexao(int id1, int id2)
{
//Despintar todos os vertices
this->despintarGrafo();
if(listaVertice[id1] && listaVertice[id2]) //Se a origem e alvo são validos fazer a busca
{
return this->buscaProfundidade(id1,id2);
}
return -1;
}
int Grafo::buscaProfundidade(int atual, int alvo)
{
int resultado = 0;
int counter = 1;
int *vizinho;
vizinho = listaVertice[atual]->getVizinho(); //Pega lista de vizinhos
if(!listaVertice[atual]->getPintado()) //Se não esta pintado
listaVertice[atual]->pintar(); //pinta
else
return 0; //Se ja foi cancela recursao
if(atual == alvo) //Se encontrado
{
return 1;
}
while(counter < vizinho[0]) //Como o indicador é do tamanho do vetor então vizinho[0] tem tamanho minimo 1
{
resultado = buscaProfundidade(vizinho[counter], alvo);
counter++;
if(resultado)
return resultado;
}
return resultado; //Para o termino de toda a recursao
}
int Grafo::despintarGrafo()
{
int i;
for(i=0;i<nvertice;i++)
{
if(listaVertice[i]) //Para só acessar válidos
listaVertice[i]->despintar();
}
return 1;
}
int * Grafo::recursivaOrdemTopologica(int * resultado)
{
int posinicio = resultado[0];//marca a posição inicial desta recursão no vetor resultado
int posfinal;//marca a posição final desta recursão no vetor resultado
int *vizinho;
int i;
int j;
if(resultado[0] < nvertice_atual)
{
for(i=0;i<nvertice;i++)
{
if(listaVertice[i] && !listaVertice[i]->getPintado() && !listaVertice[i]->getGrauEntrada())//Se existe o vertice e nao tiver pintado
{
vizinho = listaVertice[i]->getVizinho();
listaVertice[i]->pintar(); //pinta o vertice
resultado[resultado[0]] = i; //Vai imprimindo no vetor contador
resultado[0]++;
if(vizinho[0]-1)
{//Pegando os com grau entrada 0
for(i=1;i<vizinho[0];i++)
{//removendo as arestas
listaVertice[vizinho[i]]->decrementaGrauEntrada();
}
delete[] vizinho;
}
}
}
posfinal = resultado[0];
recursivaOrdemTopologica(resultado);
//Agora retornar nos vertices
for(i=posinicio;i<posfinal;i++)
{
vizinho = listaVertice[resultado[i]]->getVizinho();
for(j=1;i<vizinho[0];i++)
{
listaVertice[vizinho[j]]->incrementaGrauEntrada();
}
}
}
return resultado;
}
int * Grafo::ordemTopologica()
{
int i;
int *resultado;
this->despintarGrafo();
//Todos os grafos despintados
if(!this->direcionado) //Somente opera em direcionados;
{
resultado = new int;
*resultado = 0;
return resultado;
}
resultado = new int[nvertice+1];
resultado[0] = 1;
//tamanho do vetor
return recursivaOrdemTopologica(resultado);
}
int Grafo::getNvertice()
{
return nvertice;
}
int * Grafo::menorcaminho(int id1, int id2, int * custo)
{
int * dist;
int * conjuntoq;
int * vizinho;
int i;
int cont;
int atual;
int pos;
int alt;
int * caminho;
dist = new int[nvertice];
for(i=0;i<nvertice;i++)//Sei que acarreta em desperdicio de espaço se ha vertices deletados;
{
dist[i] = -1; //Representação simbolica para inf
}
dist[id1] = 0; //O vertice origem para todos os outros vertices
conjuntoq = new int[nvertice_atual+1];
cont=1;
for(i=0;i<nvertice;i++)
{
if(listaVertice[i]) //Se existe o vertice
{
conjuntoq[cont] = i;
cont++;
}
}
conjuntoq[0] = nvertice_atual+1; //Informa quantos vertices estão presentes no conjunto
while(conjuntoq[0])
{
cont = -1;
for(i=1;i<conjuntoq[0];i++)
{
if((dist[conjuntoq[i]] >= 0 && cont >= dist[conjuntoq[i]]) || cont==-1)
{
cont = dist[conjuntoq[i]]; //Pega o vertice com menor dist
atual = conjuntoq[i];
pos = i;
}
}
for(i=pos;i<conjuntoq[0]-1;i++)
{
conjuntoq[i] = conjuntoq[i+1]; //Faz a deleção movendo o vetor a esquerda
}
conjuntoq[0]--;
vizinho = listaVertice[atual]->getVizinho();
for(i=1;i<vizinho[0];i++)
{
alt = dist[atual] + listaVertice[atual]->getPeso(vizinho[i]);
if(dist[vizinho[i]] < 0 || alt < dist[vizinho[i]])
{
listaVertice[vizinho[i]]->zeraCaminho(); //Adiciona o caminho do vertice ao vertice
listaVertice[vizinho[i]]->addCaminho(listaVertice[atual]->getCaminho());
listaVertice[vizinho[i]]->addCaminho(atual);
dist[vizinho[i]] = alt;
}
}
delete vizinho;
}
caminho = listaVertice[id2]->getCaminho();
*custo = dist[id2];
delete[] dist;
delete[] conjuntoq;
this->zeraCaminhoGrafo();
return caminho;
}
int Grafo::zeraCaminhoGrafo()
{
int i;
for(i=0;i<nvertice;i++)
{
if(listaVertice[i])
listaVertice[i]->zeraCaminho();
}
return 1;
}
int * Grafo::arvoreminima(int * custototal)
{
//Variaveis para ter a lista ordenada de vertices
vector<int> listaaresta;
vector<int>::iterator it;
int i;
int j;
int dummy;
int * lista;
int * listaaux;
//Variaveis para fazer a arvore minima;
int contador=0;
int * arestaresultado;
vector< vector<int> > listacores;
vector< vector<int> >::iterator itlistacor;
int contcor=0;
vector<int>::iterator itcor;
int corv1;
int corv2;
if(this->direcionado) //nao funciona em direcionados;
{
lista = new int;
*lista = 0;
*custototal = 0;
return lista;
}
it = listaaresta.begin();
for(i=0;i<nvertice;i++)
{
if(listaVertice[i])
{
lista = listaVertice[i]->getAresta();
j = 1;
while(j<lista[0]*2-1)
{
listaaux = new int[3];
if(i < lista[j])
{
listaaux[0] = i;
listaaux[1] = lista[j];
}
else
{
listaaux[0] = lista[j];
listaaux[1] = i;
}
listaaux[2] = lista[j+1];
j+=2;
if(listaaresta.empty())
{
listaaresta.push_back(listaaux[0]);
listaaresta.push_back(listaaux[1]);
listaaresta.push_back(listaaux[2]);
}
else //Se não está vazio;
{
it = listaaresta.begin();
it+=2; //it = peso da aresta;
while(*it < listaaux[2] && it < listaaresta.end())
{
it+=3;
}
if(it <= listaaresta.end())
it-=2; //voltando a pos das coordenadas
else
it = listaaresta.end();
if(it == listaaresta.end() || !(*it == listaaux[0] && *(it+1) == listaaux[1])) //Se ja não foi adicionado;
{
listaaresta.insert(it,listaaux, listaaux+3);
}
}
delete[] listaaux;
}//fim while
delete[] lista;
}
}//fim for
//listaaresta possui a lista ordenada por peso das arestas;
*custototal = 0;
this->despintarGrafo();
arestaresultado = new int[(nvertice_atual-1)*2+1];
it = listaaresta.begin();
while(it < listaaresta.end()) //para um grafo conectado são necessarias nvertice-1 arestas
{
corv1 = listaVertice[*it]->getPintado();
corv2 = listaVertice[*(it+1)]->getPintado();
if(corv1 || corv2) //Se um dos dois estiver pintado;
{
if(corv1 && corv2) //Ambos estão pintados
{
if(corv1 != corv2) //Se são de cores diferentes
{
*(custototal)+= *(it+2); // Incrementa o custo da aresta;
contador++;
arestaresultado[contador*2-1] = *it;
arestaresultado[contador*2] = *(it+1);
if(corv1 < corv2) //todos ficam com a cor menor;
{
for(itcor = listacores[corv2-1].begin()+1; itcor < listacores[corv2-1].end(); itcor++)
{
listacores[corv1-1].push_back(*itcor);
listaVertice[*itcor]->colorir(corv1); //Todos serão cor do v1;
listacores[corv1-1][0]++; //Aumenta o contador;
}
listacores[corv2-1].clear();
}
else
{
for(itcor = listacores[corv1-1].begin()+1; itcor < listacores[corv1-1].end(); itcor++)
{
listacores[corv2-1].push_back(*itcor);
listaVertice[*itcor]->colorir(corv2); //Todos serão cor do v1;
listacores[corv2-1][0]++; //Aumenta o contador;
}
listacores[corv1-1].clear();
}
}
}
else //So um esta pintado
{
*(custototal)+= *(it+2); // Incrementa o custo da aresta;
contador++;
arestaresultado[contador*2-1] = *it;
arestaresultado[contador*2] = *(it+1);
if(corv1) //Se v1 é o pintado
{
listacores[corv1-1].push_back(*(it+1));
listacores[corv1-1][0]++;
listaVertice[*(it+1)]->colorir(corv1);
}
else
{
listacores[corv2-1].push_back(*it);
listacores[corv2-1][0]++;
listaVertice[*(it)]->colorir(corv2);
}
}
}
else //Nenhum esta pintado
{
*(custototal)+= *(it+2); // Aresta Valida
contador++;
arestaresultado[contador*2-1] = *it;
arestaresultado[contador*2] = *(it+1);
listacores.push_back(vector<int>());
listacores[contcor].push_back(2); //2 vertices no grupo;
listacores[contcor].push_back(*it);
listacores[contcor].push_back(*(it+1));
listaVertice[*it]->colorir(contcor+1);
listaVertice[*(it+1)]->colorir(contcor+1);
contcor++;
}
it+=3;
}
arestaresultado[0] = contador*2+1;
for(i=0;i<contcor;i++)
listacores[i].clear();
listacores.clear();
return arestaresultado;
}
int Grafo::setDirecionado(int n)
{
if(n>0)
this->direcionado = 1;
else
this->direcionado = 0;
return 1;
}
| true |
822b859ee7de1682b848d2110710966dc71c9cae | C++ | Sourav9063/Cpp-All-codes | /cpp prac/Bubble sort with steps.cpp | UTF-8 | 1,804 | 2.625 | 3 | [] | no_license |
#include<bits/stdc++.h>
using namespace std;
// __int64 variable; cin cout diye
// __uint64 variable;
#define lli long long int //lld
#define ulli unsigned long long int //llu
#define db double //lf
#define Ld long double //Lf
#define pf printf
#define sf scanf
#define nl printf("\n")
#define plf(a) printf("%lld",a)
#define slf(b) scanf("%lld",&b)
#define puf(a) printf("%llu",a)
#define suf(b) scanf("%llu",&b)
#define pif(a) printf("%d",a)
#define sif(b) scanf("%d",&b)
#define pff(a) printf("%f",a)
#define sff(b) scanf("%f",&b)
#define pLf(a) printf("%Lf",a)
#define sLf(b) scanf("%Lf",&b)
#define pdf(a) printf("%lf",a)
#define sdf(b) scanf("%lf",&b)
#define pb(a) push_back(a);
const double pie= 2*acos(0.0);
const long long mxl= 1000000007;
int cmpre=0,swp=0;
int main()
{
int n;
cout<<"Array size = ";
cin>>n;
int a[n];
for(int i=0; i<n; i++)cin>>a[i];
int c,s,k;
for(int k=1; k<n; k++)
{
cout<<"pass-"<<k<<endl;
c=0,s=0;
for(int i=0; i<n-(k-1); i++)
{
c++;
if(a[i]>a[i+1])
{
swap(a[i],a[i+1]);
s++;
cout<<"swap here ->";
for(int j=0; j<n; j++) cout<<a[j]<<" ";
}
else
{
cout<<"No swap here ->";
for(int j=0; j<n; j++) cout<<a[j]<<" ";
}
cout<<endl;
}
cmpre=cmpre+c;
swp=swp+s;
cout<<"compares "<<c<<endl<<"swaps ="<<s<<endl<<"pass end result"<<endl;
for(int j=0; j<n; j++) cout<<a[j]<<" ";
cout<<endl<<endl;
}
cout<<"Total compares ="<<cmpre<<endl<<"Total swaps ="<<swp<<endl;
cout<<"final array"<<endl;
for(int i=0; i<n; i++) cout<<a[i]<<" ";
cout<<endl;
}
| true |
3c93ac3beb4e991eb7ab9edacf12a90ab5df6dc0 | C++ | sammiiT/leetcode | /greedy/945. Minimum Increment to Make Array Unique.cpp | UTF-8 | 1,600 | 3.578125 | 4 | [] | no_license | //===類似題===
946. Validate Stack Sequences
2233. Maximum Product After K Increments
//===思路1====
(*)依據題意, 每一個數加1, 代表一個movement, 求總共的movement, 讓數列每一個數值不相等
(*)利用map<int,init>; (value, count)
-不用unordered_map<int,int>, 因為不會對key作排列;會出錯
1.遍歷數列,並用map<int,int>記錄每一個數出現的個數
2.遍歷map<int,int>,若數值出現的次數大於1
- 多於的個數累加到 [a.first+1]的個數中; 也同時累加到movement中
- 並將原本[a.first]的個數修正為1
//=====
int minIncrementForUnique(vector<int>& nums) {
map<int,int> mp;
int res = 0;
for(int a:nums) ++mp[a];
for(auto a:mp){
int t;
if(a.second>1){
t = a.second-1;
res += t;
mp[a.first+1]+=t;
mp[a.first]=1;
}
}
return res;
}
//===思路2===
int minIncrementForUnique(vector<int>& A) {
int res = 0, need = 0;
map<int, int> numCnt;
for (int num : A) ++numCnt[num];
for (auto &a : numCnt) {
res += a.second * max(need - a.first, 0) + a.second * (a.second - 1) / 2;
need = max(need, a.first) + a.second;
}
return res;
}
//===思路3===
int minIncrementForUnique(vector<int>& nums) {
int res = 0;
int tmp;
sort(nums.begin(),nums.end());
tmp = nums[0];
for(int i=1; i<nums.size(); ++i){
if(tmp>=nums[i]){
res = tmp-nums[i]+1;
tmp+=1;
}
else{//tmp< nums[i]
tmp = nums[i];
}
}
return res;
}
| true |
b8876f39c6d787a026ed32ced2f81ca7ed285607 | C++ | SoltiHo/LeetRepository | /Validate_Binary_Search_Tree/Validate_Binary_Search_Tree/Validate_Binary_Search_Tree.h | UTF-8 | 1,593 | 3.765625 | 4 | [] | no_license | // Given a binary tree, determine if it is a valid binary search tree(BST).
//
// Assume a BST is defined as follows :
//
// The left subtree of a node contains only nodes with keys less than the node's key.
// The right subtree of a node contains only nodes with keys greater than the node's key.
// Both the left and right subtrees must also be binary search trees.
#include <limits>
#include <algorithm>
using namespace std;
// Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
struct Range{
int min;
int max;
Range() : min(INT_MAX), max(INT_MIN){};
};
bool isValidBST(TreeNode *root) {
Range r;
if (root){
return BST(root, r);
}
else{
return true;
}
}
bool BST(TreeNode* root, Range& r){
Range leftRange;
bool isHealthy = true;
if (root->left){
if (!BST(root->left, leftRange)){
return false;
}
if (root->val <= leftRange.max) {
return false;
}
}
Range rightRange;
if (root->right){
if (!BST(root->right, rightRange)){
return false;
}
if (root->val >= rightRange.min){
return false;
}
}
r.min = min(root->val, leftRange.min);
r.max = max(root->val, rightRange.max);
return true;
}
};
| true |
5394ab3b043e4e1cda3c68917041d270fbf872d9 | C++ | gabrieldinse/Neat | /Neat/src/Neat/Graphics/Cameras/Camera2D.h | UTF-8 | 2,518 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include "Neat/Graphics/Cameras/Camera.h"
#include "Neat/Core/Log.h"
namespace Neat
{
enum class KeepAspect
{
Height, Width
};
class Camera2D
{
public:
Camera2D(const Vector2F& position, float size,
KeepAspect keepAspect = KeepAspect::Height);
Camera& getCamera() { return m_camera; }
const Camera& getCamera() const { return m_camera; }
const Vector2F& getPosition() const { return Vector2F(m_camera.getPosition()); }
float getRotation() const { return m_camera.getRoll(); }
const Vector2F& getUpDirection() const { return Vector2F(m_camera.getUpDirection()); }
const Vector2F& getRightDirection() const { return Vector2F(m_camera.getRightDirection()); }
float getSize() const { return m_size; }
float getZoomLevel() const { return m_zoomLevel; }
float getNear() const { return m_camera.getNear(); }
float getFar() const { return m_camera.getFar(); }
void setSize(float size, KeepAspect keepAspect);
void setSize(float size);
void setZoomLevel(float zoomLevel);
void setPosition(const Vector2F& position) { m_camera.setPosition(Vector3F(position, m_zPos)); }
void setX(float x) { m_camera.setX(x); }
void setY(float y) { m_camera.setY(y); }
void setRotation(float rotation) { m_camera.setRoll(rotation); }
void setNear(float near) { m_camera.setNear(near); }
void setFar(float far) { m_camera.setFar(far); }
void rotate(float rotation) { m_camera.rotateRoll(rotation); }
void move(const Vector2F& position) { m_camera.move(Vector3F(position, m_zPos)); }
void moveX(float distance) { m_camera.moveX(distance); }
void moveY(float distance) { m_camera.moveY(distance); }
void moveUp(float distance) { m_camera.moveUp(distance); }
void moveDown(float distance) { m_camera.moveDown(distance); }
void moveRight(float distance) { m_camera.moveRight(distance); }
void moveLeft(float distance) { m_camera.moveLeft(distance); }
Matrix4F getProjectionMatrix() const { m_camera.getProjectionMatrix(); }
Matrix4F getViewMatrix() const { m_camera.getViewMatrix(); }
Matrix4F getCameraTransform() const { return m_camera.getCameraTransform(); }
private:
void updateProjection();
private:
float m_zPos = 0.0f; // TODO: check this value
float m_zoomLevel = 1.0f;
Camera m_camera;
float m_size;
KeepAspect m_keepAspect = KeepAspect::Height;
};
} | true |
1db484d684d4a8c91898096a2b4d959ea72fdcee | C++ | KacperCichosz96/Ball-trajectory-calculation | /BallTrajectoryCalc/funcs.cpp | UTF-8 | 1,303 | 2.859375 | 3 | [] | no_license | #include "defs.h"
void display_all(const cv::Mat* imgs, std::string name, bool to_save)
{
std::string temp_name;
for (int i = 0; i < 3; i++)
{
temp_name = name + " " + std::to_string(i + 1);
cv::namedWindow(temp_name);
cv::imshow(temp_name, imgs[i]);
if(to_save)
cv::imwrite((temp_name +".jpg"), imgs[i]);
cv::waitKey(0);
}
cv::destroyAllWindows();
}
void parab_param_calc(double& a, double& b, double& c, const cv::Point& P1, const cv::Point& P2, const cv::Point& P3)
{
double x1 = P1.x;
double y1 = P1.y;
double x2 = P2.x;
double y2 = P2.y;
double x3 = P3.x;
double y3 = P3.y;
a = ((x1 - x3)*(y2 - y3) + (y1 - y3)*(x3 - x2)) / ((x1 - x3)*(x2*x2 - x3 * x3) + (x3*x3 - x1 * x1)*(x2 - x3));
b = (y1 - y3 + (a*(x3*x3 - x1 * x1))) / (x1 - x3);
c = (y3 - a * x3*x3 - b * x3);
}
int bounce_point(double a, double b, double c, double y) //calculating the common point of trajectory parabola and the line which states table surface
{
c = c - y;
double delta;
delta = b * b - 4 * a*c;
int x1 = (-b - sqrt(delta)) / (2 * a);
int x2 = (-b + sqrt(delta)) / (2 * a);
if (x1 < x2)
return x1;
else
return x2;
}
int move_equation(double a, double b, double c, int x, int maxY)
{
int y = a * (x*x) + b * x + c;
if (y >= 0 && y < maxY)
return y;
else
return -1;
} | true |
c553013739027fed51849ee5819e0bc77944b2e9 | C++ | iroot900/Algorithm-Practice-300-Plus | /187 Repeated DNA Sequences.cpp | UTF-8 | 1,031 | 2.78125 | 3 | [] | no_license | class Solution {
public:
vector<string> findRepeatedDnaSequences(string s) {
unordered_map<int,pair<int,int>> seqDict;
int n=s.size();
vector<string> result;
if(n<10) return result;
int last=0;
for(int i=0;i<10;i++)
{
last=last*4+tran(s[i]);
}
seqDict[last].first=0;
seqDict[last].second++;
for(int i=1;i<=n-10;++i)
{
last-=tran(s[i-1])*pow(4,9);
last=last*4+tran(s[i+9]);
seqDict[last].first=i;
seqDict[last].second++;
}
for(auto seq:seqDict)
{
if(seq.second.second>1) result.push_back(s.substr(seq.second.first,10));
}
return result;
}
int tran(char cha)
{
switch(cha)
{
case 'A':
return 1;
case 'C':
return 2;
case 'G':
return 3;
case 'T':
return 4;
}
}
};
| true |
e258e3fffcb458169717b786f55b592c84b68298 | C++ | sagarsubedi/competitive_notes_cpp | /multiset.cpp | UTF-8 | 1,617 | 4 | 4 | [] | no_license | #include <iostream>
#include <set>
using namespace std;
typedef multiset<int>::iterator It;
int main(){
// elements are ordered
// can store multiple same element
// once values are inserted, they can't be modified
// associative container. Refer by key or value (both are same)
// elements are refered by value not index
// underlying implementation uses BST
int arr[] = {5,10,20,30,40,20,30,10,10,30,30,75};
int size = sizeof(arr) / sizeof(int);
multiset<int> ms(arr, arr+size);
// iterate over
// will print all elemts in sorted order even if multiple same values
// .count() gives occurence
cout << "Count" << endl;
for(auto n:ms) cout << n << " " << ms.count(n) << endl;
cout << endl;
// will remove all instace of the given key
ms.erase(10);
// insert
ms.insert(50);
for(auto n:ms) cout << n << " ";
cout << endl;
// get iterator to an element
auto it = ms.find(30);
cout << (*it) << endl;
// get all elemtnts which are equal to a value
// for example for the int 30:
pair<It, It> p =ms.equal_range(30);
for(auto it=p.first; it!=p.second; it++){
cout << *it << " ";
}
cout << endl;
// lower bound and upperbound
// upper means next bigger value, lower means next bigger value if given value not present
// to print a range (left exclusive, right inclusive) we can do:
for(auto it = ms.lower_bound(10); it!=ms.upper_bound(75); it++) cout << *it << " ";
cout << endl;
cout << *ms.lower_bound(5) << " " << *ms.upper_bound(70) << endl;
return 0;
} | true |
e33d0497a48a80b46161e9d898d158fe10a3e68a | C++ | Slavq/MarchingCubesSlavq | /Plugins/Voxel/Source/Voxel/Private/VoxelNetworking.cpp | UTF-8 | 3,817 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "VoxelPrivatePCH.h"
#include "VoxelNetworking.h"
AVoxelTcpSender::AVoxelTcpSender(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
SenderSocket = NULL;
ShowOnScreenDebugMessages = true;
}
void AVoxelTcpSender::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
if (SenderSocket)
{
SenderSocket->Close();
ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->DestroySocket(SenderSocket);
}
}
bool AVoxelTcpSender::StartUDPSender(const FString& YourChosenSocketName, const FString& TheIP, const int32 ThePort)
{
//Create Remote Address.
RemoteAddr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();
bool bIsValid;
RemoteAddr->SetIp(*TheIP, bIsValid);
RemoteAddr->SetPort(ThePort);
if (!bIsValid)
{
ScreenMsg("Rama UDP Sender>> IP address was not valid!", TheIP);
return false;
}
SenderSocket = FTcpSocketBuilder(YourChosenSocketName).AsReusable().BoundToEndpoint(FIPv4Endpoint(RemoteAddr));
//Set Send Buffer Size
int32 SendSize = 2 * 1024 * 1024;
SenderSocket->SetSendBufferSize(SendSize, SendSize);
SenderSocket->SetReceiveBufferSize(SendSize, SendSize);
UE_LOG(LogTemp, Log, TEXT("\n\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"));
UE_LOG(LogTemp, Log, TEXT("Rama ****UDP**** Sender Initialized Successfully!!!"));
UE_LOG(LogTemp, Log, TEXT("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n"));
return true;
}
bool AVoxelTcpSender::RamaUDPSender_SendString(FString ToSend)
{
if (!SenderSocket)
{
ScreenMsg("No sender socket");
return false;
}
//~~~~~~~~~~~~~~~~
int32 BytesSent = 0;
FAnyCustomData NewData;
NewData.Scale = FMath::FRandRange(0, 1000);
NewData.Count = FMath::RandRange(0, 100);
NewData.Color = FLinearColor(FMath::FRandRange(0, 1), FMath::FRandRange(0, 1), FMath::FRandRange(0, 1), 1);
FArrayWriter Writer;
Writer << NewData; //Serializing our custom data, thank you UE4!
SenderSocket->SendTo(Writer.GetData(), Writer.Num(), BytesSent, *RemoteAddr);
if (BytesSent <= 0)
{
const FString Str = "Socket is valid but the receiver received 0 bytes, make sure it is listening properly!";
UE_LOG(LogTemp, Error, TEXT("%s"), *Str);
ScreenMsg(Str);
return false;
}
ScreenMsg("UDP~ Send Success! Bytes Sent = ", BytesSent);
return true;
}
AVoxelTcpListener::AVoxelTcpListener(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
}
void AVoxelTcpListener::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
//~~~~~~~~~~~~~~~~
delete TcpListener;
TcpListener = nullptr;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//Rama's Start TCP Receiver
bool AVoxelTcpListener::StartUDPReceiver(const FString& YourChosenSocketName, const FString& TheIP, const int32 ThePort)
{
ScreenMsg("RECEIVER INIT");
//~~~
FIPv4Address Addr;
FIPv4Address::Parse(TheIP, Addr);
//Create Socket
FIPv4Endpoint Endpoint(Addr, ThePort);
//BUFFER SIZE
int32 BufferSize = 2 * 1024 * 1024;
TcpListener = new FTcpListener(Endpoint);
return true;
}
void AVoxelTcpListener::Recv(const FArrayReaderPtr& ArrayReaderPtr, const FIPv4Endpoint& EndPt)
{
ScreenMsg("Received bytes", ArrayReaderPtr->Num());
FAnyCustomData Data;
*ArrayReaderPtr << Data;
}
void AVoxelTcpListener::TCPSocketListener()
{
FSocket* ListenSocket = TcpListener->GetSocket();
if (!ListenSocket)
{
return;
}
//Binary Array!
TArray<uint8> ReceivedData;
uint32 Size;
while (ListenSocket->HasPendingData(Size))
{
ReceivedData.Init(0, FMath::Min(Size, 65507u));
int32 Read = 0;
ListenSocket->Recv(ReceivedData.GetData(), ReceivedData.Num(), Read);
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Data Read! %d"), ReceivedData.Num()));
}
}
| true |
06e5ee974fb77f2aa8292731adf9810155132812 | C++ | codeljs/hello-world | /TestDataType.cpp | GB18030 | 338 | 3.25 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main() {
//list initialization;
int x{ 1 };//ʹ1.0ʽ
cout << x << endl;
//static_cast
cout << 1 / 2 << endl;
cout << static_cast <double> (1 / 2) << endl;
cout << static_cast<double>(1) / 2 << endl;
cout << 1.0f / 2.f << endl;
return 0;
} | true |
9b154fd79e7fc505c6af47e6ffd4e2eb0b8a728a | C++ | lausai/UVa | /2_stars/880.cpp | UTF-8 | 476 | 2.78125 | 3 | [] | no_license | #include <cstdio>
#include <cmath>
using namespace std;
unsigned long long AddN(unsigned long long n)
{
return (n * (n+1)) / 2;
}
int main()
{
unsigned long long n = 0;
while (scanf("%llu", &n) != EOF) {
unsigned long long i = sqrt((long double)n * 2);
while (AddN(i) < n)
i++;
unsigned long long idx = n - AddN(i-1);
// printf("%u\n", idx);
printf("%llu/%llu\n", i-idx+1, idx);
}
return 0;
}
| true |
2b9be747ff0409ed09d2a02dbddca54f32dff165 | C++ | orihehe/Codeforces | /Codeforces Round #570 (Div. 3)/H - Subsequences (hard version).cpp | UTF-8 | 1,197 | 2.59375 | 3 | [] | no_license | /*
dp[인덱스][길이] - 현재 인덱스의 글자를 마지막으로 하는 x길이의 subsequence개수를 저장
이것은 x-1길이의 가장 가까운 a,b,c,...,y,z로 끝나는 개수의 합과 같다
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
#define ll long long
using namespace std;
/* 🐣🐥 */
ll dp[101][101];
bool use[26];
char st[101];
int main() {
int n;
ll kk, ans = 0, cnt = 0;
scanf("%d %lld %s", &n, &kk, st);
for (int i = 0; i < n; i++) {
dp[i][1] = 1;
for (int j = 2; j <= i + 1; j++) { // 길이
memset(use, false, sizeof(use));
int tmp = 0;
for (int k = i - 1; k >= 0; k--) {
if (!use[st[k] - 'a'] && dp[k][j - 1] != 0) {
use[st[k] - 'a'] = true;
dp[i][j] += dp[k][j - 1];
dp[i][j] = min(dp[i][j], kk);
}
}
}
}
for (int i = n; i >= 1; i--) {
memset(use, false, sizeof(use));
for (int j = n - 1; j >= 0; j--) {
if (dp[j][i] != 0 && !use[st[j] - 'a']) {
ans += min(kk - cnt, dp[j][i])*(n - i);
cnt += dp[j][i];
use[st[j] - 'a'] = true;
}
if (cnt >= kk) return !printf("%lld", ans);
}
}
cnt++;
ans += n;
if (cnt < kk) printf("-1");
else printf("%lld", ans);
return 0;
} | true |
90a35acaba01dfb25166b7e52aa278707630c1e4 | C++ | DanielCorreia21/CGJ-TeamProject | /TeamProject/Matrix3d.h | UTF-8 | 2,735 | 3.3125 | 3 | [] | no_license | #pragma once
#include <string>
#include "Matrix2d.h"
#include "Vector3d.h"
/* AUTHORS
* Group: 11
* Bernardo Pinto - 98734
* Daniel Correia - 98745
*/
class Matrix3d
{
private:
float values[3][3];
public:
//Constructors
Matrix3d(float columnMajorArray[9]);
Matrix3d(float matrix[3][3]);
//----------------------
//General
std::string toString();
bool isEqual(Matrix3d matrix) const;
//----------------------
//Sum
//matrix + matrix
Matrix3d sumMatrix(Matrix3d matrix) const;
Matrix3d operator+(const Matrix3d& matrix);
//matrix += matrix
void operator+=(Matrix3d matrix);
//matrix + scalar
Matrix3d sumScalar(float scalar) const;
Matrix3d operator+(float scalar) const;
//matrix += scalar
void operator+=(float scalar);
//scalar + matrix
friend Matrix3d operator+(float scalar, const Matrix3d& matrix);
//----------------------
//Subtraction
//matrix - matrix
Matrix3d subMatrix(Matrix3d matrix) const;
Matrix3d operator-(const Matrix3d& matrix) const;
//matrix -= matrix
void operator-=(Matrix3d matrix);
//matrix - scalar
Matrix3d subScalar(float scalar) const;
Matrix3d operator-(float scalar) const;
//matrix -= scalar
void operator-=(float scalar);
//scalar - matrix
friend Matrix3d operator-(float scalar, const Matrix3d& matrix);
//----------------------
//Multiplication
//matrix * matrix
Matrix3d multMatrix(Matrix3d matrix) const;
Matrix3d operator*(const Matrix3d& matrix) const;
//matrix *= matrix
void operator*=(Matrix3d matrix);
//matrix * vector
Vector3d multVector(Vector3d vector) const;
Vector3d operator*(const Vector3d& vector) const;
//vector * matrix
friend Vector3d operator*(Vector3d vector, const Matrix3d& matrix);
//matrix * scalar
Matrix3d multScalar(float scalar) const;
Matrix3d operator*(float scalar) const;
//scalar * matrix
friend Matrix3d operator*(float scalar, const Matrix3d& matrix);
//----------------------
//Division
//matrix / matrix
Matrix3d divMatrix(Matrix3d matrix) const;
Matrix3d operator/(const Matrix3d& matrix) const;
//matrix /= matrix
void operator/=(Matrix3d matrix);
//matrix / vector
Vector3d divVector(Vector3d vector) const;
Vector3d operator/(const Vector3d& vector) const;
//scalar / matrix
friend Vector3d operator/(Vector3d vector, const Matrix3d& matrix);
//matrix / scalar
Matrix3d divScalar(float scalar) const;
Matrix3d operator/(float scalar) const;
//matrix /= scalar
void operator/=(float scalar);
//scalar / matrix
friend Matrix3d operator/(float scalar, const Matrix3d& matrix);
//----------------------
//Transpose
Matrix3d transpose();
//Determinant
float determinant() const;
//Inverse
Matrix3d inverse();
//Convert to OpenGL
void toColumnMajorArray(float out[9]);
};
| true |
eef20ae93f49d94be1191d993fa6d9e2583c52c4 | C++ | AntonBaracuda/caesar3_source | /basic.cpp | UTF-8 | 6,359 | 2.546875 | 3 | [] | no_license | #include "variables.h"
#include "basic.h"
int fun_getStringWidth(const char *str, int fontId)
{
unsigned __int8 c; // [sp+4Ch] [bp-14h]@12
signed int letterSpacing; // [sp+50h] [bp-10h]@3
signed int spaceWidth; // [sp+54h] [bp-Ch]@3
int stringWidth; // [sp+58h] [bp-8h]@1
signed int maxlen; // [sp+5Ch] [bp-4h]@1
maxlen = 10000;
stringWidth = 0;
if ( fontId != graphic_font + F_LargePlain && fontId != graphic_font + F_LargeBlack )
{
if ( fontId == graphic_font + F_LargeBrown )
{
spaceWidth = 10;
letterSpacing = 1;
}
else
{
if ( fontId == graphic_font + F_SmallPlain )
{
spaceWidth = 4;
letterSpacing = 1;
}
else
{
if ( fontId == graphic_font )
{
spaceWidth = 6;
letterSpacing = 1;
}
else
{
spaceWidth = 6;
letterSpacing = 0;
}
}
}
}
else
{
spaceWidth = 10;
letterSpacing = 1;
}
while ( maxlen > 0 )
{
c = *str++;
if ( !c )
return stringWidth;
if ( c == ' ' )
{
stringWidth += spaceWidth;
}
else
{
graphic_currentGraphicId = (unsigned __int8)map_char_to_fontGraphic[c];
if ( graphic_currentGraphicId )
stringWidth += letterSpacing + c3_sg2[fontId + graphic_currentGraphicId - 1].width;
}
--maxlen;
}
return stringWidth;
}
int fun_strlen(const char *str)
{
char c; // ST4C_1@3
int len; // [sp+50h] [bp-8h]@1
signed int max; // [sp+54h] [bp-4h]@1
max = 10000;
len = 0;
while ( max > 0 )
{
c = *str++;
if ( !c )
return len;
++len;
--max;
}
return len;
}
int fun_getCharWidth(unsigned __int8 c, int fontId)
{
int result; // eax@2
if ( c )
{
if ( c == ' ' )
{
result = 4;
}
else
{
graphic_currentGraphicId = (unsigned __int8)map_char_to_fontGraphic[c];
if ( graphic_currentGraphicId )
result = c3_sg2[fontId + graphic_currentGraphicId - 1].width + 1;
else
result = 0;
}
}
else
{
result = 0;
}
return result;
}
int strToInt(char *str)
{
int result; // eax@11
char *ptr; // [sp+4Ch] [bp-14h]@1
char *v3; // [sp+4Ch] [bp-14h]@6
signed int negative; // [sp+50h] [bp-10h]@1
int v5; // [sp+58h] [bp-8h]@1
int numChars; // [sp+5Ch] [bp-4h]@1
ptr = str;
negative = 0;
v5 = 0;
numChars = 0;
if ( (unsigned __int8)*str == '-' )
{
negative = 1;
ptr = str + 1;
}
while ( (signed int)(unsigned __int8)*ptr >= '0' && (signed int)(unsigned __int8)*ptr <= '9' )
{
++numChars;
++ptr;
}
v3 = str;
if ( (unsigned __int8)*str == '-' )
v3 = str + 1;
while ( numChars )
{
--numChars;
v5 += atoi_multipliers[numChars] * ((unsigned __int8)*v3++ - '0');
}
if ( negative )
result = -v5;
else
result = v5;
return result;
}
int fun_strNumDigitChars(char *str)
{
signed int check; // [sp+4Ch] [bp-8h]@1
int numChars; // [sp+50h] [bp-4h]@1
numChars = 0;
check = 0;
while ( 1 )
{
++check;
if ( check >= 1000 )
break;
if ( (signed int)(unsigned __int8)*str >= '0' && (signed int)(unsigned __int8)*str <= '9'
|| (unsigned __int8)*str == '-' )
break;
++str;
++numChars;
}
return numChars;
}
void unused_addToGameTextString(char *str, int group, int number, signed int len)
{
unsigned __int8 i; // [sp+4Ch] [bp-10h]@9
char *target; // [sp+54h] [bp-8h]@1
target = (char *)&c3eng_data
+ 256 * (unsigned __int8)byte_6ADEFE[4 * group]
+ (unsigned __int8)byte_6ADEFF[4 * group]
+ 28;
while ( number > 0 )
{
if ( !*target )
{
if ( (signed int)(unsigned __int8)*(target - 1) >= ' ' )
--number;
}
++target;
}
while ( (signed int)(unsigned __int8)*target < ' ' )
++target;
for ( i = 0; i < len; ++i )
target[i] = str[i];
}
int unused_copyGameTextString(char *dst, int group, int number, signed int maxlen)
{
int result; // eax@10
unsigned __int8 i; // [sp+4Ch] [bp-8h]@9
char *text; // [sp+50h] [bp-4h]@1
text = (char *)&c3eng_data + c3eng_index[group].offset;
while ( number > 0 )
{
if ( !*text )
{
if ( (signed int)(unsigned __int8)*(text - 1) >= 32 )
--number;
}
++text;
}
while ( (signed int)(unsigned __int8)*text < 32 )
++text;
for ( i = 0; ; ++i )
{
result = i;
if ( i >= maxlen )
break;
dst[i] = text[i];
}
return result;
}
void fun_getGameTextString_forMessagebox(int group, int number)
{
c3eng_textstring_forMessagebox = (char *)&c3eng_data + c3eng_index[group].offset;
while ( number > 0 )
{
if ( !*c3eng_textstring_forMessagebox )
{
if ( (signed int)(unsigned __int8)*(c3eng_textstring_forMessagebox - 1) >= ' '
|| !*(c3eng_textstring_forMessagebox - 1) )
--number;
}
++c3eng_textstring_forMessagebox;
}
while ( (signed int)(unsigned __int8)*c3eng_textstring_forMessagebox < ' ' )
++c3eng_textstring_forMessagebox;
}
int fun_getGameTextStringWidth(int group, int number, int fontId)
{
gametext_result = (char *)&c3eng_data + c3eng_index[group].offset;
while ( number > 0 )
{
if ( !*gametext_result )
{
if ( (signed int)(unsigned __int8)*(gametext_result - 1) >= 32 || !*(gametext_result - 1) )
--number;
}
++gametext_result;
}
while ( (signed int)(unsigned __int8)*gametext_result < 32 )
++gametext_result;
return fun_getStringWidth(gametext_result, fontId);
}
void fun_strMoveLeft(char *start, const char *end)
{
while ( start < end )
{
*start = start[1];
++start;
}
*start = 0;
}
void unused_inputRemoveSpaces()
{
int i; // [sp+4Ch] [bp-4h]@1
for ( i = 0; i <= input_length[inputtext_lastUsed] && input_text[inputtext_lastUsed][i]; ++i )
{
if ( (unsigned __int8)input_text[inputtext_lastUsed][i] == ' ' )
fun_strMoveLeft(
&input_text[inputtext_lastUsed][i],
&input_text[inputtext_lastUsed][input_length[inputtext_lastUsed]]);
}
}
| true |
52393b23db577c665ee567079218fc88725b6af9 | C++ | MarkOates/beary2d | /src/world_screen.cpp | UTF-8 | 3,202 | 2.53125 | 3 | [] | no_license |
#include <beary2d/world_screen.h>
#include <beary2d/map.h>
#include <beary2d/player.h>
#include <beary2d/entity.h>
#include <beary2d/tile_layer.h>
NewWorldScreen::NewWorldScreen(Display *display, Player *player)
: BScreen(display, "world_screen")
, level(NULL)
, camera(0, 0, display->width(), display->height())
, current_map(NULL)
, player(player)
, entity_manager()
, entity_map_move_func(NULL)
, camera_target(NULL)
{
//camera_target = entity_manager.entities[0];
}
void NewWorldScreen::render_scene()
{
/*
static ALLEGRO_BITMAP *background_bitmap = al_load_bitmap("data/backgrounds/magic_line.jpg");
BitmapObject bitmap(background_bitmap);
bitmap.stretch_to_fit(display->width(), display->height());
bitmap.align(0, 0);
bitmap.draw();
*/
al_clear_to_color(color::darkblue);
camera.start_transform();
if (current_map)
{
//int tile_width = current_map->tile_layers[i].tile_index->get_tile_width();
//int tile_height = current_map->tile_layers[i].tile_index->get_tile_height();
//int left = (camera.x+camera.w/2)/tile_width - 8;
//int top = (camera.y+camera.h/2)/tile_height - 5;
//int right = (camera.x+camera.w/2)/tile_width + 12;
//int bottom = (camera.y+camera.h/2)/tile_height + 7;
//std::cout << "(" << camera.x << " " << camera.y << " " << camera.w << " " << camera.h << " - " << camera.align_x << " " << camera.align_y << " - " << camera.scale_x << " " << camera.scale_y << ")";
//int left = (camera.x-camera.w*camera.align_x)/tile_width;
//int top = (camera.y+camera.h/2)/tile_height;
//int right = (camera.x+camera.w/2)/tile_width;
//int bottom = (camera.y+camera.h/2)/tile_height;
current_map->tile_layer.draw(); // for now
// TODO: a newer version of the beary engine has clip calculations that account for zooming and rotations.
// that will need to be updated into this part.
}
entity_manager.draw_all_in_map(current_map);
camera.restore_transform();
}
void NewWorldScreen::update_collisions_and_positions()
{
if (entity_map_move_func)
{
for (unsigned i=0; i<entity_manager.entities.size(); i++)
{
entity_map_move_func(entity_manager.entities[i], current_map);
}
}
entity_manager.update_all();
}
void NewWorldScreen::update_scene()
{
update_collisions_and_positions();
if (camera_target)
{
camera.placement.position.x = camera_target->place.position.x - camera.placement.size.x/2 - camera_target->place.size.x;
camera.placement.position.y = camera_target->place.position.y - camera.placement.size.y/2 - camera_target->place.size.y-100;
}
}
void NewWorldScreen::primary_timer_func()
{
update_scene();
render_scene();
}
void NewWorldScreen::init_world()
{
// eeeeeehhhh.... the content of this function is like it's a user function. Might want to clean it up.
camera.placement.scale.x = 1.0;
camera.placement.scale.y = 1.0;
camera.placement.align.x = 0;
camera.placement.align.y = 0;
//level.maps.push_back(Map());
//level.tile_index.load(al_load_bitmap("data/tiles/awesome_tiles-04.png"), 64, 64, 0, 0, 0, 0);
//current_map = &level.maps[0];
//current_map->tile_layers.push_back(TileLayer(&level.tile_index, 18, 10));
}
| true |
06660a439b14cfa7412e12135f7f94e050d3ec07 | C++ | funkey/cohear | /InheritanceMatchDelegateStrategy.h | UTF-8 | 3,736 | 2.828125 | 3 | [
"MIT"
] | permissive | #ifndef COHEAR_INHERITANCE_MATCH_DELEGATE_STRATEGY_H__
#define COHEAR_INHERITANCE_MATCH_DELEGATE_STRATEGY_H__
#include "Delegate.h"
#include "CallbackDescription.h"
#include "detail/SignalTraits.h"
#include "ExactMatchDelegateStrategy.h"
namespace chr {
/**
* A get-delegate-strategy, that creates a delegate from a callback description
* for a slot, if the signal type of the callback is equal or a base of the
* signal type of the slot.
*/
template <typename SignalType, typename AsSignalType = SignalType>
class InheritanceMatchDelegateStrategy {
public:
static bool IsCompatible(CallbackDescription& cd) {
if (ExactMatchDelegateStrategy<AsSignalType>::IsCompatible(cd))
return true;
typedef typename SignalTraits<AsSignalType>::parent_type ParentType;
return InheritanceMatchDelegateStrategy<SignalType, ParentType>::IsCompatible(cd);
}
static Delegate<SignalType> CastDelegate(void* delegate) {
// The following line assumes that the memory layout of Delegate<ToType>
// and Delegate<FromType> is the same (which it is, unless someone
// specializes Delegate<T> [their own fault]), and that
// Delegate<ToType>::operator() is doing what we would expect. The
// latter is probably guarnateed by the C0x-standard (see below), but at
// least true in practice for a lot of compilers/architectures. For
// instance, GLib is doing much more evil casts without problems (see
// http://stackoverflow.com/questions/559581/casting-a-function-pointer-to-another-type).
//
// What happens: We tread Delegate<Base> as a Delegate<Derived>,
// where Derived is derived from Base. The differences between
// Delegate<Base> and Delegate<Derived> are just the type of the
// stub function pointer: They are (void(*)(Base&)) and
// (void(*)(Derived&)), respectively. So what we do, is basically a
// cast of a function pointer. The C0x-standard says to that:
//
// [6.3.2.3]
// (http://c0x.coding-guidelines.com/6.3.2.3.html)
//
// 768 If a converted pointer is used to call a function whose
// type is not compatible with the pointed-to type, the behavior
// is undefined.
//
// Whether the following is guaranteed to work by the standard boils
// down to the question whether the function pointers are
// compatible. In [6.7.5.3], the standard says (amongst a lot of
// other things):
//
// [6.3.2.3]
// (http://c0x.coding-guidelines.com/6.7.5.3.html)
//
// 1611 For two function types to be compatible, both shall
// specify compatible return types.
//
// True.
//
// 1612 Moreover, the parameter type lists, if both are present,
// shall agree in the number of parameters and in use of the
// ellipsis terminator;
//
// True.
//
// 1613 corresponding parameters shall have compatible types.
//
// The parameters are references. If the same rules as for pointers
// apply (not sure), we have:
//
// [6.7.5.1]
// (http://c0x.coding-guidelines.com/6.7.5.1.html)
//
// 1562 For two pointer types to be compatible, both shall be
// identically qualified and both shall be pointers to compatible
// types.
//
// Derived and Base are compatible. All that seems to tell us that
// we are fine.
return *static_cast<Delegate<SignalType>*>(delegate);
}
};
// template specialization for the no-parent case
template <typename SignalType>
class InheritanceMatchDelegateStrategy<SignalType, NoParent> {
public:
static bool IsCompatible(CallbackDescription&) {
return false;
}
static Delegate<SignalType> CastDelegate(void*) {
return Delegate<SignalType>();
}
};
} // namespace chr
#endif // COHEAR_INHERITANCE_MATCH_DELEGATE_STRATEGY_H__
| true |
a6058f340e837d05126388f82563c1c202006ee1 | C++ | divinedev/GWEN | /gwen/src/Controls/HorizontalSlider.cpp | UTF-8 | 1,878 | 2.53125 | 3 | [
"MIT"
] | permissive | /*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#include "Gwen/Controls/Slider.h"
#include "Gwen/Controls/HorizontalSlider.h"
using namespace Gwen;
using namespace Gwen::Controls;
using namespace Gwen::ControlsInternal;
GWEN_CONTROL_CONSTRUCTOR( HorizontalSlider )
{
m_SliderBar->SetHorizontal( true );
}
float HorizontalSlider::CalculateValue()
{
return ( float ) m_SliderBar->X() / ( float )( Width() - m_SliderBar->Width() );
}
void HorizontalSlider::UpdateBarFromValue()
{
m_SliderBar->MoveTo( ( Width() - m_SliderBar->Width() ) * ( m_fValue ), m_SliderBar->Y() );
}
void HorizontalSlider::OnMouseClickLeft( int x, int y, bool bDown )
{
m_SliderBar->MoveTo( CanvasPosToLocal( Gwen::Point( x, y ) ).x - m_SliderBar->Width() * 0.5, m_SliderBar->Y() );
m_SliderBar->OnMouseClickLeft( x, y, bDown );
OnMoved( m_SliderBar );
}
void HorizontalSlider::Layout( Skin::Base* /*skin*/ )
{
m_SliderBar->SetSize( 15, Height() );
}
void HorizontalSlider::Render( Skin::Base* skin )
{
skin->DrawSlider( this, true, m_bClampToNotches ? m_iNumNotches : 0, m_SliderBar->Width() );
}
void HorizontalSlider::OnBoundsChanged( Gwen::Rect oldBounds )
{
BaseClass::OnBoundsChanged( oldBounds );
// If the control's width changed, the slider bar's position must
// be updated to keep pointing at the actual slider value
if ( GetBounds().w != oldBounds.w )
{
m_SliderBar->SetHeight( Height() ); // always keep the bar the same height as the slider
UpdateBarFromValue();
}
}
void HorizontalSlider::OnChildBoundsChanged( Gwen::Rect oldChildBounds, Base* pChild )
{
BaseClass::OnChildBoundsChanged( oldChildBounds, pChild );
// If the slider bar's width changed, the bar's position must
// be updated to keep pointing at the actual slider value
if ( pChild == m_SliderBar && pChild->GetBounds().w != oldChildBounds.w )
{
UpdateBarFromValue();
}
}
| true |
7f98b619de9262912c42257c1930735b11354e15 | C++ | Twiebs/practice_tracking_tool | /json_serialize.cpp | UTF-8 | 1,745 | 2.9375 | 3 | [] | no_license |
#include "thirdparty/json.hpp"
#include <fstream>
void SerializeTaskList(const TaskList& taskList) {
nlohmann::json json;
json["lastAccessTime"] = 0;
for (size_t i = 0; i < taskList.tasks.size(); i++) {
auto& task = taskList.tasks[i];
json["tasks"][i]["name"] = task.name;
json["tasks"][i]["description"] = task.description;
json["tasks"][i]["notes"] = task.notes;
for (size_t j = 0; j < task.taskEvents.size(); j++) {
auto& event = task.taskEvents[j];
json["tasks"][i]["events"][j]["type"] = (uint32_t)event.type;
json["tasks"][i]["events"][j]["time"] = event.timestamp;
json["tasks"][i]["events"][j]["difficulty"] = (uint32_t)event.difficulty;
}
}
std::ofstream out("tasks.json");
out << std::setw(2) << json << "\n";
}
void DeserializeTaskList(TaskList& taskList) {
std::ifstream in("tasks.json");
nlohmann::json json;
in >> json;
uint64_t lastAccessTime = json["lastAccessTime"];
auto jsonTaskList = json["tasks"];
for (size_t i = 0; i < jsonTaskList.size(); i++) {
taskList.tasks.push_back(Task{});
auto& task = taskList.tasks.back();
task.name = jsonTaskList[i]["name"].get<std::string>();
task.description = jsonTaskList[i]["description"].get<std::string>();
task.notes = jsonTaskList[i]["notes"].get<std::string>();
auto eventList = jsonTaskList[i]["events"];
for (size_t j = 0; j < eventList.size(); j++) {
task.taskEvents.push_back(TaskEvent{});
auto& event = task.taskEvents.back();
event.type = (TaskEventType)(eventList[j]["type"].get<uint32_t>());
event.timestamp = eventList[j]["time"].get<int64_t>();
event.difficulty = (TaskDifficulty)(eventList[j]["difficulty"].get<uint32_t>());
}
}
} | true |
4881d0af3167ab9b1aabeba56ed845573710f27f | C++ | saulocalixto/UriJudge | /desafio_bino.cpp | UTF-8 | 711 | 3.40625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int quant_num;
cin >> quant_num;
int numeros[quant_num], laco, mult2 = 0, mult3 = 0, mult4 = 0, mult5 = 0;
for(laco = 0; laco < quant_num; laco++)
{
cin >> numeros[laco];
if (numeros[laco] % 2 == 0)
mult2++;
if (numeros[laco] % 3 == 0)
mult3++;
if (numeros[laco] % 4 == 0)
mult4++;
if (numeros[laco] % 5 == 0)
mult5++;
}
cout << mult2 << " Multiplo(s) de 2" << endl;
cout << mult3 << " Multiplo(s) de 3" << endl;
cout << mult4 << " Multiplo(s) de 4" << endl;
cout << mult5 << " Multiplo(s) de 5" << endl;
return 0;
}
| true |
31849f4a55249fdac2ea2a5ed84c0419e57b6dc8 | C++ | God-father1/C-CC- | /recursion/printarray.cpp | UTF-8 | 586 | 3.5625 | 4 | [] | no_license | // { Driver Code Starts
#include <iostream>
using namespace std;
void printArrayRecursively(int arr[],int n);
int main() {
int T;
cin>>T;
while(T--)
{
int N;
cin>>N;
int arr[N];
for(int i=0;i<N;i++)
cin>>arr[i];
printArrayRecursively(arr,N);
cout<<endl;
}
return 0;
}// } Driver Code Ends
//User function Template for C++
void printArrayRecursively(int arr[],int n)
{
//Your code here
//Use recursion to print array elements from start to end
if(n<=0) return ;
printArrayRecursively(arr,n-1);
cout<<arr[n-1]<<" ";
}
| true |
07b1545397aa04008e9ada828ceb647d2dec409c | C++ | hafewa/MoonEngine | /ToyBox/Coroutine.h | GB18030 | 1,945 | 2.9375 | 3 | [
"MIT"
] | permissive | #pragma once
#include<memory>
#include<functional>
#include<queue>
#include<unordered_map>
#include<windows.h>
#define yield_return() Coroutine::get_current_coroutine()->yield()
enum class CoroutineState {
init,
running,
suspend,
term
};
// Based on: https://github.com/Taoist-Yu/Coroutine_Win.
class Coroutine : public std::enable_shared_from_this<Coroutine> {
public:
#define MAX_COROUTINE_NUM 32768
friend class std::shared_ptr<Coroutine>;
typedef std::function<void(void*)> call_back;
typedef std::shared_ptr<Coroutine> ptr;
static std::unordered_map<int, Coroutine::ptr> co_pool;
const static size_t default_stack_size = 1024 * 1024;
void yield();
void resume();
void close();
int get_id();
ptr get_this();
CoroutineState get_state();
static Coroutine::ptr create_coroutine(call_back func, void* args, size_t stack_size = 0);
static ptr get_current_coroutine();
static int get_coroutine_number();
static void deleter(Coroutine* co);
private:
int m_id;
void* cb_args;
bool is_destroyed;
PVOID m_fiber;
call_back cb_func;
CoroutineState m_state;
static Coroutine::ptr main_coroutine;
static ptr current_coroutine;
static int coroutine_num;
static std::queue<Coroutine::ptr> delete_queue;
Coroutine();
Coroutine(Coroutine&) = default;
Coroutine(call_back func, void* args, size_t stack_size);
~Coroutine() { if (m_id != 0) DeleteFiber(this->m_fiber); }
void destroy_self();
static void CALLBACK coroutine_main_func(LPVOID lpFiberParameter);
static void auto_delete();
};
/*
* NOTE:
Ĺ캯һpublicģҲprivateġ캯Ϊ˽еص㣺
<1>ʵΪʵʱⲿڲ˽еĹ캯
<2>ܼ̳Уͬ<1>
ʵķжһstaticһԪרŸʵ
JavaеĹ㡣
*/
| true |
d7ba1c79715e9e0cd195463e1ef122c9ed0a8c77 | C++ | ph4r05/polynomial-distinguishers-cpp | /DataSource/DataSourceDecim.cpp | UTF-8 | 1,567 | 2.546875 | 3 | [] | no_license | //
// Created by Dusan Klinec on 21.06.16.
//
#include <sstream>
#include "DataSourceDecim.h"
#define DECIM_DEFAULT_IV_LEN 16
#define DECIM_DEFAULT_KEY_LEN 16
DataSourceDecim::DataSourceDecim(unsigned long seed, int rounds) {
this->m_gen = new std::minstd_rand((unsigned int) seed);
this->m_rounds = (unsigned)rounds;
this->m_cipher = new ECRYPT_Decim();
this->m_cipher->numRounds = rounds;
this->m_cipher->ECRYPT_init();
uint8_t keyBuff[DECIM_DEFAULT_KEY_LEN];
uint8_t ivBuff[DECIM_DEFAULT_IV_LEN];
for (unsigned char i = 0; i < DECIM_DEFAULT_KEY_LEN; i++) {
keyBuff[i] = (uint8_t) this->m_gen->operator()();
}
for (unsigned char i = 0; i < DECIM_DEFAULT_IV_LEN; i++) {
ivBuff[i] = (uint8_t) this->m_gen->operator()();
}
this->m_cipher->ECRYPT_keysetup(&this->m_ctx, keyBuff, (u32)DECIM_DEFAULT_KEY_LEN*8, (u32)DECIM_DEFAULT_IV_LEN*8);
this->m_cipher->ECRYPT_ivsetup(&this->m_ctx, ivBuff);
}
DataSourceDecim::~DataSourceDecim() {
if (this->m_gen != nullptr) {
delete this->m_gen;
this->m_gen = nullptr;
}
if (this->m_cipher != nullptr){
delete this->m_cipher;
this->m_cipher = nullptr;
}
}
long long DataSourceDecim::getAvailableData() {
return 9223372036854775807; // 2^63-1
}
void DataSourceDecim::read(char *buffer, size_t size) {
this->m_cipher->DECIM_keystream_bytes(&this->m_ctx, (u8*)buffer, (u32)size);
}
std::string DataSourceDecim::desc() {
std::stringstream ss;
ss << "Decim-r" << this->m_rounds;
return ss.str();
}
| true |
36a2802fbed72805e2d355041a0e9fed1a0b1030 | C++ | rohanpillai/bit-torrent | /src/parser.cpp | UTF-8 | 6,319 | 2.9375 | 3 | [] | no_license | #include <parser.h>
using namespace std;
bool isString(char *str) {
if ((((int) str[0]) > 47) && (((int) str[0]) < 58)) {
return true;
}
return false;
}
string getValue(char *str, char **next) {
ostringstream oss;
while ((*str) != ':') {
oss << (*str);
str++;
}
str++;
int size = stoi(oss.str());
oss.clear();
oss.str("");
for (int i = 0; i < size; i++) {
oss << (*str);
str++;
}
*next = str;
return oss.str();
}
bencodedString::bencodedString(char **str) {
char *next;
value = getValue(*str, &next);
*str = next;
type = BENCODED_STRING;
}
void bencodedString::printValue(stringstream &ss) {
ss << '"' << value << '"';
}
bencodedDict::bencodedDict() {
type = BENCODED_DICT;
}
bencodedInteger::bencodedInteger(char **str) {
ostringstream oss;
while (*(*str) != 'e') {
oss << *(*str);
(*str)++;
}
(*str)++;
value = stoi(oss.str());
type = BENCODED_INTEGER;
}
void bencodedInteger::printValue(stringstream &oss) {
oss << value ;
}
bencodedList::bencodedList() {
type = BENCODED_LIST;
}
void bencodedList::insert(char **str) {
if (isString(*str)) {
bencodedString* bstr = new bencodedString(str);
lst.push_back(bstr);
} else {
switch (*(*str)) {
case 'i': {
(*str)++;
bencodedInteger* bint = new bencodedInteger(str);
lst.push_back(bint);
break;
}
case 'e': {
(*str)++;
return;
}
case 'l': {
bencodedList *blist = new bencodedList();
(*str)++;
blist->insert(str);
lst.push_back(blist);
break;
}
case 'd': {
bencodedDict *bdict = new bencodedDict();
(*str)++;
bdict->insert(str);
lst.push_back(bdict);
break;
}
default: {
cout << "Unexpected value " << *str << '\n';
}
}
}
insert(str);
}
void bencodedList::printValue(stringstream &oss) {
oss << "[";
for (list<bencodedObject *>::iterator it=lst.begin(); it != lst.end(); it++) {
(*it)->printValue(oss);
oss << ',';
}
oss << "]\n";
}
bencodedObject *constructValue(char **str) {
if (isString(*str)) {
bencodedString *value = new bencodedString(str);
return value;
}
switch(*(*str)) {
case 'i': {
(*str)++;
return (new bencodedInteger(str));
}
case 'l': {
(*str)++;
bencodedList *value = new bencodedList();
value->insert(str);
return value;
}
case 'd': {
(*str)++;
bencodedDict *value = new bencodedDict();
value->insert(str);
return value;
}
}
}
void bencodedDict::insert(char **str) {
bencodedString *key = new bencodedString(str);
bencodedObject *value = constructValue(str);
bmap[key] = value;
if (*(*str) == 'e') {
(*str)++;
return;
}
insert(str);
}
void bencodedDict::printValue(stringstream &oss) {
oss << "{";
for (map<bencodedString *, bencodedObject *>::iterator it = bmap.begin(); it != bmap.end(); it++) {
oss << '(';
((*it).first)->printValue(oss);
oss << " , ";
((*it).second)->printValue(oss);
oss << ')';
}
oss << "}\n";
}
bencodedObject *bencodedDict::getValueForKey(string key) {
for (map<bencodedString *, bencodedObject *>::iterator it = bmap.begin(); it != bmap.end(); it++) {
if (key.compare(((*it).first)->value) == 0) {
return (*it).second;
}
}
return NULL;
}
bencodedDict *parse_torrent_file(char *file_name) {
ifstream ifs(file_name);
bencodedDict *bdict = NULL;
if (ifs) {
ifs.seekg(0, ifs.end);
int size = ifs.tellg();
ifs.seekg(0, ifs.beg);
char *buffer = new char[size];
ifs.read(buffer, size);
ifs.close();
if (*buffer == 'd') {
bdict = new bencodedDict();
buffer++;
bdict->insert(&buffer);
}
}
return bdict;
}
bt_info_t *extract_bt_info(bencodedDict *metadata) {
string info("info");
string name("name");
string piece_length("piece length");
string length("length");
string pieces("pieces");
bt_info_t *bt_info = (bt_info_t *) malloc(sizeof(bt_info_t));
bencodedObject *binfo = metadata->getValueForKey(info);
if (binfo->type != BENCODED_DICT) {
cout << "The value for info key is not a dictionary\n";
return NULL;
}
bencodedDict *binfo_dict = (bencodedDict *) binfo;
bencodedObject *bname = binfo_dict->getValueForKey(name);
if (bname->type != BENCODED_STRING) {
cout << "The value for name in the torrent file should be a string\n";
return NULL;
}
strncpy(bt_info->name, (((bencodedString *)bname)->value).c_str(), FILE_NAME_MAX);
bencodedObject *bpiece_length= binfo_dict->getValueForKey(piece_length);
if (bpiece_length->type != BENCODED_INTEGER) {
cout << "The value for piece_length in the torrent file should be an integer\n";
return NULL;
}
bt_info->piece_length = (((bencodedInteger *) bpiece_length)->value);
bencodedObject *bfile_length= binfo_dict->getValueForKey(length);
if (bfile_length->type != BENCODED_INTEGER) {
cout << "The value for file length in the torrent file should be an integer\n";
return NULL;
}
bt_info->length = (((bencodedInteger *) bfile_length)->value);
bt_info->num_pieces = (int) ceil(((float) bt_info->length)/((float) bt_info->piece_length));
bencodedObject *bpieces = binfo_dict->getValueForKey(pieces);
if (bpieces->type != BENCODED_STRING) {
cout << "The value for pieces in the torrent file should be a string\n";
return NULL;
}
const char *piece_hashes = (((bencodedString *) bpieces)->value).c_str();
bt_info->piece_hashes = new char*[bt_info->num_pieces];
for (int i=0; i < bt_info->num_pieces; i++) {
bt_info->piece_hashes[i] = new char[20];
strncpy(bt_info->piece_hashes[i], (piece_hashes + i*20), 20);
}
return bt_info;
}
void printInfo(bt_info_t *bt_info) {
printf("Name: %s\n", bt_info->name);
printf("File length: %d\n", bt_info->length);
printf("Piece length: %d\n", bt_info->piece_length);
printf("Number of pieces: %d\n", bt_info->num_pieces);
for (int i=0; i< bt_info->num_pieces; i++) {
printf("Hash value for piece %d: ", i + 1);
for (int j=0; j < 20; j++) {
printf("%02x", (unsigned char) *(bt_info->piece_hashes[i] + j));
}
printf("\n");
}
}
| true |
33ec6cf4cd4c9bfa9b71f82f9dc79cb35be4aad5 | C++ | retrobrain/qChess | /Chess/chesspiece.cpp | UTF-8 | 2,871 | 3.046875 | 3 | [] | no_license | #include "chesspiece.h"
ChessPiece::ChessPiece(QObject *parent) : QObject(parent)
{
}
ChessPiece::ChessPiece(const PieceType &type, const PieceColor &color)
:
QObject(),
m_type(type),
m_color(color),
m_bFirstMoveMade(false)
{
switch (m_type)
{
case PieceType::Knight:
m_vecPossibleDirection.push_back(DirectionHelpers::NNE);
m_vecPossibleDirection.push_back(DirectionHelpers::ENE);
m_vecPossibleDirection.push_back(DirectionHelpers::ESE);
m_vecPossibleDirection.push_back(DirectionHelpers::SSE);
m_vecPossibleDirection.push_back(DirectionHelpers::SSW);
m_vecPossibleDirection.push_back(DirectionHelpers::WSW);
m_vecPossibleDirection.push_back(DirectionHelpers::WNW);
m_vecPossibleDirection.push_back(DirectionHelpers::NNW);
break;
case PieceType::Rook:
m_vecPossibleDirection.push_back(DirectionHelpers::E);
m_vecPossibleDirection.push_back(DirectionHelpers::W);
m_vecPossibleDirection.push_back(DirectionHelpers::N);
m_vecPossibleDirection.push_back(DirectionHelpers::S);
break;
case PieceType::Queen:
case PieceType::King:
m_vecPossibleDirection.push_back(DirectionHelpers::E);
m_vecPossibleDirection.push_back(DirectionHelpers::W);
case PieceType::Pawn:
m_vecPossibleDirection.push_back(DirectionHelpers::N);
m_vecPossibleDirection.push_back(DirectionHelpers::S);
case PieceType::Bishop:
m_vecPossibleDirection.push_back(DirectionHelpers::NW);
m_vecPossibleDirection.push_back(DirectionHelpers::NE);
m_vecPossibleDirection.push_back(DirectionHelpers::SW);
m_vecPossibleDirection.push_back(DirectionHelpers::SE);
break;
}
}
bool ChessPiece::isMovementValid(Direction direction, int range, bool take)
{
for(auto iter : m_vecPossibleDirection)
if(iter == direction)
{
if(m_type == PieceType::Pawn)
return isPawnMovementLegal(direction, range, take);
else if(m_type == PieceType::King)
return isOneTileMove(range);
else
return true;
}
}
bool ChessPiece::isPawnMovementLegal(Direction direction, int range, bool take)
{
if(!(m_color == PieceColor::White && direction < DirectionHelpers::W
|| m_color == PieceColor::Black && direction > DirectionHelpers::E))
return false;
int iFirstPawnMove = m_bFirstMoveMade ? 1 : 2;
if(isOneTileMove(range) && range == DirectionHelpers::S || range / iFirstPawnMove == DirectionHelpers::S)
return !take;
else if(abs(range) == DirectionHelpers::SW || abs(range) == DirectionHelpers::SE)
return take;
return false;
}
bool ChessPiece::isOneTileMove(int range)
{
return (range <= DirectionHelpers::SE);
}
| true |
6c1d24e81bb864bd0db01b25c4fd37d8fb35a3b4 | C++ | sashank-tirumala/mechatronics_lab_project | /17_ButtonLCD_Count/17_ButtonLCD_Count.ino | UTF-8 | 2,027 | 3.203125 | 3 | [] | no_license | /*
Button
Turns on and off a light emitting diode(LED) connected to digital pin 13,
when pressing a pushbutton attached to pin 2.
The circuit:
- LED attached from pin 13 to ground
- pushbutton attached to pin 2 from +5V
- 10K resistor attached to pin 2 from ground
- Note: on most Arduinos there is already an LED on the board
attached to pin 13.
created 2005
by DojoDave <http://www.0j0.org>
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Button
*/
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 7; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
#include <LiquidCrystal.h>
// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 2, en = 3, d4 = 4, d5 = 8, d6 = 12, d7 = 13;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
int count = 0;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT_PULLUP);
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
Serial.begin(9600);
}
int prevstate = 0;
int newstate = 1;
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
newstate= 1;
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
newstate= 0;
}
if(newstate == 0 && prevstate == 1)
{
count++;
}
lcd.print(count);
Serial.println(count);
// Turn off the display:
lcd.noDisplay();
// Turn on the display:
lcd.display();
delay(150);
lcd.clear();
prevstate = newstate;
}
| true |
89212cb221f506e88d5c8f00e2a20aa0545e1f46 | C++ | brunoassish/poorSnake | /snake_.h | UTF-8 | 1,280 | 3.078125 | 3 | [] | no_license | #pragma once
#include "entity.h"
#include "screen.h"
class Snake : public Entity
{
private:
unsigned short int length;
Entity mytail[15];
bool tail[15];
public:
Snake ()
{
setPos(30,30);
setLength(3);
for (int i = 0; i < 3; i++)
mytail[i] = new Entity(position.x, position.y-(i+1));
}
~Snake() {}
void setLength(const int L)
{
length = L;
}
int getLength() const
{
return length;
}
void Ate()
{
tail[length]=true;
length++;
updateTail();
}
void print(Screen& SCR)
{
SCR.screen[position.x-1][position.y-1]=true;
unsigned short int i;
for(i=0; i <length; i++)
{
mytail[i].print(SCR);
}
}
void up()
{
updateTail();
position.y--;
}
void down()
{
updateTail();
position.y++;
}
void right()
{
updateTail();
position.x++;
}
void left()
{
updateTail();
position.x--;
}
void updateTail()
{
unsigned short int i;
for(i=length-1; i > 0; i--)
{
mytail[i] = mytail[i-1];
}
mytail[0].setPos(position);
}
};
| true |
0052ed80ec3cac68a51b394c8b7e833af40e48cd | C++ | nicoperetti/TAP-2016 | /UVA/10646.cc | UTF-8 | 962 | 3.203125 | 3 | [] | no_license | #define toDigit(c) c-'0'
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int value(string card) {
if (isdigit(card[0])) {
return toDigit(card[0]);
} else {
return 10;
}
}
int main() {
int TC;
int i; // iterator
int index_pile;
int Y, X;
string card;
vector<string> v, h;
cin >> TC;
for (int j=0; j<TC; j++) {
cout << "Case " << j+1 << ": ";
Y = 0;
index_pile = 51;
v.clear();
for (i=0; i <= index_pile; i++) {
cin >> card;
v.push_back(card);
}
index_pile -= 25;
for(i=0; i < 3; i++) {
X = value(v[index_pile]);
Y += X;
index_pile -= (11 - X);
}
Y--;
if (Y <= index_pile) {
cout << v[Y] << endl;
} else {
cout << v[(52-25)+Y-(index_pile+1)] << endl;
}
}
}
| true |
0fd3fcc3488544cac210d151ca00ce00342b9705 | C++ | saranshrawat/Data-structure-and-algorithms | /strings/strings 1st/longest recurring subsequce in a string.cpp | UTF-8 | 590 | 3.171875 | 3 | [] | no_license | //dynamic programming --- length of longest recurring subsequecne
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void lrs(string s)
{ int n=s.length();
int arr[n][n]={};
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(s[i-1]==s[j-1] &&i!=j) //this i!=j only for recurring subseq
arr[i][j]=1+ arr[i-1][j-1];
else
arr[i][j]=max(arr[i][j-1],arr[i-1][j]);
}
}
int len=arr[n][n];
cout<<len;
}
int main()
{
cout<<"enter a string";
string s;
cin>>s;
lrs(s);
return 0;
}
| true |
2019f43a7dc29fb7846d1e73cd86946195dbb742 | C++ | l1021635438/Game_zinx | /customer/Player/aoi.cpp | UTF-8 | 3,220 | 2.671875 | 3 | [] | no_license | #include "aoi.h"
AOIMgr *AOIMgr::pxAoiMgr = NULL;
Grid::Grid(int _gid, int _minx, int _maxx, int _miny, int _maxy):Gid(_gid), MinX(_minx), MaxX(_maxx), MinY(_miny), MaxY(_maxy)
{
}
void Grid::Add(PlayerRole * _player)
{
players.push_back(_player);
}
void Grid::Remove(PlayerRole * _player)
{
players.remove(_player);
}
AOIMgr::AOIMgr(int _minx, int _maxx, int _miny, int _maxy, int _cntx, int _cnty):MinX(_minx),MaxX(_maxx), MinY(_miny), MaxY(_maxy), CntsX(_cntx), CntsY(_cnty)
{
for (int y = 0; y < CntsY; ++y)
{
for (int x = 0; x < CntsX; x++)
{
int gid = y * CntsX + x;
Grid *pxGrid = new Grid(gid,
MinX + x * gridWidth(),
MinX + (x + 1) * gridWidth(),
MinY + y * gridLength(),
MinY + (y + 1) * gridLength());
m_grids.push_back(pxGrid);
}
}
}
void AOIMgr::GetSurroundingGridsByGid(int _gid, list<Grid *> &outgrids)
{
if (_gid < 0 || (unsigned int)_gid >= m_grids.size())
{
return;
}
outgrids.push_back(m_grids[_gid]);
int y = _gid / CntsX;
if (y > 0)
{
outgrids.push_back(m_grids[_gid - CntsX]);
}
if (y < (CntsY - 1))
{
outgrids.push_back(m_grids[_gid + CntsX]);
}
int x = _gid % CntsX;
if (x > 0)
{
int gid = (_gid - 1);
outgrids.push_back(m_grids[gid]);
int y = gid / CntsX;
if (y > 0)
{
outgrids.push_back(m_grids[gid - CntsX]);
}
if (y < (CntsY - 1))
{
outgrids.push_back(m_grids[gid + CntsX]);
}
}
if (x < (CntsX - 1))
{
int gid = _gid + 1;
outgrids.push_back(m_grids[gid]);
int y = gid / CntsX;
if (y > 0)
{
outgrids.push_back(m_grids[gid - CntsX]);
}
if (y < (CntsY - 1))
{
outgrids.push_back(m_grids[gid + CntsX]);
}
}
}
int AOIMgr::GetGidbyPos(int x, int y)
{
int gx = (x - MinX) / gridWidth();
int gy = (y - MinY) / gridLength();
return gy * CntsX + gx;
}
void AOIMgr::GetPlayersByPos(int x, int y, list < PlayerRole * > &players)
{
int gid = GetGidbyPos(x, y);
list<Grid *> Grids;
GetSurroundingGridsByGid(gid, Grids);
auto itr = Grids.begin();
for (; itr != Grids.end(); itr++)
{
list<PlayerRole *> tmpList = list<PlayerRole *>((*itr)->players);
players.splice(players.begin(), tmpList);
}
return;
}
void AOIMgr::GetPlayersInGridByGid(int _gid, list < PlayerRole * > & players)
{
players = m_grids[_gid]->players;
}
void AOIMgr::RemovePlayerFromGrid(PlayerRole * _player, int _gid)
{
m_grids[_gid]->Remove(_player);
}
void AOIMgr::AddPlayerToGrid(PlayerRole * _player, int _gid)
{
m_grids[_gid]->Add(_player);
}
void AOIMgr::Add2GridByPos(PlayerRole * _player, int x, int y)
{
int gid = GetGidbyPos(x, y);
AddPlayerToGrid(_player, gid);
}
void AOIMgr::RemoveFromGridByPos(PlayerRole * _player, int x, int y)
{
int gid = GetGidbyPos(x, y);
RemovePlayerFromGrid(_player, gid);
}
| true |
d72d108655cdf6bb6ed0ed7d69af588abf7499ba | C++ | Bifido/NetworkingProgramming | /ProfSolution/netlib/BitStream.h | UTF-8 | 2,851 | 2.84375 | 3 | [] | no_license | //
// BitStream.h
// superasteroids
//
// Created by Cristian Marastoni on 31/05/14.
//
//
#pragma once
#include <string.h>
#include "NetTypes.h"
#include <string>
class BitStream {
public:
BitStream();
BitStream(uint8 *data, size_t size, bool read=false);
BitStream(const uint8 *data, size_t size);
virtual ~BitStream();
const uint8 *buffer() const;
const uint8 *read_ptr() const;
uint32 size() const;
void seek(int32 nbits) const;
void skip(uint32 nbits) const;
void skip_bytes(uint32 nbytes) const;
uint32 bitpos() const;
uint32 bytepos() const;
uint32 remaining_bytes() const;
bool eof() const;
void flush();
void setData(uint8 *data, size_t size);
void setData(uint8 const *data, size_t size);
void subStream(uint32 bitPos, uint32 size, BitStream &out) const;
void copyData(uint32 bytePos, uint32 size, void *out) const;
BitStream &pack_s8(char data);
BitStream &pack_s16(int16 data);
BitStream &pack_s32(int32 data);
BitStream &pack8(uint8 data);
BitStream &pack16(uint16 data);
BitStream &pack32(uint32 data);
BitStream &pack64(uint64 data);
BitStream &packFloat(float data);
BitStream &packString(const char *str);
BitStream &packString(std::string const &str);
BitStream &packData(void const *data, size_t size);
//Attention! data must be byte aligned to append the content (for both performance and correctness)
BitStream &append(void const *data, size_t size);
BitStream &align();
BitStream const &align() const;
BitStream const &unpack8(uint8 &data) const;
BitStream const &unpack16(uint16 &data) const;
BitStream const &unpack32(uint32 &data) const;
BitStream const &unpack64(uint64 &data) const;
BitStream const &unpackFloat(float &data) const;
BitStream const &unpack_s8(char &data) const;
BitStream const &unpack_s16(int16 &data) const;
BitStream const &unpack_s32(int32 &data) const;
BitStream const &unpackString(char *buffer, uint32 bufferSize) const;
BitStream const &unpackString(std::string &str) const;
uint32 unpackData(uint8 *buffer, uint32 bufferSize) const;
private:
BitStream &packBits(unsigned int data, int nBits);
uint32 unpackBits(int nBits) const ;
void writeToBuffer(uint32 bits);
void readFromBuffer(uint32 *bits) const;
void cacheBits(uint32 *bits) const;
private:
union {
uint8 *mWriteBuffer;
uint8 const *mReadBuffer;
};
uint32 mBufferSize;
uint32 mBitCount;
mutable uint32 mBitPos;
mutable uint32 mBitLeft;
mutable uint32 mBitBuf;
};
template<int SIZE>
class NetStackData : public BitStream {
public:
NetStackData() : BitStream(mBuffer, SIZE) {
}
uint32 capacity() const {
return SIZE;
}
private:
uint8 mBuffer[SIZE];
};
| true |
0efde6015feb13190adf169b17512c432467d049 | C++ | HassanDhariwal/my_programs- | /time calculation/funcations/Level 1/program 5/5.cpp | UTF-8 | 294 | 3 | 3 | [] | no_license | #include<iostream>//take nothing retrun nothing
void whether();
using namespace std;
int main()
{
whether();
}
void whether()
{
int a;
cout<<"enter a number for whether even and odd:";
cin>>a;
if(a%2==0) //
cout<<"Even no is"<<" : "<<a<<endl;
else
cout<<"odd no is"<<" : "<<a<<endl;
}
| true |
ef08c48ec73e0ce48fada8a211bcec38f170656f | C++ | Uxell/SimulatedAnnealing_JobShop | /cpp_code/task.cpp | UTF-8 | 290 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "task.h"
Task::Task() {}
void Task::setMachineId(int machine_id)
{
this->machine_id = machine_id;
}
void Task::setDuration(int duration)
{
this->duration = duration;
}
int Task::getMachineId()
{
return this->machine_id;
}
int Task::getDuration()
{
return this->duration;
} | true |
34ba0cea7f95c7ece0a22abe8ba588682196edda | C++ | harababurel/homework | /sem5/pkc/classpher/util/factorization.cc | UTF-8 | 501 | 2.546875 | 3 | [] | no_license | #include "factorization.h"
#include "ntl_hash.h"
namespace f11n {
Factorization Factorization::operator&(const Factorization& other) const {
Factorization common;
for (const auto& factor : factors()) {
const auto& base = factor.first;
const auto& exponent = factor.second;
if (other.Contains(base)) {
const auto& other_exponent = other.GetExponent(base);
common.AddOrUpdate(base, std::min(exponent, other_exponent));
}
}
return common;
}
} // namespace f11n
| true |
0069368256bba9a573e1a8fd94e6e3b7d3a07fea | C++ | 0llamh/university | /Object Oriented Programming/assignments/assignment3/time.cpp | UTF-8 | 7,993 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <iomanip>
#include "time.h"
using namespace std;
//FRIEND FUNCTIONS
bool operator<(const Time& t1, const Time& t2)
{
//ALL BOOL FUNCTIONS ARE DEFINED USING THIS ONE. ALL OTHER
//BOOLS HAVE REFERENCE BACK TO HERE JUST TO MAKE BUG FIXING EASIER
if (t1.day < t2.day)
return true;
else if (t1.day == t2.day)
{
if (t1.hour < t2.hour)
return true;
else if (t1.hour == t2.hour)
{
if (t1.minute < t2.minute)
return true;
else if (t1.minute == t2.minute)
{
if (t1. second < t2.second)
return true;
else
return false;
}
else
return false;
}
else
return false;
}
else
return false;
}
bool operator>(const Time& t1, const Time& t2)
{
if (t2 < t1)
return true;
else
return false;
}
bool operator==(const Time& t1, const Time& t2)
{
if (t1 < t2 || t2 < t1)
return false;
else
return true;
}
bool operator!=(const Time& t1, const Time& t2)
{
if (t1 < t2 || t2 < t1)
return true;
else
return false;
}
bool operator<=(const Time& t1, const Time& t2)
{
if (t2 < t1)
return false;
else
return true;
}
bool operator>=(const Time& t1, const Time& t2)
{
if (t1 < t2) //USES THE ORIGINAL BOOL OPERATOR (FOR EASIER BUG FIXES)
return false;
else
return true;
}
Time operator+(const Time& t1, const Time& t2)
{
//CONVERTS ALL TO SECONDS AND ADDS UP BOTH TIME VALUES
int seconds = ((t1.second + t2.second) + (60 * (t1.minute + t2.minute)) + (3600 * (t1.hour + t2.hour)) + (86400 * (t1.day + t2.day)));
Time t3(seconds); //INIT RESULT TIME WITH TOTAL # OF SECONDS
t3.TimeCheck(t3.day, t3.hour, t3.minute, t3.second); //ERROR CHECKING
return t3; //RETURNS THE RESULT
}
Time operator-(const Time& t1, const Time& t2)
{
//CONVERTS ALL TO THEIR INDIVIDUAL TOTAL SECOND VALUES
int t3_seconds, t2_seconds, t1_seconds;
t1_seconds = (t1.second + ( 60 * (t1.minute)) + ( 3600 * ( t1.hour)) + ( 86400 * ( t1.day)));
t2_seconds = (t2.second + ( 60 * (t1.minute)) + ( 3600 * ( t1.hour)) + ( 86400 * ( t1.day)));
if (t1_seconds > t2_seconds) //DETERMINES IF T1 IS GREATER
t3_seconds = t1_seconds - t2_seconds;
else //IF NOT, T3 = 0 SECONDS
t3_seconds = 0;
Time t3(t3_seconds); //INITALIZES RESULT TIME WITH TOTAL REMAINING SECONDS
t3.TimeCheck(t3.day, t3.hour, t3.minute, t3.second); //ERROR CHECKING
return t3; //RETURNS RESULT
}
Time operator*(const Time& t1, int x)
{
int seconds = ((t1.second) + (60 * (t1.minute)) + (3600 * (t1.hour)) + (86400 * (t1.day)));
seconds = seconds * x; //TOTAL # OF SECONDS MULTIPLIED BY AN INTEGER
Time t2(seconds); //INIT RESULT TIME WITH TOTAL SECONDS
t2.TimeCheck(t2.day, t2.hour, t2.minute, t2.second); //ERROR CHECK AND OVERLAP FUNCTION
return t2; //RETURNS RESULT TIME
}
ostream& operator<<(ostream& x, const Time& t1)
{
if (t1.day == 0) //DAY COUNTER
x << "0" << '~';
else
x << t1.day << '~';
if ( t1.hour == 0) //HOUR COUNTER
x << "00:";
else if (t1.hour < 10)
x << '0' << t1.hour << ':';
else
x << t1.hour << ':';
if (t1.minute == 0) //MINUTE COUNTER
x << "00:";
else if (t1.minute < 10)
x << '0' << t1.minute << ':';
else
x << t1.minute << ':';
if (t1.second == 0) //SECOND COUNTER
x << "00";
else if (t1.second < 10)
x << '0' << t1.second;
else
x << t1.second;
return x; //RETURN THE OUTPUT
}
istream& operator>>(istream& x, Time& t1)
{
char colon; //DUMMY CHAR TO ABSORB THE :
char tilda; //ABSORBS THE ~
int d, h, m, s; //INPUT VALUES
x >> d >> tilda >> h >> colon >> m >> colon >> s; //INSERTION OPERATOR
t1.Time::TimeCheck(d, h, m, s); //CONVERSION/OVERLAP/ERROR CHECK FUNCTION
return x; //RETURNS THE INSERTION
}
//CONSTRUCTORS
Time::Time() //DEFAULT CONSTRUCTOR
{
day = 0;
hour = 0;
minute = 0;
second = 0;
}
Time::Time(int s)
{
day = 0; //VARIABLE INITIATION
hour = 0;
minute = 0;
second = s;
int sec_overlap = second/60; //ALLOWS FOR THE THE NUMBER OF OVERLAPS IN THE SECOND
for (int i1 = 0; i1 < sec_overlap; i1++)
{
second = second - 60; //DECREMENTS THE NUMBER OF SECONDS PER MINUTE
minute++; //MINUTE INCREMENT
}
if (minute >= 60) //ALLOWS FOR MINUTE OVERLAP FOR HOURS
{
int min_overlap = minute/60; //NUMBER OF MINUTE OVERLAPS
for (int i2 = 0; i2 < min_overlap; i2++)
{
minute = minute - 60; //MINUTE DECCREMENT IN HOURS
hour++; //HOUR INCREMENT
}
}
if (hour >= 24) //HOUR OVERLAP
{
int hour_overlap = hour/24;
for (int i3 = 0; i3 < hour_overlap; i3++)
{
hour = hour - 24; //HOUR DECREMENT
day++; //DAY INCREMENT
}
}
}
Time::Time(int d, int h, int m, int s)
{
TimeCheck(d, h, m, s); //ERROR CHECKING FUNCTION
}
//MEMBER FUNCTIONS
Time& Time::operator++()
{
second = second + 1; //CHANGES THE TIME BY +1 SECOND
TimeCheck(day, hour, minute, second); //ERROR CHECK
return *this; //RETURNS THE NEW TIME
}
Time& Time::operator--()
{
second = second - 1;
if (second < 0 && (minute > 0 || hour > 0 || day > 0))
{
second = 59; //RESETS SECONDS
minute = minute - 1; //DOCKS ONE MINUTE
if (minute < 0 && (hour > 0 || day > 0))
{
minute = 59; //RESETS MINUTES
hour = hour - 1; //DOCKS ONE HOUR
if (hour < 0 && day > 0)
{
hour = 23; //RESETS HOURS
day = day - 1; //DOCKS ONE DAY
}
}
else if (minute < 0 && (hour <= 0 || day <= 0))
minute = 0;
}
else if (second < 0)
second = 0;
TimeCheck(day, hour, minute, second); //ERROR CHECKING FOR NEGATIVES
return *this;
}
Time Time::operator++(int)
{
Time temp = *this; //INITIALIZES A COPY OF THE CALLING OBJECT
second = second + 1; //CHANGES THE TIME BY +1 SECOND
TimeCheck(day, hour, minute, second);
return temp; //RETURNS THE OLD TIME
}
Time Time::operator--(int)
{
Time temp = *this;
second = second - 1;
if (second < 0 && (minute > 0 || hour > 0 || day > 0))
{
second = 59; //RESETS SECONDS
minute = minute - 1; //DOCKS ONE MINUTE
if (minute < 0 && (hour > 0 || day > 0))
{
minute = 59; //RESETS MINUTES
hour = hour - 1; //DOCKS ONE HOUR
if (hour < 0 && day > 0)
{
hour = 23; //RESETS HOURS
day = day - 1; //DOCKS ONE DAY
}
}
else if (minute < 0 && (hour <= 0 || day <= 0))
minute = 0;
}
else if (second < 0)
second = 0;
TimeCheck(day, hour, minute, second); //ERROR CHECKING FOR NEGATIVES
return temp;
}
//ERROR CHECKING FUNCTION
void Time::TimeCheck(int d, int h, int m, int s)
{
day = d; //INITIATION VALUES OF TIME
hour = h; //ERROR CHECKING IN ORDER
minute = m; //TO CHECK FOR OVERFLOW
second =s;
if (second >= 60) //ERROR CHECKING FOR SECOND OVERLAPS
{
int sec_overlap = second/60;
for (int i4 = 0; i4 < sec_overlap; i4++)
{
second = second - 60;
minute++;
}
}
else if (second <= 0) //NEGATIVE CHECK
second = 0;
if (minute >= 60) //ERROR CHECKING FOR MINUTE OVERLAPS
{
int min_overlap = minute/60;
for (int i5 = 0; i5 < min_overlap; i5++)
{
minute = minute - 60;
hour++;
}
}
else if (minute <= 0) //NEGATIVE CHECK
minute = 0;
if (hour >= 24) //ERROR CHECKING FOR HOUR OVERLAPS
{
int hour_overlap = hour/24;
for (int i6 = 0; i6 < hour_overlap; i6++)
{
hour = hour - 24;
day++;
}
}
else if (hour <= 0) //NEGATIVE CHECK
hour = 0;
if (day <= 0) //NEGATIVE CHECK
day = 0;
}
| true |
f27b9db5de039b833e3777e59a70616cc20dddb8 | C++ | Harkaan/imPROVE | /Engine/TextureCache.cpp | ISO-8859-1 | 721 | 3.171875 | 3 | [] | no_license | #include "TextureCache.h"
#include <iostream>
namespace Engine
{
TextureCache::TextureCache()
{
}
TextureCache::~TextureCache()
{
}
Texture TextureCache::getTexture(std::string texturePath)
{
//Cherche la texture dans le cache
auto mit = _textureMap.find(texturePath);
//Si la texture recherche n'est pas dans le cache, on la charge
if (mit == _textureMap.end()) {
Texture newTexture = Texture::loadPNG(texturePath); // on charge la texture
std::cout << "Loaded new texture " << texturePath << std::endl;
_textureMap.insert(make_pair(texturePath, newTexture)); // on l'insre dans la map (cache)
return newTexture;
}
//Si la texture existe on la renvoie
return mit->second;
}
}
| true |