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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8f464b713a60aab24fdd56c4969f571cc7e8d762 | C++ | 4nc3str4l/CrisIGuillem | /Grafics/p0/Poligons/circle.cpp | UTF-8 | 232 | 2.890625 | 3 | [] | no_license | #include "circle.h"
Circle::Circle()
{
}
Circle::Circle(double r):
radius(r)
{
}
Circle::~Circle()
{
}
double Circle::getPerimeter()
{
return 2*M_PI*radius;
}
void Circle::setRadius(double r)
{
this->radius = r;
}
| true |
c6a456c1e2d25550dfd938254466bde793554101 | C++ | ArduinoMeetsZXSpectrum/ZX-Modern-Controller-Interface | /KeyboardMapping.h | UTF-8 | 701 | 2.609375 | 3 | [] | no_license | /*
* KeyboardMapping.h
*
* Created on: 11. 8. 2017
* Author: aluchava
*/
#ifndef KEYBOARDMAPPING_H_
#define KEYBOARDMAPPING_H_
#include <stdint.h>
class KeyboardMapping
{
private:
uint8_t keyUp;
uint8_t keyDown;
uint8_t keyLeft;
uint8_t keyRight;
uint8_t keyFire1;
uint8_t keyAutoFire1;
public:
KeyboardMapping(uint8_t keyUp, uint8_t keyDown, uint8_t keyLeft, uint8_t keyRight, uint8_t keyFire1, uint8_t keyAutoFire1);
virtual ~KeyboardMapping();
uint8_t getKeyUp();
uint8_t getKeyDown();
uint8_t getKeyLeft();
uint8_t getKeyRight();
uint8_t getKeyFire1();
uint8_t getKeyAutoFire1();
};
#endif /* KEYBOARDMAPPING_H_ */
| true |
5263e732bbdc60dd588f811ae1eab65ddd8253aa | C++ | alexfordc/Quan | /StockAnalysis/StockAnlysis/ema.cpp | UTF-8 | 381 | 2.71875 | 3 | [] | no_license | #include "StdAfx.h"
#include "ema.h"
EMA::EMA(int cycle)
:cycle_(cycle)
{
}
EMA::~EMA(void)
{
}
void EMA::Calculate(const double value)
{
if (items_.empty())
{
items_.push_back(value);
return;
}
double d = (2 * value + (cycle_ - 1) * items_[items_.size()-1]) / (cycle_ + 1);
items_.push_back(d);
}
double EMA::GetLatestValue()
{
return items_[items_.size() - 1];
} | true |
e08f12a4eb2f139dc5a1b23642a338fb7df1909e | C++ | andmcgregor/project_euler | /020.cpp | UTF-8 | 644 | 3.359375 | 3 | [] | no_license | #include <stdio.h>
#include <vector>
int factorial_sum(int num)
{
std::vector<int> bignum = { num };
int sum = 0,
remainder = 0;
for (int i = num - 1; i > 0; i--) {
for (int j = bignum.size() - 1; j >= 0; j--) {
bignum[j] *= i;
bignum[j] += remainder;
remainder = bignum[j] / 10;
bignum[j] = bignum[j] % 10;
}
while (remainder != 0) {
bignum.insert(bignum.begin(), remainder % 10);
remainder /= 10;
}
}
for (int i = 0; i < bignum.size(); i++)
sum += bignum[i];
return sum;
}
int main(int argc, char** argv)
{
printf("%i\n", factorial_sum(100));
return 0;
}
| true |
1904b0b17904b87365b19030aa3985fbe6d92849 | C++ | DyingBunny/C-Plus-Plus | /课堂代码/Person.h | UTF-8 | 161 | 2.609375 | 3 | [] | no_license | #pragma once
class Person
{
void SetPersonInfo(char* name, char* gender, int age);
void PrintPersonInfo();
char _name[20];
char _gender[3];
int _age;
};
| true |
cec8073dc9be1ac679a93f19fee49362fb363cbf | C++ | Suqu13/ZMPO_Lab | /List_Live/CPunkt.cpp | UTF-8 | 728 | 3.5 | 4 | [] | no_license | //
// Created by Jakub on 22.11.2018.
//
#include <sstream>
#include "CPunkt.h"
CPunkt::CPunkt(int x, int y) {
this->x = new int(x);
this->y = new int(y);
}
CPunkt::CPunkt(CPunkt &pcOther) {
x = new int();
y = new int();
*x = *(pcOther.x);
*y = *(pcOther.y);
}
CPunkt::~CPunkt() {
delete x;
delete y;
}
int CPunkt::getX() const {
return *x;
}
void CPunkt::setX(int x_) {
*x = x_;
}
int CPunkt::getY() const {
return *y;
}
void CPunkt::setY(int y_) {
*y = y_;
}
void CPunkt::operator=(CPunkt &punkt) {
*x = *(punkt.x);
*y = *(punkt.y);
}
ostream &operator<<(ostream &os, const CPunkt &punkt) {
os << "x: " << *punkt.x << " y: " << *punkt.y;
return os;
}
| true |
8b150cfe5b2b43bc926309649ca6cb5f6692d91c | C++ | Tachone/AVL | /Lend/UserInfo.cpp | GB18030 | 787 | 3.375 | 3 | [] | no_license | #include "UserInfo.h"
//ֹ캯ʵ
UserInfo::UserInfo(string name, string pass)
{
username = name;
password = "123456";
}
UserInfo::UserInfo(string name)
{
username = name;
password = "123456";
}
UserInfo::UserInfo(const UserInfo &b)//ƹ캯
{
username = b.username;
password = b.password;
}
//
bool operator <(const UserInfo &a, const UserInfo &b)
{
return a.username < b.username;
}
bool operator >(const UserInfo &a, const UserInfo &b)
{
return a.username > b.username;
}
bool UserInfo::operator == (const UserInfo &b)//뱾Ƚ
{
if (this->username == b.username)
return true;
else
return false;
}
ostream& operator <<(ostream &output, const UserInfo &b)
{
output << b.username;
return output;
} | true |
c171538d3a3d9347483e40a93aeada6a4776b088 | C++ | esalagran/practicaPro2 | /Cjt_Clusters.cc | UTF-8 | 3,073 | 2.640625 | 3 | [] | no_license | #include "Cjt_Clusters.hh"
#include "Taula_de_distancies.hh"
#include <iostream>
using namespace std;
Cjt_Clusters::Cjt_Clusters() {
Arbre = map<string, BinTree< pair<string, double>>>();
}
void Cjt_Clusters::ejecutar_paso_wpgma() {
pair<string,string> id_minims = Taula_Clusters.dist_min();
string nou_cluster = id_minims.first + id_minims.second;
Taula_Clusters.afegeix_especie_cluster(nou_cluster, id_minims);
double distancia_cluster = Taula_Clusters.distancia(id_minims.first,id_minims.second)/2;
Taula_Clusters.eliminar_especie(id_minims.first);
Taula_Clusters.eliminar_especie(id_minims.second);
pair<string, double> nou_clu;
nou_clu.first = nou_cluster;
nou_clu.second = distancia_cluster;
map<string, BinTree< pair<string, double>>>::iterator it1 = Arbre.find(id_minims.first);
BinTree<pair<string,double>> clu_left = it1->second;
map<string, BinTree< pair<string, double>>>::iterator it2 = Arbre.find(id_minims.second);
BinTree<pair<string,double>> clu_righ = it2->second;
BinTree<pair<string,double>> arbre_nou(nou_clu,clu_left,clu_righ);
Arbre.insert(make_pair(nou_cluster,arbre_nou));
Arbre.erase(id_minims.first);
Arbre.erase(id_minims.second);
}
void Cjt_Clusters::imprime_cluster(BinTree<pair<string,double>> arbre) {
if (not arbre.empty()) {
cout <<"[";
if (arbre.value().second != 0) {
cout << "(" << arbre.value().first << ", " << arbre.value().second << ") ";
imprime_cluster(arbre.left());
imprime_cluster(arbre.right());
}
else {
cout << arbre.value().first;
}
cout << "]";
}
}
void Cjt_Clusters::imprime_cluster_aux(BinTree<pair<string,double>>& arb) {
imprime_cluster(arb);
cout << endl;
}
bool Cjt_Clusters::existe_cluster(string id) {
map <string, BinTree<pair<string,double>>>::iterator it = Arbre.find(id);
if (it == Arbre.end()) {
Arbre.erase(id);
return false;
}
else {
return true;
}
}
int Cjt_Clusters::numero_clusters() {
return Arbre.size();
}
void Cjt_Clusters::imprime_arbol_filogenetico() {
for (map <string, BinTree<pair<string,double>>>::const_iterator it = Arbre.begin(); it != Arbre.end(); ++it) {
imprime_cluster(it->second);
}
cout << endl;
}
void Cjt_Clusters::inicializa_clusters(Cjt_Especies& Mostra, Taula_de_distancies& Taula) {
Arbre.clear();
vector<string> vec = Mostra.retorna_especies();
Taula_Clusters = Taula;
for (int i = 0; i < vec.size(); ++i) {
pair<string, double> p;
p.first = vec[i];
p.second = 0;
BinTree<pair<string, double>> arb(p);
Arbre.insert(make_pair(vec[i], arb));
}
}
void Cjt_Clusters::taula_clusters_imprime() {
Taula_Clusters.tabla_distancias();
}
BinTree<pair<string,double>> Cjt_Clusters::retorna_subarb(string id) {
map<string,BinTree<pair<string,double>>>::const_iterator it = Arbre.find(id);
return it->second;
}
| true |
86aa194cd2c6e924b03697862e58ec032ba44759 | C++ | Fraguinha/BSc | /CG/Projecto/src/game.cpp | UTF-8 | 10,092 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "game.hpp"
// -----------------------------------------------------------------------------
// Private methods
void Game::processInput(Window *window, Pacman *pacman) {
if (Game::state == active) {
if (glfwGetKey(window->getWindow(), GLFW_KEY_W) == GLFW_PRESS ||
glfwGetKey(window->getWindow(), GLFW_KEY_UP) == GLFW_PRESS) {
pacman->setOrientation(up);
}
if (glfwGetKey(window->getWindow(), GLFW_KEY_A) == GLFW_PRESS ||
glfwGetKey(window->getWindow(), GLFW_KEY_LEFT) == GLFW_PRESS) {
pacman->setOrientation(left);
}
if (glfwGetKey(window->getWindow(), GLFW_KEY_S) == GLFW_PRESS ||
glfwGetKey(window->getWindow(), GLFW_KEY_DOWN) == GLFW_PRESS) {
pacman->setOrientation(down);
}
if (glfwGetKey(window->getWindow(), GLFW_KEY_D) == GLFW_PRESS ||
glfwGetKey(window->getWindow(), GLFW_KEY_RIGHT) == GLFW_PRESS) {
pacman->setOrientation(right);
}
}
if (Game::state == pause) {
if (glfwGetKey(window->getWindow(), GLFW_KEY_ENTER) == GLFW_PRESS) {
switch (this->menuItem) {
case 0:
Game::state = active;
break;
case 1:
this->resetGame();
break;
case 2:
glfwSetWindowShouldClose(this->window->getWindow(), 1);
break;
}
}
}
}
void Game::handleKeyboardInput(GLFWwindow *window, int key, int scancode,
int action, int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
if (Game::state != pause) {
Game::state = pause;
} else {
Game::state = active;
}
}
if (Game::state == pause) {
if ((key == GLFW_KEY_W && action == GLFW_PRESS) ||
(key == GLFW_KEY_UP && action == GLFW_PRESS)) {
Game::menuItem = (Game::menuItem - 1) % 3;
if (Game::menuItem < 0) {
Game::menuItem += 3;
}
}
if ((key == GLFW_KEY_S && action == GLFW_PRESS) ||
(key == GLFW_KEY_DOWN && action == GLFW_PRESS)) {
Game::menuItem = (Game::menuItem + 1) % 3;
}
}
}
bool Game::processExit(Window *window) {
return !glfwWindowShouldClose(window->getWindow());
}
void Game::setMode(long long seconds, long long timer) {
this->checkDuration(seconds);
this->checkEnergyzer(timer);
}
void Game::checkDuration(long long seconds) {
// wave 1
if (seconds == 0 + 1 + START_STATE + ENERGYZER_TIME * this->energyzerEaten &&
this->modeTracker == 0) {
Ghost::setMode(scatter);
this->modeTracker += 1;
}
if (seconds == 7 + 1 + START_STATE + ENERGYZER_TIME * this->energyzerEaten &&
this->modeTracker == 1) {
for (Ghost *ghost : this->ghosts) {
ghost->turnAround();
}
Ghost::setMode(chase);
this->modeTracker += 1;
}
// wave 2
if (seconds == 27 + 1 + START_STATE + ENERGYZER_TIME * this->energyzerEaten &&
this->modeTracker == 2) {
for (Ghost *ghost : this->ghosts) {
ghost->turnAround();
}
Ghost::setMode(scatter);
this->modeTracker += 1;
}
if (seconds == 34 + 1 + START_STATE + ENERGYZER_TIME * this->energyzerEaten &&
this->modeTracker == 3) {
for (Ghost *ghost : this->ghosts) {
ghost->turnAround();
}
Ghost::setMode(chase);
this->modeTracker += 1;
}
// wave 3
if (seconds == 54 + 1 + START_STATE + ENERGYZER_TIME * this->energyzerEaten &&
this->modeTracker == 4) {
for (Ghost *ghost : this->ghosts) {
ghost->turnAround();
}
Ghost::setMode(scatter);
this->modeTracker += 1;
}
if (seconds == 59 + 1 + START_STATE + ENERGYZER_TIME * this->energyzerEaten &&
this->modeTracker == 5) {
for (Ghost *ghost : this->ghosts) {
ghost->turnAround();
}
Ghost::setMode(chase);
this->modeTracker += 1;
}
// wave 4
if (seconds == 79 + 1 + START_STATE + ENERGYZER_TIME * this->energyzerEaten &&
this->modeTracker == 6) {
for (Ghost *ghost : this->ghosts) {
ghost->turnAround();
}
Ghost::setMode(scatter);
this->modeTracker += 1;
}
if (seconds == 84 + 1 + START_STATE + ENERGYZER_TIME * this->energyzerEaten &&
this->modeTracker == 7) {
for (Ghost *ghost : this->ghosts) {
ghost->turnAround();
}
Ghost::setMode(chase);
this->modeTracker += 1;
}
}
void Game::checkEnergyzer(long long timer) {
if (timer <= ENERGYZER_TIME && this->energyzerEaten > 0) {
if (this->lastModeTracker == false) {
this->lastMode = Ghost::getMode();
}
this->lastModeTracker = true;
Ghost::setMode(frightened);
} else if (this->lastModeTracker) {
this->lastModeTracker = false;
Ghost::setMode(this->lastMode);
this->ghostMultiplyer = 1;
}
}
void Game::checkColision() {
glm::vec2 pacmanCenter = this->maze->getCenter(this->pacman->getPosition());
glm::vec2 ghostCenter;
for (Ghost *ghost : ghosts) {
ghostCenter = this->maze->getCenter(ghost->getPosition());
if ((ghostCenter.x == pacmanCenter.x &&
fabs(ghostCenter.y - pacmanCenter.y) <= 8.0f) ||
(ghostCenter.y == pacmanCenter.y &&
fabs(ghostCenter.x - pacmanCenter.x) <= 8.0f)) {
if (Ghost::getMode() != frightened && !ghost->isDead()) {
this->startTime = std::chrono::steady_clock::now();
this->energyzerEaten = 0;
this->modeTracker = 0;
this->pacman->setIsDead(true);
} else {
if (!ghost->isDead()) {
this->score += this->ghostMultiplyer * 200;
this->ghostMultiplyer += this->ghostMultiplyer;
ghost->setDead(true);
}
}
}
}
}
void Game::resetGame() {
this->maze->reset();
this->pacman->reset(true);
Ghost::setMode(scatter);
for (Ghost *ghost : ghosts) {
ghost->reset();
}
this->state = start;
this->score = 0;
this->startTime = std::chrono::steady_clock::now();
this->lastEnergyzerTime = std::chrono::steady_clock::now();
this->modeTracker = 0;
this->lastModeTracker = false;
this->energyzerEaten = 0;
}
// -----------------------------------------------------------------------------
// Public methods
void Game::setup() {
// set random seed
srand(time(NULL));
// initialize window
this->window->initialize();
this->window->transferDataToGPUMemory();
// Set key callback
glfwSetKeyCallback(this->window->getWindow(), handleKeyboardInput);
}
void Game::run() {
do {
// process input
processInput(this->window, pacman);
if (Game::state != pause && Game::state != over && Game::state != win) {
// get seconds since start
long long seconds = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - startTime)
.count();
// Start
while (seconds <= START_STATE) {
// set state
Game::state = start;
// get seconds since start
seconds = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - startTime)
.count();
// render window
this->window->render(Game::state);
}
// set state
Game::state = active;
// update positions
this->pacman->updatePosition(1.0f);
for (Ghost *ghost : ghosts) {
ghost->updatePosition(1.0f);
}
// handle colisions
this->checkColision();
// consume points
glm::vec2 center = this->maze->getCenter(this->pacman->getPosition());
glm::ivec2 block = this->maze->pixelToBlock(center);
int points = this->maze->eat(block);
if (points > 0) {
this->score += points;
this->maze->decrementDotsRemaining();
if (points == 50) {
this->lastEnergyzerTime = std::chrono::steady_clock::now();
for (Ghost *ghost : this->ghosts) {
ghost->turnAround();
}
this->energyzerEaten += 1;
}
}
// get seconds since enegizer eaten
long long timer =
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - lastEnergyzerTime)
.count();
// set mode
this->setMode(seconds, timer);
// render window
this->window->render(Game::state);
// handle pacman death
if (this->pacman->isDead()) {
// reset pacman
this->pacman->reset(false);
this->pacman->setIsDead(false);
this->pacman->decrementLives();
// reset ghosts
for (Ghost *ghost : ghosts) {
ghost->reset();
}
}
// handle game end
if (this->pacman->getLives() == 0) {
Game::state = over;
}
if (this->maze->getDotsRemaining() == 0) {
Game::state = win;
}
// render window
this->window->render(Game::state);
} else {
// render window
this->window->render(Game::state);
}
} while (processExit(this->window));
}
void Game::clean() {
this->window->deleteDataFromGPUMemory();
this->window->terminate();
}
// -----------------------------------------------------------------------------
// Initialization
gameState Game::state = active;
int Game::menuItem = 0;
// -----------------------------------------------------------------------------
// Constructors
Game::Game() {
this->maze = new Maze();
this->pacman = new Pacman(this->maze);
this->ghosts.push_back(new Blinky(this->pacman, this->maze));
this->ghosts.push_back(new Pinky(this->pacman, this->maze));
this->ghosts.push_back(new Inky(this->pacman, this->maze, this->ghosts[0]));
this->ghosts.push_back(new Clyde(this->pacman, this->maze));
this->window =
new Window(this->maze, this->pacman, this->ghosts, this->startTime,
&(this->lastEnergyzerTime), &(this->score), &(Game::menuItem));
this->startTime = std::chrono::steady_clock::now();
this->lastEnergyzerTime = std::chrono::steady_clock::now();
this->ghostMultiplyer = 1;
this->modeTracker = 0;
this->lastModeTracker = false;
this->energyzerEaten = 0;
this->score = 0;
}
Game::~Game() {}
| true |
e1cf693cab9717e8ae58e13568c8f42c3183ba37 | C++ | Rorenzuru/group-13-lab-3 | /Generator.cc | UTF-8 | 1,683 | 2.609375 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <omnetpp.h>
using namespace omnetpp;
class Generator : public cSimpleModule
{
private:
cPacket *packet;
cMessage *event;
int generated;
protected:
// The following redefined virtual function holds the algorithm.
virtual void initialize() override;
virtual void handleMessage(cMessage *msg) override;
virtual void refreshDisplay() const override;
public:
Generator();
virtual ~Generator();
};
Generator::Generator()
{
event = packet = nullptr;
}
Generator::~Generator()
{
cancelAndDelete(event);
}
// The module class needs to be registered with OMNeT++
Define_Module(Generator);
void Generator::initialize()
{
generated = 0;
// Boot the process scheduling the initial message as a self-message.
//packet = new cMessage("packet");
simsignal_t interGenTime;
event = new cMessage("event");
scheduleAt(simTime()+par("interGenTime"), event);
}
void Generator::handleMessage(cMessage *msg)
{ // events are the only type of msg the generator will ever receive so:
// generate new packet and send it to the queuing sub system and start
// countdown for another event (distributed as Exponential)
packet = new cPacket("packet");
packet -> setByteLength((long)par("avgPcktSize"));
send(packet, "out");
generated++;
//compute the new departure time:
simsignal_t interGenTime;
scheduleAt(simTime()+par("interGenTime"), event);
}
void Generator::refreshDisplay() const
{
char buf[40];
sprintf(buf, "Packets sent: %d", generated);
getDisplayString().setTagArg("t", 0, buf);
}
| true |
6c7c2fd5eda4440008a495c6f0cb96b3acd2198e | C++ | anyWareSculpture/physical | /arduino/Test sketches/HandshakeTester/LEDStrip.h | UTF-8 | 2,969 | 2.96875 | 3 | [
"MIT"
] | permissive | #ifndef LEDSTRIP_H_
#define LEDSTRIP_H_
#include "Pixel.h"
#include "AnywareEasing.h"
#include "./FastLED.h"
struct Pair {
Pair(uint8_t stripid = -1, uint8_t pixelid = -1) : stripid(stripid), pixelid(pixelid) {}
int8_t stripid;
int8_t pixelid;
};
class LEDStripInterface {
public:
LEDStripInterface(uint8_t numpixels, Pixel *pixels) : numpixels(numpixels), pixels(pixels) {
stripid = numStrips++;
LEDStrips[stripid] = this;
}
virtual void setup() {
for (uint8_t i=0;i<numpixels;i++) {
mapping[pixels[i].strip][pixels[i].panel] = Pair(stripid,i);
}
}
uint8_t getNumPixels() {
return numpixels;
}
Pixel &getPixel(uint8_t pixelid) {
return pixels[pixelid];
}
static LEDStripInterface &getStrip(uint8_t stripid) {
return *LEDStrips[stripid];
}
static uint8_t getNumStrips() {
return numStrips;
}
static const Pair &mapToLED(uint8_t stripid, uint8_t panelid) {
return mapping[stripid][panelid];
}
static void setAllColors(const CRGB &col) {
for (uint8_t s=0;s<numStrips;s++) {
LEDStripInterface &strip = *LEDStrips[s];
for (int i = 0; i < strip.getNumPixels(); i++) strip.setColor(i, col);
}
FastLED.show(); // This sends the updated pixel color to the hardware.
}
virtual void setColor(uint8_t pixel, const CRGB &col) = 0;
virtual const CRGB &getColor(uint8_t pixel) = 0;
virtual void ease(uint8_t pixel, AnywareEasing::EasingType type, const CRGB &toColor) = 0;
virtual bool applyEasing() = 0;
static void applyEasings() {
bool changed = false;
for (uint8_t s=0;s<numStrips;s++) {
LEDStripInterface &strip = *LEDStrips[s];
changed |= strip.applyEasing();
}
if (changed) FastLED.show(); // This sends the updated pixel color to the hardware.
}
static LEDStripInterface *LEDStrips[MAX_STRIPS];
static uint8_t numStrips;
// logical strip, logical panel => physical strip, physical pixel
static Pair mapping[MAX_STRIPS][MAX_PANELS];
protected:
uint8_t stripid;
uint8_t numpixels;
Pixel *pixels;
};
template<uint8_t dataPin, uint8_t clockPin> class LEDStrip : public LEDStripInterface {
public:
LEDStrip(uint8_t numpixels, CRGB *leds, Pixel *pixels)
: LEDStripInterface(numpixels, pixels), leds(leds) {
}
virtual void setup() {
LEDStripInterface::setup();
FastLED.addLeds<APA102, dataPin, clockPin, BGR, DATA_RATE_KHZ(100)>(leds, getNumPixels());
}
virtual void setColor(uint8_t pixelid, const CRGB &col) {
leds[pixelid] = col;
}
virtual const CRGB &getColor(uint8_t pixelid) {
return leds[pixelid];
}
virtual void ease(uint8_t pixelid, AnywareEasing::EasingType type, const CRGB &toColor) {
pixels[pixelid].ease(type, toColor, leds[pixelid]);
}
virtual bool applyEasing() {
bool changed = false;
for (uint8_t i=0;i<numpixels;i++) {
changed |= pixels[i].applyEasing(leds[i]);
}
return changed;
}
CRGB *leds;
};
#endif
| true |
714468583b727f380ffa02fb5d654b2ae4f237c4 | C++ | mbradber/tc_solutions | /574/TheNumberGameDiv2.cpp | UTF-8 | 3,848 | 3.265625 | 3 | [] | no_license | #include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <typeinfo>
#include <climits>
using namespace std;
int Reverse(int op){
int reverse = 0;
for(; op != 0 ;)
{
reverse = reverse * 10;
reverse = reverse + op % 10;
op = op / 10;
}
return reverse;
}
int Shrink(int op){
op /= 10;
return op;
}
int Transform(int A, int B, bool flipped, int numMoves){
if(B > A){
if(Reverse(A) == B) return numMoves + 1;
}
if(A < B) return INT_MAX;
if(A == B) return numMoves;
int x = INT_MAX;
if(!flipped)
x = Transform(Reverse(A), B, true, numMoves + 1);
int y = Transform(Shrink(A), B, false, numMoves + 1);
return std::min(x, y);
}
class TheNumberGameDiv2 {
public:
int minimumMoves(int A, int B) {
int minMoves = Transform(A, B, false, 0);
if(minMoves == INT_MAX) minMoves = -1;
return minMoves;
}
};
// CUT begin
template <typename T> string pretty_print(T t) { stringstream s; typeid(T) == typeid(string) ? s << "\"" << t << "\"" : s << t; return s.str(); }
bool do_test(int A, int B, int __expected, int caseNo) {
cout << " Testcase #" << caseNo << " ... ";
time_t startClock = clock();
TheNumberGameDiv2 *instance = new TheNumberGameDiv2();
int __result = instance->minimumMoves(A, B);
double elapsed = (double)(clock() - startClock) / CLOCKS_PER_SEC;
delete instance;
if (__result == __expected) {
cout << "PASSED!" << " (" << elapsed << " seconds)" << endl;
return true;
}
else {
cout << "FAILED!" << " (" << elapsed << " seconds)" << endl;
cout << " Expected: " << pretty_print(__expected) << endl;
cout << " Received: " << pretty_print(__result) << endl;
return false;
}
}
bool run_testcase(int __no) {
switch (__no) {
case 0: {
int A = 25;
int B = 5;
int __expected = 2;
return do_test(A, B, __expected, __no);
}
case 1: {
int A = 5162;
int B = 16;
int __expected = 4;
return do_test(A, B, __expected, __no);
}
case 2: {
int A = 334;
int B = 12;
int __expected = -1;
return do_test(A, B, __expected, __no);
}
case 3: {
int A = 218181918;
int B = 9181;
int __expected = 6;
return do_test(A, B, __expected, __no);
}
case 4: {
int A = 9798147;
int B = 79817;
int __expected = -1;
return do_test(A, B, __expected, __no);
}
// Your custom testcase goes here
case 5: {
int A = 95282784;
int B = 5282784;
int __expected = 3;
return do_test(A, B, __expected, __no);
}
default: break;
}
return 0;
}
int main(int argc, char *argv[]) {
cout.setf(ios::fixed,ios::floatfield);
cout.precision(2);
cout << "TheNumberGameDiv2 (500 Points)" << endl << endl;
int nPassed = 0, nAll = 0;
if (argc == 1)
for (int i = 0; i < 6; ++i) nAll++, nPassed += run_testcase(i);
else
for (int i = 1; i < argc; ++i) nAll++, nPassed += run_testcase(atoi(argv[i]));
cout << endl << "Passed : " << nPassed << "/" << nAll << " cases" << endl;
int T = time(NULL) - 1408313895;
double PT = T / 60.0, TT = 75.0;
cout << "Time : " << T / 60 << " minutes " << T % 60 << " secs" << endl;
cout << "Score : " << 500 * (0.3 + (0.7 * TT * TT) / (10.0 * PT * PT + TT * TT)) << " points" << endl;
return 0;
}
// CUT end
| true |
e1456bc4ef6ed36f1708abc74ed76d8b42693983 | C++ | RobbeDGreef/ASWJ | /src/stlparser/stlparser.cpp | UTF-8 | 4,424 | 2.796875 | 3 | [
"MIT"
] | permissive | #include <stlparser/stlparser.h>
StlParser::StlParser(std::string file)
{
m_stlfile.open(file, std::ios::binary);
LOG("Opened file " << file);
}
StlParser::~StlParser()
{
m_stlfile.close();
}
void StlParser::parse()
{
LOG("parsing file");
// The first 80 bytes are a unimportant ascii, however
// for testing we will print it anyway
char header[80];
m_stlfile.read(header, 80);
LOG("File header reads: '" << header << "'");
// Read the facet count.
uint32_t facet_count;
m_stlfile.read((char*) &facet_count, 4);
LOG("Facet count: " << facet_count);
// Initialize the facet array that will be used to keep all the facets.
m_facet_array = std::vector<Facet>(facet_count);
for (uint i = 0; i < facet_count; i++)
{
m_stlfile.read((char*) &(m_facet_array[i]), FACET_STRUCT_SIZE);
m_facet_array[i].calc_z_minmax();
if (m_facet_array[i].min_z < m_min_z)
m_min_z = m_facet_array[i].min_z;
}
apply_transform();
}
std::vector<Layer> &StlParser::slice()
{
// This algorithm is O(n*m) where is n is the amount of facets
// and m the height of the object divided by the layer height.
// Thats bad. However we will focus on a better solution later.
// We create a vector of lists of lines to hold the layer data.
// For the amount of layers we choose a vector because we already know
// how large this array will be and random access is nice. We don't know
// how many lines it will hold though and using a vector here would
// be very inefficient.
//
// The amount of layers is equal to the height of the object divided by the
// layer height rounded up. (+1 because we use <= in the loop instead of <
// and don't want any segfaults)
m_layers = std::vector<Layer>(ceil(m_object_height / m_layer_height)+1);
int i_layer = 0;
for (float height = 0; height <= m_object_height; height += m_layer_height)
{
for (Facet facet : m_facet_array)
{
// If the height is in range of the facets min and max height
// try and find the intersection points.
// Accounting for floating point precision is needed here as well.
if (facet.min_z <= (height + COMP_PRECISION) && facet.max_z >= (height - COMP_PRECISION))
{
// The three lines every triangle consists of
Line lines[3] = {
Line(facet.vertices[0], facet.vertices[1]),
Line(facet.vertices[1], facet.vertices[2]),
Line(facet.vertices[2], facet.vertices[0]),
};
// We keep track of the intersecting points in this vector
std::vector<Vec3f> intersections;
for (int i = 0; i < 3; i++)
{
if (lines[i].contains_height(height))
{
intersections.push_back(lines[i].calc_point_from_z(height));
}
}
// If only one point intersects the z plane, we ignore it
// because this means we cannot create a line. And printing
// a single point is useless.
//
// We don't handle any cases where all 3 points intersect because
// we already check if this is the case in Line::contains_height()
// and if so, discard the case as false.
// meaning we can never reach the point where 3 vertices intersect.
if (intersections.size() == 2 && intersections[0] != intersections[1])
m_layers[i_layer].insert(Line(intersections[0], intersections[1]));
}
}
i_layer++;
}
return m_layers;
}
void StlParser::apply_transform()
{
m_offset.z = -m_min_z * m_scale.z;
LOG("min_z: " << m_min_z);
LOG("offset: " << m_offset.to_string());
LOG("scale: " << m_scale.to_string());
for (Facet &facet : m_facet_array)
{
for (int i = 0; i < 3; i++)
{
facet.vertices[i].transform(m_offset, m_scale);
if (facet.vertices[i].z > m_object_height)
m_object_height = facet.vertices[i].z;
}
facet.calc_z_minmax();
}
LOG("Object height: " << m_object_height);
} | true |
5f48db11f92036888814624a81ff2e6e3389b064 | C++ | TXC4/DataStructuresHash | /DataStructuresHash/myStack.h | UTF-8 | 329 | 3.046875 | 3 | [] | no_license | #pragma once
#include <string>
struct stackNode
{
stackNode* next;
stackNode* previous;
std::string data;
};
class myStack
{
private:
stackNode* head = new stackNode;
stackNode* top;
public:
myStack()
{
top = head;
}
void push(std::string);
void pop();
stackNode* getTop();
bool isEmpty();
void print();
}; | true |
2ce08d7777e200746ae1d65f3ee67dba9b868403 | C++ | yanohitoshi/test | /Action/LandingEffectManeger.cpp | SHIFT_JIS | 1,751 | 2.59375 | 3 | [] | no_license | #include "LandingEffectManeger.h"
#include "LandingEffect.h"
#include "PlayerObject.h"
LandingEffectManeger::LandingEffectManeger(GameObject* _owner)
: GameObject(false, Tag::PARTICLE)
{
particleState = ParticleState::PARTICLE_DISABLE;
owner = _owner;
position = Vector3(0.0f, 0.0f, 0.0f);
ChackOnFlag = false;
tmpVelZ = 0.0f;
generateFlag = false;
}
LandingEffectManeger::~LandingEffectManeger()
{
}
void LandingEffectManeger::UpdateGameObject(float _deltaTime)
{
if (owner->GetVelocity().z == 0.0f && tmpVelZ != 0.0f && PlayerObject::GetChackJumpFlag() == false)
{
particleState = ParticleState::PARTICLE_ACTIVE;
generateFlag = true;
}
else
{
particleState = ParticleState::PARTICLE_DISABLE;
}
switch (particleState)
{
case (PARTICLE_DISABLE):
break;
case PARTICLE_ACTIVE:
//particlet[̏
if (generateFlag == true)
{
position = owner->GetPosition();
for (int i = 0; i < 8; i++)
{
if (i == 0)
{
velocity = Vector3(1.0f,0.0f,0.0f);
}
if (i == 1)
{
velocity = Vector3(0.0f,1.0f,0.0f);
}
if (i == 2)
{
velocity = Vector3(-1.0f, 0.0f, 0.0f);
}
if (i == 3)
{
velocity = Vector3(0.0f, -1.0f, 0.0f);
}
if (i == 4)
{
velocity = Vector3(1.0f, 1.0f, 0.0f);
}
if (i == 5)
{
velocity = Vector3(1.0f, -1.0f, 0.0f);
}
if (i == 6)
{
velocity = Vector3(-1.0f, 1.0f, 0.0f);
}
if (i == 7)
{
velocity = Vector3(-1.0f, -1.0f, 0.0f);
}
//particle
new LandingEffect(position, velocity);
}
generateFlag = false;
}
particleState = ParticleState::PARTICLE_DISABLE;
break;
}
tmpVelZ = owner->GetVelocity().z;
}
| true |
889748364176f19125485dc94778f6973f24e963 | C++ | carllinley/3D-Model-Viewer | /Light.cpp | UTF-8 | 151 | 2.5625 | 3 | [] | no_license | #include "Light.h"
void Light::setPosition(Vector3 & position) {
this->position.set(position);
}
Vector3& Light::getPosition() {
return position;
} | true |
3a3c3e99da6c7e6d5f2310fc491ca79b13c99ee7 | C++ | ToruTakefusa/AtCoder | /ABC090/B/main.cpp | UTF-8 | 482 | 3.703125 | 4 | [] | no_license | #include <iostream>
using namespace std;
bool isPalindromic(string s);
int main() {
int a, b;
cin >> a >> b;
int count = 0;
for (int i = a; i <= b; ++i) {
if (isPalindromic(to_string(i))) {
++count;
}
}
cout << count << endl;
return 0;
}
bool isPalindromic(string s) {
for (int i = 0; i <= s.length() / 2; ++i) {
if (s[i] != s[s.length() - 1 - i]) {
return false;
}
}
return true;
}
| true |
3002e54dd9bd8138fbcb54187e1010eca6717cb3 | C++ | tom-fougere/Projets | /Tools/sources/colorOperation.cpp | UTF-8 | 2,375 | 2.859375 | 3 | [] | no_license | #include "../colorOperation.h"
#include <iostream>
#include <math.h>
using namespace std;
void rgb2hsv(int R, int G, int B, int &H, int &S, int &V){
int RGB[3];
RGB[RED] = R;
RGB[GREEN] = G;
RGB[BLUE] = B;
float HSV[3];
rgb2hsv(RGB, HSV);
H = (int)HSV[HUE];
S = (int)round(HSV[SAT]*100);
V = (int)round(HSV[VAL]*100);
}
void rgb2hsv(int R, int G, int B, int &H, float &S, float &V){
int RGB[3];
RGB[RED] = R;
RGB[GREEN] = G;
RGB[BLUE] = B;
float HSV[3];
rgb2hsv(RGB, HSV);
H = HSV[HUE];
S = HSV[SAT];
V = HSV[VAL];
}
void rgb2hsv8bitsNorm(int R, int G, int B, int &H, int &S, int &V){
int RGB[3];
RGB[RED] = R;
RGB[GREEN] = G;
RGB[BLUE] = B;
float HSV[3];
rgb2hsv(RGB, HSV);
H = HSV[HUE]*255/360;
S = HSV[SAT]*255;
V = HSV[VAL]*255;
}
void hsv8bitsNorm2hsv(int H8N, int S8N, int V8N, int &H, int &S, int &V){
H = round(H8N*360/(float)255);
float f_S = S8N/(float)255;
S = round(f_S*100);
float f_V = V8N/(float)255;
V = round(f_V*100);
}
void rgb2hsv(int RGB[], float HSV[]){
float tf_RGBnorm[3];
tf_RGBnorm[0] = RGB[RED]/(float)255;
tf_RGBnorm[1] = RGB[GREEN]/(float)255;
tf_RGBnorm[2] = RGB[BLUE]/(float)255;
int imax = 4;
int imin = 4;
for(int i=0 ; i < 3 ; i++){
// Find max
if(tf_RGBnorm[i] >= tf_RGBnorm[(i+1)%3] && tf_RGBnorm[i] >= tf_RGBnorm[(i+2)%3]){
imax = i;
}
// Find min
if(tf_RGBnorm[i] <= tf_RGBnorm[(i+1)%3] && tf_RGBnorm[i] <= tf_RGBnorm[(i+2)%3]){
imin = i;
}
}
//float Cmin = tf_RGBnorm[imin];
float Cmax = tf_RGBnorm[imax];
float fdelta = tf_RGBnorm[imax] - tf_RGBnorm[imin];
// HUE
if(imax == imin){
HSV[HUE] = 0;
}
else{ if(imax == RED){
HSV[HUE] = 60 * (((int)((tf_RGBnorm[GREEN]-tf_RGBnorm[BLUE])/fdelta))%6);
}
else{ if(imax == GREEN){
HSV[HUE] = 60 * ((tf_RGBnorm[BLUE]-tf_RGBnorm[RED])/fdelta + 2);
}
else{ if(imax == BLUE){
HSV[HUE] = 60 * ((tf_RGBnorm[RED]-tf_RGBnorm[GREEN])/fdelta + 4);
}
}
}
}
// SATURATION
if(Cmax == 0){
HSV[SAT] = 0;
}
else HSV[SAT] = fdelta/Cmax;
// VALUE
HSV[VAL] = Cmax;
}
| true |
3f3c766e9b709453c7bc94ccb3cc9055ef6d453f | C++ | frouioui/plazza | /tests/test_Kitchen_CookBook.cpp | UTF-8 | 2,792 | 2.890625 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2017
** Test_criterion
** File description:
** Test de CookBook
*/
#include <criterion/criterion.h>
#include <criterion/redirect.h>
#include "Kitchen/CookBook.hpp"
#include "Kitchen/Error.hpp"
#include <iostream>
TestSuite(Kitchen_CookBook,
.init = NULL,
.fini = NULL,
.signal = 0,
.exit_code = 0,
.disabled = 0,
.description = "Test the Group: Kitchen_CookBook",
.timeout = 0);
Test(Kitchen_CookBook, construct)
{
Kitchen::CookBook();
}
Test(Kitchen_CookBook, ValueOfSubject_Margarita)
{
Kitchen::CookBook tmp;
Pizza::Command command = {Pizza::Margarita, Pizza::Size::XXL};
Kitchen::CookBook::Recipe recipe = {{"DOE"}, {"TOMATO"}, {"GRUYERE"}};
cr_assert_eq(tmp.getCookingTime(command), 1);
cr_assert_eq(recipe.size(), tmp.getRecipe(command).size());
for (size_t i = 0; i < recipe.size(); i++) {
cr_assert_eq(recipe.at(i).name, tmp.getRecipe(command).at(i).name);
}
}
Test(Kitchen_CookBook, ValueOfSubject_Regina)
{
Kitchen::CookBook tmp;
Pizza::Command command = {Pizza::Regina, Pizza::Size::XXL};
Kitchen::CookBook::Recipe recipe = {{"DOE"}, {"TOMATO"}, {"GRUYERE"}, {"HAM"}, {"MUSHROOMS"}};
cr_assert_eq(tmp.getCookingTime(command), 2);
cr_assert_eq(recipe.size(), tmp.getRecipe(command).size());
for (size_t i = 0; i < recipe.size(); i++) {
cr_assert_eq(recipe.at(i).name, tmp.getRecipe(command).at(i).name);
}
}
Test(Kitchen_CookBook, ValueOfSubject_Americana)
{
Kitchen::CookBook tmp;
Pizza::Command command = {Pizza::Americana, Pizza::Size::XXL};
Kitchen::CookBook::Recipe recipe = {{"DOE"}, {"TOMATO"}, {"GRUYERE"}, {"STEAK"}};
cr_assert_eq(tmp.getCookingTime(command), 2);
cr_assert_eq(recipe.size(), tmp.getRecipe(command).size());
for (size_t i = 0; i < recipe.size(); i++) {
cr_assert_eq(recipe.at(i).name, tmp.getRecipe(command).at(i).name);
}
}
Test(Kitchen_CookBook, ValueOfSubject_Fantasia)
{
Kitchen::CookBook tmp;
Pizza::Command command = {Pizza::Fantasia, Pizza::Size::XXL};
Kitchen::CookBook::Recipe recipe = {{"DOE"}, {"TOMATO"}, {"EGGPLANT"}, {"GOAT CHEESE"}, {"CHIEF LOVE"}};
cr_assert_eq(tmp.getCookingTime(command), 4);
cr_assert_eq(recipe.size(), tmp.getRecipe(command).size());
for (size_t i = 0; i < recipe.size(); i++) {
cr_assert_eq(recipe.at(i).name, tmp.getRecipe(command).at(i).name);
}
}
Test(Kitchen_CookBook, Value_Invalid)
{
Kitchen::CookBook tmp;
Pizza::Command command = {static_cast<Pizza::Type>(567), Pizza::Size::XXL};
Kitchen::CookBook::Recipe recipe = {{"DOE"}, {"TOMATO"}, {"EGGPLANT"}, {"GOAT CHEESE"}, {"CHIEF LOVE"}};
cr_assert_throw(tmp.getCookingTime(command), Kitchen::Error);
cr_assert_throw(tmp.getRecipe(command), Kitchen::Error);
}
| true |
71a8b648fff7f9d3f7a875be2051c9245a5d72e6 | C++ | Matix426/gitrepo | /cpp/petla_5.cpp | UTF-8 | 191 | 2.6875 | 3 | [] | no_license | /*
* petla_5.cpp
*/
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
int x;
cin>>x;
for (int i=0;i <=x;i++)
cout <<i*i<<endl;
return 0;
}
| true |
bb3247c131de1e3a5978d733696d584940dd163c | C++ | supertask/icpc | /atcoder/003/b.cpp | UTF-8 | 431 | 2.75 | 3 | [] | no_license | #include<iostream>
#include<map>
#include<vector>
#include<algorithm>
#define REP(i,p,n) for(int i=p;i<(int)(n);i++)
#define rep(i,n) REP(i,0,n)
#define all(c) (c).begin(), (c).end()
using namespace std;
int main() {
int n;
cin >> n;
vector<string> words(n);
rep(i,n) {
cin >> words[i];
reverse(all(words[i]));
}
sort(all(words));
rep(i,n) {
reverse(all(words[i]));
cout << words[i] << endl;
}
return 0;
}
| true |
ad3103033bb35dafb1d0955540f9ef2d0a6c47b1 | C++ | ryantherileyman/riley-colon-case | /src/test/r3/colon-case/level-data/GameMapTests/GameMapTests-main.cpp | UTF-8 | 8,859 | 2.578125 | 3 | [] | no_license |
#include <assert.h>
#include <iostream>
#include <r3/colon-case/level-data/r3-colonCase-levelDefn.hpp>
#include <r3/colon-case/level-data/r3-colonCase-GameMap.hpp>
using namespace r3::colonCase;
GameTileImageDefn createAtlasTileImageDefn(int x, int y) {
GameTileImageDefn result;
result.tileId = y * 4 + x;
result.filename = "texture-atlas.png";
result.imageSize = sf::Vector2i(128, 96);
result.textureRect = sf::IntRect(x * 32, y * 32, 32, 32);
return result;
}
GameTileImageDefn createSprite1ImageDefn() {
GameTileImageDefn result;
result.tileId = 12;
result.filename = "sprite1.png";
result.imageSize = sf::Vector2i(64, 64);
result.textureRect = sf::IntRect(0, 0, 64, 64);
return result;
}
GameTileImageDefn createSprite2ImageDefn() {
GameTileImageDefn result;
result.tileId = 13;
result.filename = "sprite2.png";
result.imageSize = sf::Vector2i(48, 48);
result.textureRect = sf::IntRect(0, 0, 48, 48);
return result;
}
GameMapLayerDefn createFloorLayerDefn() {
int tileIdArray[70] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 0, 2, 3, 4, 0, 2, 4, 0, 1,
1, 0, 5, 6, 0, 0, 5, 6, 0, 1,
1, 0, 7, 9, 0, 7, 8, 9, 0, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
};
GameMapLayerDefn result;
result.layerType = GameMapLayerType::TILE;
result.renderFlag = true;
result.collisionFlag = true;
result.tileIdList.insert(std::begin(result.tileIdList), std::begin(tileIdArray), std::end(tileIdArray));
return result;
}
GameMapLayerDefn createSpriteLayerDefn() {
GameMapSpriteDefn sprite1Defn;
sprite1Defn.tileId = 12;
sprite1Defn.position = sf::Vector2f(64.0f, 128.0f);
sprite1Defn.size = sf::Vector2f(64.0f, 64.0f);
GameMapSpriteDefn sprite2Defn;
sprite2Defn.tileId = 13;
sprite2Defn.position = sf::Vector2f(208.0f, 112.0f);
sprite2Defn.size = sf::Vector2f(48.0f, 48.0f);
GameMapLayerDefn result;
result.layerType = GameMapLayerType::SPRITE;
result.renderFlag = true;
result.spriteDefnList.push_back(sprite1Defn);
result.spriteDefnList.push_back(sprite2Defn);
return result;
}
GameMapLayerDefn createCollisionTileLayerDefn() {
int tileIdArray[70] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
GameMapLayerDefn result;
result.layerType = GameMapLayerType::TILE;
result.collisionFlag = true;
result.tileIdList.insert(std::begin(result.tileIdList), std::begin(tileIdArray), std::end(tileIdArray));
return result;
}
GameMapDefn createGameMapDefn() {
GameMapDefn result;
result.size = sf::Vector2i(10, 7);
result.tileSize = sf::Vector2i(32, 32);
result.tileImageDefnMap[0] = createAtlasTileImageDefn(0, 0);
result.tileImageDefnMap[1] = createAtlasTileImageDefn(1, 0);
result.tileImageDefnMap[2] = createAtlasTileImageDefn(2, 0);
result.tileImageDefnMap[3] = createAtlasTileImageDefn(3, 0);
result.tileImageDefnMap[4] = createAtlasTileImageDefn(0, 1);
result.tileImageDefnMap[5] = createAtlasTileImageDefn(1, 1);
result.tileImageDefnMap[6] = createAtlasTileImageDefn(2, 1);
result.tileImageDefnMap[7] = createAtlasTileImageDefn(3, 1);
result.tileImageDefnMap[8] = createAtlasTileImageDefn(0, 2);
result.tileImageDefnMap[9] = createAtlasTileImageDefn(1, 2);
result.tileImageDefnMap[10] = createAtlasTileImageDefn(2, 2);
result.tileImageDefnMap[11] = createAtlasTileImageDefn(3, 2);
result.tileImageDefnMap[12] = createSprite1ImageDefn();
result.tileImageDefnMap[13] = createSprite2ImageDefn();
result.layerDefnList.push_back(createFloorLayerDefn());
result.layerDefnList.push_back(createSpriteLayerDefn());
result.layerDefnList.push_back(createCollisionTileLayerDefn());
return result;
}
bool testGetLayerCount() {
GameMapDefn mapDefn = createGameMapDefn();
GameMap map(mapDefn);
bool result = (map.getLayerCount() == 2);
return result;
}
bool testGetLayerType() {
GameMapDefn mapDefn = createGameMapDefn();
GameMap map(mapDefn);
bool result =
(map.getLayerType(0) == GameMapLayerType::TILE) &&
(map.getLayerType(1) == GameMapLayerType::SPRITE);
return result;
}
bool testGetTileIdPtr_InvalidLayerType() {
GameMapDefn mapDefn = createGameMapDefn();
GameMap map(mapDefn);
try {
map.getTileIdPtr(1, 0, 0);
return false;
}
catch (std::invalid_argument) {
return true;
}
}
bool testGetTileIdPtr_InvalidPosition() {
GameMapDefn mapDefn = createGameMapDefn();
GameMap map(mapDefn);
bool result = true;
try {
map.getTileIdPtr(0, -1, 0);
result = false;
}
catch (std::out_of_range) {
}
try {
map.getTileIdPtr(0, 0, -1);
result = false;
}
catch (std::out_of_range) {
}
try {
map.getTileIdPtr(0, 10, 0);
result = false;
}
catch (std::out_of_range) {
}
try {
map.getTileIdPtr(0, 0, 7);
result = false;
}
catch (std::out_of_range) {
}
return result;
}
bool testGetTileIdPtr() {
GameMapDefn mapDefn = createGameMapDefn();
GameMap map(mapDefn);
const int* tileIdPtr = map.getTileIdPtr(0, 4, 2);
bool result =
(tileIdPtr[0] == 4) &&
(tileIdPtr[1] == 0) &&
(tileIdPtr[2] == 2) &&
(tileIdPtr[3] == 4) &&
(tileIdPtr[4] == 0) &&
(tileIdPtr[5] == 1);
return result;
}
bool testGetTileImageFilename() {
GameMapDefn mapDefn = createGameMapDefn();
GameMap map(mapDefn);
std::string filename = map.getTileImageFilename(4);
bool result = (filename.compare("texture-atlas.png") == 0);
return result;
}
bool testGetTileTextureRect() {
GameMapDefn mapDefn = createGameMapDefn();
GameMap map(mapDefn);
sf::IntRect textureRect = map.getTileTextureRect(7);
bool result =
(textureRect.left == 96) &&
(textureRect.top == 32) &&
(textureRect.width == 32) &&
(textureRect.height == 32);
return result;
}
bool testGetSpriteRenderDetailsList_InvalidLayerType() {
GameMapDefn mapDefn = createGameMapDefn();
GameMap map(mapDefn);
try {
map.getSpriteRenderDetailsList(0, sf::IntRect(0, 0, 10, 7));
return false;
}
catch (std::invalid_argument) {
return true;
}
}
bool testGetSpriteRenderDetailsList_None() {
GameMapDefn mapDefn = createGameMapDefn();
GameMap map(mapDefn);
const std::vector<GameSpriteRenderDetails> spriteRenderDetailsList = map.getSpriteRenderDetailsList(1, sf::IntRect(4, 4, 4, 2));
bool result = spriteRenderDetailsList.empty();
return result;
}
bool testGetSpriteRenderDetailsList_Partial() {
GameMapDefn mapDefn = createGameMapDefn();
GameMap map(mapDefn);
const std::vector<GameSpriteRenderDetails> spriteRenderDetailsList = map.getSpriteRenderDetailsList(1, sf::IntRect(0, 3, 4, 2));
bool result =
(spriteRenderDetailsList.size() == 1) &&
(spriteRenderDetailsList[0].filename.compare("sprite1.png") == 0) &&
(spriteRenderDetailsList[0].imageSize.x == 64) &&
(spriteRenderDetailsList[0].imageSize.y == 64) &&
(spriteRenderDetailsList[0].textureRect.left == 0) &&
(spriteRenderDetailsList[0].textureRect.top == 0) &&
(spriteRenderDetailsList[0].textureRect.width == 64) &&
(spriteRenderDetailsList[0].textureRect.height == 64) &&
(lround(spriteRenderDetailsList[0].position.x) == 64) &&
(lround(spriteRenderDetailsList[0].position.y) == 128) &&
(lround(spriteRenderDetailsList[0].size.x) == 64) &&
(lround(spriteRenderDetailsList[0].size.y) == 64);
return result;
}
bool testGetPositionOccupied_InvalidPosition() {
GameMapDefn mapDefn = createGameMapDefn();
GameMap map(mapDefn);
bool result = true;
try {
map.getPositionOccupied(-1, 0);
result = false;
}
catch (std::out_of_range) {
}
try {
map.getPositionOccupied(10, 0);
result = false;
}
catch (std::out_of_range) {
}
try {
map.getPositionOccupied(0, -1);
result = false;
}
catch (std::out_of_range) {
}
try {
map.getPositionOccupied(0, 10);
result = false;
}
catch (std::out_of_range) {
}
return result;
}
bool testGetPositionOccupied_NotOccupied() {
GameMapDefn mapDefn = createGameMapDefn();
GameMap map(mapDefn);
bool result = !map.getPositionOccupied(2, 1);
return result;
}
bool testGetPositionOccupied_Occupied() {
GameMapDefn mapDefn = createGameMapDefn();
GameMap map(mapDefn);
bool result = map.getPositionOccupied(2, 2);
return result;
}
int main() {
assert(testGetLayerCount());
assert(testGetLayerType());
assert(testGetTileIdPtr_InvalidLayerType());
assert(testGetTileIdPtr_InvalidPosition());
assert(testGetTileIdPtr());
assert(testGetTileImageFilename());
assert(testGetTileTextureRect());
assert(testGetSpriteRenderDetailsList_InvalidLayerType());
assert(testGetSpriteRenderDetailsList_None());
assert(testGetSpriteRenderDetailsList_Partial());
assert(testGetPositionOccupied_InvalidPosition());
assert(testGetPositionOccupied_NotOccupied());
assert(testGetPositionOccupied_Occupied());
std::cout << "All tests passed!\n";
return 0;
}
| true |
9ca069baa63695a5df2dbf7be3a976939be9bcee | C++ | krazychase/SchoolStuff | /CS2/Xtra1/Xtra1/Xtra1.cpp | UTF-8 | 1,652 | 3.125 | 3 | [] | no_license | //Chase Brown
//Xtra Credit 1
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const int maxlist = 50;
struct listtype
{
string last, first;
int id;
};
void createlist(listtype l[], int &numlist)
{
int i;
for (i = 0; i < maxlist-1; i++)
{
l[i].last = "NoLast";
l[i].first = "NoFirst";
l[i].id = -1;
}
numlist = 0;
}
bool emptylist(int numlist)
{
return numlist <= 0;
}
bool fulllist(int numlist)
{
return numlist >= maxlist;
}
void insert(listtype l[], int &numlist, string last,
string first, int id, ofstream &outf)
{
int i, where;
if (!fulllist(numlist))
{
where = 0;
while (where < numlist && last > l[where].last) where++;
for (i = numlist - 1; i >= where; i--)
{
l[where].last = last;
l[where].first = first;
l[where].id = id;
numlist++;
}
}
else outf << "List is full" << endl;
}
void read(listtype l[], int numlist, ofstream &outf)
{
ifstream inf("Xtra1.dat");
string first, last;
int id;
while (!inf.eof())
{
inf >> last >> first >> id;
last.erase(last.find(","));
insert(l, numlist, last, first, id, outf);
}
}
void printlist(listtype l[], int numlist, ofstream &outf)
{
int i;
if (!emptylist(numlist))
{
outf << "ID # Name" << endl;
for (i = 0; i <= 35; i++) outf << "=";
outf << endl;
for (i = 0; i < numlist; i++)
cout << l[i].id << " " << l[i].first << " " << l[i].last << endl;
}
else outf << "List is empty" << endl;
outf << endl;
}
void main()
{
listtype l[maxlist];
ofstream outf("Xtra1.ot");
int numlist=0;
createlist(l, numlist);
read(l, numlist, outf);
printlist(l, numlist, outf);
system("pause");
} | true |
1693b06cefa975fc28aa49735c6cbd99d3f1d4b9 | C++ | hitwlh/leetcode | /200_Number_of_Islands/solution.cpp | UTF-8 | 1,179 | 3.109375 | 3 | [] | no_license | class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if(grid.empty()) return 0;
my_grid = grid;
int ret = 0;
for(int i = 0; i < my_grid.size(); i++){
for(int j = 0; j < my_grid[i].size(); j++){
if(my_grid[i][j] == '1'){
my_grid[i][j] = '0';
my_queue.push({i, j});
ret++;
bfs(i, j);
}
}
}
return ret;
}
private:
vector<vector<char>> my_grid;
queue<pair<int, int>> my_queue;
void bfs(int i, int j){
while(!my_queue.empty()){
my_push(my_queue.front().first-1, my_queue.front().second);
my_push(my_queue.front().first+1, my_queue.front().second);
my_push(my_queue.front().first, my_queue.front().second-1);
my_push(my_queue.front().first, my_queue.front().second+1);
my_queue.pop();
}
}
void my_push(int i, int j){
if(i >= 0 && i < my_grid.size() && j >= 0 && j < my_grid[i].size() && my_grid[i][j] == '1')
my_grid[i][j] = '0', my_queue.push({i,j});
}
}; | true |
7e5a8caf53b97b6139544d58f23191d80df96bc0 | C++ | RicardoAltamiranoSanchez/C-_Programas | /fecha con asignacion dinamica.cpp | ISO-8859-10 | 1,044 | 3.546875 | 4 | [] | no_license | #include<iostream>
#include <windows.h>
using namespace std;
class dianio{
private:
int dia,mes;
public:
dianio(int,int);
bool igual(dianio&);
void visualizar();
};
dianio::dianio(int _d,int _m)
{
dia=_d;
mes=_m;
}
bool dianio::igual(dianio &n)
{
if(dia==n.dia && mes==n.mes)
{
return true;
}
else
{
return false;
}
}
void dianio::visualizar()
{
cout<<"EL dia es :"<<dia<<endl;
cout<<"El mes es :"<<mes<<endl;
}
int main (int argc, char *argv[])
{
int d,m;
dianio* hoy;
dianio* cumple;
cout<<"Digite la fecha de hoy,dia"<<endl;
cin>>d;
cout<<"Digite la fecha de hoy,mes"<<endl;
cin>>m;
hoy=new dianio(d,m);
cout<<"Fecha de tu cumpleaos"<<endl;
cout<<"Digite la fecha de tu cumpleaos ,dia"<<endl;
cin>>d;
cout<<"Digite la fecha de tu cumpleaos ,mes"<<endl;
cin>>m;
cumple=new dianio(d,m);
hoy->visualizar();
cout<<endl;
cumple->visualizar();
if(hoy->igual(*cumple))
{
cout<<"Feliz cumple"<<endl;
}
else{
cout<<"Que tenga un buen dia"<<endl;
}
system("pause");
return 0;
}
| true |
e2c4448afec8a8c68773564a06b628f944e6acdc | C++ | wuxin20/my_git | /C++/vector/vector/test.cpp | UTF-8 | 1,048 | 3.390625 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS 1
#if 0
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<int> v1;
vector<int> v2(10, 5);
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
vector<int> v3(array, array + sizeof(array) / sizeof(int));
vector<int> v4(v3);
return 0;
}
#endif
#if 0
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v{ 1, 2, 3, 4, 5 };
cout << v.size << endl;
cout << v.capacity() << endl;
for (auto e : v)
{
cout << e << endl;
}
cout << endl;
//auto it = v.begin();
//vector<int>::iterator it = v.begin();
//while(it != v.end)
//{
// cout << *it << " ";
// ++it;
//}
//cout << endl;
v.resize(20, 9);
cout << v.size() << endl;
cout << v.capacity() << endl;
for (auto e : v)
{
cout << e << endl;
}
cout << endl;
return 0;
}
#endif
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
cout << v.front << endl;
cout << v.back << endl;
return 0;
} | true |
75bbb07f22b2073a61eaf6e01c55d7906916bafc | C++ | adishavit/mesh | /IsenburgStreamingMesh/OOC/psreader_dist/src/littlecache.h | UTF-8 | 1,798 | 3.09375 | 3 | [] | no_license | /*
===============================================================================
FILE: littlecache.h
CONTENTS:
PROGRAMMERS:
martin isenburg@cs.unc.edu
COPYRIGHT:
copyright (C) 2003 martin isenburg@cs.unc.edu
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
CHANGE HISTORY:
07 October 2003 -- initial version created the day of the California recall
===============================================================================
*/
#ifndef LITTLE_CACHE_H
#define LITTLE_CACHE_H
class LittleCache
{
public:
LittleCache();
~LittleCache();
inline void put(int i0, int i1, int i2);
inline void put(void* d0, void* d1, void* d2);
inline void put(int i0, int i1, int i2, void* d0, void* d1, void* d2);
inline void* get(int i);
inline int pos(int i);
private:
int index[3];
void* data[3];
};
inline LittleCache::LittleCache()
{
index[0] = -1;
index[1] = -1;
index[2] = -1;
data[0] = 0;
data[1] = 0;
data[2] = 0;
}
inline LittleCache::~LittleCache()
{
}
inline void LittleCache::put(int i0, int i1, int i2)
{
index[0] = i0;
index[1] = i1;
index[2] = i2;
}
inline void LittleCache::put(void* d0, void* d1, void* d2)
{
data[0] = d0;
data[1] = d1;
data[2] = d2;
}
inline void LittleCache::put(int i0, int i1, int i2, void* d0, void* d1, void* d2)
{
index[0] = i0;
index[1] = i1;
index[2] = i2;
data[0] = d0;
data[1] = d1;
data[2] = d2;
}
inline void* LittleCache::get(int i)
{
return data[i];
}
inline int LittleCache::pos(int i)
{
if (i == index[0])
{
return 0;
}
if (i == index[1])
{
return 1;
}
if (i == index[2])
{
return 2;
}
return -1;
}
#endif
| true |
51a87e4158204e270698b1630b73d6ddc5f42bf7 | C++ | booknu/PS_Relative | /Books/C++프로그래밍/Chapter 13/OOP_NormalAccount.h | UHC | 494 | 2.515625 | 3 | [] | no_license | /************
<ּ> : p553 - OOP Ʈ 10ܰ
**********
<ذ> :
Entity Ŭ
ּ ڸ ϴ
**********
<Ʈ> :
*/
#ifndef __NORMAL_ACCOUNT_H__
#define __NORMAL_ACCOUNT_H__
#include "OOP_Account.h"
class NormalAccount : public Account {
private:
int interest;
public:
NormalAccount(int accID, String name, int money, int interest);
virtual void deposit(int amount);
virtual void print() const;
};
#endif | true |
45e185075a5860dfb72a51205e9311486b7e07b9 | C++ | Andrey-Uvarov/the-riddle-of-jacques-fresco-when-Obeme | /main.cpp | WINDOWS-1251 | 4,510 | 3.765625 | 4 | [] | no_license | #include<iostream>
#include<time.h>
using namespace std;
/*
int main() {
srand(time(NULL));
const int size = 10;
int arr[size];
//
for (int i = 0; i < size; i++) {
arr[i] = rand() % 20;
arr[i] = arr[i] - 10;
}
//
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
int sum1 = 0, count1 = 0;
int sum2 = 0, count2 = 0;
for (int i = 0; i < size; i++) {
if (arr[i] >= 0) {
sum1 += arr[i];
count1++;
}
else {
sum2 += arr[i];
count2++;
}
}
cout << "There are " << count1 << " positive elements" << endl;
cout << "Their sum = " << sum1 << endl;
cout << "There are " << count2 << " negative elements" << endl;
cout << "Their sum = " << sum2 << endl;
return 0;
}
*/
/*
int main() {
srand(time(NULL));
const int size = 10;
int arr[size];
int min;
//
for (int i = 0; i < size; i++) {
arr[i] = rand() % 20 + 1;
}
//
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
for (int i = 0; i < size; i++) {
if (arr[i] % 2 == 0) {
min = arr[i];
break;
}
}
for (int i = 0; i < size; i++) {
if (arr[i] % 2 == 0 && arr[i] < min) {
min = arr[i];
}
}
cout << "Minimum even element = " << min << endl;
return 0;
}
*/
/*
int main() {
srand(time(NULL));
const int size = 10;
int arr[size];
//
for (int i = 0; i < size; i++) {
arr[i] = rand() % 50 + 1;
}
//
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
cout << "Max elem = " << max << endl;
return 0;
}
*/
/*
int main() {
srand(time(NULL));
const int size = 20;
int arr[size];
//
for (int i = 0; i < size; i++) {
arr[i] = rand() % 6;
}
//
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
int counter = 0;
for (int i = 0; i < size; i++) {
if(arr[i] == 0)
counter++
}
cout << "Number of '
return 0;
}
*/
void fillArray(int a[], int size);
void printArray(int a[], int size);
double findMultiplication(int a[], int size);
int findIndexMin(int a[], int size);
int findIndexMax(int a[], int size);
void swapElement(int a[], int minIndex, int maxIndex);
double average(int a[], int size);
int calcGreaterAvarage(int a[], int size, double avarage);
int main() {
srand(time(NULL));
const int size = 10;
int arr[size];
fillArray(arr, size);
/*cout << "Before swap" << endl;
printArray(arr, size);
int minIndex = findIndexMin(arr, size);
int maxIndex = findIndexMax(arr, size);
swapElement(arr, minIndex, maxIndex);
cout << "After swap" << endl;
printArray(arr, size);*/
//double mul = findMultiplication(arr, size);
//cout << "Res = " << mul << endl;
return 0;
}
double findMultiplication(int a[], int size) {
double mul = 1;
for (int i = 0; i < size; i++) {
if (a[i] % 2 != 0) {
mul = mul * a[i];
}
}
mul /= 2;
return mul;
}
int findIndexMin(int a[], int size)
{
int index = 0;
int min = a[0];
for (int i = 1; i < size; i++) {
if (a[i] < min) {
min = a[i];
index = i;
}
}
return index;
}
int findIndexMax(int a[], int size)
{
int index = 0;
int max = a[0];
for (int i = 1; i < size; i++) {
if (a[i] > max) {
max = a[i];
index = i;
}
}
return index;
}
void swapElement(int a[], int minIndex, int maxIndex)
{
int temp = a[minIndex];
a[minIndex] = a[maxIndex];
a[maxIndex] = temp;
}
double average(int a[], int size)
{
int sum = 0;
for (int i = 0; i < size; i++) {
sum += a[i];
}
// (_) - _ (double) x
return (double) sum / 2;
}
int calcGreaterAvarage(int a[], int size, double avarage)
{
int counter = 0;
for (int i = 0; i < size; i++) {
if (a[i] > average)
counter++;
}
return 0;
}
void fillArray(int a[], int size) {
for (int i = 0; i < size; i++) {
a[i] = rand() % 100 + 1;
}
}
void printArray(int a[], int size)
{
cout << "Array: " << endl;
for (int i = 0; i < size; i++) {
cout << a[i] << " ";
}
cout << endl;
}
| true |
d4ea2db86290dbeed0c837807e43db76e7ce64e9 | C++ | TaIos/text_rpg | /src/Item.h | UTF-8 | 828 | 3.03125 | 3 | [] | no_license | #ifndef GAMEBOOK_ITEM_H
#define GAMEBOOK_ITEM_H
#include <iostream>
#include <string>
#include "Display.h"
#include "Equipment.h"
#include "HeroStats.h"
class CItem
{
public:
CItem() = default;
CItem(int id, int gold, std::string text)
: itemID(id), price(gold), name(text)
{}
virtual ~CItem() = default;
virtual void useItem(HeroStats &stats, CEquipment &equipment) const = 0;
int getID() const
{ return itemID; }
int getPrice() const
{ return price; }
std::string getName() const
{ return name; }
virtual void print(const CDisplay &display) const = 0;
virtual void printForShop(const CDisplay &display) const = 0;
protected:
int itemID;
int price;
std::string name;
};
#endif //GAMEBOOK_ITEM_H
| true |
66218bff6293f68b5037c9cf7234eda90b465c6f | C++ | hzh0/LeetCode | /350. 两个数组的交集 II.cpp | UTF-8 | 347 | 2.640625 | 3 | [] | no_license | class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> ans;
map<int, int> m;
for (auto& i : nums1) m[i]++;
for (auto& i : nums2) {
if (m[i]) {
ans.push_back(i);
m[i]--;
}
}
return ans;
}
}; | true |
385fb8428bb54b93769857d7abb878f0471783f7 | C++ | 6uclz1/idd_medilab15 | /example/21_particleStartpoint/src/ParticleVec2.cpp | UTF-8 | 961 | 2.9375 | 3 | [
"MIT"
] | permissive | #include "ParticleVec2.h"
ParticleVec2::ParticleVec2(){
position.set(ofGetWidth()/2.0, ofGetHeight()/2.0);
velocity.set(0, 0);
acceleration.set(0, 0);
mass = 1.0;
radius = 5.0;
friction = 0.01;
}
void ParticleVec2::update(){
acceleration -= velocity * friction;
velocity += acceleration;
position += velocity;
acceleration.set(0, 0);
}
void ParticleVec2::draw(){
ofCircle(position.x, position.y, radius);
}
void ParticleVec2::addForce(ofVec2f force){
acceleration += force / mass;
}
void ParticleVec2::bounceOffWalls(){
if (position.x < 0) {
velocity.x *= -1;
position.x = 0;
}
if (position.x > ofGetWidth()) {
velocity.x *= -1;
position.x = ofGetWidth();
}
if (position.y < 0) {
velocity.y *= -1;
position.y = 0;
}
if (position.y > ofGetHeight()) {
velocity.y *= -1;
position.y = ofGetHeight();
}
}
| true |
03ad5c69c376c1e120ec01e167205c7a0f312c88 | C++ | kukaro/KamangBlogData | /ZZZ-MyStudy/question/DynamicProgramming/11057/main.cpp | UTF-8 | 740 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#define MAXSIZE 1005
using namespace std;
int N;
vector<vector<int>> memo(MAXSIZE, vector<int>(10, -1));
int f(int n, int start) {
int sum_val = 0;
if (n == 1) {
return 1;
}
for (int i = start; i < 10; i++) {
if (memo[n - 1][i] == -1) {
memo[n - 1][i] = f(n - 1, i) % 10007;
}
sum_val += memo[n - 1][i] % 10007;
}
return sum_val;
}
int main() {
int sum_val = 0;
cin >> N;
for (int i = 0; i < 10; i++) {
if (memo[N][i] == -1) {
memo[N][i] = f(N, i) % 10007;
}
sum_val += memo[N][i] % 10007;
}
cout << sum_val%10007 << endl;
return 0;
}
| true |
afe9beaf6fa9ef24008f72f2105a673fdc116e1f | C++ | opencor/llvmclang | /tools/clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp | UTF-8 | 4,605 | 3.171875 | 3 | [
"Apache-2.0",
"LLVM-exception",
"NCSA"
] | permissive | // RUN: %clang_cc1 -std=c++1z -verify %s
// RUN: %clang_cc1 -std=c++1z -verify %s -DUNDEFINED
#ifdef UNDEFINED
// "used but not defined" errors don't get produced if we have more interesting
// errors.
namespace std_example {
template <typename T, typename... Rest> void g(T &&p, Rest &&... rs) {
// use p
if constexpr(sizeof...(rs) > 0)
g(rs...);
}
void use_g() {
g(1, 2, 3);
}
static int x(); // no definition of x required
int f() {
if constexpr (true)
return 0;
else if (x())
return x();
else
return -x();
}
}
namespace odr_use_in_selected_arm {
static int x(); // expected-warning {{is not defined}}
int f() {
if constexpr (false)
return 0;
else if (x()) // expected-note {{here}}
return x();
else
return -x();
}
}
#else
namespace ccce {
struct S {
};
void f() {
if (5) {}
if constexpr (5) {
}
}
template<int N> void g() {
if constexpr (N) {
}
}
template void g<5>();
void h() {
if constexpr (4.3) { //expected-warning {{implicit conversion from 'double' to 'bool' changes value}}
}
constexpr void *p = nullptr;
if constexpr (p) {
}
}
void not_constant(int b, S s) { // expected-note 2{{declared here}}
if constexpr (bool(b)) { // expected-error {{constexpr if condition is not a constant expression}} expected-note {{cannot be used in a constant expression}}
}
if constexpr (b) { // expected-error {{constexpr if condition is not a constant expression}} expected-note {{cannot be used in a constant expression}}
}
if constexpr (s) { // expected-error {{value of type 'ccce::S' is not contextually convertible to 'bool'}}
}
constexpr S constexprS;
if constexpr (constexprS) { // expected-error {{value of type 'const ccce::S' is not contextually convertible to 'bool'}}
}
}
}
namespace generic_lambda {
// Substituting for T produces a hard error here, even if substituting for
// the type of x would remove the error.
template<typename T> void f() {
[](auto x) {
if constexpr (sizeof(T) == 1 && sizeof(x) == 1)
T::error(); // expected-error 2{{'::'}}
} (0);
}
template<typename T> void g() {
[](auto x) {
if constexpr (sizeof(T) == 1)
if constexpr (sizeof(x) == 1)
T::error(); // expected-error {{'::'}}
} (0);
}
void use() {
f<int>(); // expected-note {{instantiation of}}
f<char>(); // expected-note {{instantiation of}}
g<int>(); // ok
g<char>(); // expected-note {{instantiation of}}
}
}
namespace potentially_discarded_branch_target {
void in_switch(int n) {
switch (n)
case 4: if constexpr(sizeof(n) == 4) return;
if constexpr(sizeof(n) == 4)
switch (n) case 4: return;
switch (n) {
if constexpr (sizeof(n) == 4) // expected-note 2{{constexpr if}}
case 4: return; // expected-error {{cannot jump}}
else
default: break; // expected-error {{cannot jump}}
}
}
template<typename T>
void in_switch_tmpl(int n) {
switch (n) {
if constexpr (sizeof(T) == 4) // expected-note 2{{constexpr if}}
case 4: return; // expected-error {{cannot jump}}
else
default: break; // expected-error {{cannot jump}}
}
}
void goto_scope(int n) {
goto foo; // expected-error {{cannot jump}}
if constexpr(sizeof(n) == 4) // expected-note {{constexpr if}}
foo: return;
bar:
if constexpr(sizeof(n) == 4)
goto bar; // ok
}
template<typename T>
void goto_scope(int n) {
goto foo; // expected-error {{cannot jump}}
if constexpr(sizeof(n) == 4) // expected-note {{constexpr if}}
foo: return;
bar:
if constexpr(sizeof(n) == 4)
goto bar; // ok
}
void goto_redef(int n) {
a: if constexpr(sizeof(n) == 4) // expected-error {{redefinition}} expected-note {{constexpr if}}
a: goto a; // expected-note 2{{previous}}
else
a: goto a; // expected-error {{redefinition}} expected-error {{cannot jump}}
}
void evil_things() {
goto evil_label; // expected-error {{cannot jump}}
if constexpr (true || ({evil_label: false;})) {} // expected-note {{constexpr if}}
if constexpr (true) // expected-note {{constexpr if}}
goto surprise; // expected-error {{cannot jump}}
else
surprise: {}
}
}
namespace deduced_return_type_in_discareded_statement {
template <typename T>
auto a(const T &t) {
return t;
}
void f() {
if constexpr (false) {
a(a(0));
}
}
} // namespace deduced_return_type_in_discareded_statement
#endif
| true |
fa5829e922376225635e92ece990db25d058f165 | C++ | Roger-Chuh/plane-sweeping-stereo | /stereo.cpp | UTF-8 | 9,987 | 3.171875 | 3 | [
"BSD-3-Clause"
] | permissive | /*cpp file that has the definitions for the function in epipoles.h
Author: Sasidharan Mahalingam
Date Created: March 10 2018 */
#include "stereo.h"
/*Function that scales the translation vectors
Usage:
Parameters:
R_list: vector of matrices that contains all the rotation matrices
t_list: vector of matrices that contains the unscaled translation vectors
st_list: vector of matrices that contains the scaled translation vectors
min_params: vector of doubles that contains the values of alpha and gamma
*/
void find_alpha_gamma(const std::vector<Mat> R_list, std::vector<Mat> t_list, vector<Mat> &st_list, vector<double> & min_params)
{
vector<Mat> rescaled_t_vec, tmp(t_list.begin(),t_list.end());
for (auto &j : t_list)
{
//normalize each translation vector
normalize(j, j, 1);
}
//express all the translation vector in the first camera's frame of reference
//Rotating r12 to express it in the frame of reference of the first camera
cout << "R12\n" << R_list[0] << endl;
cout << "R21\n" << R_list[0].t() << endl;
rescaled_t_vec.push_back(R_list[0].t() * t_list[0]);
//Rotating r23 to express it in the frame of reference of the first camera
cout << "R13\n" << R_list[2] << endl;
cout << "R31\n" << R_list[2].t() << endl;
rescaled_t_vec.push_back(R_list[2].t() * t_list[1]);
//Changin r13 to r31
cout << "t_list" << t_list[2] << endl;
t_list[2] = -(t_list[2]);
cout << "t_list" << t_list[2] << endl;
//Rotating r31 to express it in the frame of reference of the first camera
rescaled_t_vec.push_back(R_list[2].t() * t_list[2]);
for (auto & ele : rescaled_t_vec)
cout << ele << endl;
double a11, a12, a21, a22, b1, b2;
Mat t;
multiply(rescaled_t_vec[1],rescaled_t_vec[1],t);
cout << "r23 " << rescaled_t_vec[1].dot(rescaled_t_vec[1]) << endl;
cout << "r23 " << sum(t) << endl;
cout << "r31 " << rescaled_t_vec[2].dot(rescaled_t_vec[2]) << endl;
a11 = 2.0 * static_cast<double>(rescaled_t_vec[1].dot(rescaled_t_vec[1]));
a12 = static_cast<double>(rescaled_t_vec[2].dot(rescaled_t_vec[1]) + rescaled_t_vec[1].dot(rescaled_t_vec[2]));
a21 = static_cast<double>(rescaled_t_vec[1].dot(rescaled_t_vec[2]) + rescaled_t_vec[2].dot(rescaled_t_vec[1]));
a22 = 2.0 * static_cast<double>(rescaled_t_vec[2].dot(rescaled_t_vec[2]));
b1 = -static_cast<double>(rescaled_t_vec[0].dot(rescaled_t_vec[1]) + rescaled_t_vec[1].dot(rescaled_t_vec[0]));
b2 = -static_cast<double>(rescaled_t_vec[0].dot(rescaled_t_vec[2]) + rescaled_t_vec[2].dot(rescaled_t_vec[0]));
cout << "a11" << a11 << endl;
cout << "a12" << a12 << endl;
cout << "a21" << a21 << endl;
cout << "a22" << a22 << endl;
Eigen::MatrixXd A(2,2);
Eigen::VectorXd b(2);
A(0,0) = a11;
A(0,1) = a12;
A(1,0) = a21;
A(1,1) = a22;
b << b1, b2;
cout << "The matrix A is:\n" << A << endl;
cout << "The vector b is:\n" << b << endl;
VectorXd x(2);
x = A.colPivHouseholderQr().solve(b);
cout << "The solution is:\n" << x << endl;
double relative_error = (A*x - b).norm() / b.norm(); // norm() is L2 norm
cout << "The relative error is:\n" << relative_error << endl;
cout << "Sum of unscaled translation vectors: " << rescaled_t_vec[0] + rescaled_t_vec[1] + rescaled_t_vec[2] << endl;
rescaled_t_vec[1] = rescaled_t_vec[1] * x[0];
rescaled_t_vec[2] = rescaled_t_vec[2] * x[1];
cout << "Sum of scaled translation vectors: " << rescaled_t_vec[0] + rescaled_t_vec[1] + rescaled_t_vec[2] << endl;
//st_list.push_back(t_list[0]);
//st_list.push_back(t_list[1] * x[0]);
//st_list.push_back(t_list[2] * x[1]);
st_list = rescaled_t_vec;
min_params.push_back(x[0]);
min_params.push_back(x[1]);
}
/* Function that gives the set of sweeping planes for a given Rotation matrix and translation vector
Usage:
Parameters:
R: Rotational matrix (3x3)
t: Translation vector (3x1)
plane_set: vector of matrices that represent the planes
*/
void find_plane_sets(const Mat R, const Mat t, std::vector<Mat> & plane_set)
{
Mat A;
hconcat(R,t,A);
string param_filename = "camera_params.xml";
string intr_param_filename = "camera_params.xml";
Mat intrinsic;
//get intrinsic matrix and focal length from the xml
FileStorage intr_fs(intr_param_filename, FileStorage::READ);
intr_fs["camera_matrix"] >> intrinsic;
double f = intrinsic.at<double>(0,0);
intr_fs.release();
Mat plane_eq = Mat::zeros(1,4,CV_64FC1);
plane_eq.at<double>(0,2) = 1;
for (double i = 1; i <= 5 ; i= i + 0.02)
{
Mat P;
double tmp = f / static_cast<double>(i * i);
plane_eq.at<double>(0,3) = tmp;
vconcat(A,plane_eq,P);
plane_set.push_back(P);
}
}
/* Function that gives the set of homographies given corresponding sweeping planes
Usage:
Parameters:
P1: vector of Matrices that gives the equations of planes w.r.t the first camera refernce
P2: vector of Matrices that gives the equations of planes w.r.t the second camera refernce
H: vector of Matrices that stores the homographies that relate the points of the plane in the second camera
to points on the same plane in the first camera
*/
void find_homographies(const std::vector<Mat> P1, const std::vector<Mat> P2, std::vector<Mat> & H)
{
vector<Mat>::const_iterator itr1,itr2;
CV_Assert(P1.size() == P2.size());
for (itr1 = P1.begin(), itr2 = P2.begin(); itr1 < P1.end(); itr1++, itr2++)
{
Mat h2, h1 = Mat::zeros(3,3,CV_64FC1);
cout << "P1:\n" << (*itr1) << endl << "P2:\n" << (*itr2) << endl << "inv(P2):\n" << (*itr2).inv() << endl;
h2 = (*itr1) * ((*itr2).inv());
cout << "P1(inv(P2)):\n" << h2 << endl;
for (int i = 0; i <= 2; i++)
{
for (int j = 0; j <= 2; j++)
{
if ((i == 2) && (j == 2))
h1.at<double>(i,j) = h2.at<double>(i+1,j+1) / h2.at<double>(3,3);
else
{
if(i == 2)
h1.at<double>(i,j) = h2.at<double>(i+1,j) / h2.at<double>(3,3);
else
{
if(j == 2)
h1.at<double>(i,j) = h2.at<double>(i,j+1) / h2.at<double>(3,3);
else
h1.at<double>(i,j) = h2.at<double>(i,j) / h2.at<double>(3,3);
}
}
}
}
H.push_back(h1);
}
}
/*Function that calculates the depth given two images
Usage:
*/
void find_depth(stringvec &v, std::vector<Mat> R_list, std::vector<Mat> t_list, std::vector<Mat> & depth_image)
{
vector<Mat> plane_set1,plane_set2,H_set,warped_imgs;
if(v.size() <2)
{
cout << "Folder empty";
return;
}
vector<string>::const_iterator i = v.begin();
vector<string>::const_iterator j = i + 1;
int k = 0;
while(j < v.end())
{
Mat I = Mat::eye(3,3,CV_64FC1);
Mat z = Mat::zeros(3,1,CV_64FC1);
Mat img1, img2;
img1 = imread( *i );
img2 = imread( *j );
//checking if both the images are readable
if( !img1.data || !img2.data )
{
std::cout<< " --(!) Error reading images " << std::endl;
return;
}
namedWindow("left image", CV_WINDOW_FREERATIO | CV_GUI_NORMAL);
resizeWindow("left image", 1000, 700);
moveWindow("left image", 500,500);
imshow( "left image", img1 );
namedWindow("right image", CV_WINDOW_FREERATIO | CV_GUI_NORMAL);
resizeWindow("right image", 1000, 700);
moveWindow("right image", 2000,500);
imshow( "right image", img2 );
waitKey(0);
destroyAllWindows();
cout << "Finding plane sets of right image...\n";
find_plane_sets(I,z,plane_set1);
cout << "The calculated plane sets of the left image are:\n";
for (auto & plane : plane_set1)
cout << plane << endl;
Mat R,t;
transpose(R_list[k], R);
t = - t_list[k];
cout << "The rotation matrices linking the right image with the left image is:\n";
cout << R << endl;
cout << "The scaled translation vector linking right image with the left image is:\n";
cout << t << endl;
cout << "Finding plane sets of right image...\n";
find_plane_sets(R, t, plane_set2);
cout << "The calculated plane sets of the right image are:\n";
for (auto & plane : plane_set2)
cout << plane << endl;
cout << "Now calculating the homography matrices...\n";
find_homographies(plane_set1, plane_set2, H_set);
cout << "The calculated homography are:\n";
for (auto & h : H_set)
cout << h << endl;
cout << "Calculated homography matrices. Now warping images...\n";
for (auto & H : H_set )
{
Mat warped_img;
warpPerspective(img2, warped_img, H, img1.size());
namedWindow("Warped Image", WINDOW_NORMAL);
resizeWindow("Warped Image", 1000, 700);
cv::imshow("Warped Image", warped_img);
cv::waitKey(200);
destroyAllWindows();
warped_imgs.push_back(warped_img);
}
double min_val = 999, min_d = 0;
Mat tmp_d_image = Mat::zeros(img1.rows,img1.cols,CV_8UC1);
for (int u = 0; u < img1.rows; u++)
{
for (int v = 0; v < img1.cols; v++)
{
//cout << "u: " << u << "\t v: " << v;
for (int d = 0; d < warped_imgs.size(); d++)
{
double diff;
cv::Vec3b color = img1.at<cv::Vec3b>(u,v) - warped_imgs[d].at<cv::Vec3b>(u,v);
//cout << "color: " << color << endl;
diff = static_cast<double>(color[0] + color[1] + color[2]);
//cout << "diff: " << diff << endl;
if (diff < min_val)
{
min_val = diff;
min_d = d;
}
}
//cout << "min distance: " << min_d << endl;
tmp_d_image.at<uchar>(u,v) = 255 / static_cast<int>(warped_imgs.size()) * (min_d + 1);
}
}
cout << "depth calculated\n";
namedWindow("Depth Image", WINDOW_NORMAL);
resizeWindow("Depth Image", 1000, 700);
cv::imshow("Depth Image", tmp_d_image);
cv::waitKey(0);
destroyAllWindows();
depth_image = tmp_d_image;
j++;
}
}
| true |
030edee4fb96a9b4fc2069e04de42533ae83d8c2 | C++ | isliulin/jashliao_VC | /001_C++基本觀念/29_VC_組合語言/test/test.cpp | BIG5 | 261 | 2.65625 | 3 | [] | no_license | #include <iostream>
using namespace std;
//CyB~W[ܼƱN2ܼƭȤ!
void main()
{
float a=9.004, b=-28.5;
//@k... for int or float
_asm {
push a
push b
pop a
pop b}
cout<< a <<" "<<b<<"\n";
} | true |
dd2ea15794c16da1b3f862b75c5ee0f3925d2366 | C++ | EijiSugiura/TinyLecture | /cplusplus/main2.cc | UTF-8 | 753 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <regex>
#include <boost/filesystem.hpp>
#include <boost/range/algorithm.hpp>
using namespace std;
using namespace boost::filesystem;
void dump(vector<path>& v)
{
for_each(begin(v),end(v),[](path &x){ cout << x << endl; });
}
int main(int argc, char* argv[])
{
path p(".");
vector<path> v;
const regex filter( ".*\\.csv$" );
for( directory_iterator i( p ); i != directory_iterator(); ++i ){
smatch what;
if( !regex_match( i->path().filename().string(), what, filter) ) continue;
v.push_back( i->path() );
}
cout << "Before sort" << std::endl;
dump(v);
boost::sort(v);
cout << "After sort" << std::endl;
dump(v);
return 0;
}
| true |
2b118c998959d5bb9cd1665faa709b8bc8f45945 | C++ | ybai62868/BlackMa_Learning | /P117/main.cpp | UTF-8 | 890 | 2.640625 | 3 | [] | no_license | /*
* @Author: your name
* @Date: 2020-02-18 15:27:53
* @LastEditTime: 2020-02-18 15:27:53
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: /glow/Users/apple/Desktop/BlackMa_Learning/P117/main.cpp
*/
/*
* @Author: your name
* @Date: 2020-02-18 15:27:53
* @LastEditTime: 2020-02-18 15:27:53
* @LastEditors: your name
* @Description: In User Settings Edit
* @FilePath: /glow/Users/apple/Desktop/BlackMa_Learning/P117/main.cpp
*/
# include <cstdio>
# include <iostream>
using namespace std;
class Person
{
public:
void showPerson() const {
this->m_A = 100;
}
int m_B;
mutable int m_A;
};
void test01()
{
Person p;
p.showPerson();
cout << p.m_A << endl;
}
void test02()
{
Person p2;
cout << p2.m_A << endl;
p2.showPerson();
}
int main(void)
{
test01();
test02();
return 0;
} | true |
692df8bedd3899cab9209f730c9d1ae263e38825 | C++ | linuxaged/BansheeEngine | /Source/BansheeEditor/Include/BsEditorWidget.h | UTF-8 | 7,468 | 2.625 | 3 | [] | no_license | //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
//**************** Copyright (c) 2016 Marko Pintera (marko.pintera@gmail.com). All rights reserved. **********************//
#pragma once
#include "BsEditorPrerequisites.h"
#include "BsEditorWidgetManager.h"
#include "BsEvent.h"
#include "BsRect2I.h"
namespace BansheeEngine
{
/** @addtogroup Implementation
* @{
*/
/**
* Editor widget represents a single "window" in the editor. It may be dragged, docked and can share space with multiple
* other widgets by using tabs.
*
* Each widget has its own position, size, GUI and update method. Widget is always docked inside an
* EditorWidgetContainer unless it's being dragged and is not visible.
*/
class BS_ED_EXPORT EditorWidgetBase
{
public:
/** Gets a unique name for this widget. This name will be used for referencing the widget by other systems. */
const String& getName() const { return mName; }
/** Gets the display name for the widget. This is what editor users will see in the widget title bar. */
const HString& getDisplayName() const { return mDisplayName; }
/** Returns the X position of the widget inside of its container. */
INT32 getX() const { return mX; }
/** Returns the Y position of the widget inside of its container. */
INT32 getY() const { return mY; }
/** Returns the width of the widget in pixels. */
UINT32 getWidth() const { return mWidth; }
/** Returns the height of the widget in pixels. */
UINT32 getHeight() const { return mHeight; }
/** Returns the width of the widget when initially created, in pixels. */
UINT32 getDefaultWidth() const { return mDefaultWidth; }
/** Returns the height of the widget when initially created, in pixels. */
UINT32 getDefaultHeight() const { return mDefaultHeight; }
/** Returns the bounds of the widget in pixels, relative to its parent container. */
Rect2I getBounds() const { return Rect2I(mX, mY, mWidth, mHeight); }
/** Makes the widget in or out focus. Widget can only be made in focus if it is active. */
void setHasFocus(bool focus);
/** Checks if the widget has focus (usually means user clicked on it last). */
bool hasFocus() const { return mHasFocus; }
/**
* Checks is the widget the currently active widget in its container. This means the widget's tab is active or
* the widget is the only one in its container.
*/
bool isActive() const { return mIsActive; }
/**
* Gets the parent editor window this widget is docked in. Can be null (for example when widget is in the process of
* dragging and not visible).
*/
EditorWindowBase* getParentWindow() const;
/**
* Returns the parent widget container. Can be null (for example when widget is in the process of dragging and not
* visible).
*/
EditorWidgetContainer* _getParent() const { return mParent; }
/** Converts screen coordinates to coordinates relative to the widget. */
Vector2I screenToWidgetPos(const Vector2I& screenPos) const;
/** Converts widget relative coordinates to screen coordiantes. */
Vector2I widgetToScreenPos(const Vector2I& widgetPos) const;
/** Closes the widget, undocking it from its container and freeing any resources related to it. */
void close();
/** Internal method. Called once per frame. */
virtual void update() { }
Event<void(UINT32, UINT32)> onResized; /**< Triggered whenever widget size changes. */
Event<void(INT32, INT32)> onMoved; /**< Triggered whenever widget position changes. */
Event<void(EditorWidgetContainer*)> onParentChanged; /**< Triggered whenever widget parent container changes. */
Event<void(bool)> onFocusChanged; /**< Triggered whenever widget receives or loses focus. */
/** @name Internal
* @{
*/
/** Changes the size of the widget (and its internal GUI panel). */
void _setSize(UINT32 width, UINT32 height);
/** Changes the position of the widget (and its internal GUI panel), relative to its parent container. */
void _setPosition(INT32 x, INT32 y);
/**
* Changes the parent container of the widget (for example when re-docking or moving a widget to another window).
* Parent can be null (for example when widget is in the process of dragging and not visible).
*/
void _changeParent(EditorWidgetContainer* parent);
/** Sets or removes focus for this widget. */
void _setHasFocus(bool focus);
/** Disables the widget making its GUI contents not visible. The widget remains docked in its container. */
void _disable();
/** Enables the widget making its previously hidden GUI contents visible. */
void _enable();
/** @} */
protected:
friend class EditorWidgetManager;
EditorWidgetBase(const HString& displayName, const String& name, UINT32 defaultWidth,
UINT32 defaultHeight, EditorWidgetContainer& parentContainer);
virtual ~EditorWidgetBase();
/** Triggered whenever widget position changes. */
virtual void doOnMoved(INT32 x, INT32 y);
/** Triggered whenever widget size changes. */
virtual void doOnResized(UINT32 width, UINT32 height);
/** Triggered whenever widget parent container changes. */
virtual void doOnParentChanged();
/**
* Returns the parent GUI widget. Before calling this you must ensure the widget has a container parent otherwise
* this method will fail.
*/
GUIWidget& getParentWidget() const;
/** Frees widget resources and deletes the instance. */
static void destroy(EditorWidgetBase* widget);
String mName;
HString mDisplayName;
EditorWidgetContainer* mParent;
INT32 mX, mY;
UINT32 mWidth, mHeight;
UINT32 mDefaultWidth, mDefaultHeight;
GUIPanel* mContent;
bool mHasFocus;
bool mIsActive;
};
/** @} */
/** @addtogroup EditorWindow-Internal
* @{
*/
/**
* Helper class that registers a widget creation callback with the widget manager. The creation callback allows the
* runtime to open widgets just by their name without knowing the actual type.
*/
template<typename Type>
struct RegisterWidgetOnStart
{
public:
RegisterWidgetOnStart()
{
EditorWidgetManager::preRegisterWidget(Type::getTypeName(), &create);
}
/** Creates a new widget of a specific type and adds it to the provided container. */
static EditorWidgetBase* create(EditorWidgetContainer& parentContainer)
{
return bs_new<Type>(EditorWidget<Type>::ConstructPrivately(), parentContainer);
}
};
/**
* Editor widget template class that widgets can inherit from. Ensures that all widget implementations are automatically
* registered with the widget manager.
*
* @see EditorWidgetBase
*/
template <class Type>
class EditorWidget : public EditorWidgetBase
{
static volatile RegisterWidgetOnStart<Type> RegisterOnStart;
protected:
friend struct RegisterWidgetOnStart<Type>;
struct ConstructPrivately {};
EditorWidget(const HString& displayName, UINT32 defaultWidth, UINT32 defaultHeight,
EditorWidgetContainer& parentContainer)
:EditorWidgetBase(displayName, Type::getTypeName(), defaultWidth, defaultHeight, parentContainer)
{ }
public:
virtual ~EditorWidget() { }
};
template <typename Type>
volatile RegisterWidgetOnStart<Type> EditorWidget<Type>::RegisterOnStart;
/** @} */
} | true |
2d571a7b5de03322075845ff721f9bc81965f8a6 | C++ | OpenLocalizationTestOrg/ECMA2YamlTestRepo2 | /fulldocset/add/codesnippet/CPP/p-system.windows.forms.r_23_1.cpp | UTF-8 | 908 | 2.65625 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | private:
void WriteIndentedTextToRichTextBox()
{
// Clear all text from the RichTextBox;
richTextBox1->Clear();
// Specify a 20 pixel indent in all paragraphs.
richTextBox1->SelectionIndent = 20;
// Set the font for the text.
richTextBox1->Font = gcnew System::Drawing::Font( "Lucinda Console",12 );
// Set the text within the control.
richTextBox1->SelectedText = "All text is indented 20 pixels from the left edge of the RichTextBox.";
richTextBox1->SelectedText = "You can use this property to provide proper indentation such as when writing a letter.";
richTextBox1->SelectedText = "After this paragraph the indent is returned to normal spacing.\n\n";
richTextBox1->SelectionIndent = 0;
richTextBox1->SelectedText = "No indenation is applied to this paragraph. All text in the paragraph flows from each control edge.";
} | true |
d45789302259633dc0bb2834283bdd37f1f036fd | C++ | CreoValis/MiniWebSrv | /MiniWebSrv/HTTP/IResponse.h | UTF-8 | 1,391 | 2.734375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <boost/asio/spawn.hpp>
#include "Common.h"
#include "Header.h"
namespace HTTP
{
class ConnectionBase;
/**Base class for response reader classes.*/
class IResponse
{
public:
virtual ~IResponse() { }
virtual unsigned int GetExtraHeaderCount() { return 0; }
virtual bool GetExtraHeader(unsigned int Index,
const char **OutHeader, const char **OutHeaderEnd,
const char **OutHeaderVal, const char **OutHeaderValEnd) { return false; }
virtual unsigned int GetResponseCode() { return RC_OK; }
virtual const char *GetContentType() const { return "text/plain"; }
virtual const char *GetContentTypeCharset() const { return NULL; }
/**Queries the response length, in bytes.
@return The length of the response, or ~0, if it's unknown.*/
virtual unsigned long long GetLength()=0;
/**@return True, if the response is finished.*/
virtual bool Read(unsigned char *TargetBuff, unsigned int MaxLength, unsigned int &OutLength,
boost::asio::yield_context &Ctx)=0;
/**Upgrades the specified connection to another type.
This method will be called after the response was successfully sent.
@param CurrConn The connection to upgrade. This is the connection that sent this response.
@return A new ConnectionBase object, or nullptr, if the connection shouldn't be upgraded.*/
virtual ConnectionBase *Upgrade(ConnectionBase *CurrConn) { return NULL; }
};
}; //HTTP
| true |
a20048e0928a743c6e51f2f22e3737f4af37a6f2 | C++ | songgaoxian/NumericalMethods | /MTH9821/MonteCarlo/MonteCarlo/MonteCarlo/MCBasketOption.hpp | UTF-8 | 3,911 | 2.640625 | 3 | [] | no_license | //implement BasketOption pricing using Monte Carlo Simulation
#ifndef MCBasketOption_HPP
#define MCBasketOption_HPP
#include "MonteCarlo.hpp"
#include<cmath>
class MCBasketOption : public MonteCarlo
{
protected:
std::tuple<double, double,double> stock2;
double rho;
public:
MCBasketOption(long size_, std::tuple<double, double, double, double, double, double>& stck, int type, std::tuple<double, double,double>& stck2, double corr) :
MonteCarlo(size_, stck, type), stock2(stck2), rho(corr) {}
double EuroBasketCall(long N) {
if (2 * N > normal.size()) throw "normal variables are not enough";
double S1, S2, V, V_bar = 0;
double s10 = std::get<0>(stock), s20 = std::get<0>(stock2);
double k = std::get<1>(stock);
double t = std::get<2>(stock);
double sigma1 = std::get<3>(stock), sigma2 = std::get<1>(stock2);
double q1 = std::get<4>(stock), q2 = std::get<2>(stock2);
double r = std::get<5>(stock);
for (int i = 0; i < N; ++i) {
S1 = s10*std::exp((r - 0.5*sigma1*sigma1 - q1)*t + sigma1*std::sqrt(t)*normal[2 * i]);
S2 = s20*std::exp((r - 0.5*sigma2*sigma2 - q2)*t + sigma2*std::sqrt(t)*(rho*normal[2 * i] + std::sqrt(1 - rho*rho)*normal[2 * i + 1]));
V = std::exp(-r*t)*std::max(S1 + S2 - k, 0.0);
V_bar += V / double(N);
//if (i % 1000000 == 0) std::cout << i << " ";
}
return V_bar;
}
double DependentBasketCall(long m, long n) {
if (2 * n*m > normal.size()) throw "normal variables are not enough";
double s10 = std::get<0>(stock), s20 = std::get<0>(stock2);
double k = std::get<1>(stock);
double t = std::get<2>(stock);
double sigma1 = std::get<3>(stock), sigma2 = std::get<1>(stock2);
double q1 = std::get<4>(stock), q2 = std::get<2>(stock2);
double r = std::get<5>(stock);
double dt = t / double(m);
long count = 0;
double maxsum = s10 + s20;
double S1, S2, Vi, V_bar = 0;
for (int i = 0; i < n; ++i) {
S1 = s10; S2 = s20; maxsum = s10 + s20;
for (int j = 0; j < m; ++j) {
double z1 = normal[count];
++count;
double z2 = normal[count];
++count;
S1 = S1*std::exp((r - q1 - 0.5*sigma1*sigma1)*dt + sigma1*std::sqrt(dt)*z1);
S2 = S2*std::exp((r - q2 - 0.5*sigma2*sigma2)*dt + sigma2*std::sqrt(dt)*(rho*z1 + std::sqrt(1 - rho*rho)*z2));
maxsum = std::max(maxsum, S1 + S2);
}
Vi = std::max(maxsum - k, 0.0)*std::exp(-r*t);
V_bar += Vi / double(n);
}
return V_bar;
}
};
class MCBarrierOption : public MonteCarlo
{
protected:
double Bup, Blow, pay;
public:
MCBarrierOption(long size_,double Bup_,double Blow_,double pay_, std::tuple<double, double, double, double, double, double>& stck, int type) :
MonteCarlo(size_, stck, type), Bup(Bup_),Blow(Blow_),pay(pay_) {}
std::tuple<double,double,double> DependentBarriertCall(long Nk) {
if (Nk > normal.size()) throw "normal variables are not enough";
double s10 = std::get<0>(stock);
double k = std::get<1>(stock);
double t = std::get<2>(stock);
long m = std::ceil(std::pow(Nk, 1.0 / 3.0)*std::pow(t, 2.0 / 3.0));
long n = std::floor(Nk / m);
double sigma1 = std::get<3>(stock);
double q1 = std::get<4>(stock);
double r = std::get<5>(stock);
double dt = t / double(m);
long count = 0;
double S1, Vi, V_bar = 0;
for (int i = 0; i < n; ++i) {
S1 = s10;
bool isValid = true;
double t_pay;
for (int j = 0; j < m; ++j) {
double z1 = normal[count];
++count;
S1 = S1*std::exp((r - q1 - 0.5*sigma1*sigma1)*dt + sigma1*std::sqrt(dt)*z1);
if (isValid && (S1 >= Bup || S1 <= Blow)) {
isValid = false;
t_pay = dt*j + dt;
}
}
if (isValid) {
Vi = std::max(S1 - k, 0.0)*std::exp(-r*t);
}
else {
Vi = pay*std::exp(-r*t_pay);
}
V_bar += Vi / double(n);
}
std::tuple<double, double, double> result1(m, n, V_bar);
return result1;
}
};
#endif | true |
4587f056a713a4647247e9090a63aa2720faf921 | C++ | pianista215/arduinoexamples | /project3/project3.ino | UTF-8 | 1,287 | 3.046875 | 3 | [] | no_license | const int sensorPin = A0;
const float baseLineTemp = 26.5;
void setup() {
Serial.begin(9600);
for(int pinNumber = 2; pinNumber < 5 ; pinNumber++){
pinMode(pinNumber, OUTPUT);
digitalWrite(pinNumber, LOW);
}
}
void loop() {
// put your main code here, to run repeatedly:
int sensorVal = analogRead(sensorPin);
Serial.print("Sensor value: ");
Serial.print(sensorVal);
//Convert the adc reading to volgate
float voltage = (sensorVal/1024.0) *5.0;
Serial.print(", Volts:");
Serial.print(voltage);
//Temperature (converting voltage into temperature)
Serial.print(", degrees C");
float temperature = (voltage - .5)*100;
Serial.println(temperature);
if(temperature < baseLineTemp){
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
} else if(temperature >= baseLineTemp +2 && temperature < baseLineTemp + 4){
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
} else if(temperature >= baseLineTemp +4 && temperature < baseLineTemp + 6){
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
} else if(temperature >= baseLineTemp +6){
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
}
delay(250);
}
| true |
1aec1677ab6546596a04b04bb821bc5938eeaac8 | C++ | ftanvir/Bit-Manipulation-Basic | /XxOoRr.cpp | UTF-8 | 640 | 2.65625 | 3 | [] | no_license | /*
Codechef July Long Challenge 2021 problem
problem link: https://www.codechef.com/JULY21C/problems/XXOORR
*/
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, k;
cin>>n>>k;
vector<int>arr(n);
for(int i=0; i<n; i++) {
cin>>arr[i];
}
int ans =0;
for(int i =0; i<32; i++) {
int bitCounter =0;
for(int j=0; j<n; j++) {
if(arr[j]&1) {
bitCounter++;
}
arr[j]/=2;
}
ans += ((bitCounter+ k-1)/k);
}
cout<<ans<<endl;
}
int main()
{
int t;
cin>>t;
while (t--) {
solve();
}
} | true |
3b994da8b539b8e390c55bc663021c4262be0eed | C++ | robotics-upo/siar_packages | /localization_siar/functions/include/functions/RealVector.h | UTF-8 | 4,591 | 3.46875 | 3 | [] | no_license | #ifndef __REAL_VECTOR_H__
#define __REAL_VECTOR_H__
#include <string>
#include <sstream>
#include <cmath>
#include <iostream>
#include <vector>
/** @brief 3D Point structure and operators
*/
#include "Point3D.h"
namespace functions {
class RealVector:public std::vector<double> {
protected:
//! init without arguments -> all internal data to empty or zero values
void init();
//! @brief Initializing method from a standard vector
//! @param vec Std vector of double. If not enough values --> the rest are set to zero. Discards excessive values
void init(const std::vector<double> &vec);
//! @brief Initializer from point 3D
//! @param p The point
void init(const Point3D &p);
void init(const RealVector &v);
void init(int dim, bool random = false);
public:
RealVector();
//! @brief Constructor from a std vector.
//! @param vec Std vector of double. If not enough values --> the rest are set to zero. Discards excessive values
RealVector(const std::vector<double> &vec);
//! @brief Constructor from an array of double
RealVector(const double* vec, size_t size);
//! @brief Constructor from a std string.
//! @param st The string. The format has to be: (n1, n2, ..., nm)
RealVector(const std::string &st);
//! @brief Constructor from Point 3D
//! @param p The point
RealVector (const Point3D &p);
//! @brief Constructor with a specified dimension
//! @param dim The dimension
//! @param random If true, each component is initialized to a random number with U(0,1)
RealVector (int dim, bool random = false);
RealVector(const RealVector &v);
//!Returns a string representation of the object
std::string toString() const;
//!Returns a MATLAB-compatible representation of the object
std::string toMatlabString() const;
void fromString(const std::string &s);
//!addition operator (sums each coordinate)
friend const RealVector operator+(const RealVector &left, const RealVector &right);
//!substraction operator(substracts each coordinate)
friend const RealVector operator-(const RealVector &left, const RealVector &right);
//!multiply operator(multiplies each coordinate by a constant)
friend const RealVector operator*(const RealVector &left, const double &right);
//!dot product operator
friend double operator*(const RealVector &left, const RealVector &right);
//!exponentiation operator( exponentiates each coordinate to a given power)
friend const RealVector operator^(const RealVector &left, const double &right);
//!scalar division operator
friend const RealVector operator/(const RealVector &left, const double &right);
//!operator opposite (changes sign to each coordinate)
friend const RealVector operator-(const RealVector &a);
//! assignment operator
RealVector & operator = (const RealVector &that);
//! comparison operator
bool operator == (const RealVector &other) const;
double distance(const RealVector &p)const;
double norm()const;
double angle(const RealVector &other) const;
//! @brief Calculates the distance between the point and a segment with vertices s1 and s2
double distanceToSegment(const RealVector &s1, const RealVector &s2) const;
//! @brief Calculates the cross product between two tridimensional vectors.
//! \NOTE The vectors must be tridimensional
//! @param p A 3D vector
//! @return The cross product (this x p) (note that is not conmutative)
//! @throws A runtime exception if the input vectors are not tridimensional
RealVector crossProduct(const RealVector &p)const;
//! @brief Makes the product component by component of two vectors.
//! \note The vector must be of the same dimension.
//! @param p The other vector
//! @return Another vector with the same dimension. Each components will be obtained by multiplying the
//! @return same components of the other vectors.
//! @throws A runtime exception if the input vectors are not of the same dimension
RealVector componentProduct(const RealVector &p) const;
//! @brief normalizes the vector
inline void normalize() {
double norm_ = norm();
for (unsigned int i = 0; i < size(); i++) {
(*this)[i] /= norm_;
}
}
};
double pathLength(const std::vector<RealVector> &v);
}
#endif //__REAL_VECTOR_3D_H__
| true |
497dd3f9cdb7453070cf3f7aca53d1865326865a | C++ | TurbulentRice/stack-searching-sorting | /StackModel.h | UTF-8 | 6,819 | 3.765625 | 4 | [] | no_license | //
// StackModel.h
// TemplateLibrary
//
// Created by Sean Russell on 4/5/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#ifndef TemplateLibrary_StackModel_h
#define TemplateLibrary_StackModel_h
using namespace std;
// vector stack
template <typename Type>
class stack
{
Type* container; // array of Type
int top; // index of next open space
int top_item; // index of top item
public:
// constructors
stack();
// check methods
bool isempty();
// get methods
int size(); // returns # of elements (top)
Type at(int); // returns element at given index
Type last(); // returns last element
Type first(); // returns first element
Type middle(); // returns middle element
Type* copy(); // returns a pointer array of Type
// add methods
void push(Type); // adds to back
void putin(Type); // adds to front
void insert(Type, int); // inserts this(Type) here(int)
void put(Type, int); // puts this(Type) here(int)
// remove methods
bool pop();
bool remove(int);
void clear();
// mutation methods
void swap(int, int);
void sort();
void scramble();
};
// constructor creates empty stack object
template <typename Type>
stack<Type>::stack()
{
container = new Type[0];
top = 0;
top_item = -1;
}
// isempty() returns bool indicating whether stack is empty
template <typename Type>
bool stack<Type>::isempty()
{
if (top == 0) return true;
else if (top > 0) return false;
}
// size() returns number of items stored in container (top)
template <typename Type>
int stack<Type>::size()
{
return top;
}
// at() returns item at loc
template <typename Type>
Type stack<Type>::at(int loc)
{
return container[loc];
}
// last() returns last item in container
template <typename Type>
Type stack<Type>::last()
{
return container[top_item];
}
// first() returns first item in container
template <typename Type>
Type stack<Type>::first()
{
return container[0];
}
// middle() returns item in middle of container
template <typename Type>
Type stack<Type>::middle()
{
return container[(top_item / 2)];
}
// get() returns pointer array of Type
template <typename Type>
Type* stack<Type>::copy()
{
return container;
}
// push() copies container, increases size
template <typename Type>
void stack<Type>::push(Type item)
{
// create new array of size top + 1
Type* new_container = new Type[top + 1];
// copy elements of old array into new one
for (int i = 0; i < top; ++i)
{
new_container[i] = container[i];
}
// clear old container
delete [] container;
// add new item and copy into container
new_container[top] = item;
top++;
top_item++;
container = new Type[top];
for (int i = 0; i < top; ++i)
{
container[i] = new_container[i];
}
delete [] new_container;
}
// putin() creates new array, pushes everything back and adds item at beginning
template <typename Type>
void stack<Type>::putin(Type item)
{
// create new array of size top + 1
Type* new_container = new Type[top + 1];
// copy elements of old array into new one
for (int i = 0; i < top; ++i)
{
new_container[i + 1] = container[i];
}
// clear old container
delete [] container;
// add new item and copy into container
new_container[0] = item;
top++;
top_item++;
container = new Type[top];
for (int i = 0; i < top; ++i)
{
container[i] = new_container[i];
}
delete [] new_container;
}
// insert() creates new array, pulls everything after loc back and adds item at loc
template <typename Type>
void stack<Type>::insert(Type item, int loc)
{
// create new array of size top + 1
Type* new_container = new Type[top + 1];
// copy elements of old array into new one
for (int i = 0; i < top; ++i)
{
new_container[i] = container[i];
}
for (int i = top + 1; i > loc; --i)
{
new_container[i] = new_container[i - 1];
}
// clear old container
delete [] container;
// add new item and copy into container
new_container[loc] = item;
top++;
top_item++;
container = new Type[top];
for (int i = 0; i < top; ++i)
{
container[i] = new_container[i];
}
delete [] new_container;
}
// put() changes an item at a specified index
template <typename Type>
void stack<Type>::put(Type item, int loc)
{
container[loc] = item;
}
// pop() if not empty, remove() top element
template <typename Type>
bool stack<Type>::pop()
{
if (!isempty())
{
remove(top_item);
return true;
}
else return false;
}
// remove() if not empty, pulls everything after loc down one and deletes element
template <typename Type>
bool stack<Type>::remove(int loc)
{
if (!isempty())
{
// create new array of size top - 1
Type* new_container = new Type[top - 1];
// pulls everything after loc in container down one
for (int i = loc; i < top; ++i)
{
container[i] = container[i + 1];
i++;
}
// copy elements of old array into new one
for (int i = 0; i < top - 1; ++i)
{
new_container[i] = container[i];
}
// clear old container
delete [] container;
// change size and copy into container
top--;
top_item--;
container = new Type[top];
for (int i = 0; i < top; ++i)
{
container[i] = new_container[i];
}
delete [] new_container;
return true;
}
else return false;
}
// clear() deletes allocated memory
template <typename Type>
void stack<Type>::clear()
{
delete [] container;
cout << "Stack cleared!" << endl;
top = 0;
top_item = -1;
return;
}
// swap() switches the condents of two indeces
template <typename Type>
void stack<Type>::swap(int a, int b)
{
int t = container[a];
container[a] = container[b];
container[b] = container[t];
return;
}
// scramble() randomizes order of items
template <typename Type>
void stack<Type>::scramble()
{
return;
}
// sorts() sorts container in ascending order
template <typename Type>
void stack<Type>::sort()
{
for (int start = 1; start < top; ++start)
{
Type insert = at(start);
int here = start;
while ((here > 0) && (at(here - 1) > insert))
{
swap(here, here - 1);
--here;
}
put(insert, here);
}
}
#endif
| true |
08de41596108d7d5980d42b4f046d84a2294e324 | C++ | VinInn/ctest | /vecfunBench/hex.cc | UTF-8 | 950 | 2.796875 | 3 | [] | no_license | union hexdouble {
double d;
struct {
unsigned long long mant:52;
unsigned int exp:11;
unsigned int sign:1;
} s;
};
inline
void d2hex(double x, unsigned long long & mant, int & e) {
hexdouble h; h.d=x;
mant = h.s.mant;
e = h.s.exp-1023;
}
inline
void hex2d(double & x, unsigned long long mant, int e) {
hexdouble h;
h.s.mant=mant;
h.s.exp =e+1023;
x=h.d;
}
inline
unsigned long long d2ll(double x) {
hexdouble h; h.d=x; return h.s.mant;
}
inline
int d2e(double x) {
hexdouble h; h.d=x; return h.s.exp-1023;
}
double a[1024],b[1024];
float c[1024];
long long ll[1024];
int e[1024];
unsigned long long l1[1024], l2[1024]; int i3[1024];
void foo() {
for (int i=0;i!=1024;++i)
l1[i]=d2ll(a[i]);
}
void foo2() {
for (int i=0;i!=1024;++i)
e[i]=d2e(a[i]);
}
void bar() {
for (int i=0;i!=1024;++i)
d2hex(a[i],l1[i],e[i]);
}
void bar2() {
for (int i=0;i!=1024;++i)
hex2d(a[i],l1[i],-1);
}
| true |
1a6707314c2c66af896ba9fba9d1d33a5d858974 | C++ | mangalaman93/netlib | /examples/lserver.cpp | UTF-8 | 669 | 2.734375 | 3 | [] | no_license | /* written by Aman Mangal <mangalaman93@gmail.com>
* on Oct 28, 2014
* server to test large number of connections
*/
#include "base_network.h"
const int PORT = 8000;
BaseNetwork *rnet;
void receive_handler(std::string address, unsigned port,
const std::vector<unsigned char>& data, uint64_t request_id) {
uint32_t i = *((unsigned*)data.data());
uint32_t j = *((unsigned*)(data.data()+4));
std::cout<<"received confirmation for "<<i<<","<<j<<std::endl;
std::vector<unsigned char> to_send(data.begin(), data.begin()+8);
rnet->send(address, port, to_send);
}
int main() {
rnet = new BaseNetwork(PORT, receive_handler);
rnet->join();
}
| true |
0a346abc645dead6dd5530d52201221c9ee69c47 | C++ | nsq974487195/DPTree-code | /misc/ARTOLC/ARTOLC.hpp | UTF-8 | 4,846 | 2.59375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Tree.h"
#include "index_key.h"
template <typename KeyType>
class ArtOLCIndex
{
public:
~ArtOLCIndex() { delete idx; }
static void setKey(Key &k, uint64_t key) { k.setInt(key); }
static void setKey(Key &k, GenericKey<31> key) { k.set(key.data, 31); }
template<typename F>
bool insert(KeyType key, uint64_t value, F f)
{
auto t = idx->getThreadInfo();
Key k;
setKey(k, key);
idx->insert(k, value, t, f);
return true;
}
bool find(KeyType key, uint64_t & v)
{
auto t = idx->getThreadInfo();
Key k;
setKey(k, key);
uint64_t result = idx->lookup(k, t);
v = result;
return true;
}
template<typename F>
bool upsert(KeyType key, uint64_t value, F f)
{
auto t = idx->getThreadInfo();
Key k;
setKey(k, key);
idx->insert(k, value, t, f);
return true;
}
bool scan(const KeyType & start_key, int range, KeyType & continue_key, TID results[], size_t & result_count)
{
auto t = idx->getThreadInfo();
Key startKey;
startKey.setInt(start_key);
result_count = 0;
Key continueKey;
bool has_more = idx->lookupRange(startKey, maxKey, continueKey, results, range, result_count,
t);
continue_key = continueKey.getInt();
return has_more;
}
ArtOLCIndex(uint64_t kt)
{
if (sizeof(KeyType) == 8)
{
idx = new ART_OLC::Tree([](TID tid, Key &key) {
key.setInt(*reinterpret_cast<uint64_t *>(tid));
});
maxKey.setInt(~0ull);
}
else
{
idx = new ART_OLC::Tree([](TID tid, Key &key) {
key.set(reinterpret_cast<char *>(tid), 31);
});
uint8_t m[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
maxKey.set((char *)m, 31);
}
}
struct iterator {
static const uint64_t scan_unit_size = 64;
ArtOLCIndex<KeyType> *artindex;
int count;
int pos;
bool nomore;
KeyType continue_key;
KeyType start_key;
KeyType cur_key;
uint64_t values[scan_unit_size];
explicit iterator(ArtOLCIndex<KeyType> *artindex=nullptr)
: artindex(artindex), count(0), pos(0), nomore(false), start_key(0), cur_key(std::numeric_limits<KeyType>::max()), continue_key(0){}
explicit iterator(ArtOLCIndex<KeyType> *artindex, const KeyType & startKey)
: artindex(artindex), count(0), pos(0), nomore(false), start_key(startKey), cur_key(std::numeric_limits<KeyType>::max()), continue_key(0){
while (nomore == false && count == 0)
fill();
if (is_end()) {
cur_key = std::numeric_limits<KeyType>::max();
} else {
cur_key = *(KeyType*)values[pos];
}
}
void fill() {
if (nomore == false) {
start_key = continue_key;
size_t result_count = 0;
nomore = !artindex->scan(start_key, scan_unit_size, continue_key, values, result_count);
count = result_count;
} else {
count = 0;
}
pos = 0;
}
int next_node(KeyType&last_key) {
last_key = this->last_key();
int ret = count;
fill();
return ret;
}
bool is_end() { return count == 0 && nomore == true; }
iterator &operator++() {
if (++pos == count) {
fill();
}
if (is_end()) {
cur_key = std::numeric_limits<KeyType>::max();
} else {
cur_key = *(KeyType*)values[pos];
}
return *this;
}
bool operator==(const iterator &rhs) {
return cur_key == rhs.cur_key;
}
bool operator!=(const iterator &rhs) {
return !operator==(rhs);
}
KeyType last_key() { return *(KeyType *) values[count - 1]; }
KeyType key() { return *(KeyType *) values[pos]; }
uint64_t value() { return values[pos]; }
};
iterator begin() {
return iterator(this, std::numeric_limits<KeyType>::min());
}
iterator end() {
return iterator(this);
}
iterator lookup_range(const KeyType & start_key) {
return iterator(this, start_key);
}
private:
Key maxKey;
ART_OLC::Tree *idx;
};
| true |
dc4c703d2660111b43132da1eeab23a0e15b1faa | C++ | PathogenDavid/trdrop | /trdrop_c/trdrop_c/Tasks.h | UTF-8 | 1,293 | 2.515625 | 3 | [
"MIT"
] | permissive | #pragma once
#ifndef TRDROP_TASKS_H
#define TRDROP_TASKS_H
#include <functional>
#include <opencv2/core.hpp>
namespace trdrop {
namespace tasks {
// preprocessing task which gets
// * the previous frame
// * the current frame
// * the frame index
// * the video index to access the respective configuration
//
// these tasks will be ran asynchronous with threads because we only read from the frames
// therefore they have to be commutative
using pretask = std::function<void(const cv::Mat & prev, const cv::Mat & cur, const size_t currentFrame, const size_t videoIndex)>;
// intermediate task which gets
// * the resulting frame which is to be modified
// * the video index to access the respective configuration
//
// this task may be asynchronous for different videoIndex'es
using intertask = std::function<void(cv::Mat & res, const size_t currentFrame, const size_t videoIndex)>;
// postprocessing task which gets
// * the possibly merged frame from all videos which is to be modified
//
// these task should be appended in order to the schedueler because they modify the written frame
using posttask = std::function<void(cv::Mat & res, const size_t currentFrameIndex)>;
} // namespace tasks
} //namespace trdrop
#endif // ! TRDROP_TASKS_H | true |
b80a31d14085eb6f602ce4763f35ce2f4cabcc77 | C++ | lizhiwill/LeetCodeStudy | /算法/1046_最后一块石头的重量/Solution02.cpp | UTF-8 | 1,001 | 2.984375 | 3 | [] | no_license | class Solution
{
public:
int lastStoneWeight(vector<int>& stones)
{
priority_queue<int> pqi;
int maxdata1 = 0;
int maxdata2 = 0;
int i = 0;
for(i = 0;i<stones.size();i++)
{
pqi.push(stones[i]);
}
while (pqi.size() > 1)
{
maxdata1 = pqi.top();
pqi.pop();
maxdata2 = pqi.top();
pqi.pop();
if(maxdata1!=maxdata2)
{
pqi.push(maxdata1-maxdata2);
}
}
if(pqi.size() ==0)
{
return 0;
}
else
{
return pqi[0];
}
}
};
/*
执行结果:
通过
显示详情
执行用时 :4 ms, 在所有 C++ 提交中击败了84.90% 的用户
内存消耗 :8.3 MB, 在所有 C++ 提交中击败了100.00%的用户
*/ | true |
0e20b4a96222a6ca3c4b5631def6b591ec4c7e5f | C++ | WhiZTiM/coliru | /Archive2/26/4c6bec14143bd3/main.cpp | UTF-8 | 15,649 | 3.203125 | 3 | [] | no_license | #include <type_traits>
#include <utility>
#include <iterator>
#include <cstdint>
#include <functional>
#include <algorithm>
#include <iostream>
#include <vector>
#define sgi_assert(cond) ((void)0)
namespace sgi { namespace detail
{
template<typename T>
struct remove_cvr : std::remove_cv<std::remove_reference_t<T>> {};
template<typename T>
using remove_cvr_t = typename remove_cvr<T>::type;
template<typename T>
class is_iterable_container
{
template<typename U>
static auto check(U&) -> decltype(std::begin(std::declval<U&>()) != std::end(std::declval<U&>()), std::uint8_t(0))
{
return 0;
}
static std::uint16_t check(...)
{
return 0;
}
public:
static constexpr bool value = sizeof(check(std::declval<remove_cvr_t<T>&>())) < sizeof(std::uint16_t); //!< true if T is iterable. false if T otherwise
};
template<typename T>
class is_contiguous_container
{
template<typename U>
static auto check(U&) -> decltype(std::declval<U&>().data(), std::declval<U&>().size(), std::enable_if_t<std::is_pointer<decltype(std::declval<U&>().data())>::value>(0), std::uint8_t(0))
{
return 0;
}
static std::uint16_t check(...)
{
return 0;
}
public:
static constexpr bool value = sizeof(check(std::declval<remove_cvr_t<T>&>())) < sizeof(std::uint16_t); // true if T is iterable. false if T otherwise
};
template<typename T, bool Iterable> // T any type. Iterable==true if T is iterable false otherwise
struct value_type_of_imp
{
// Iterable is true here
using type = remove_cvr_t<decltype(*std::begin(std::declval<T&>()))>; //!< value_type of values in T if T is iterable. value_type is the same as T otherwise
};
template<typename T>
struct value_type_of_imp<T, false>
{
using type = T; //!< value_type of values in T if T is iterable. value_type is the same as T otherwise
};
template<typename T>
using value_type_of_t = typename value_type_of_imp<T, is_iterable_container<T>::value>::type;
}}
namespace sgi
{
/**
* @brief trait to check if a type can be used with std::being and std::end
* @tparam T any type
*/
template<typename T>
struct is_iterable_container : detail::is_iterable_container<T> {};
/**
* @brief trait to check if a type has the methods data() and size()
* @tparam T any type
* @note concept contiguous_container: a container with values in contiguous memory with a pointer accessed through data() and the number of values is queried with size()
* @note the trait only checks the methods data() and size() without a guaranties whether the memory is contiguous or not
*/
template<typename T>
struct is_contiguous_container : detail::is_contiguous_container<T> {};
/**
* @brief remove a reference if it exists then remove a const or a volatile if one exists
* @tparam T any type
*/
template<typename T>
using remove_cvr = detail::remove_cvr<T>;
/**
* @brief equivalent to typename detail::remove_cvr<T>::type
* @tparam T any type
*/
template<typename T>
using remove_cvr_t = detail::remove_cvr_t<T>;
/**
* @brief return the value_type of values of an iterable sequence. If the type is not iterable the value type remains the same
* @tparam T any typename
*/
template<typename T>
using value_type_of_t = detail::value_type_of_t<T>;
} // namespace
/**
* @file math.hpp
* @author alasram
* @brief general math functions
* @copyright 2014
*/
#ifndef SGI_MATH_MATH_HPP
#define SGI_MATH_MATH_HPP
namespace sgi
{
/**
* @brief convert degrees to radians
* @param x angle in degrees
* @tparam T floating point typename
* @return angle in radians
*/
template<typename T>
T radians(T x);
/**
* @brief convert radians to degrees
* @param x angle in radians
* @tparam T floating point typename
* @return angle in degrees
*/
template<typename T>
T degrees(T x);
/**
* @brief extract the sign
* @param x arithmetic value
* @tparam T signed arithmetic typename
* @return 1 if x > 0, 0 if x == 0, or -1 if x < 0
*/
template<typename T>
T sign(T x);
/**
* @brief fractional part
* @param x floating point value
* @tparam T floating point typename (an error is triggered otherwise)
* @return fractional part of x
*/
template<typename T>
T frac(T x);
/**
* @brief alias to frac
* @param x floating point value
* @tparam T floating point typename (an error is triggered otherwise)
* @return fractional part of x
*/
template<typename T>
T fract(T x);
/**
* @brief clamp x to range [mini, maxi]
* @param x value to clamp
* @param mini range start
* @param maxi range end. UB if(mini > maxi)
* @tparam T comparable non iterable typename
* @tparam U comparable non iterable typename. std::common_type<T,U>::type must be T
* @return clamped x
*/
template<typename T, typename U>
typename std::enable_if<!is_iterable_container<T>::value && !is_iterable_container<U>::value, T>::type clamp(T x, U mini, U maxi);
/**
* @brief clamp x to range [mini, maxi]
* @param x value to clamp
* @param mini range start
* @param maxi range end. UB if(mini > maxi)
* @tparam T iterable type with a comparable value_type
* @tparam U non iterable comparable type
* @return clamped x
*/
template<typename T, typename U>
typename std::enable_if<is_iterable_container<T>::value && !is_iterable_container<U>::value, T>::type clamp(T x, U mini, U maxi);
/**
* @brief clamp x to range [0, 1]
* @param x value to be clamped
* @tparam T float typename
* @return saturated x
*/
template<typename T>
T saturate(T x);
/**
* @brief wrap value in [0,1[ ex wrap(2.1) -> 0.1 and wrap(-0.1) -> 0.9
* @param x value to wrapped
* @tparam T floating point typename
* @return wrapped x
*/
template<typename T>
T wrap(T x);
/**
* @brief wrap value in range R. R=[0,n[
* @param x value to wrapped
* @param n wrapping range
* @tparam T floating point or integral typename
* @return wrapped x
*/
template<typename T>
T wrap(T x, T n);
/**
* @brief vector dot product
* @param a first vector operand (any iterable type)
* @param b second vector operand. must have the same size as a
* @tparam V iterable type
* @return dot product result
*/
template<typename V>
auto dot(V const& x, V const& y) -> remove_cvr_t<decltype(*std::begin(x))>;
/**
* @brief vector squared length
* @param v vector
* @tparam V iterable type
* @return vector squared length result
*/
template<typename V>
auto square_length(V const& v) -> decltype( dot(v,v) );
/**
* @brief vector length
* @param v vector
* @tparam V iterable type
* @return vector length result
*/
template<typename V>
auto length(V const& v) -> decltype(std::sqrt(square_length(v)));
/**
* @brief squared distance between 2 points
* @param x first point
* @param y second point, must have the same size as x
* @tparam V iterable type with value_type supporting operator-
* @return squared distance between x and y
*/
template<typename V>
auto square_distance(V const& x, V const& y) -> remove_cvr_t<decltype(*std::begin(x))>;
/**
* @brief distance between 2 points
* @param x first point
* @param y second point
* @tparam V iterable type with value_type supporting operator-
* @return distance between x and y
*/
template<typename V>
auto distance(V const& x, V const& y) -> decltype(std::sqrt(square_distance(x,y)));
/**
* @brief vector normalization
* @param v vector
* @tparam V copyable iterable type different from a static array
* @return unit vector with same direction/orientation as v
*/
template<typename V>
V normalize(V const& v);
/**
* @brief linear interpolation
* @param x starting point of the linear curve
* @param y ending point of the linear curve
* @param a interpolation factor: must be between 0 and 1
* @tparam T arithmetic typename
* @return linear interpolation between x and y with scalar factor a
*/
template<typename T>
T lerp(T const& x, T const& y, T const& a);
/**
* @brief linear interpolation
* @param x starting point of the linear curve
* @param y ending point of the linear curve
* @param a interpolation factor: must be between 0 and 1
* @tparam V copyable iterable type with value_type T
* @tparam T arithmetic typename
* @return linear interpolation between x and y with scalar factor a
*/
template<typename V, typename T>
V lerp(V const& x, V const& y, T const& a);
/**
* @brief step if x reaches y
* @param x any position
* @param y step position
* @tparam T arithmetic typename
* @return T(0) if x<y, T(1) otherwise
*/
template<typename T>
T step(T y, T x);
/**
* @brief pulse between y0 and y1
* @param x any position
* @param y0 pulse start
* @param y1 pulse end
* @tparam T arithmetic typename
* @return T(1) if y0 <= x <= y1, T(0) otherwise
*/
template<typename T>
T pulse(T y0, T y1, T x);
/**
* @brief smooth t using s-curve Perlin noise function
* @param t value between 0 and 1
* @tparam T arithmetic typename
* @return 3*t*t - 2*t*t*t
*/
template<typename T>
T smooth(T t);
/**
* @brief smoth t using s-curve Improved Perlin noise function
* @param t value between 0 and 1
* @tparam T arithmetic typename
* @return 6*t*t*t*t*t - 15*t*t*t*t + 10*t*t*t
*/
template<typename T>
T ismooth(T t);
/**
* @brief smoothly step from y0 to y1
* @param x any position
* @param y0 smooth stepping starting position
* @param y1 smooth stepping ending position
* @tparam T arithmetic typename
* @return T(0) if x<y0, T(1) if x>y1, smooth((x-y0)/(y1-y0)) otherwise
*/
template<typename T>
T smoothstep(T y0, T y1, T x);
/**
* @brief smoothly step from y0 to y1
* @param x any position
* @param y0 smooth stepping starting position
* @param y1 smooth stepping ending position
* @tparam T arithmetic typename
* @return T(0) if x<y0, T(1) if x>y1, ismooth((x-y0)/(y1-y0)) otherwise
*/
template<typename T>
T ismoothstep(T y0, T y1, T x);
} // namespace
#endif // include guard
/**
* @file math.hpp
* @author alasram
* @brief general math functions
* @copyright 2014
*/
#ifndef SGI_MATH_MATH_IPP
#define SGI_MATH_MATH_IPP
#include <functional>
#include <algorithm>
#include <cmath>
#include <boost/math/constants/constants.hpp>
namespace sgi { namespace detail
{
template<typename T, bool>
struct wrap
{
static T call(T x, T n)
{
static_assert(std::is_floating_point<T>::value, "T must be a floating point typename");
return fmod(fmod(x, n) + n, n);
}
};
template<typename T>
struct wrap<T,false>
{
static T call(T x, T n)
{
static_assert(std::is_integral<T>::value, "T must be an integral typename");
using type = typename std::make_unsigned<T>::type;
return type(x) % type(n);
}
};
}} // namespace
namespace sgi
{
template<typename T>
T sign(T x)
{
static_assert(std::is_signed<T>::value, "T must be a signed arithmetic typename");
return x > T(0) ? T(1) : (x==T(0) ? T(0) : T(-1));
}
template<typename T>
T frac(T x)
{
static_assert(std::is_floating_point<T>::value, "T must be a floating point typename");
return x - std::floor(x);
}
template<typename T>
T fract(T x)
{
return frac(x);
}
template<typename T, typename U>
typename std::enable_if<!is_iterable_container<T>::value && !is_iterable_container<U>::value, T>::type clamp(T x, U mini, U maxi)
{
sgi_assert(mini <= maxi);
static_assert(std::is_same<typename std::common_type<T,U>::type, T>::value, "T must be the common type");
return std::min(std::max(x, T(mini)), T(maxi));
}
template<typename T, typename U>
typename std::enable_if<is_iterable_container<T>::value && !is_iterable_container<U>::value, T>::type clamp(T x, U mini, U maxi)
{
std::transform(std::begin(x), std::end(x), std::begin(x), [mini, maxi](value_type_of_t<T> x){return clamp(x, mini, maxi);});
return x;
}
template<typename T>
T saturate(T x)
{
return clamp(x, T(0), T(1));
}
template<typename T>
T wrap(T x)
{
return detail::wrap<T,true>::call(x, T(1));
}
template<typename T>
T wrap(T x, T n)
{
return detail::wrap<T,std::is_floating_point<T>::value>::call(x, n);
}
template<typename V>
auto dot(V const& x, V const& y) -> remove_cvr_t<decltype(*std::begin(x))>
{
static_assert(is_iterable_container<V>::value, "V must be an iterable type");
sgi_assert( std::distance(std::begin(x), std::end(x)) == std::distance(std::begin(y), std::end(y)) );
return std::inner_product(std::begin(x), std::end(x), std::begin(y), remove_cvr_t<decltype(*std::begin(x))>(0));
}
template<typename V>
auto square_length(V const& v) -> decltype(dot(v,v) )
{
return dot(v,v);
}
template<typename V>
auto length(V const& v) -> decltype(std::sqrt(square_length(v)))
{
return std::sqrt( square_length(v) );
}
template<typename V>
auto square_distance(V const& x, V const& y) -> remove_cvr_t<decltype(*std::begin(x))>
{
static_assert(is_iterable_container<V>::value, "V must be an iterable type");
sgi_assert( std::distance(std::begin(x), std::end(x)) == std::distance(std::begin(y), std::end(y)) );
using type = remove_cvr_t<decltype(*std::begin(x))>;
return std::inner_product(std::begin(x), std::end(x), std::begin(y), type(0), std::plus<type>(), [](type const& x, type const& y){ return (x-y)*(x-y); });
}
template<typename V>
auto distance(V const& x, V const& y) -> decltype(std::sqrt(square_distance(x,y)))
{
return std::sqrt(square_distance(x,y));
}
template<typename V>
V normalize(V const& v)
{
static_assert(is_iterable_container<typename std::decay<V>::type>::value, "V must be an iterable type different from a static array"); // the decay eleminates the static array
static_assert(std::is_copy_constructible<V>::value, "V must be copyable");
V r(v);
auto l = square_length(r);
using value_type = typename std::decay<decltype(l)>::type;
sgi_assert( l >= value_type(0) );
l = value_type(1) / std::sqrt(l);
for(auto& i : r)
i *= l;
return r;
}
template<typename T>
T lerp(T const& x, T const& y, T const& a)
{
sgi_assert( a >= T(0) && a <= T(1) );
return x + a * (y - x);
}
template<typename V, typename T>
V lerp(V const& x, V const& y, T const& a)
{
static_assert(is_iterable_container<V>::value, "V must be an iterable type");
static_assert(std::is_same<value_type_of_t<V>, T>::value, "V value_tpe must be the same as T");
static_assert(std::is_copy_constructible<V>::value, "V must be copyable");
sgi_assert( std::distance(std::begin(x), std::end(x)) == std::distance(std::begin(y), std::end(y)) );
V r(x);
std::transform(std::begin(r), std::end(r), std::begin(y), std::begin(r), std::bind(lerp<T>, std::placeholders::_1, std::placeholders::_2, a));
return r;
}
template<typename T>
T step(T y, T x)
{
static_assert(std::is_arithmetic<T>::value, "T must be an arithmetic typename");
return static_cast<T>(x >= y);
}
template<typename T>
T pulse(T y0, T y1, T x)
{
return step(y0,x) - step(y1,x);
}
template<typename T>
T smooth(T t)
{
sgi_assert( t >= T(0) && t <= T(1) );
return t * t * (T(3) - T(2) * t);
}
template<typename T>
T ismooth(T t)
{
sgi_assert( t >= T(0) && t <= T(1) );
return t * t * t * (t * (t * T(6) - T(15)) + T(10));
}
template<typename T>
T smoothstep(T y0, T y1, T x)
{
sgi_assert( y0 != y1 );
return smooth( clamp( (x-y0)/(y1-y0), T(0), T(1) ) );
}
template<typename T>
T ismoothstep(T y0, T y1, T x)
{
sgi_assert( y0 != y1 );
return ismooth( clamp( (x-y0)/(y1-y0), T(0), T(1) ) );
}
} // namespace
#endif // include guard
int main()
{
using namespace sgi;
std::cout << wrap(3.14f, 2.f) << std::endl;
return 0;
// std::cout << sgi::clamp(3, 5, 10) << std::endl;
std::vector<int> vec = {0,1,2,3,4,5,6,7,8,9};
std::vector<int> vecc = sgi::clamp(vec, short(3), short(7));
std::cout << "norm = " << sgi::dot(vec, vec) << std::endl;
for(auto v : vecc)
{
std::cout << sgi::pulse(4,6,v) << std::endl;
}
}
| true |
1e27d17ddba422367c809d6a5d7b86427e079c49 | C++ | jurses/p2cya | /word.cpp | UTF-8 | 1,795 | 3.578125 | 4 | [] | no_license | #include "word.hpp"
#include <iostream>
namespace CYA{
Word::Word(){
word_.resize(0);
empty_ = true;
}
Word::Word(const Alphabet& A)
{
alphabet_ = A;
}
Word::Word(char c){
if(c == '&')
empty_ = true;
word_.push_back(c);
}
Word::Word(const std::string& ws){
word_ = ws;
empty_ = false;
}
Word::Word(const Word& w){
alphabet_ = w.alphabet_;
word_ = w.word_;
empty_ = w.empty_;
}
const char* Word::obtWord(void)const{
return word_.c_str();
}
Word& Word::operator=(const Word& word){
word_ = word.word_; // qué lío ;-)
// Word es la clase
// word es el objeto de la clase Word
// word_ es el atributo string del objeto word de la clase Word...
empty_ = word.empty_;
return *this;
}
Word& Word::operator=(const char* word){
word_ = word;
empty_ = false;
return *this;
}
bool Word::operator<(const Word& word)const{ // necesario, promete al compilador no tocar el word
if(word_.size() != word.word_.size())
return word_.size() < word.word_.size();
for(int i = 0; i < word_.size(); i++)
if(word_[i] != word.word_[i])
return word_[i] < word.word_[i];
return false; // es la misma palabra
}
void Word::invert(void){
char swapTemp;
for(int i = 0; i < word_.size()/2; i++){
swapTemp = word_[i];
word_[i] = word_[word_.size() - 1 - i];
word_[word_.size() - 1 - i] = swapTemp;
}
}
std::string Word::obtString(void){
return word_;
}
void Word::concatenate(Word w){
if(!empty_)
word_ += w.obtString();
else
word_ = w.obtString();
}
bool Word::operator==(const Word& w)const{
if(word_.compare(w.word_) == 0)
return true;
else
return false;
}
std::ostream& Word::write(std::ostream& os){
os << word_;
return os;
}
bool Word::isEmpty(void){
return empty_;
}
} | true |
801c359a05999ec1520c7a0c814f7e9183abb117 | C++ | Stephen1993/ACM-code | /hdu1236.cpp | UTF-8 | 882 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<algorithm>
using namespace std;
struct point
{
string number;
int n,s[11],sum;
}student[1002];
bool cmp(point a,point b)
{
if(a.sum!=b.sum)return a.sum>b.sum;
return a.number<b.number;
}
int main()
{
int m,num,grade[11],mingrade,student_num;
while(cin>>m,m)
{
cin>>num>>mingrade;
student_num=0;
for(int i=1;i<=num;++i)
cin>>grade[i];
for(int i=0;i<m;++i)
{
cin>>student[i].number>>student[i].n;
student[i].sum=0;
for(int j=0;j<student[i].n;++j)
{
cin>>student[i].s[j];
student[i].sum+=grade[student[i].s[j]];
}
if(student[i].sum>=mingrade)
student_num++;
}
sort(student,student+m,cmp);
cout<<student_num<<endl;
for(int i=0;i<student_num;++i)
cout<<student[i].number<<' '<<student[i].sum<<endl;
}
return 0;
} | true |
2ea58e1dd2f9fa082337546ae441411b921cec57 | C++ | ananthanandanan/academics | /CPP/tutorial/Bitsets.cpp | UTF-8 | 290 | 2.84375 | 3 | [] | no_license |
#include <bits/stdc++.h>
#define Max 8
int main()
{
std::bitset<Max> visited;
for(int i=0 ;i<Max;i++)
{ int x;
std::cin>>x;
visited[x] = true;
}
std::cout << visited.count()<<std::endl;
std::cout << visited << std::endl;
return 0;
}
| true |
97b70537f64d8434fe425db76fa97896f69528c7 | C++ | phuonghtruong/cplusplus | /practice/designpattern/abstractFactory/ConcreteProductB2.h | UTF-8 | 467 | 3 | 3 | [] | no_license | #pragma once
#include "AbstractProductB.h"
class ConcreteProductB2 : public AbstractProductB
{
public:
std::string UsefulFunctionB() const override
{
return "The result of the product B2";
}
std::string AnotherUsefulFunctionB(const AbstractProductA &collaboration) const override
{
const std::string result = collaboration.UsefulFunctionA();
return "The result of the B2 collaborating with ( " + result + " )";
}
}; | true |
6eeb5e94c53038a8592c083dda4b3c4ec9083a84 | C++ | whytui/code4cpp | /ch13/thread_print.cpp | UTF-8 | 533 | 3.109375 | 3 | [] | no_license | /**
* 作者:刘时明
* 时间:2020/11/19 0019
*/
#include "main.h"
void print_work(const int &i, char *buf)
{
cout << i << endl;
cout << buf << endl;
}
void print_work_ok(int i, const string &buf)
{
cout << i << endl;
cout << buf.c_str() << endl;
}
void thread_print()
{
int v = 1;
int &vy = v;
char buf[] = "this is a test!";
// thread_print结束,vy、buf均被回收
thread t1(print_work, vy, buf);
t1.detach();
thread t2(print_work_ok, v, string(buf));
t2.detach();
} | true |
548eaee7bc15a508285b60fc2377ce814879f7be | C++ | javang/mlearning | /trunk/cplusplus/include/trees/information_gain.h | UTF-8 | 3,765 | 2.984375 | 3 | [] | no_license |
#ifndef INFORMATION_GAIN_H
#define INFORMATION_GAIN_H
#include "utility/eigen_helper.h"
#include "definitions.h"
#include "types.h"
#include <utility>
#include <set>
#include <vector>
namespace ml {
namespace trees {
enum InformationMeasure {
GINI, ENTROPY
};
//std::vector<InformationMeasure> InformationMeasures;
enum ThresholdType {
LOWER, HIGHER
};
typedef std::pair<double, double> GainPair; // (gain, threshold)
//! Computes the information gain
/**
* @param [in] classes A vector of ints identifying the classes of the
* values
* @param [in] values The vector of values used to compute the information
* gain
* @param [in] v_type Identifies if values contains a categorical
* variable
* @param [in] measure The information measure used. GINI or ENTROPY
* \return The function returns a pair (gain, threshold)
*/
GainPair information_gain(const Eigen::VectorXd &values,
const Eigen::VectorXi &classes,
VariableType v_type, InformationMeasure measure);
//! Computes the Gini information gain for a set of values given their
//! classes Y
/**
* gain(classes|values) = G(Y) - sum_j ( P(xj) * G(Y|xj) )
* where:
* G(classes) is the total_gini impurity = 1 - sum_k( fy^2)
* G(classes|value_j) - gini impurity calculated over the classes
* corresponding to value_j
* fy = Fraction of class y within the classes
* P(value_j) = Probability of value xj in "values", estimated as fraction.
* @param classes A vector ints identifying the classes for the values
* @param values
* @return a gain pair
*/
double nominal_gini_gain(const Eigen::VectorXi &values, const Eigen::VectorXi &classes);
/**
* Information gain according to the Gini impurity for a continuous variable X.
* The function finds the threshold (t) that produces the best split gain
* gain = G(Y) - ( P(X<T) G(Y|X<t) + P(X>T) G(Y|X<t) )
* @param values A column vector with values of X
* @param classes A column vector with the classes for the values
* @return A pair of values (gain, threshold)
*/
GainPair continuous_gini_gain(const Eigen::VectorXd &values, const Eigen::VectorXi &classes);
/**
* Shannon's entropy gain for a nominal variable:
* gain(classes|values) = H(classes) - sum_j ( P(value_j) * H(classes|value_j) )
* where:
* H(Y) = log2(fy) * fy --> fy = fraction of values of Y with class y
P(value_j) = Probability of value_j (estimated as fraction).
H(classes|value_j) - Entropy of the classes given value_j
* @param values
* @param classes
* @return
*/
double nominal_entropy_gain(const Eigen::VectorXi &values, const Eigen::VectorXi &classes);
GainPair continuous_entropy_gain(const Eigen::VectorXd &values,
const Eigen::VectorXi &classes);
/** Computes the cross table T
* The element T(i,j) is the number of times that value i belongs to class j
* the table has rows = number of values, cols = number of classes
* @param classes
* @param values
* @return the cross table
*/
Eigen::MatrixXi get_cross_table(const Eigen::VectorXi &values,
const Eigen::VectorXi &classes);
/**
* Cross table in 1D. It is equivalent to a histogram
* @param values
* @return The number of times that each value appears
*/
Eigen::VectorXi get_cross_table(const Eigen::VectorXi &values);
/**
* Computes the gini impurity for a set of values
* @param values
* @return The value of the gini impurity
*/
double gini(const Eigen::VectorXd &values);
/**
* Computes the Shannon's entropy of a set of values
* @param values
* @return the value of the entropy
*/
double entropy(const Eigen::VectorXd &values);
} // trees
} // ml
#endif
| true |
6563342b76003413764c59c41527821b732b13c1 | C++ | thirtiseven/CF | /EDU 32/D.cc | UTF-8 | 589 | 2.640625 | 3 | [] | no_license | #include <iostream>
typedef long long LL;
const int Maxn = 1000 + 10;
LL CArr[Maxn + 10][Maxn + 10];
void CInit(int n) {
for (int i = 0; i <= n; i++) {
CArr[i][0] = CArr[i][i] = 1;
for (int j = 1; j < i; j++)
CArr[i][j] = (CArr[i - 1][j - 1] + CArr[i - 1][j]);
}}
LL C(int n, int m) { return CArr[n][m];
}
int main(int argc, char *argv[]) {
LL n, k;
LL kk[5] = {0, 0, 1, 2, 9};
std::cin >> n >> k;
CInit(n);
LL ans = 1;
for(int i = 2; i <= k; i++) {
ans += (C(n, n-i) * kk[i]);
//std::cout << C(n, n-i) << " " << kk[i] << " ";
}
std::cout << ans << std::endl;
return 0;
} | true |
f950e13c05e51f3641392dc82fa527227644962f | C++ | wkerstiens/MissileCommand | /source/MissileCommand.cpp | UTF-8 | 3,239 | 2.8125 | 3 | [] | no_license | //
// Created by William Kerstiens on 11/6/20.
//
#include <mutex>
#include <iostream>
#include "MissileCommand.h"
#include "EventHandler.h"
#include "Renderer.h"
#include "SDL.h"
MissileCommand::MissileCommand(std::size_t width, std::size_t height, std::size_t target_frame_duration)
: _width(width), _height(height), _target_frame_duration(target_frame_duration) {
renderer = std::make_unique<Renderer>(_width, _height);
eventHandler = std::make_unique<EventHandler>();
cities.push_back(std::make_unique<City>(80, 580, 50, 30));
cities.push_back(std::make_unique<City>(150, 580, 50, 30));
cities.push_back(std::make_unique<City>(220, 580, 50, 30));
cities.push_back(std::make_unique<City>(370, 580, 50, 30));
cities.push_back(std::make_unique<City>(440, 580, 50, 30));
cities.push_back(std::make_unique<City>(510, 580, 50, 30));
laserCannons.push_back(std::make_unique<LaserCannon>(20, 550, 20, 30));
laserCannons.push_back(std::make_unique<LaserCannon>(310, 550, 20, 30));
laserCannons.push_back(std::make_unique<LaserCannon>(600, 550, 20, 30));
Running(true);
std::lock_guard<std::mutex> lock(_mtxCout);
std::cout << "Missile Command instantiated. \n";
}
void MissileCommand::Run() {
Uint32 title_timestamp = SDL_GetTicks();
Uint32 last_console_dump = SDL_GetTicks();
Uint32 frame_start;
Uint32 frame_end;
Uint32 frame_duration;
int frame_count = 0;
while (Running()) {
frame_start = SDL_GetTicks();
// input, update, render
HandleInput();
Update();
renderer->Render(cities, laserCannons);
frame_end = SDL_GetTicks();
// Keep track of how long each loop through the input/update/render cycle
// takes.
frame_count++;
frame_duration = frame_end - frame_start;
// After every second, update the window title.
if (frame_end - title_timestamp >= 1000) {
renderer->SetTitle(frame_count);
frame_count = 0;
title_timestamp = frame_end;
}
// After every 10 seconds, dump info to console.
if (frame_end - last_console_dump >= 100000) {
printStatus();
last_console_dump = frame_end;
}
// If the time for this frame is too small (i.e. frame_duration is
// smaller than the target ms_per_frame), delay the loop to
// achieve the correct frame rate.
if (frame_duration < _target_frame_duration) {
SDL_Delay(_target_frame_duration - frame_duration);
}
}
}
void MissileCommand::Running(bool running) {
std::unique_lock<std::mutex> lck (mtxRunning);
_running = running;
}
bool MissileCommand::Running() {
std::unique_lock<std::mutex> lck (mtxRunning);
return _running;
}
void MissileCommand::HandleInput() {
eventHandler->HandleInput(std::move(_running), laserCannons);
}
void MissileCommand::Update() {
for( auto &lc : laserCannons) {
lc->Update();
}
}
void MissileCommand::printStatus() {
std::unique_lock<std::mutex> lock(_mtxCout);
std::cout << "Missile command is running\n";
lock.unlock();
eventHandler->printStatus();
renderer->printStatus();
}
| true |
53745bcd09e37923b79c99181629d640d5eb5a97 | C++ | IanJoseph/CPP-Code | /SDL Basic/src/Screen.cpp | UTF-8 | 3,695 | 3.109375 | 3 | [] | no_license | /*
* Screen.cpp
*
* Created on: Aug 2, 2017
* Author: Ian J
*/
#include "Screen.h"
#include <iostream>
#include <stdio.h>
namespace CPPTutorials {
Screen::Screen() :
m_window(NULL), m_renderer(NULL), m_texture(NULL), m_buffer1(NULL), m_buffer2(NULL) {
}
// Initialize screen, create window.
bool Screen::init() {
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
return false;
}
// Create Window
m_window = SDL_CreateWindow("Particle Fire Explosion",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH,
SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (m_window == NULL) {
SDL_Quit();
return false;
}
// Create rendering context
m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_PRESENTVSYNC);
if (m_renderer == NULL) {
SDL_DestroyWindow(m_window);
SDL_Quit();
return false;
}
// Create texture, loads in Video card's VRAM
m_texture = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_STATIC, SCREEN_WIDTH, SCREEN_HEIGHT);
if (m_texture == NULL) {
SDL_DestroyRenderer(m_renderer);
SDL_DestroyWindow(m_window);
SDL_Quit();
return false;
}
//Create variable to hold screen pixel data
m_buffer1 = new Uint32[SCREEN_WIDTH * SCREEN_HEIGHT];
m_buffer2 = new Uint32[SCREEN_WIDTH * SCREEN_HEIGHT];
// Initialize buffer to black
memset(m_buffer1, 0x0, SCREEN_WIDTH * SCREEN_HEIGHT * sizeof(Uint32));
memset(m_buffer2, 0x0, SCREEN_WIDTH * SCREEN_HEIGHT * sizeof(Uint32));
return true;
}
// Process Window Events
bool Screen::processEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
return false;
}
}
return true;
}
// Blur last screen
void Screen::boxBlur() {
Uint32 *temp = m_buffer1;
m_buffer1 = m_buffer2;
m_buffer2 = temp;
for (int y=0; y < SCREEN_HEIGHT; y++) {
for (int x = 0; x < SCREEN_WIDTH; x++) {
int redTotal = 0;
int greenTotal = 0;
int blueTotal = 0;
for (int row = - 1; row <= 1; row++) {
for (int col = - 1; col <= 1; col++) {
int currentX = x + col;
int currentY = y+row;
if (currentX >= 0 && currentX < SCREEN_WIDTH && currentY >= 0 && currentY < SCREEN_HEIGHT) {
Uint32 color = m_buffer2[currentY*SCREEN_WIDTH + currentX];
Uint8 red = color >> 24;
Uint8 green = color >> 16;
Uint8 blue = color >> 8;
redTotal += red;
greenTotal += green;
blueTotal += blue;
}
}
}
Uint8 red = redTotal/9;
Uint8 green = greenTotal/9;
Uint8 blue = blueTotal/9;
setPixel(x,y, red, green, blue);
}
}
}
// Clear screen
void Screen::clear() {
memset(m_buffer1, 0, SCREEN_WIDTH * SCREEN_HEIGHT * sizeof(Uint32));
memset(m_buffer2, 0, SCREEN_WIDTH * SCREEN_HEIGHT * sizeof(Uint32));
}
// Set color for each individual pixelv
void Screen::setPixel(int x, int y, Uint8 red, Uint8 green, Uint8 blue) {
if (x < 0 || x >= SCREEN_WIDTH || y < 0 || y >= SCREEN_HEIGHT) {
return;
}
Uint32 pixelColor = 0;
pixelColor += red;
pixelColor <<= 8;
pixelColor +=green;
pixelColor <<= 8;
pixelColor +=blue;
pixelColor <<= 8;
pixelColor += 0xFF;
m_buffer1[(y * SCREEN_WIDTH) + x] = pixelColor;
}
// Draw buffer data in WIndow
void Screen::update() {
SDL_UpdateTexture(m_texture, NULL, m_buffer1, SCREEN_WIDTH * sizeof(Uint32));
SDL_RenderClear(m_renderer);
SDL_RenderCopy(m_renderer, m_texture, NULL, NULL);
SDL_RenderPresent(m_renderer);
}
// Close screen and release memory
void Screen::close() {
delete[] m_buffer1;
delete[] m_buffer2;
SDL_DestroyRenderer(m_renderer);
SDL_DestroyTexture(m_texture);
SDL_DestroyWindow(m_window);
SDL_Quit();
}
Screen::~Screen() {
// TODO Auto-generated destructor stub
}
} /* namespace CPPTutorials */
| true |
d33a192bfdeb7fbd0f60d68d69e2767c73c80082 | C++ | Cthutu/agf | /src/agf/platform/fad.h | UTF-8 | 3,331 | 2.78125 | 3 | [] | no_license | //----------------------------------------------------------------------------------------------------------------------
// FAD API
//----------------------------------------------------------------------------------------------------------------------
#pragma once
#include <cstdint>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#ifdef _WIN32
#include <windows.h>
#endif
#include <iosfwd>
namespace agf
{
class ExeDrive
{
public:
ExeDrive()
{
using namespace std;
string exeFileName = win32GetExePathName();
fstream f(exeFileName, ios::in | ios::binary | ios::ate);
if (f.is_open())
{
uint64_t s1 = f.tellg();
f.seekg(-int(sizeof(uint64_t) * 2), ios::end);
uint64_t s2 = f.tellg();
uint64_t magic;
int64_t size;
std::streampos end = f.tellg();
f.read((char *)&magic, 8);
f.read((char *)&size, 8);
if (magic == 0xc0deface)
{
f.seekg(-size, ios::end);
while (f.tellg() < end)
{
FileInfo fi;
uint8_t len;
f.read((char *)&len, 1);
vector<char> name;
name.resize(len);
f.read(name.data(), len);
f.read((char *)&fi.size, sizeof(uint64_t));
fi.offset = (uint64_t)f.tellg();
f.seekg(fi.size, ios::cur);
m_fileMap[string(name.begin(), name.end())] = fi;
}
}
f.close();
}
}
std::vector<uint8_t> loadFile(std::string name)
{
using namespace std;
vector<uint8_t> data;
auto it = m_fileMap.find(name);
if (it != m_fileMap.end())
{
FileInfo& fi = it->second;
string exeFileName = win32GetExePathName();
fstream f(exeFileName, ios::in | ios::binary);
if (f.is_open())
{
f.seekg(fi.offset);
data.resize(fi.size);
f.read((char *)data.data(), fi.size);
f.close();
}
}
return data;
}
private:
std::string win32GetExePathName()
{
int len = MAX_PATH;
for (;;)
{
char* buf = (char *)malloc(len);
if (!buf) return 0;
DWORD pathLen = GetModuleFileName(0, buf, len);
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
// Not enough memory!
len = 2 * len;
free(buf);
continue;
}
std::string path(buf);
free(buf);
return path;
}
}
private:
struct FileInfo
{
uint64_t offset;
uint64_t size;
};
std::map<std::string, FileInfo> m_fileMap;
};
}
| true |
ac444ef826e4d5636d91a59fd39572f92baf1f02 | C++ | opendarkeden/server | /src/server/gameserver/skill/ReactiveArmor.h | UTF-8 | 1,197 | 2.59375 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////////
// Filename : ReactiveArmor.h
// Written By :
// Description :
//////////////////////////////////////////////////////////////////////////////
#ifndef __SKILL_REACTIVE_ARMOR_HANDLER_H__
#define __SKILL_REACTIVE_ARMOR_HANDLER_H__
#include "SkillHandler.h"
//////////////////////////////////////////////////////////////////////////////
// class ReactiveArmor;
//////////////////////////////////////////////////////////////////////////////
class ReactiveArmor : public SkillHandler
{
public:
ReactiveArmor() throw() {}
~ReactiveArmor() throw() {}
public:
string getSkillHandlerName() const throw() { return "ReactiveArmor"; }
SkillType_t getSkillType() const throw() { return SKILL_REACTIVE_ARMOR; }
void execute(Ousters* pOusters, OustersSkillSlot* pOustersSkillSlot, CEffectID_t CEffectID) ;
void execute(Ousters* pOusters, ObjectID_t ObjectID, OustersSkillSlot* pOustersSkillSlot, CEffectID_t CEffectID) ;
void computeOutput(const SkillInput& input, SkillOutput& output);
};
// global variable declaration
extern ReactiveArmor g_ReactiveArmor;
#endif // __SKILL_REACTIVE_ARMOR_HANDLER_H__
| true |
635074de1407e9cab84124bae5b03faa179f5b9a | C++ | utec-poo/tarea-semana-1-3-LordGlovaton | /ejercicio2/main.cpp | UTF-8 | 934 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include "Tipos.h"
using namespace std;
int main(){
int zona=0;
char dato;
cout<<"diga zona:";
cin>>zona;
cout<<"el cliente es claro (responder V(verdadero) o F(falso):";
cin>>dato;
if (char(102)==dato){
switch(zona){
case 1: cout<<"Super Vip:"<<212<<" soles";
break;
case 2:cout<<"Vip:"<<170<<" soles";
break;
case 3:cout<<"Preferencial:"<<136<<" soles";
break;
case 4:cout<<"General: "<<59<<" soles";
break;
default:cout<<"No existe esa zona";
break;
}
}
if (char(118)==dato){
switch(zona){
case 1: cout<<"Super Vip:"<<212-(212*0.2)<<" soles";
break;
case 2:cout<<"Vip:"<<170-(170*0.2)<<" soles";
break;
case 3:cout<<"Preferencial:"<<136-(136*0.2)<<" soles";
break;
case 4:cout<<"General:"<<59-(59*0.2)<<" soles";
break;
default:cout<<"No existe esa zona";
break;
}
}
}
| true |
f8367b5665d71bb2351a4e5ff18c56cadab2a4d0 | C++ | acelster/noise-terrain-gen | /nmlib/model/moduleoutput.hpp | UTF-8 | 1,022 | 2.96875 | 3 | [] | no_license | #ifndef NM_MODULEOUTPUT_HPP
#define NM_MODULEOUTPUT_HPP
#include <nmlib/model/signaltype.hpp>
#include <nmlib/util/userdataprovider.hpp>
#include <nmlib/util/signals.hpp>
#include <string>
namespace nm {
class ModuleType;
/**
* @brief Describes one of a ModuleType's outputs (name, SignalType)
* @ingroup model
*/
class ModuleOutput : public UserDataProvider
{
public:
explicit ModuleOutput(std::string name, SignalType signalType, const ModuleType& moduleType):
c_name(name),
c_signalType(signalType),
c_moduleType(moduleType)
{}
~ModuleOutput(){destroying(*this);}
// ModuleOutput(ModuleOutput&&) = default;
// ModuleOutput(ModuleOutput&) = default;
std::string getName() const {return c_name;}
SignalType getSignalType() const {return c_signalType;}
signal<void(ModuleOutput&)> destroying;
private:
const std::string c_name;
const SignalType c_signalType;
const ModuleType &c_moduleType;
};
} // namespace nm
#endif // NM_MODULEOUTPUT_HPP
| true |
314afb8f708553efb85aaaa9b34a2cb545acc74e | C++ | pratyush2311/Spoj-Solutions | /debug 2 year.cpp | UTF-8 | 135 | 2.5625 | 3 | [] | no_license | #include<iostream>
using namespace std;
struct code
{
int a,b;
code *c;
}a;
int main()
{
cin>>a.a>>a.c->b;
cout<<a.b;
return 0;
}
| true |
12297b3504046d43c9e303ee6ac824d3f2d14b71 | C++ | sreekanth025/coding-problems | /DynamicProgramming/Longest-Increasing-Subsequence/54d_longestStringChain.cpp | UTF-8 | 2,506 | 3.515625 | 4 | [] | no_license | /*
Given a list of words, each word consists of English lowercase letters.
Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter
anywhere in word1 to make it equal to word2. For example, "abc" is a predecessor of "abac".
A word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1,
where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on.
Return the longest possible length of a word chain with words chosen from the given list of words.
*/
// Problem Link: https://leetcode.com/problems/longest-string-chain/
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int longestStrChain(vector<string>& words) {
int n = words.size();
if(n<=1) return n;
sort(words.begin(), words.end(), compare);
unordered_map<string, int> dp;
int result=0;
for(string w: words) {
for(int i=0; i<w.size(); i++) {
dp[w] = max(dp[w], 1+dp[w.substr(0,i) + w.substr(i+1)]);
}
result = max(result, dp[w]);
}
return result;
}
private:
static bool compare(string& a, string& b) {
return (a.size() < b.size());
}
};
// Method 2: (Time Limit Exceeded)
class Solution {
public:
int longestStrChain(vector<string>& words) {
int n = words.size();
if(n<=1) return n;
sort(words.begin(), words.end(), compare);
vector<int> dp(n, 1);
for(int i=1; i<n; i++) {
for(int j=0; j<i; j++) {
if(isPred(words[j], words[i]) && dp[j]+1 > dp[i]) {
dp[i] = dp[j]+1;
}
}
}
int result=0;
for(int x: dp) result = max(result, x);
return result;
}
private:
bool isPred(string a, string b) {
vector<int> c1(26, 0), c2(26, 0);
for(char x: a) c1[x-'a']++;
for(char x: b) c2[x-'a']++;
bool diff = false;
for(int i=0;i<26; i++) {
if(c1[i] != c2[i]) {
if(abs(c1[i]-c2[i]) > 1) return false;
if(diff) return false;
diff = true;
}
}
if(diff) return true;
return false;
}
static bool compare(string& a, string& b) {
return (a.size() < b.size());
}
}; | true |
1074b5343dae2f276b800a4d1096114cb68d6be7 | C++ | bangalcat/Algorithms | /graph/network-flow/9577.cc | UTF-8 | 1,482 | 2.859375 | 3 | [] | no_license | /*
백준 : 토렌트
*/
#include <bits/stdc++.h>
using namespace std;
vector<int> A, B;
vector<vector<int>> adj;
vector<bool> visited;
int n, m;
bool dfs(int a){
if(visited[a]) return false;
visited[a] = true;
for(auto v : adj[a]){
if(B[v] == -1 || !visited[B[v]] && dfs(B[v])){
A[a] = v;
B[v] = a;
return true;
}
}
return false;
}
int bipartite(int startTime, int endTime){
A = vector<int>(200,-1); B = vector<int>(200,-1);
int size= 0;
for(int start=startTime; start < endTime; ++ start){
visited = vector<bool>(200,false);
size += dfs(start);
}
return size;
}
int main(){
int T; cin >> T;
while(T--){
cin >> n >> m;
adj = vector<vector<int>>(101);
int st=999, et=0; //start, end time
for(int i=0;i<m;++i){
int t1, t2, a_ct, q;
cin >> t1 >> t2 >> a_ct;
st = min(st, t1);
et = max(et, t2);
for (int j = 0; j < a_ct; ++j) {
cin >> q;
for(int t=t1; t<t2;++t)
adj[t].push_back(q-1);
}
}
auto solve = [&](){
int minEndTime = st + n;
for(int mEt = minEndTime; mEt <= et; ++mEt){
if(bipartite(st, mEt) == n)
return mEt;
}
return -1;
};
cout << solve() << '\n';
}
return 0;
} | true |
d16840c9cdedd741f0e022ee1ba72cfc6fb8275c | C++ | linoyda/Even2 | /State.h | UTF-8 | 2,003 | 3.5 | 4 | [] | no_license | //
// Created by yael and linoy on 14/01/2020.
//
#ifndef EVEN2_STATE_H
#define EVEN2_STATE_H
#include <vector>
template <class T>
class State {
private:
T vertexIndex;
double vertexValue; //This field actually represents the COST of each vertex
double subCost;
State* fatherVertex;
bool isVisited;
int xPosition;
int yPosition;
public:
//Constructor of a state according to T (type) of index, and the current cell's value.
State(T indexOfVertex, double valOfVertex) {
this->vertexIndex = indexOfVertex;
this->vertexValue = valOfVertex;
this->subCost = valOfVertex;
this->fatherVertex = nullptr;
isVisited = false;
this->xPosition = -1;
this->yPosition = -1;
}
State* getFatherVertex() {
return this->fatherVertex;
}
void setSubCost(double cost) {
this->subCost = cost;
}
double getSubCost() {
return this->subCost;
}
void setFatherVertex(State<T>* state) {
this->fatherVertex = state;
}
T getVertexIndex() {
return this->vertexIndex;
}
double getVertexValue() {
return this->vertexValue;
}
void setIsVisited(bool visited) {
this->isVisited = visited;
}
bool getIsVisited() {
return this->isVisited;
}
//This method returns true only if a given state EQUALS to this state.
bool isEqual(State<T>* state) {
if (state->getVertexValue() == this->getVertexValue()) {
if (state->getIsVisited() == this->getIsVisited()) {
if (state->getVertexIndex() == this->getVertexIndex()) {
return true;
}
}
}
return false;
}
int getX() {
return this->xPosition;
}
int getY() {
return this->yPosition;
}
void setXAndYPositions(int x, int y) {
this->xPosition = x;
this->yPosition = y;
}
};
#endif //EVEN2_STATE_H
| true |
8f433bcf089aea7ba57131370fd8035f8067e01e | C++ | yhyhUMich/cxx11 | /c6.cpp | UTF-8 | 5,580 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <list>
#include <deque>
#include <set>
#include <typeinfo>
#include <cstring>
using namespace std;
class MyString {
public:
static size_t DCtor;
static size_t Ctor;
static size_t CCtor;
static size_t CAsgn;
static size_t MCtor;
static size_t MAsgn;
static size_t Dtor;
private:
char* _data;
size_t _len;
void _init_data(const char* s) {
_data = new char[_len+1];
memcpy(_data, s, _len);
_data[_len] = '\0';
}
public:
MyString() : _data(nullptr), _len(0) {
DCtor++;
}
MyString(const char* p) : _len(strlen(p)) {
Ctor++;
_init_data(p);
}
MyString(const MyString& str) : _len(str._len) {
CCtor++;
_init_data(str._data);
}
MyString(MyString&& str) noexcept
: _data(str._data), _len(str._len) {
MCtor++;
str._len = 0;
str._data = nullptr;
}
MyString& operator=(const MyString& str) {
CAsgn++;
if(this != &str) {
if(_data) {
delete _data;
}
_len = str._len;
_init_data(str._data);
}
return *this;
}
MyString& operator=(MyString&& str) noexcept {
MAsgn++;
if(this != &str) {
if(_data) {
delete(_data);
}
_len = str._len;
_data = str._data;
str._data = nullptr;
str._len = 0;
}
return *this;
}
virtual ~MyString() {
Dtor++;
if(_data) {
delete _data;
}
}
bool operator < (const MyString& rhs) const {
return string(this->_data) < string(rhs._data);
}
bool operator == (const MyString& rhs) const {
return string(this->_data) == string(rhs._data);
}
char* get() const {
return _data;
}
};
size_t MyString::DCtor = 0;
size_t MyString::Ctor = 0;
size_t MyString::CCtor = 0;
size_t MyString::CAsgn = 0;
size_t MyString::MAsgn = 0;
size_t MyString::MCtor = 0;
size_t MyString::Dtor = 0;
namespace std {
template<>
struct hash<MyString> {
size_t operator() (const MyString& s) const noexcept {
return hash<string>() (string(s.get()));
}
};
}
class MyStrNoMove {
public:
static size_t DCtor;
static size_t Ctor;
static size_t CCtor;
static size_t CAsgn;
static size_t Dtor;
static size_t MAsgn;
static size_t MCtor;
private:
char* _data;
size_t _len;
void _init_data(const char* s) {
_data = new char[_len+1];
memcpy(_data, s, _len);
_data[_len] = '\0';
}
public:
MyStrNoMove() : _data(nullptr), _len(0) {
DCtor++;
}
MyStrNoMove(const char* p) : _len(strlen(p)) {
Ctor++;
_init_data(p);
}
MyStrNoMove(const MyStrNoMove& str) : _len(str._len) {
CCtor++;
_init_data(str._data);
}
MyStrNoMove& operator=(const MyStrNoMove& str) {
CAsgn++;
if(this != &str) {
if(_data) {
delete _data;
}
_len = str._len;
_init_data(str._data);
}
return *this;
}
virtual ~MyStrNoMove() {
Dtor++;
if(_data) {
delete _data;
}
}
bool operator < (const MyStrNoMove& rhs) const {
return string(this->_data) < string(rhs._data);
}
bool operator == (const MyStrNoMove& rhs) const {
return string(this->_data) == string(rhs._data);
}
char* get() const {
return _data;
}
};
size_t MyStrNoMove::DCtor = 0;
size_t MyStrNoMove::Ctor = 0;
size_t MyStrNoMove::CCtor = 0;
size_t MyStrNoMove::CAsgn = 0;
size_t MyStrNoMove::Dtor = 0;
size_t MyStrNoMove::MCtor= 0;
size_t MyStrNoMove::MAsgn = 0;
namespace std {
template<>
struct hash<MyStrNoMove> {
size_t operator() (const MyStrNoMove& s) const noexcept {
return hash<string>() (string(s.get()));
}
};
}
template<typename T>
void output_static_data(const T& myStr) {
cout << typeid(myStr).name() << "--" << endl;
cout << "CCtor = " << T::CCtor;
cout << "MCtor = " << T::MCtor;
cout << "CAsng = " << T::CAsgn;
cout << "MAsgn = " << T::MAsgn;
cout << "Dtor = " << T::Dtor;
cout << "Ctor = " << T::Ctor;
cout << "DCtor = " << T::DCtor;
cout << endl;
}
template<typename M, typename NM>
void test_moveable(M c1, NM c2, long& value) {
char buf[10];
typedef typename iterator_traits<typename M::iterator>::value_type V1type;
clock_t timeStart = clock();
for(long i = 0; i < value; i++) {
snprintf(buf, 10, "%d", rand());
auto ite = c1.end();
c1.insert(ite, V1type(buf));
}
cout << "construction, milli-second : " <<(clock() - timeStart) << endl;
cout << "size() = " << c1.size() << endl;
output_static_data(*(c1.begin()));
timeStart = clock();
M c11(c1);
cout << "copy, milli-second : " << (clock() - timeStart) << endl;
timeStart = clock();
M c12(move(c1));
cout << "move copy, milli-second : " << (clock() - timeStart) << endl;
timeStart = clock();
c11.swap(c12);
cout << "swap, milli-second : " << (clock() - timeStart) << endl;
cout << endl << endl;
//NM
typedef typename iterator_traits<typename NM::iterator>::value_type V2type;
timeStart = clock();
for(long i = 0; i < value; i++) {
snprintf(buf, 10, "%d", rand());
auto ite = c2.end();
c2.insert(ite, V2type(buf));
}
cout << "construction, milli-second : " << clock() - timeStart << endl;
cout << "size() = " << c2.size() << endl;
output_static_data(*(c2.begin()));
timeStart = clock();
NM c21(c2);
cout << "copy, milli-second : " << (clock() - timeStart) << endl;
timeStart = clock();
NM c22(move(c2));
cout << "move copy, milli-second : " << (clock() - timeStart) << endl;
timeStart = clock();
c21.swap(c22);
cout << "swap, milli-second : " << (clock() - timeStart) << endl;
cout << endl << endl;
}
int main(int argc, char* argv[]) {
long value = 3000000;
test_moveable(deque<MyString>(), list<MyStrNoMove>(), value);
return 0;
}
| true |
b7ea57901a7a1d09a81635ebd796ccf49f66a8de | C++ | Michidu/ARK-Server-API | /version/Core/Public/Logger/Logger.h | UTF-8 | 775 | 2.5625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "../API/Base.h"
#include "Logger/spdlog/spdlog.h"
ARK_API std::vector<spdlog::sink_ptr>& APIENTRY GetLogSinks();
class Log
{
public:
Log(const Log&) = delete;
Log(Log&&) = delete;
Log& operator=(const Log&) = delete;
Log& operator=(Log&&) = delete;
static Log& Get()
{
static Log instance;
return instance;
}
static std::shared_ptr<spdlog::logger>& GetLog()
{
return Get().logger_;
}
void Init(const std::string& plugin_name)
{
auto& sinks = GetLogSinks();
logger_ = std::make_shared<spdlog::logger>(plugin_name, begin(sinks), end(sinks));
logger_->set_pattern("%D %R [%n][%l] %v");
logger_->flush_on(spdlog::level::info);
}
private:
Log() = default;
~Log() = default;
std::shared_ptr<spdlog::logger> logger_;
};
| true |
f43450f2220775d0de92b14ebc4182b1ddc55724 | C++ | bancsdan/3DMeshConverter | /src/reader/obj_reader.cpp | UTF-8 | 5,482 | 2.640625 | 3 | [] | no_license | #include <Eigen/Dense>
#include <algorithm>
#include <array>
#include <exception>
#include <fstream>
#include <iostream>
#include <optional>
#include <sstream>
#include <string>
#include <vector>
#include "exception.hpp"
#include "geometry/meshdata.hpp"
#include "obj_reader.hpp"
#include "utility.hpp"
namespace Converter {
MeshData ObjReader::read(std::istream &in_stream) {
MeshData result;
std::vector<Eigen::Vector4d> vertices;
std::vector<Eigen::Vector4d> vertex_normals;
std::vector<Eigen::Vector4d> vertex_textures;
for (std::string line; std::getline(in_stream, line);) {
const auto words_vect = Utility::splitString(line);
if (!words_vect.empty()) {
if (Utility::startsWith(words_vect[0U], c_vn)) {
readVector(words_vect, vertex_normals, true);
} else if (Utility::startsWith(words_vect[0U], c_vt)) {
readVector(words_vect, vertex_textures);
} else if (Utility::startsWith(words_vect[0U], c_v)) {
readVector(words_vect, vertices);
} else if (Utility::startsWith(words_vect[0U], c_f)) {
readFace(words_vect, vertices, vertex_textures, vertex_normals, result);
} else if (Utility::startsWith(words_vect[0U], c_mtllib)) {
if (words_vect.size() > 1) {
result.material_file = words_vect[1U];
}
}
}
}
return result;
}
void ObjReader::readVector(const std::vector<std::string> &line,
std::vector<Eigen::Vector4d> &vectors,
bool is_normal) const {
// If the line doesn't contain 3 or 4 coordinates after the type.
if (line.size() != 4 && line.size() != 5) {
throw IllFormedFileException();
}
Eigen::Vector4d vec{0.0, 0.0, 0.0, is_normal ? 0.0 : 1.0};
unsigned int index = 0U;
for (auto it = line.begin() + 1; it != line.end(); ++it) {
try {
vec[index++] = std::stod(*it);
} catch (const std::exception &) {
throw IllFormedFileException();
}
}
vectors.push_back(vec);
}
std::array<std::optional<int>, 3U>
ObjReader::readIndicesFromSlashSeparatedWord(const std::string &word) const {
std::array<std::optional<int>, 3U> result;
std::istringstream iss(word);
for (auto &elem : result) {
std::string idx;
std::getline(iss, idx, '/');
if (!idx.empty()) {
elem = std::stoi(idx);
}
}
return result;
}
void ObjReader::readFace(const std::vector<std::string> &line,
const std::vector<Eigen::Vector4d> &vertices,
const std::vector<Eigen::Vector4d> &vertex_textures,
const std::vector<Eigen::Vector4d> &vertex_normals,
MeshData &mesh) const {
// A face definition should consist of at least 3 vertices.
if (line.size() < 4U) {
throw IllFormedFileException();
}
std::vector<const Eigen::Vector4d *> face_vertices;
std::vector<const Eigen::Vector4d *> face_vertex_textures;
std::vector<const Eigen::Vector4d *> face_vertex_normals;
for (auto it = line.begin() + 1; it != line.end(); ++it) {
try {
const auto face_vertex_indices = readIndicesFromSlashSeparatedWord(*it);
face_vertices.push_back(&vertices[face_vertex_indices[0U].value() - 1U]);
if (face_vertex_indices[1U]) {
face_vertex_textures.push_back(
&vertex_textures[face_vertex_indices[1U].value() - 1U]);
}
if (face_vertex_indices[2U]) {
face_vertex_normals.push_back(
&vertex_normals[face_vertex_indices[2U].value() - 1U]);
}
} catch (const std::exception &) {
throw IllFormedFileException();
}
}
// Either has textures defined for every vertex or none.
if (face_vertex_textures.size() != 0U &&
face_vertex_textures.size() != face_vertices.size()) {
throw IllFormedFileException();
}
// Either has normals defined for every vertex or none.
if (face_vertex_normals.size() != 0U &&
face_vertex_normals.size() != face_vertices.size()) {
throw IllFormedFileException();
}
for (std::size_t i = 0U; i < face_vertices.size() - 2U; ++i) {
Triangle triangle;
const auto &face_vertices_0 = *face_vertices[0U];
const auto &face_vertices_i1 = *face_vertices[i + 1U];
const auto &face_vertices_i2 = *face_vertices[i + 2U];
// Some functionality like determining if point is inside the
// mesh or not are relying on the face not defining a vertex
// multiple times, the resulting mesh possibly still can be
// converted, depending on the target format.
if (face_vertices_0.isApprox(face_vertices_i1) ||
face_vertices_0.isApprox(face_vertices_i2) ||
face_vertices_i1.isApprox(face_vertices_i2)) {
std::cerr << "WARNING: There is a redundant vertex in a face definition, "
"it can cause unpredictable results!\n";
}
triangle.a.pos = face_vertices_0;
triangle.b.pos = face_vertices_i1;
triangle.c.pos = face_vertices_i2;
if (face_vertex_textures.size() != 0U) {
triangle.a.texture = *face_vertex_textures[0U];
triangle.b.texture = *face_vertex_textures[i + 1U];
triangle.c.texture = *face_vertex_textures[i + 2U];
}
if (face_vertex_normals.size() != 0U) {
triangle.a.normal = *face_vertex_normals[0U];
triangle.b.normal = *face_vertex_normals[i + 1U];
triangle.c.normal = *face_vertex_normals[i + 2U];
}
mesh.triangles.push_back(std::move(triangle));
}
}
} // namespace Converter | true |
43e10da4a97b8db0c060dbd8c30568d30c557723 | C++ | zj4775/cprojects | /排序树创建与删除.cpp | GB18030 | 1,645 | 3.515625 | 4 | [] | no_license | #include<stdio.h>
#include<sys/malloc.h>
#include<stdlib.h>
typedef struct node
{
int elem;
node *lchild;
node *rchild;
}node;
void insert(node **root,int n)
{
node *p;
if(!(*root))
{
p=(node *)malloc(sizeof(node));
p->elem=n;
p->lchild=p->rchild=NULL;
*root=p;
}
else
{
if((*root)->elem>n){insert(&((*root)->lchild),n);}
if((*root)->elem<n){insert(&((*root)->rchild),n);}
}
}
void del(node **root,int n)
{
node *p1,*p2;
if((*root)==NULL){printf("");exit(0);}
else if((*root)->elem>n){del(&((*root)->lchild),n);}
else if((*root)->elem<n){del(&((*root)->rchild),n);}
else
{
if((*root)->rchild==NULL){(*root)=(*root)->lchild;}//ַҪѧ
else if((*root)->lchild==NULL){(*root)=(*root)->rchild;}
else
{
if((*root)->lchild->rchild==NULL)
{
(*root)->elem=(*root)->lchild->elem;
del(&(*root)->lchild,(*root)->lchild->elem);
}
else
{
p1=(*root);
p2=(*root)->lchild;
while(p2->rchild!=NULL){p1=p2;p2=p2->rchild;}
(*root)->elem=p2->elem;
del(&(p1->rchild),p2->elem);//p1->rchildܻp2
}
}
}
}
void print(node *root)
{
if(root)
{
printf("%d ",root->elem);
print(root->lchild);
print(root->rchild);
}
}
int main()
{
int n;
node *R=NULL;
printf("һ0Ϊβ");
scanf("%d",&n);
while(n!=0)
{
insert(&R,n);
printf("һ0Ϊβ");
scanf("%d",&n);
}
print(R);
printf("Ҫɾ");
scanf("%d",&n);
del(&R,n);
printf("ʣµΪ\n");
print(R);
return 0;
} | true |
5b56c96314d3abd3857cae01a910847fbc486174 | C++ | sanikakharkar/atm | /include/BankDatabase.hpp | UTF-8 | 870 | 3.234375 | 3 | [] | no_license | #pragma once
#include <map>
#include <iostream>
template <class Key, class Data>
class BankDatabase
{
public:
friend class BankInterface;
BankDatabase() = default;
~BankDatabase() = default;
protected:
bool isValidKey(const Key key);
Data& getAccountData(const Key key);
void addDatabaseEntry(const Key key, const Data data);
std::map<Key, Data> database;
};
template <class Key, class Data>
bool BankDatabase<Key, Data>::isValidKey(const Key key)
{
auto it = database.find(key);
if (it != database.end())
{
return true;
}
return false;
}
template <class Key, class Data>
Data& BankDatabase<Key, Data>::getAccountData(const Key key)
{
return database[key];
}
template <class Key, class Data>
void BankDatabase<Key, Data>::addDatabaseEntry(const Key key, const Data data)
{
database[key] = data;
}
| true |
c1128ac2b5e36c305213bb952e4c6a36cc40a64a | C++ | smealum/SPACECRAFT | /src/utils/Tools.cpp | UTF-8 | 817 | 2.859375 | 3 | [] | no_license | #include "utils/Tools.h"
//#include <cstdlib>
//#include <cstdio>
//#include <sys/types.h>
//#include <sys/stat.h>
//#if defined(_WIN32) || defined(__WIN32__)
//#include <direct.h> // _mkdir
//#endif
bool createDir(const char *dir)
{
return true;
//bool success = false;
//#if defined(_WIN32) || defined(__WIN32__)
//success = _mkdir(dir) == 0;
//#else
//success = mkdir(dir, 0755) == 0;
//#endif
//if (!success && !dirExists(dir))
//printf("Couldn't create the directory: %s\n", dir);
//return success;
}
bool dirExists(const char *dir)
{
//#if defined(_WIN32) || defined(__WIN32__)
//struct _stat buf;
//if(_stat(dir, &buf)==0)return (buf.st_mode & S_IFDIR) != 0;
//#else
//struct stat buf;
//if(stat(dir, &buf)==0)return (buf.st_mode & S_IFDIR) != 0;
//#endif
return false;
}
| true |
a8c6d2403b47218e6507f3714ffa4837772879dd | C++ | yjbong/problem-solving | /leetcode/42/42.cpp | UTF-8 | 839 | 2.859375 | 3 | [] | no_license | int D[30000]; // D[i] = 지형 height[0~i]에 담을 수 있는 물의 양
int lMax[30000]; // lMax[i] = max(height[0], height[1], ... , height[i])
int rMax[30000]; // rMax[i] = max(height[n-1], height[n-2], ... , height[i])
class Solution {
public:
int trap(vector<int>& height) {
int n=height.size();
if(n==0) return 0;
lMax[0]=height[0];
for(int i=1; i<n; i++)
lMax[i]=max(lMax[i-1],height[i]);
rMax[n-1]=height[n-1];
for(int i=n-2; i>=0; i--)
rMax[i]=max(rMax[i+1],height[i]);
D[0]=0;
for(int i=1; i<n; i++){
// D[i]를 구할 때, 인덱스 (i-1) 에 얼마만큼의 물을 채울 수 있는지 확인한다.
D[i]=D[i-1]+max(0,min(lMax[i-1],rMax[i-1])-height[i-1]);
}
return D[n-1];
}
}; | true |
b84330147661566a001f231f049f89e869af8053 | C++ | pramod3009/leetcode | /oddEvenList.cpp | UTF-8 | 1,027 | 3.296875 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head or !head->next or !head->next->next){
return head;
}
ListNode* oddend = head;
ListNode* evenend = head->next;
ListNode* evenstart = head->next;
int nodenumber = 3;
ListNode* runner = head->next->next;
while(runner){
if(nodenumber % 2 == 1){
oddend->next = runner;
oddend = runner;
} else {
evenend->next = runner;
evenend = runner;
}
runner = runner->next;
nodenumber++;
}
evenend->next = NULL;
oddend->next = evenstart;
return head;
}
};
| true |
c12344c9bab4cf66c88843d4d4b301c50a64558b | C++ | jjsullivan5196/cst311-classwork | /project/pong.h | UTF-8 | 2,834 | 2.875 | 3 | [] | no_license | #pragma once
#include <cstdint>
#include <iostream>
#include <array>
#include <algorithm>
#include <SFML/Graphics.hpp>
// display constants
const uint32_t WIDTH = 800, HEIGHT = 400;
const uint32_t BALL_R = WIDTH * 0.01f;
const uint32_t BAT_W = WIDTH * 0.03f, BAT_H = HEIGHT / 4;
const uint32_t BAT_HH = BAT_H / 2;
// game win state
enum win_state : uint8_t {
None = 0,
Player1,
Player2
};
// global game state
struct gamestate {
uint8_t bats[2];
uint8_t scores[2];
uint8_t ball[2];
short dir[2];
win_state win;
};
// shapes for bats/ball
struct drawinfo {
sf::CircleShape ball = sf::CircleShape(BALL_R);
std::array<sf::RectangleShape, 2> bats = {
sf::RectangleShape{sf::Vector2f(BAT_W, BAT_H)},
sf::RectangleShape{sf::Vector2f(BAT_W, BAT_H)}
};
std::array<sf::Shape*, 3> shapes = { &bats[0], &bats[1], &ball };
drawinfo() {
for(auto* shape : shapes) {
shape->setFillColor(sf::Color::Red);
}
}
};
// check if ball hits a bat
bool bat_collide(const gamestate& state, uint8_t b) {
const uint8_t& bx = state.ball[0], by = state.ball[1];
const uint8_t& height = state.bats[b];
const uint8_t wbound = (100 * b) + (b ? -3 : 3);
const uint8_t hbound = height + 25;
return ((by >= height) && (by <= hbound)) && (b ? (bx > wbound) : (bx < wbound));
}
// game rules/physics
void update_game(gamestate& state) {
// bat check
for(uint8_t i = 0; i < 2; i++) {
if(bat_collide(state, i))
state.dir[0] *= -1;
}
// screen check
for(uint8_t i = 0; i < 2; i++) {
// change direction
if(state.ball[i] == 0 || state.ball[i] == 100) {
state.dir[i] *= -1;
// score check
if(!i) {
state.ball[i] ? state.scores[0]++ : state.scores[1]++;
state.ball[0] = state.ball[1] = 50;
std::cout << (uint16_t)state.scores[0] << ' ' << (uint16_t)state.scores[1] << '\n';
}
}
// update position
state.ball[i] += state.dir[i];
}
}
// update shapes on screen
void update_display(const gamestate& state, drawinfo& info) {
info.bats[0].setPosition(0, (HEIGHT * (state.bats[0]/100.0f)));
info.bats[1].setPosition(WIDTH - BAT_W, (HEIGHT * (state.bats[1]/100.0f)));
info.ball.setPosition((WIDTH - BALL_R) * (state.ball[0]/100.0f), (HEIGHT - BALL_R) * (state.ball[1]/100.0f));
}
// draw game
void draw(sf::RenderWindow& win, drawinfo& info) {
win.clear(sf::Color::Black);
for(auto* shape : info.shapes) {
win.draw(*shape);
}
win.display();
}
// fake source of gamestates
gamestate recv_state() {
static gamestate g {
{75, 75}, {0, 0}, {50, 50}, {1, 1},
win_state::None
};
update_game(g);
return g;
}
| true |
185da8191b99639d72d961c13f38cb3d8dd18702 | C++ | prampec/IotWebConf | /src/IotWebConfTParameter.h | UTF-8 | 26,015 | 2.5625 | 3 | [
"MIT"
] | permissive | /**
* IotWebConfTParameter.h -- IotWebConf is an ESP8266/ESP32
* non blocking WiFi/AP web configuration library for Arduino.
* https://github.com/prampec/IotWebConf
*
* Copyright (C) 2021 Balazs Kelemen <prampec+arduino@gmail.com>
* rovo89
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#ifndef IotWebConfTParameter_h
#define IotWebConfTParameter_h
// TODO: This file is a mess. Help wanted to organize thing!
#include <IotWebConfParameter.h>
#include <Arduino.h>
#include <IPAddress.h>
#include <errno.h>
// At least in PlatformIO, strtoimax/strtoumax are defined, but not implemented.
#if 1
#define strtoimax strtoll
#define strtoumax strtoull
#endif
namespace iotwebconf
{
/**
* This class is to hide web related properties from the
* data manipulation.
*/
class ConfigItemBridge : public ConfigItem
{
public:
virtual void update(WebRequestWrapper* webRequestWrapper) override
{
if (webRequestWrapper->hasArg(this->getId()))
{
String newValue = webRequestWrapper->arg(this->getId());
this->update(newValue);
}
}
void debugTo(Stream* out) override
{
out->print("'");
out->print(this->getId());
out->print("' with value: '");
out->print(this->toString());
out->println("'");
}
protected:
ConfigItemBridge(const char* id) : ConfigItem(id) { }
virtual int getInputLength() { return 0; };
virtual bool update(String newValue, bool validateOnly = false) = 0;
virtual String toString() = 0;
};
///////////////////////////////////////////////////////////////////////////
/**
* DataType is the data related part of the parameter.
* It does not care about web and visualization, but takes care of the
* data validation and storing.
*/
template <typename ValueType, typename _DefaultValueType = ValueType>
class DataType : virtual public ConfigItemBridge
{
public:
using DefaultValueType = _DefaultValueType;
DataType(const char* id, DefaultValueType defaultValue) :
ConfigItemBridge(id),
_defaultValue(defaultValue)
{
}
/**
* value() can be used to get the value, but it can also
* be used set it like this: p.value() = newValue
*/
ValueType& value() { return this->_value; }
ValueType& operator*() { return this->_value; }
protected:
int getStorageSize() override
{
return sizeof(ValueType);
}
virtual bool update(String newValue, bool validateOnly = false) = 0;
bool validate(String newValue) { return update(newValue, true); }
virtual String toString() override { return String(this->_value); }
ValueType _value;
const DefaultValueType _defaultValue;
};
///////////////////////////////////////////////////////////////////////////
class StringDataType : public DataType<String>
{
public:
using DataType<String>::DataType;
protected:
virtual bool update(String newValue, bool validateOnly) override {
if (!validateOnly)
{
this->_value = newValue;
}
return true;
}
virtual String toString() override { return this->_value; }
};
///////////////////////////////////////////////////////////////////////////
template <size_t len>
class CharArrayDataType : public DataType<char[len], const char*>
{
public:
using DataType<char[len], const char*>::DataType;
CharArrayDataType(const char* id, const char* defaultValue) :
ConfigItemBridge::ConfigItemBridge(id),
DataType<char[len], const char*>::DataType(id, defaultValue) { };
virtual void applyDefaultValue() override
{
strncpy(this->_value, this->_defaultValue, len);
}
protected:
virtual bool update(String newValue, bool validateOnly) override
{
if (newValue.length() + 1 > len)
{
return false;
}
if (!validateOnly)
{
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
Serial.print(this->getId());
Serial.print(": ");
Serial.println(newValue);
#endif
strncpy(this->_value, newValue.c_str(), len);
}
return true;
}
void storeValue(std::function<void(
SerializationData* serializationData)> doStore) override
{
SerializationData serializationData;
serializationData.length = len;
serializationData.data = (byte*)this->_value;
doStore(&serializationData);
}
void loadValue(std::function<void(
SerializationData* serializationData)> doLoad) override
{
SerializationData serializationData;
serializationData.length = len;
serializationData.data = (byte*)this->_value;
doLoad(&serializationData);
}
virtual int getInputLength() override { return len; };
};
///////////////////////////////////////////////////////////////////////////
/**
* All non-complex types should be inherited from this base class.
*/
template <typename ValueType>
class PrimitiveDataType : public DataType<ValueType>
{
public:
using DataType<ValueType>::DataType;
PrimitiveDataType(const char* id, ValueType defaultValue) :
ConfigItemBridge::ConfigItemBridge(id),
DataType<ValueType>::DataType(id, defaultValue) { };
void setMax(ValueType val) { this->_max = val; this->_maxDefined = true; }
void setMin(ValueType val) { this->_min = val; this->_minDefined = true; }
virtual void applyDefaultValue() override
{
this->_value = this->_defaultValue;
}
protected:
virtual bool update(String newValue, bool validateOnly) override
{
errno = 0;
ValueType val = fromString(newValue);
if ((errno == ERANGE)
|| (this->_minDefined && (val < this->_min))
|| (this->_maxDefined && (val > this->_max)))
{
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
Serial.print(this->getId());
Serial.print(" value not accepted: ");
Serial.println(val);
#endif
return false;
}
if (!validateOnly)
{
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
Serial.print(this->getId());
Serial.print(": ");
Serial.println((ValueType)val);
#endif
this->_value = (ValueType) val;
}
return true;
}
void storeValue(std::function<void(
SerializationData* serializationData)> doStore) override
{
SerializationData serializationData;
serializationData.length = this->getStorageSize();
serializationData.data =
reinterpret_cast<byte*>(&this->_value);
doStore(&serializationData);
}
void loadValue(std::function<void(
SerializationData* serializationData)> doLoad) override
{
byte buf[this->getStorageSize()];
SerializationData serializationData;
serializationData.length = this->getStorageSize();
serializationData.data = buf;
doLoad(&serializationData);
ValueType* valuePointer = reinterpret_cast<ValueType*>(buf);
this->_value = *valuePointer;
}
virtual ValueType fromString(String stringValue) = 0;
ValueType getMax() { return this->_max; }
ValueType getMin() { return this->_min; }
ValueType isMaxDefined() { return this->_maxDefined; }
ValueType isMinDefined() { return this->_minDefined; }
private:
ValueType _min;
ValueType _max;
bool _minDefined = false;
bool _maxDefined = false;
};
///////////////////////////////////////////////////////////////////////////
template <typename ValueType, int base = 10>
class SignedIntDataType : public PrimitiveDataType<ValueType>
{
public:
SignedIntDataType(const char* id, ValueType defaultValue) :
ConfigItemBridge::ConfigItemBridge(id),
PrimitiveDataType<ValueType>::PrimitiveDataType(id, defaultValue) { };
protected:
virtual ValueType fromString(String stringValue)
{
return (ValueType)strtoimax(stringValue.c_str(), nullptr, base);
}
};
template <typename ValueType, int base = 10>
class UnsignedIntDataType : public PrimitiveDataType<ValueType>
{
public:
UnsignedIntDataType(const char* id, ValueType defaultValue) :
ConfigItemBridge::ConfigItemBridge(id),
PrimitiveDataType<ValueType>::PrimitiveDataType(id, defaultValue) { };
protected:
virtual ValueType fromString(String stringValue)
{
return (ValueType)strtoumax(stringValue.c_str(), nullptr, base);
}
};
class BoolDataType : public PrimitiveDataType<bool>
{
public:
BoolDataType(const char* id, bool defaultValue) :
ConfigItemBridge::ConfigItemBridge(id),
PrimitiveDataType<bool>::PrimitiveDataType(id, defaultValue) { };
protected:
virtual bool fromString(String stringValue)
{
return stringValue.c_str()[0] == 1;
}
};
class FloatDataType : public PrimitiveDataType<float>
{
public:
FloatDataType(const char* id, float defaultValue) :
ConfigItemBridge::ConfigItemBridge(id),
PrimitiveDataType<float>::PrimitiveDataType(id, defaultValue) { };
protected:
virtual float fromString(String stringValue)
{
return atof(stringValue.c_str());
}
};
class DoubleDataType : public PrimitiveDataType<double>
{
public:
DoubleDataType(const char* id, double defaultValue) :
ConfigItemBridge::ConfigItemBridge(id),
PrimitiveDataType<double>::PrimitiveDataType(id, defaultValue) { };
protected:
virtual double fromString(String stringValue)
{
return strtod(stringValue.c_str(), nullptr);
}
};
/////////////////////////////////////////////////////////////////////////
class IpDataType : public DataType<IPAddress>
{
using DataType<IPAddress>::DataType;
protected:
virtual bool update(String newValue, bool validateOnly) override
{
if (validateOnly)
{
IPAddress ip;
return ip.fromString(newValue);
}
else
{
return this->_value.fromString(newValue);
}
}
virtual String toString() override { return this->_value.toString(); }
};
///////////////////////////////////////////////////////////////////////////
/**
* Input parameter is the part of the parameter that is responsible
* for the appearance of the parameter in HTML.
*/
class InputParameter : virtual public ConfigItemBridge
{
public:
InputParameter(const char* id, const char* label) :
ConfigItemBridge::ConfigItemBridge(id),
label(label) { }
virtual void renderHtml(
bool dataArrived, WebRequestWrapper* webRequestWrapper) override
{
String content = this->renderHtml(
dataArrived,
webRequestWrapper->hasArg(this->getId()),
webRequestWrapper->arg(this->getId()));
webRequestWrapper->sendContent(content);
}
const char* label;
/**
* This variable is meant to store a value that is displayed in an empty
* (not filled) field.
*/
const char* placeholder = nullptr;
virtual void setPlaceholder(const char* placeholder) { this->placeholder = placeholder; }
/**
* Usually this variable is used when rendering the form input field
* so one can customize the rendered outcome of this particular item.
*/
const char* customHtml = nullptr;
/**
* Used when rendering the input field. Is is overridden by different
* implementations.
*/
virtual String getCustomHtml()
{
return String(customHtml == nullptr ? "" : customHtml);
}
const char* errorMessage = nullptr;
protected:
void clearErrorMessage() override
{
this->errorMessage = nullptr;
}
virtual String renderHtml(
bool dataArrived, bool hasValueFromPost, String valueFromPost)
{
String pitem = String(this->getHtmlTemplate());
pitem.replace("{b}", this->label);
pitem.replace("{t}", this->getInputType());
pitem.replace("{i}", this->getId());
pitem.replace(
"{p}", this->placeholder == nullptr ? "" : this->placeholder);
int length = this->getInputLength();
if (length > 0)
{
char parLength[11];
snprintf(parLength, 11, "%d", length - 1); // To allow "\0" at the end of the string.
String maxLength = String("maxlength=") + parLength;
pitem.replace("{l}", maxLength);
}
else
{
pitem.replace("{l}", "");
}
if (hasValueFromPost)
{
// -- Value from previous submit
pitem.replace("{v}", valueFromPost);
}
else
{
// -- Value from config
pitem.replace("{v}", this->toString());
}
pitem.replace("{c}", this->getCustomHtml());
pitem.replace(
"{s}",
this->errorMessage == nullptr ? "" : "de"); // Div style class.
pitem.replace(
"{e}",
this->errorMessage == nullptr ? "" : this->errorMessage);
return pitem;
}
/**
* One can override this method in case a specific HTML template is required
* for a parameter.
*/
virtual String getHtmlTemplate() { return FPSTR(IOTWEBCONF_HTML_FORM_PARAM); };
virtual const char* getInputType() = 0;
};
template <size_t len>
class TextTParameter : public CharArrayDataType<len>, public InputParameter
{
public:
using CharArrayDataType<len>::CharArrayDataType;
TextTParameter(const char* id, const char* label, const char* defaultValue) :
ConfigItemBridge(id),
CharArrayDataType<len>::CharArrayDataType(id, defaultValue),
InputParameter::InputParameter(id, label) { }
protected:
virtual const char* getInputType() override { return "text"; }
};
class CheckboxTParameter : public BoolDataType, public InputParameter
{
public:
CheckboxTParameter(const char* id, const char* label, const bool defaultValue) :
ConfigItemBridge(id),
BoolDataType::BoolDataType(id, defaultValue),
InputParameter::InputParameter(id, label) { }
bool isChecked() { return this->value(); }
protected:
virtual const char* getInputType() override { return "checkbox"; }
virtual void update(WebRequestWrapper* webRequestWrapper) override
{
bool selected = false;
if (webRequestWrapper->hasArg(this->getId()))
{
String valueFromPost = webRequestWrapper->arg(this->getId());
selected = valueFromPost.equals("selected");
}
// this->update(String(selected ? "1" : "0"));
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
Serial.print(this->getId());
Serial.print(": ");
Serial.println(selected ? "selected" : "not selected");
#endif
this->_value = selected;
}
virtual String renderHtml(
bool dataArrived, bool hasValueFromPost, String valueFromPost) override
{
bool checkSelected = false;
if (dataArrived)
{
if (hasValueFromPost && valueFromPost.equals("selected"))
{
checkSelected = true;
}
}
else
{
if (this->isChecked())
{
checkSelected = true;
}
}
if (checkSelected)
{
this->customHtml = CheckboxTParameter::_checkedStr;
}
else
{
this->customHtml = nullptr;
}
return InputParameter::renderHtml(dataArrived, true, String("selected"));
}
private:
const char* _checkedStr = "checked='checked'";
};
template <size_t len>
class PasswordTParameter : public CharArrayDataType<len>, public InputParameter
{
public:
using CharArrayDataType<len>::CharArrayDataType;
PasswordTParameter(const char* id, const char* label, const char* defaultValue) :
ConfigItemBridge(id),
CharArrayDataType<len>::CharArrayDataType(id, defaultValue),
InputParameter::InputParameter(id, label)
{
this->customHtml = _customHtmlPwd;
}
void debugTo(Stream* out)
{
out->print("'");
out->print(this->getId());
out->print("' with value: ");
#ifdef IOTWEBCONF_DEBUG_PWD_TO_SERIAL
out->print("'");
out->print(this->_value);
out->println("'");
#else
out->println(F("<hidden>"));
#endif
}
virtual bool update(String newValue, bool validateOnly) override
{
if (newValue.length() + 1 > len)
{
return false;
}
if (validateOnly)
{
return true;
}
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
Serial.print(this->getId());
Serial.print(": ");
#endif
if (newValue.length() > 0)
{
// -- Value was set.
strncpy(this->_value, newValue.c_str(), len);
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
# ifdef IOTWEBCONF_DEBUG_PWD_TO_SERIAL
Serial.println(this->_value);
# else
Serial.println("<updated>");
# endif
#endif
}
else
{
#ifdef IOTWEBCONF_DEBUG_TO_SERIAL
Serial.println("<was not changed>");
#endif
}
return true;
}
protected:
virtual const char* getInputType() override { return "password"; }
virtual String renderHtml(
bool dataArrived, bool hasValueFromPost, String valueFromPost) override
{
return InputParameter::renderHtml(dataArrived, true, String(""));
}
private:
const char* _customHtmlPwd = "ondblclick=\"pw(this.id)\"";
};
/**
* All non-complex type input parameters should be inherited from this
* base class.
*/
template <typename ValueType>
class PrimitiveInputParameter :
public InputParameter
{
public:
PrimitiveInputParameter(const char* id, const char* label) :
ConfigItemBridge::ConfigItemBridge(id),
InputParameter::InputParameter(id, label) { }
virtual String getCustomHtml() override
{
String modifiers = String(this->customHtml);
if (this->isMinDefined())
{
modifiers += " min='" ;
modifiers += this->getMin();
modifiers += "'";
}
if (this->isMaxDefined())
{
modifiers += " max='";
modifiers += this->getMax();
modifiers += "'";
}
if (this->step != 0)
{
modifiers += " step='";
modifiers += this->step;
modifiers += "'";
}
return modifiers;
}
ValueType step = 0;
void setStep(ValueType step) { this->step = step; }
virtual ValueType getMin() = 0;
virtual ValueType getMax() = 0;
virtual bool isMinDefined() = 0;
virtual bool isMaxDefined() = 0;
};
template <typename ValueType, int base = 10>
class IntTParameter :
public virtual SignedIntDataType<ValueType, base>,
public PrimitiveInputParameter<ValueType>
{
public:
IntTParameter(const char* id, const char* label, ValueType defaultValue) :
ConfigItemBridge(id),
SignedIntDataType<ValueType, base>::SignedIntDataType(id, defaultValue),
PrimitiveInputParameter<ValueType>::PrimitiveInputParameter(id, label) { }
// TODO: somehow organize these methods into common parent.
virtual ValueType getMin() override
{
return PrimitiveDataType<ValueType>::getMin();
}
virtual ValueType getMax() override
{
return PrimitiveDataType<ValueType>::getMax();
}
virtual bool isMinDefined() override
{
return PrimitiveDataType<ValueType>::isMinDefined();
}
virtual bool isMaxDefined() override
{
return PrimitiveDataType<ValueType>::isMaxDefined();
}
protected:
virtual const char* getInputType() override { return "number"; }
};
template <typename ValueType, int base = 10>
class UIntTParameter :
public virtual UnsignedIntDataType<ValueType, base>,
public PrimitiveInputParameter<ValueType>
{
public:
UIntTParameter(const char* id, const char* label, ValueType defaultValue) :
ConfigItemBridge(id),
UnsignedIntDataType<ValueType, base>::UnsignedIntDataType(id, defaultValue),
PrimitiveInputParameter<ValueType>::PrimitiveInputParameter(id, label) { }
// TODO: somehow organize these methods into common parent.
virtual ValueType getMin() override
{
return PrimitiveDataType<ValueType>::getMin();
}
virtual ValueType getMax() override
{
return PrimitiveDataType<ValueType>::getMax();
}
virtual bool isMinDefined() override
{
return PrimitiveDataType<ValueType>::isMinDefined();
}
virtual bool isMaxDefined() override
{
return PrimitiveDataType<ValueType>::isMaxDefined();
}
protected:
virtual const char* getInputType() override { return "number"; }
};
class FloatTParameter :
public FloatDataType,
public PrimitiveInputParameter<float>
{
public:
FloatTParameter(const char* id, const char* label, float defaultValue) :
ConfigItemBridge(id),
FloatDataType::FloatDataType(id, defaultValue),
PrimitiveInputParameter<float>::PrimitiveInputParameter(id, label) { }
virtual float getMin() override
{
return PrimitiveDataType<float>::getMin();
}
virtual float getMax() override
{
return PrimitiveDataType<float>::getMax();
}
virtual bool isMinDefined() override
{
return PrimitiveDataType<float>::isMinDefined();
}
virtual bool isMaxDefined() override
{
return PrimitiveDataType<float>::isMaxDefined();
}
protected:
virtual const char* getInputType() override { return "number"; }
};
/**
* Options parameter is a structure, that handles multiple values when redering
* the HTML representation.
*/
template <size_t len>
class OptionsTParameter : public TextTParameter<len>
{
public:
/**
* @optionValues - List of values to choose from with, where each value
* can have a maximal size of 'length'. Contains 'optionCount' items.
* @optionNames - List of names to render for the values, where each
* name can have a maximal size of 'nameLength'. Contains 'optionCount'
* items.
* @optionCount - Size of both 'optionValues' and 'optionNames' lists.
* @nameLength - Size of any item in optionNames list.
* (See TextParameter for arguments!)
*/
OptionsTParameter(
const char* id, const char* label, const char* defaultValue,
const char* optionValues, const char* optionNames,
size_t optionCount, size_t nameLength) :
ConfigItemBridge(id),
TextTParameter<len>(id, label, defaultValue)
{
this->_optionValues = optionValues;
this->_optionNames = optionNames;
this->_optionCount = optionCount;
this->_nameLength = nameLength;
}
// TODO: make these protected
void setOptionValues(const char* optionValues) { this->_optionValues = optionValues; }
void setOptionNames(const char* optionNames) { this->_optionNames = optionNames; }
void setOptionCount(size_t optionCount) { this->_optionCount = optionCount; }
void setNameLength(size_t nameLength) { this->_nameLength = nameLength; }
protected:
OptionsTParameter(
const char* id, const char* label, const char* defaultValue) :
ConfigItemBridge(id),
TextTParameter<len>(id, label, defaultValue)
{
}
const char* _optionValues;
const char* _optionNames;
size_t _optionCount;
size_t _nameLength;
};
///////////////////////////////////////////////////////////////////////////////
/**
* Select parameter is an option parameter, that rendered as HTML SELECT.
* Basically it is a dropdown combobox.
*/
template <size_t len>
class SelectTParameter : public OptionsTParameter<len>
{
public:
/**
* Create a select parameter for the config portal.
*
* (See OptionsParameter for arguments!)
*/
SelectTParameter(
const char* id, const char* label, const char* defaultValue,
const char* optionValues, const char* optionNames,
size_t optionCount, size_t nameLength) :
ConfigItemBridge(id),
OptionsTParameter<len>(
id, label, defaultValue, optionValues, optionNames, optionCount, nameLength)
{ }
// TODO: make this protected
SelectTParameter(
const char* id, const char* label, const char* defaultValue) :
ConfigItemBridge(id),
OptionsTParameter<len>(id, label, defaultValue) { }
protected:
// Overrides
virtual String renderHtml(
bool dataArrived, bool hasValueFromPost, String valueFromPost) override
{
String options = "";
for (size_t i=0; i<this->_optionCount; i++)
{
const char *optionValue = (this->_optionValues + (i*len) );
const char *optionName = (this->_optionNames + (i*this->_nameLength) );
String oitem = FPSTR(IOTWEBCONF_HTML_FORM_OPTION);
oitem.replace("{v}", optionValue);
// if (sizeof(this->_optionNames) > i)
{
oitem.replace("{n}", optionName);
}
// else
// {
// oitem.replace("{n}", "?");
// }
if ((hasValueFromPost && (valueFromPost == optionValue)) ||
(strncmp(this->value(), optionValue, len) == 0))
{
// -- Value from previous submit
oitem.replace("{s}", " selected");
}
else
{
// -- Value from config
oitem.replace("{s}", "");
}
options += oitem;
}
String pitem = FPSTR(IOTWEBCONF_HTML_FORM_SELECT_PARAM);
pitem.replace("{b}", this->label);
pitem.replace("{i}", this->getId());
pitem.replace(
"{c}", this->customHtml == nullptr ? "" : this->customHtml);
pitem.replace(
"{s}",
this->errorMessage == nullptr ? "" : "de"); // Div style class.
pitem.replace(
"{e}",
this->errorMessage == nullptr ? "" : this->errorMessage);
pitem.replace("{o}", options);
return pitem;
}
private:
};
///////////////////////////////////////////////////////////////////////////////
/**
* Color chooser.
*/
class ColorTParameter : public CharArrayDataType<8>, public InputParameter
{
public:
using CharArrayDataType<8>::CharArrayDataType;
ColorTParameter(const char* id, const char* label, const char* defaultValue) :
ConfigItemBridge(id),
CharArrayDataType<8>::CharArrayDataType(id, defaultValue),
InputParameter::InputParameter(id, label) { }
protected:
virtual const char* getInputType() override { return "color"; }
};
///////////////////////////////////////////////////////////////////////////////
/**
* Date chooser.
*/
class DateTParameter : public CharArrayDataType<11>, public InputParameter
{
public:
using CharArrayDataType<11>::CharArrayDataType;
DateTParameter(const char* id, const char* label, const char* defaultValue) :
ConfigItemBridge(id),
CharArrayDataType<11>::CharArrayDataType(id, defaultValue),
InputParameter::InputParameter(id, label) { }
protected:
virtual const char* getInputType() override { return "date"; }
};
///////////////////////////////////////////////////////////////////////////////
/**
* Time chooser.
*/
class TimeTParameter : public CharArrayDataType<6>, public InputParameter
{
public:
using CharArrayDataType<6>::CharArrayDataType;
TimeTParameter(const char* id, const char* label, const char* defaultValue) :
ConfigItemBridge(id),
CharArrayDataType<6>::CharArrayDataType(id, defaultValue),
InputParameter::InputParameter(id, label) { }
protected:
virtual const char* getInputType() override { return "time"; }
};
} // end namespace
#include <IotWebConfTParameterBuilder.h>
#endif
| true |
2e2006c5fb911d33f71d4216692d6aefc57cff37 | C++ | Osch-1/oop | /FindMaxEx/FindMaxEx/FindMaxEx.h | UTF-8 | 448 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
template <typename T, typename Less>
inline bool FindMax(vector<T> const& arr, T& maxValue, Less const& less)
{
if (arr.empty())
{
return false;
}
int maxElementIndex = 0;
for (int i = 1; i < arr.size(); ++i)
{
if (less(arr[maxElementIndex], arr[i]))
maxElementIndex = i;
}
maxValue = arr[maxElementIndex];
return true;
} | true |
a06c29e73a55939141a0fd232592bdd7b656561d | C++ | alexandraback/datacollection | /solutions_5744014401732608_1/C++/VsonicV/main.cpp | UTF-8 | 1,344 | 2.84375 | 3 | [] | no_license | //
// main.cpp
// Slides
//
// Created by Qiu Xin on 8/5/16.
// Copyright © 2016 Qiu Xin. All rights reserved.
//
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main(int argc, const char * argv[]) {
int runNum, B, M;
cin >> runNum;
for (int i=1;i<=runNum;i++)
{
cout<<"Case #"<<i<<":";
cin>>B;
cin>>M;
vector<vector<int>> store(B,vector<int>(B,0));
for (int j=0;j<B;j++)
{
for (int k=j+1;k<B;k++)
store[j][k]=1;
}
double num=pow(2,B-2);
if (M>num)
{
cout<<' '<<"IMPOSSIBLE"<<endl;
continue;
}
cout<<' '<<"POSSIBLE"<<endl;
if (M==num)
{
for (int j=0;j<B;j++)
{
for (int k=0;k<B;k++)
cout<<store[j][k];
cout<<endl;
}
continue;
}
num/=2;
int del=B-2;
while(M)
{
if (M>=num)
{
M-=num;
store[del][B-1]=0;
}
del--;
num/=2;
}
for (int j=0;j<B;j++)
{
for (int k=0;k<B;k++)
cout<<store[j][k];
cout<<endl;
}
}
return 0;
}
| true |
fe2126828b312207a6c6dd611a297d9bc5ffe18c | C++ | compscisi/Programming-Fundamentals-1-SI | /Activities/Session 09 - 5 Feb/staticcastSOLUTION.cpp | UTF-8 | 864 | 3.84375 | 4 | [] | no_license | /*******************************************************************************]
This is the solution to the problem presented in staticcast.cpp
This program should be able to tell you the ASCII value of any character you
enter into the program.
********************************************************************************/
#include <iostream>
using namespace std;
int main()
{
char letter;
//prompt user to enter a character
cout << "Please enter a charact: ";
cin >> letter;
//display the letter that the user entered as an ASCII value
cout << "The ASCII value for " << letter << " is " << static_cast<int>(letter);
//EXPLANATION: remember that an ASCII value is the integer value of a symbol or character!
//So, we used static cast to turn a char into an integer. This is the ASCII value.
system("PAUSE");
return 0;
}
| true |
6e970482429f4b6b1df8ceb0521a73fd13254ea4 | C++ | PPL-IIITA/ppl-assignment-faheemzunjani | /Q4/library/utility.cpp | UTF-8 | 5,770 | 3.109375 | 3 | [] | no_license | #include <cstdio>
#include <string>
#include "utility.hpp"
using namespace data;
using namespace std;
void utility::read_boys_data(vector <geek_boy> &geek_boys, vector <generous_boy> &generous_boys,
vector <miser_boy> &miser_boys)
{
FILE * fptr;
std::string name, type;
char name_in[100], type_in[100], flush_char;
int attract, min_attract_req, intel;
double budg;
fptr = fopen("./data/boys.dat", "r");
while (!feof(fptr)) {
fscanf(fptr, "%s %d %d %lf %d %s", name_in, &attract, &min_attract_req, &budg,
&intel, type_in);
name = name_in;
type = type_in;
if (type == "geek") {
geek_boy temp_geek(name, attract, min_attract_req, budg, intel);
geek_boys.push_back (temp_geek);
} else if (type == "generous") {
generous_boy temp_generous(name, attract, min_attract_req, budg, intel);
generous_boys.push_back (temp_generous);
} else if (type == "miser") {
miser_boy temp_miser(name, attract, min_attract_req, budg, intel);
miser_boys.push_back (temp_miser);
}
}
fclose(fptr);
}
void utility::read_girls_data(vector <normal_girl> &normal_girls, vector <choosy_girl> &choosy_girls,
vector <desperate_girl> &desperate_girls)
{
FILE * fptr;
char name_in[100], type_in[100];
std::string name, type;
int attract, intel;
double maint_cost;
char crit;
fptr = fopen("./data/girls.dat", "r");
while (!feof(fptr)) {
fscanf(fptr, "%s %d %lf %d %c %s", name_in, &attract, &maint_cost,
&intel, &crit, type_in);
name = name_in;
type = type_in;
if (type == "normal") {
normal_girl temp_normie(name, attract, maint_cost, intel, crit);
normal_girls.push_back (temp_normie);
} else if (type == "choosy") {
choosy_girl temp_choosy(name, attract, maint_cost, intel, crit);
choosy_girls.push_back (temp_choosy);
} else if (type == "desperate") {
desperate_girl temp_despo(name, attract, maint_cost, intel, crit);
desperate_girls.push_back (temp_despo);
}
}
fclose(fptr);
}
void utility::read_couples_data(vector <couple> &couples)
{
FILE * couple_file;
char name_in[100], type_in[100];
std::string name, type;
int attract, intel, min_attract_req;
double maint_cost, budg;
char crit;
couple_file = fopen("./data/couples.dat", "r");
while(!feof(couple_file)) {
fscanf(couple_file, "%s %d %lf %d %c %s", name_in, &attract, &maint_cost,
&intel, &crit, type_in);
name = name_in;
type = type_in;
normal_girl temp_girl(name, attract, maint_cost, intel, crit);
temp_girl.change_commit_type(type);
fscanf(couple_file, "%s %d %d %lf %d %s", name_in, &attract, &min_attract_req,
&budg, &intel, type_in);
name = name_in;
type = type_in;
geek_boy temp_boy(name, attract, min_attract_req, budg, intel);
temp_boy.change_commit_type(type);
couple temp_couple(temp_boy, temp_girl);
couples.push_back (temp_couple);
}
couples.pop_back();
fclose(couple_file);
}
void utility::read_gifts_data(vector <essential_gift> &essential_gifts,
vector <luxury_gift> &luxury_gifts, vector <utility_gift> &utility_gifts)
{
FILE * fptr;
char t_name[5], utility_class[20];
std::string name, util_class;
int price, value, utility_value, rating, difficulty;
fptr = fopen("./data/essential_gifts.dat", "r");
while (!feof(fptr)) {
fscanf(fptr, "%s %d %d\n", t_name, &price, &value);
name = t_name;
essential_gift temp_gift(name, price, value);
essential_gifts.push_back (temp_gift);
}
fclose(fptr);
fptr = fopen("./data/luxury_gifts.dat", "r");
while (!feof(fptr)) {
fscanf(fptr, "%s %d %d %d %d\n", t_name, &price, &value, &rating, &difficulty);
name = t_name;
luxury_gift temp_gift(name, price, value, rating, difficulty);
luxury_gifts.push_back (temp_gift);
}
fclose(fptr);
fptr = fopen("./data/utility_gifts.dat", "r");
while (!feof(fptr)) {
fscanf(fptr, "%s %d %d %d %s\n", t_name, &price, &value, &utility_value, utility_class);
name = t_name;
util_class = utility_class;
utility_gift temp_gift(name, price, value, utility_value, util_class);
utility_gifts.push_back (temp_gift);
}
fclose(fptr);
}
void utility::print_k_happiest_couples(vector <couple> &couples)
{
vector <couple> temp_couple = couples;
int max_happ;
int max_j;
int j;
int k;
printf("\n\nEnter k for happiest couples: ");
scanf("%d", &k);
printf("\n%d happiest couples:\n\n", k);
printf("Boy <-> Girl\n\n");
for (int i = 0; i < k; i++) {
max_happ = 0;
max_j = 0;
for (j = 0; j < temp_couple.size(); j++) {
if (temp_couple[j].get_happiness() > max_happ) {
max_happ = temp_couple[j].get_happiness();
max_j = j;
}
}
if (temp_couple.size() != 0) {
printf("%s <-> %s\n", temp_couple[max_j].cboy.get_name().c_str(),
temp_couple[max_j].cgirl.get_name().c_str());
temp_couple.erase (temp_couple.begin() + max_j);
} else {
printf("\nOnly %lu couples present.\n", couples.size());
break;
}
}
}
void utility::print_k_compatibile_couples(vector <couple> &couples)
{
vector <couple> temp_couple = couples;
int max_comp;
int max_j;
int j;
int k;
printf("\n\nEnter k for most compatible couples: ");
scanf("%d", &k);
printf("\n%d most compatible couples:\n\n", k);
printf("Boy <-> Girl\n\n");
for (int i = 0; i < k; i++) {
max_comp = 0;
max_j = 0;
for (j = 0; j < temp_couple.size(); j++) {
if (temp_couple[j].get_compatibility() > max_comp) {
max_comp = temp_couple[j].get_compatibility();
max_j = j;
}
}
if (temp_couple.size() != 0) {
printf("%s <-> %s\n", temp_couple[max_j].cboy.get_name().c_str(),
temp_couple[max_j].cgirl.get_name().c_str());
temp_couple.erase (temp_couple.begin() + max_j);
} else {
printf("\nOnly %lu couples present.\n", couples.size());
break;
}
}
} | true |
01b5a58f320a78ab69665bff885674f994627edf | C++ | musicalentropy/Font-Rendering | /Source/CustomLookAndFeel.cpp | UTF-8 | 4,134 | 2.6875 | 3 | [
"MIT"
] | permissive | /*
==============================================================================
==============================================================================
*/
#include "CustomLookAndFeel.h"
CustomLookAndFeel::CustomLookAndFeel()
{ setDefaultLookAndFeelBaseColours();
}
CustomLookAndFeel::~CustomLookAndFeel()
{
}
void CustomLookAndFeel::setDefaultLookAndFeelBaseColours()
{
setLookAndFeelBaseColours(Colour(0xff001F36), Colours::white);
}
void CustomLookAndFeel::setLookAndFeelBaseColours(Colour backgroundColour, Colour textColour)
{
setColour(ComboBox::backgroundColourId, backgroundColour);
setColour(ComboBox::textColourId, textColour);
setColour(ComboBox::arrowColourId, textColour);
setColour(ComboBox::buttonColourId, textColour);
setColour(ComboBox::outlineColourId, textColour);
setColour(PopupMenu::textColourId, textColour);
setColour(PopupMenu::backgroundColourId, backgroundColour);
setColour(PopupMenu::headerTextColourId, textColour);
setColour(PopupMenu::highlightedBackgroundColourId, textColour.withAlpha(0.5f));
setColour(PopupMenu::highlightedTextColourId, textColour);
setColour(Label::backgroundColourId, backgroundColour);
setColour(Label::textColourId, textColour);
setColour(TextButton::buttonColourId, backgroundColour);
setColour(ToggleButton::textColourId, textColour);
setColour(TextEditor::backgroundColourId, backgroundColour);
setColour(TextEditor::focusedOutlineColourId, backgroundColour);
//setColour(TextEditor::highlightColourId, backgroundColour);
setColour(TextEditor::highlightedTextColourId, textColour);
setColour(TextEditor::outlineColourId, textColour);
setColour(TextEditor::shadowColourId, backgroundColour);
setColour(TextEditor::textColourId, textColour);
setColour(CaretComponent::caretColourId, textColour);
}
void CustomLookAndFeel::drawComboBox (Graphics& g, int width, int height, const bool isButtonDown,
int buttonX, int buttonY, int buttonW, int buttonH, ComboBox& box)
{
g.fillAll (box.findColour (ComboBox::backgroundColourId));
g.setColour (box.findColour (ComboBox::outlineColourId));
g.drawRect (0, 0, width, height);
const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
if (box.isEnabled())
{
const float arrowX = 0.3f;
const float arrowH = 0.2f;
Path p;
p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
g.setColour (box.findColour (ComboBox::arrowColourId));
g.fillPath (p);
}
}
void CustomLookAndFeel::drawToggleButton(Graphics &g, ToggleButton &button, bool isMouseOverButton, bool isButtonDown)
{
float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
const int tickWidth = juce::roundFloatToInt(fontSize * 1.1f);
/*drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
tickWidth, tickWidth,
button.getToggleState(),
button.isEnabled(),
isMouseOverButton,
isButtonDown);
*/
g.setColour (button.findColour (ToggleButton::textColourId));
g.drawRect(0, (button.getHeight() - tickWidth) / 2, tickWidth, tickWidth, 1);
if (button.getToggleState())
g.fillRect(4, (button.getHeight() - tickWidth) / 2 + 4, tickWidth - 8, tickWidth - 8);
g.setFont (fontSize);
if (! button.isEnabled()) g.setOpacity (0.5f);
const int textX = tickWidth + 6;
g.drawFittedText (button.getButtonText(),
textX, 0,
button.getWidth() - textX, button.getHeight(),
Justification::centredLeft, 10);
}
| true |
37f74b07304c13b491ff76d2df76f2997b799935 | C++ | gaoji1/algorithm | /test/Zero-complexity_Transposition.cpp | UTF-8 | 514 | 3 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int input[n];
for(int i=0;i<n;i++)
{
int temp;
cin>>temp;
input[i] = temp;
}
for(int i=0,j=n-1;i<=j;i++,j--)
{
int temp = input[i];
input[i] = input[j];
input[j] = temp;
}
for(int i=0;i<n-1;i++)
{
cout<<input[i]<<" ";
}
cout<<input[n-1]<<endl;
}
}
| true |
1546f298fef608897685d841b68b697194a75ebf | C++ | vladfaust/kaleidoscope | /ast/prototype.cpp | UTF-8 | 365 | 2.96875 | 3 | [] | no_license | #pragma once
#include <string>
#include <vector>
using namespace std;
namespace AST {
class Prototype {
string _name;
vector<string> _args;
public:
const string &name() const { return _name; };
vector<string> args() { return _args; };
Prototype(const string &name, vector<string> args)
: _name(name), _args(move(args)) {}
};
} // namespace AST
| true |
603f647c2810a838a0448de13659d97567f74999 | C++ | skalyanasundaram/BrainTuners | /uva/106-fermat-pythagoras.cpp | UTF-8 | 3,272 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
// #define MAX_SIZE 1000000
// #define COUNT(x) if(!flags[x]) { count--; flags[x] = 1; }
// inline int GCD(unsigned long a, unsigned long b) {
// unsigned long temp = 0;
// while(b > 0) {
// temp = b;
// b = a % b;
// a = temp;
// }
// return a;
// }
// int main() {
// unsigned long n = 0;
// int flags[MAX_SIZE] = {0};
// while(cin >> n) {
// int count = n;
// int pythogras_triple = 0;
// for(int i=1;i<=count; i++)
// flags[i] = 0;
// for(unsigned long i=1; i<=n; i++)
// for(unsigned long j=i+1; j<=n; j++)
// for(unsigned long k=j+1; k<=n; k++)
// if (pow(i, 2) + pow(j, 2) == pow(k, 2)) {
// cout << i << " " << j << " " << k << endl;
// COUNT(i);
// COUNT(j);
// COUNT(k);
// if (GCD(i, GCD(j, k)) == 1)
// pythogras_triple ++;
// }
// cout << pythogras_triple << " " << count << endl;
// }
// }
#define MAX_SIZE 1000000
#define COUNT(x) flags[x] = 1;
inline int GCD(unsigned long a, unsigned long b) {
unsigned long temp = 0;
while(b > 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
unsigned long N = 0;
int flags[MAX_SIZE+1] = {0};
while(cin >> N) {
unsigned long count = 0;
unsigned long pythogras_triple = 0;
unsigned long target = sqrt(N);
for(unsigned long n=1; n<=target; n++)
for(unsigned long m=n+1; m<=target; m++) {
unsigned long x = m*m - n*n;
unsigned long y = 2 * m * n;
unsigned long z = m*m + n*n;
if (z > N)
break;
// COUNT(x);
// COUNT(y);
// COUNT(z);
//x,y,z or co-primes iff m,n are co-prime and one of (m,n) should be odd and other should be even
//wiki: The triple generated by Euclid's formula is primitive if and only if m and n are coprime and m − n is odd.
if (GCD(m,n) == 1 && ((m+n) % 2) != 0)
pythogras_triple ++;
//Euclid's formula does not produce all triples. This can be remedied by inserting an additional parameter k to the formula.
//The following will generate all Pythagorean triples (although not uniquely):
for (unsigned long k=1; k<N; k++) {
unsigned long kx = k*x;
unsigned long ky = k*y;
unsigned long kz = k*z;
if (kz > N)
break;
COUNT(kx);
COUNT(ky);
COUNT(kz);
}
}
for(unsigned long i=1; i<=N; i++) {
if(!flags[i])
count++;
flags[i] = 0;
}
cout << pythogras_triple << " " << count << endl;
}
return 0;
}
// 1 2 9
// 11 14 18
// 19 21 22 23
| true |
e3e9fb5a447df190721a2bd9967d0471e441cd3f | C++ | garamizo/poker | /poker/include/poker.h | UTF-8 | 1,059 | 3.046875 | 3 | [] | no_license | #ifndef _H_POKER_
#define _H_POKER_
#include <iostream>
#include <vector>
#include <algorithm>
namespace poker {
class Card {
public:
int id;
Card(int suit, int number) : id(number + suit*13) {};
Card() {Card(0, 0);};
int Suit() const { return(id / 13); };
int Number() const { return(id % 13); };
bool operator<(Card& c2) const
{
return (Number() < c2.Number());
}
friend std::ostream& operator<<(std::ostream& os, Card& c);
};
enum Combination {HIGH, PAIR, PAIR2, TRIPLE, STR8, FLUSH, FULL, FOURS, STR8FLUSH};
const char* combination_str[] = {"high", "pair", "2 pairs", "3 of a kind", "straight",
"flush", "full-house", "4 of a kind", "straight-flush"};
class Hand {
public:
enum Combination combo;
std::vector<Card> card; // sorted
Hand(const std::vector<Card>& cards);
bool operator<(Hand & h2) const;
friend std::ostream& operator<<(std::ostream& os, Hand& h);
};
float WinChances(Hand& p, Hand& t, std::vector<Card*> card_inv);
}
#endif | true |
32028a958f143299e4827186adef0bcf9feb3e4d | C++ | bisakhmondal/InterviewPrep | /Solutions/DeepCopyLL.cpp | UTF-8 | 1,423 | 3.4375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* next;
Node* random;
Node(int data) : data(data), next(NULL), random(NULL) {}
};
Node* clone(Node* head){
if(head == NULL) return NULL;
Node* travellingPtr = head;
// Insert clone node of n-th node between original n-th node and (n + 1)-th node
while(travellingPtr){
Node* temp = travellingPtr->next;
travellingPtr->next = new Node(travellingPtr->data);
travellingPtr->next->next = temp;
travellingPtr = temp;
}
travellingPtr = head;
// Clone random pointer of clone nodes
while(travellingPtr) {
if(travellingPtr->next)
travellingPtr->next->random = travellingPtr->random? travellingPtr->random->next: travellingPtr->random;
travellingPtr = travellingPtr->next? travellingPtr->next->next: travellingPtr->next;
}
Node* originalHead = head, *cloneHead = head->next, *finalPtr = head->next;
// Split it into two list, which will produce additional copy of original List
while(originalHead && cloneHead) {
originalHead->next = (originalHead->next? originalHead->next->next : originalHead->next);
cloneHead->next = (cloneHead->next? cloneHead->next->next: cloneHead->next);
originalHead = originalHead->next;
cloneHead = cloneHead->next;
}
return finalPtr;
}
| true |
8cad9422e86ffe2190d70baf715ab7ba76b9321d | C++ | xidianlina/cppplus | /chapter_11_complex.h | UTF-8 | 586 | 3 | 3 | [] | no_license | #ifndef COMPLEX_H_
#define COMPLEX_H_
#include <iostream>
class Complex
{
private:
double real;
double imag;
public:
Complex();
Complex(double r);
Complex(double r, double i);
~Complex();
Complex operator+(const Complex &c)const;
Complex operator-(const Complex &c)const;
Complex operator*(const Complex &c)const;
Complex operator*(double n)const;
Complex operator~()const;
friend Complex operator*(double n, const Complex &c);
friend std::ostream &operator<<(std::ostream &os, const Complex &c);
friend std::istream &operator>>(std::istream &is, Complex &c);
};
#endif | true |
68e97aa426d7c148f3fc6e16548350bd7710063e | C++ | Kronecker/WissRech2 | /Task4/aufg13a.cpp | UTF-8 | 3,548 | 2.796875 | 3 | [] | no_license | //
// Created by grabiger on 08.06.2018.
//
using namespace std;
void aufg13a();
flouble* initMatrixRightHandSide(int n, flouble h );
flouble* jacobiIter(int n, flouble *f, flouble valBoundary, int* numberOfIterations, flouble h);
void aufg13a() {
// Init Chrono
std::chrono::high_resolution_clock::time_point start,finish ;
std::chrono::duration<double> elapsed;
start = std::chrono::high_resolution_clock::now();
int n=1024;
flouble h = 1./(n-1);
flouble boundaryValue=0;
flouble *fun;
flouble *result;
int doneIterations=0;
fun=initMatrixRightHandSide(n,h);
result=jacobiIter(n, fun, boundaryValue, &doneIterations,h);
cudaThreadExit();
finish = std::chrono::high_resolution_clock::now();
elapsed=std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start);
cout<< "Jacobi Iteration mit CPU: "<< elapsed.count() * 1000 << "ms"<<endl;
saveMyMatrix(result, n,n,h,0);
//cout << "Results saved to results_a.dat"<<endl;
delete(fun);
delete(result);
}
flouble* jacobiIter(int n, flouble *f, flouble valBoundary, int* numberOfIterations, flouble h) {
flouble* actualIteration=new flouble[n*n]();
flouble* lastIterSol=new flouble[n*n]();
flouble *temp;
flouble tol=0.0001;
int iteration=0;
flouble resi=tol+1;
int step=100;
flouble hsquare=h*h;
flouble valLowBlockDiag=-1/hsquare;
flouble valUpBlockDiag=-1/hsquare;
flouble valLowMinDiag=-1/hsquare;
flouble valUpDiag=-1/hsquare;
flouble valMainDiag=4/hsquare;
// boundary values init (outer)
for(int i=0;i<n;i++) {
actualIteration[i]=valBoundary;
lastIterSol[i]=valBoundary;
actualIteration[n*(n-1)+i]=valBoundary;
lastIterSol[n*(n-1)+i]=valBoundary;
}
for(int k=1;k<n-1;k++) { // iterate through blocks
actualIteration[k*n]=valBoundary;
lastIterSol[k*n]=valBoundary;
actualIteration[(k+1)*n-1]=valBoundary;
lastIterSol[(k+1)*n-1]=valBoundary;
}
int nm1=n-1;
int index;
while(iteration<MAXITERATIONS&&resi>tol) {
// consecutive blocks
for(int k=1;k<nm1;k++) { // iterate through blocks
for(int i=1;i<nm1;i++) { // iterate in block
index=k*n+i;
actualIteration[index]=1/valMainDiag*(f[index]-valLowBlockDiag*lastIterSol[index-n]-valLowMinDiag*lastIterSol[index-1]-valUpDiag*lastIterSol[index+1]-valUpBlockDiag*lastIterSol[index+n]);
}
}
if (false&&!(iteration % step)) {// War nicht gefragt, und Häufigkeit kann Geschwindigkeitsvergleich beeinflussen
resi=0;
for(int i=0;i<n*n;i++) {
resi+=fabs(actualIteration[i]- lastIterSol[i]);
}
//std::cout << iteration <<": "<< resi<< std::endl;
}
temp=lastIterSol;
lastIterSol=actualIteration;
actualIteration=temp;
iteration++;
}
//std::cout << "Calculation finished after "<<iteration<<" Iterations.(%"<<step<<")"<<std::endl;
*numberOfIterations=iteration;
delete(lastIterSol);
return actualIteration;
}
flouble* initMatrixRightHandSide(int n, flouble h ) {
flouble*matrix=new flouble[n*n];
flouble x;
flouble y;
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {
x=h*i;
y=h*j;
matrix[i*n+j]=x*(1-x)+y*(1-y);
// printf("<%f %f> %f\n",x,y,matrix[i*m+j]);
}
}
return matrix;
}
| true |
0d7052338bcd56440795586f9f37613933fde6b1 | C++ | Ashatta/study | /semester_2/hw_6/hw6_task2/settest.h | UTF-8 | 1,865 | 3.0625 | 3 | [] | no_license | #pragma once
#include <QtTest/QtTest>
#include <sstream>
#include <string>
#include "set.h"
class SetTest : public QObject
{
Q_OBJECT
private slots:
void init()
{
set = new Set<int>();
}
void cleanup()
{
delete set;
}
void testAddSet()
{
set->add(6);
set->add(8);
set->add(0);
set->add(4);
set->add(2);
Set<int> second;
second.add(5);
second.add(7);
second.add(9);
second.add(1);
second.add(3);
set->add(second);
std::stringstream out;
std::string result("0 1 2 3 4 5 6 7 8 9 \n");
set->print(out);
QCOMPARE(out.str(), result);
}
void testIntersection()
{
set->add(2);
set->add(4);
set->add(6);
Set<int> second;
second.add(6);
second.add(3);
Set<int> intersection = set->setIntersection(second);
std::stringstream out;
std::string result("6 \n");
intersection.print(out);
QCOMPARE(out.str(), result);
}
void testEmptyIntersecton()
{
set->add(2);
set->add(4);
Set<int> second;
second.add(5);
second.add(3);
Set<int> intersection = set->setIntersection(second);
std::stringstream out;
std::string result("\n");
intersection.print(out);
QCOMPARE(out.str(), result);
}
void testUnion()
{
set->add(2);
set->add(6);
set->add(5);
Set<int> second;
second.add(3);
second.add(8);
second.add(6);
Set<int> setUnion = set->setUnion(second);
std::stringstream out;
std::string result("2 3 5 6 8 \n");
setUnion.print(out);
QCOMPARE(out.str(), result);
}
private:
Set<int>* set;
};
| true |
5e6107df77a44e503fdb97b251ade9c463d65dcf | C++ | adityanjr/code-DS-ALGO | /GeeksForGeeks/Practice/VerticalSum.cpp | UTF-8 | 620 | 3.625 | 4 | [
"MIT"
] | permissive | /*Complete the function below
Node is as follows:
struct Node{
int data;
Node *left,*right;
};
*/
void make(Node* root, int width, map<int, int>& m){
if(!root){
return;
}
if(m.find(width) == m.end()){
m[width] = root->data;
}
else{
m[width] += root->data;
}
make(root->left, width-1, m);
make(root->right, width+1, m);
}
void printVertical(Node *root)
{
//add code here.
map<int, int> m;
make(root, 0, m);
map<int, int> :: iterator it = m.begin();
while(it != m.end()){
cout << it->second << " ";
it++;
}
}
| true |
48321bde01d1457394fb11563ccfdebd654e55d9 | C++ | izabera/ulam | /ompulam.cpp | UTF-8 | 941 | 3.3125 | 3 | [
"LicenseRef-scancode-public-domain"
] | permissive | /*
prints ulam numers
a(1) = 1
a(2) = 2
a(n) = minimum number > a(n-1) that can be espressed as the sum of two distinct ulam numbers in exactly one way
*/
#include <iostream>
#include <vector>
using namespace std;
vector<int> ulam, sums(2,1);
int nextulam (int n) {
int i;
for (i = sums.size(); i < ulam[n-1]*2; i++) //ulam(n)<=ulam(n-1)+ulam(n-2)
sums.push_back(0);
//sums.insert(sums.end(), ulam[n-1], 0); <--- 10x slower if compiled with gcc -Ofast, wtf
int size = sums.size();
#pragma omp parallel for
for (i = 0; i < n-1; i++)
sums[ulam[i]+ulam[n-1]-1]++;
for (i = ulam[n-1]; i < size; i++)
if (sums[i] == 1) return i+1;
}
main () {
int n, found = 2, temp;
cin >> n;
ulam.push_back(1);
ulam.push_back(2);
if (n == 1) {
cout << "1" << endl;
return 0;
}
else cout << "1 2";
while (found < n) {
temp = nextulam(found);
cout << " " << temp;
found++;
ulam.push_back(temp);
}
cout << endl;
return 0;
}
| true |
03ed69b2bb764289d5e63857847ea477aa192c4c | C++ | FerCremonez/College-3rd-semester | /ex4.cpp | UTF-8 | 197 | 2.984375 | 3 | [] | no_license | #include <stdio.h>
main() {
int x;
printf("Insira o valor desejada para o numero : ");
scanf("%d",&x);
for (int i = 1;i <= x;i++){
if (x % i == 0){
printf("%d\n",i);
}
}
}
| true |
d6e9d2c4b7df52c50d8900f5c21524b100930745 | C++ | Ga-PaYin/MySuckWorks | /BigballEatLittleball/源.cpp | GB18030 | 4,376 | 2.890625 | 3 | [] | no_license | #include"circle.h"
#include<ctime>
#include<fstream>
#include<iostream>
using namespace std;
int versusEnermy(myCircle *user, Circle *enermy) {
if (sqrt(pow(user->getX() - enermy->getX(), 2) + pow(user->getY() - enermy->getY(), 2)) - user->getRadius() - enermy->getRadius() <= 0.00001) {
if (user->getRadius() > enermy->getRadius()) {
delete enermy;
user->resize();
return 1;
}
else {
delete user;
return 0;
}
}
else {
return 2;
}
}
int Larger(Circle **enermy,myCircle *user) {
int n = 0;
for (int i = 0; i < CIRCLECOUNT; i++) {
if (enermy[i] != NULL) {
if (enermy[i]->getRadius() >= user->getRadius()) {
n++;
}
}
}
return n;
}
int Smaller(Circle **enermy,myCircle *user) {
int n = 0;
for (int i = 0; i < CIRCLECOUNT; i++) {
if (enermy[i] != NULL) {
if (enermy[i]->getRadius() < user->getRadius()) {
n++;
}
}
}
return n;
}
Circle *newEnermy(myCircle *user,Circle **enermyArr) {
srand((unsigned)time(NULL));
int enermyR;
if (Smaller(enermyArr,user) == 0) {
enermyR = rand() % (user->getRadius() - 5) + 5;
}
else if(Larger(enermyArr,user) == 0) {
enermyR = rand() % (user->getMax() - user->getRadius()) + user->getRadius();
}
else {
if (rand() % 2) {
enermyR = rand() % (user->getRadius() - 5) + 5;
}
else {
enermyR = rand() % (user->getMax() - user->getRadius()) + user->getRadius();
}
}
Circle *enermy = new Circle(rand() % (graphWidth - enermyR * 2) + enermyR, rand() % (graphHeight - enermyR * 2) + enermyR, enermyR, rand() % 16777216, rand() % (graphWidth / 100) + 1, rand() % (graphHeight / 100) + 1);
return enermy;
}
void startGame() {
/*ʽдϷ̵ĺ*/
cleardevice();
srand((unsigned)time(NULL));
MOUSEMSG mousemsg = GetMouseMsg();
myCircle *user = new myCircle(mousemsg.x, mousemsg.y, ORIGINALR, MAGENTA,MAX);
Circle *enermy[CIRCLECOUNT];
for (int i = 0; i < CIRCLECOUNT / 2; i++) {
int enermyR = rand() % (ORIGINALR - 5) + 5;
enermy[i] = new Circle(rand() % (graphWidth - enermyR * 2) + enermyR, rand() % (graphHeight - enermyR * 2) + enermyR, enermyR, rand()%16777216, rand() % (graphWidth / 100), rand() % (graphHeight / 100));
}
for (int i = CIRCLECOUNT / 2; i < CIRCLECOUNT; i++) {
int enermyR = rand() % (user->getMax() - user->getRadius());
enermy[i] = new Circle(rand() % (graphWidth - enermyR * 2) + enermyR, rand() % (graphHeight - enermyR * 2) + enermyR, enermyR, rand()%16777216, rand() % (graphWidth / 100), rand() % (graphHeight / 100));
}
Sleep(1500);
while (true) {
if (MouseHit()) {
FlushMouseMsgBuffer();
mousemsg = GetMouseMsg();
user->move(mousemsg);
}
Sleep(5);//ŻϷ࣬Ȼسɺ
for (int i = 0; i < CIRCLECOUNT; i++) {
if (enermy[i] != NULL) {
enermy[i]->move();
int result = versusEnermy(user, enermy[i]);
if (result == 0) goto outside;
else if (result == 1) {
enermy[i] = NULL;
enermy[i] = newEnermy(user, enermy);
}
}
}
}
outside:
for (int i = 0; i < 4; i++) {
if(enermy[i] != NULL)
delete enermy[i];
}
cleardevice();
}
bool click(MOUSEMSG mousemsg, LPCTSTR word) {
//жĸַ
bool result = false;
short x, y;
if(word == _T("start")||word == _T("restart")){
x = STARTX;
y = STARTY;
}
else if (word == _T("exit")) {
x = EXITX;
y = EXITY;
}
if (mousemsg.x >= x && mousemsg.x <= x + textwidth(word)) {
if (mousemsg.y >= y && mousemsg.y <= y + textwidth(word)) {
result = true;
}
}
return result;
}
int main(int argc, char *argv[]) {
initgraph(graphWidth,graphHeight/*,SHOWCONSOLE/**/);
setbkcolor(WHITE);
settextcolor(BLACK);
cleardevice();
//ɫBGR
Circle Circle1(420,125, 50, 0xe22b8a);
Circle Circle2(380, 125, 25, 0xFFFF);
LPCTSTR start = _T("start");
LPCTSTR exit = _T("exit");
outtextxy(STARTX, STARTY, start);
outtextxy(EXITX, EXITY, exit);
struct MOUSEMSG mousemsg;
while (true) {
if (MouseHit()) {
mousemsg = GetMouseMsg();
if (mousemsg.mkLButton && click(mousemsg, start)) {
startGame();
Circle1.draw();
Circle2.draw();
start = _T("restart");
outtextxy(STARTX, STARTY, start);
outtextxy(EXITX, EXITY, exit);
}else if (mousemsg.mkLButton && click(mousemsg, exit)) {
FlushMouseMsgBuffer();
break;
}
}
}
FlushMouseMsgBuffer();
closegraph();
return 0;
} | true |
d99463d59d3768814ee7a96f6df1a41c7abf0dbc | C++ | deepthombare/SPPU-Computer-graphics-assignments | /Sunrise sunset/Source.cpp | UTF-8 | 4,098 | 2.90625 | 3 | [] | no_license | #include<iostream>
#include<GL/glut.h>
using namespace std;
float ballX = -0.8f;
float ballY = -0.3f;
float ballZ = -1.2f;
float colR = 3.0;
float colG = 1.5;
float colB = 1.0;
float bgColR = 0.0;
float bgColG = 0.0;
float bgColB = 0.0;
static int flag = 1;
void drawSun(void) { // to draw sun
glColor3f(colR, colG, colB); //set ball colour
glTranslatef(ballX, ballY, ballZ); //moving it toward the screen a bit on creation
glutSolidSphere(0.05, 30, 30); //create ball.
}
void drawMountains(void) {//To draw mountains
glBegin(GL_POLYGON);
glColor3f(2.0, 1.0, 1.0);
glVertex3f(-0.9, -0.7, -1.0);
glVertex3f(-0.5, -0.1, -1.0);
glVertex3f(-0.2, -1.0, -1.0);
glVertex3f(0.5, 0.0, -1.0);
glVertex3f(0.6, -0.2, -1.0);
glVertex3f(0.9, -0.7, -1.0);
glEnd();
}
void initRendering() {
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING); //Enable lighting
glEnable(GL_LIGHT0); //Enable light #0
glEnable(GL_LIGHT1); //Enable light #1
glEnable(GL_NORMALIZE); //Automatically normalize normals
glShadeModel(GL_SMOOTH); //Enable smooth shading
}
//Called when the window is resized
void handleResize(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, //The camera angle
(double)w / (double)h, //The width-to-height ratio
1.0, //The near z clipping coordinate
200.0); //The far z clipping coordinate
}
void drawScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(bgColR, bgColG, bgColB, 0.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//Add ambient light
GLfloat ambientColor[] = { 0.2f, 0.2f, 0.2f, 1.0f }; //Color (0.2, 0.2, 0.2)
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor);
//Add positioned light
GLfloat lightColor0[] = { 0.5f, 0.5f, 0.5f, 1.0f }; //Color (0.5, 0.5, 0.5)
GLfloat lightPos0[] = { 4.0f, 0.0f, 8.0f, 1.0f }; //Positioned at (4, 0, 8)
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0);
glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);
//Add directed light
GLfloat lightColor1[] = { 0.5f, 0.2f, 0.2f, 1.0f }; //Color (0.5, 0.2, 0.2)
//Coming from the direction (-1, 0.5, 0.5)
GLfloat lightPos1[] = { -1.0f, 0.5f, 0.5f, 0.0f };
glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1);
glLightfv(GL_LIGHT1, GL_POSITION, lightPos1);
//drawing the SUN
glPushMatrix();
drawSun();
glPopMatrix();
//drawing the Mountains
glPushMatrix();
drawMountains();
glPopMatrix();
glutSwapBuffers();
}
//float _angle = 30.0f;
void update(int value) {
if (ballX > 0.9f)
{
ballX = -0.8f;
ballY = -0.3f;
flag = 1;
colR = 2.0;
colG = 1.50;
colB = 1.0;
bgColB = 0.0;
}
if (flag)
{
ballX += 0.001f;
ballY += 0.0007f;
colR -= 0.001;
colG += 0.002;
colB += 0.005;
bgColB += 0.001;
if (ballX > 0.01)
{
flag = 0;
}
}
if (!flag)
{
ballX += 0.001f;
ballY -= 0.0007f;
colR += 0.001;
colB -= 0.01;
bgColB -= 0.001;
if (ballX < -0.3)
{
flag = 1;
}
}
glutPostRedisplay(); //Tell GLUT that the display has changed
//Tell GLUT to call update again in 5 milliseconds
glutTimerFunc(5, update, 0);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(400, 400);
glutCreateWindow("Sun");
initRendering();
glutDisplayFunc(drawScene);
glutReshapeFunc(handleResize);
glutTimerFunc(5, update, 0);
glutMainLoop();
return(0);
} | true |
642e49786eef84ed9cb1d7aa0f89c6c39b51816a | C++ | FionaQi/LeetCode | /BTree/zigzagLevelOrder.cpp | UTF-8 | 1,586 | 3.4375 | 3 | [] | no_license | #include<iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<TreeNode*> current, next;
bool reverse = 0;
vector<int> temp;
vector<int> printcurrentlevel;
current.push(root);
while(!current.empty()){
while(!current.empty()){
TreeNode* cur = current.front();
temp.push_back(cur->val);
if(cur->left) next.push(cur->left);
if(cur->right) next.push(cur->right);
current.pop();
}
if(reverse){
for(int i = temp.size()-1 ; i >= 0; --i )
{
printcurrentlevel.push_back(temp[i]);
}
if(printcurrentlevel.size() != 0)
res.push_back(printcurrentlevel);
reverse = 0;
}
else{
res.push_back(temp);
reverse = 1;
}
temp.clear();
printcurrentlevel.clear();
swap(current, next);
}
return res;
}
int Numberof1s(int n)
{
int cnt = 0;
while(n){
++cnt;
n = (n-1) & n;
}
return cnt;
}
void main()
{
TreeNode * r= new TreeNode(1);
r->left = new TreeNode(2);
// zigzagLevelOrder(r);
int t = Numberof1s(11);
} | true |
351f6a667ca06fe98cf7df6cdea29199298223fa | C++ | davidflogo12/POO-FINAL-C- | /untitled/Alumno.cpp | UTF-8 | 792 | 2.6875 | 3 | [] | no_license | //
// Created by balta on 16/02/2018.
//
#include "Alumno.h"
#include "Horario.h"
Alumno::Alumno() {
this->matricula="";
this->gene="";
}
Alumno::Alumno(std::string &mat, std::string &gen, char &c, std::string &b, std::string &a) {
this->matricula = mat;
this->gene = gen;
this->Persona::genero = c;
this->Persona::nombre = a;
this->Persona::fechaNac = b;
}
Horario Alumno::getHorario() {
return this->horario;
}
std::string Alumno::getMatricula() {
return this->matricula;
}
std::string Alumno::getGene() {
return this->gene;
}
void Alumno::setHorario(Horario horario) {
this->horario=horario;
}
void Alumno::setMaterias(Materia **materias) {
this->materias[] = materias[6];
}
Materia* Alumno::getMaterias() {
return this->materias;
}
| true |
aa43c177af4df6340440129470b048b198b407b4 | C++ | AnaDz/3DGraphic | /src/students/ParticleExplosion.cpp | UTF-8 | 1,983 | 2.578125 | 3 | [] | no_license | #include"../../include/students/ParticleExplosion.hpp"
#include <glm/gtc/type_ptr.hpp>
#include <GL/glew.h>
#include <iostream>
#include "../../include/gl_helper.hpp"
#include "../../include/log.hpp"
#include "../../include/Utils.hpp"
#include "./../../teachers/Geometries.hpp"
#include"../../include/dynamics/Particle.hpp"
ParticleExplosion::ParticleExplosion(ShaderProgramPtr shaderProgram, const MaterialPtr& material, ParticlePtr particle):
ParticleRenderableStudent(shaderProgram, particle, material), m_pBuffer(0), m_cBuffer(0), m_nBuffer(0)
{
std::vector<glm::vec3> tmp_x, tmp_n;
unsigned int strips=5, slices=5;
teachers::getUnitSphere(tmp_x, tmp_n, strips, slices);
m_positions.insert(m_positions.end(), tmp_x.begin(), tmp_x.end());
m_normals.insert(m_normals.end(), tmp_n.begin(), tmp_n.end());
m_colors.resize(m_positions.size(), randomColor());
//Create buffers
glGenBuffers(1, &m_pBuffer); //vertices
glGenBuffers(1, &m_cBuffer); //colors
glGenBuffers(1, &m_nBuffer); //normals
//Activate buffer and send data to the graphics card
glcheck(glBindBuffer(GL_ARRAY_BUFFER, m_pBuffer));
glcheck(glBufferData(GL_ARRAY_BUFFER, m_positions.size()*sizeof(glm::vec3), m_positions.data(), GL_STATIC_DRAW));
glcheck(glBindBuffer(GL_ARRAY_BUFFER, m_cBuffer));
glcheck(glBufferData(GL_ARRAY_BUFFER, m_colors.size()*sizeof(glm::vec4), m_colors.data(), GL_STATIC_DRAW));
glcheck(glBindBuffer(GL_ARRAY_BUFFER, m_nBuffer));
glcheck(glBufferData(GL_ARRAY_BUFFER, m_normals.size()*sizeof(glm::vec3), m_normals.data(), GL_STATIC_DRAW));
}
void ParticleExplosion::do_draw()
{
Material::sendToGPU(m_shaderProgram, getMaterial());
ParticleRenderableStudent::do_draw();
}
void ParticleExplosion::do_animate(float time){
ParticleRenderableStudent::do_animate(time);
}
ParticleExplosion::~ParticleExplosion()
{
glcheck(glDeleteBuffers(1, &m_pBuffer));
glcheck(glDeleteBuffers(1, &m_cBuffer));
glcheck(glDeleteBuffers(1, &m_nBuffer));
}
| true |