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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f154a073c180e868190f520031173547190d63b5 | C++ | noagol/interpreter | /expressions/Var.cpp | UTF-8 | 275 | 2.796875 | 3 | [] | no_license | #include "Var.h"
/**
* Base class to var
* @param n - number
* @param st - symbol table
*/
Var::Var(const string &n, SymbolTable *st) : name(n), symbolTable(st) {}
/**
*
* @return the the value of var
*/
double Var::calculate() {
return symbolTable->get(name);
} | true |
2574a659ab0a2fabd7b1a81c31a67c9f8429d76a | C++ | AndreFWeber/ProtocoloDeAplicacao | /simu_velha.cc | UTF-8 | 2,350 | 2.921875 | 3 | [] | no_license | #include "proto_aplicacao.h"
#include <limits>
int main() {
proto_aplicacao protocolo(8000);
protocolo.initialize(false, "191.36.10.178", "PeDeCabra", false);
/* USA SE FOR SERVIDOR
cout << "Jogo da Velha\n";
cout << "Vez do jogador 1 (X): ";
// cin >> escolhe;
int escolhe=0;
while (!(cin >> escolhe))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Por favor, entre com um número " << endl;
}
*/
cout << "O zé jogou " << protocolo.receive() << endl;
protocolo.send(4);
/* TMensagem pkt;
pkt.set_id(1234);
pkt.set_nome("manoel");
// verifica se os valores contidos na estrutura de dados respeitam
// a especificação
pkt.check_constraints();
// mostra a estrutura de dados na tela
cout << "Estrutura de dados em memória (antes de codificação XER):" << endl;
pkt.show();
//Criação do socket TCP
TCPClientSocket client;
// conecta no servidor da wiki
client.connect("localhost", 8000);
for (int i =0; i<5;i++) {
// cria o codificador
ostringstream out;
TMensagem::XerSerializer encoder(out);
// codifica a estrutura de dados
encoder.serialize(pkt);
cout << endl;
cout << out.str() << endl;
// faz uma requisição HTTP
client.send(out.str());
}
TMensagem pkt;
// define o valor do campo "id"
pkt.set_id(8);
// Acessa o campo choice, que será referenciado
// pela variável "msg" (note o operador &)
TMensagem::Choice_msg & msg = pkt.get_msg();
// Dentro de "msg" acessa-se "inicio": isso faz
// com que o campo choice contenha um valor do tipo
// "Login" (não pode mais ser mudado).
TLogin login = msg1.get_inicio();
// define os valores dos campos de "inicio"
login.set_usuario("aluno");
login.set_senha("blabla...");
return 0;
// cria o decodificador
istringstream inp(out.str());
TMensagem::XerDeserializer decoder(inp);
// tenta decodificar uma estrutura de dados
TMensagem * other = decoder.deserialize();
cout << endl;
if (other) {
cout << "Estrutura de dados obtida da decodificação XER:" << endl;
other->show();
} else cerr << "Erro: não consegui decodificar a estrutura de dados ..." << endl;
// devem-se destruir explicitamente as estruturas de dados obtidas
// do decodificador
delete other; */
}
| true |
14bd0ea740b5528636efc1226b1bf7fb9725ce5c | C++ | VitorHKato/2DGameC- | /Terreno.cpp | UTF-8 | 216 | 2.53125 | 3 | [] | no_license | #include "Terreno.h"
Terreno::Terreno(int x, int y, bool wall) : Entidade(x, y)
{
}
Terreno::~Terreno()
{
}
void Terreno::setWall(bool wall)
{
this->wall = wall;
}
bool Terreno::getWall()
{
return wall;
}
| true |
d041dce48711bf6cf3bfb4157855e6bb269fb6e6 | C++ | JiangKevin/FishEngine | /Engine/Source/FishEditor/UI/UIColor.hpp | UTF-8 | 483 | 2.578125 | 3 | [
"MIT"
] | permissive | #ifndef UICOLOR_HPP
#define UICOLOR_HPP
#include <QWidget>
namespace Ui {
class UIColor;
}
class UIColor : public QWidget
{
Q_OBJECT
public:
explicit UIColor(std::string const & label, QColor const & value, QWidget *parent = 0);
~UIColor();
bool CheckUpdate(std::string const & label, QColor & value);
private slots:
void ShowColorDialog();
private:
Ui::UIColor *ui;
bool m_changed = false;
std::string m_label;
QColor m_value;
};
#endif // UICOLOR_HPP
| true |
8ffcafb8480c449eb4a813756d4149309082e761 | C++ | zimingwei/leetcode | /3sum.cpp | UTF-8 | 1,260 | 3.140625 | 3 | [] | no_license | class Solution {
public:
// Time: O(n^2)
// Space: O(1)
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > result;
sort(num.begin(), num.end());
int target = 0;
int size = num.size();
for (int i = 0; i < size-2 ; i++) {
if (i != 0 && num[i] == num[i-1]) {
continue;
}
int j = i + 1;
int k = size - 1;
int diff = target - num[i];
while (j < k) {
if (num[j] + num[k] == diff) {
vector<int> triplet;
triplet.push_back(num[i]);
triplet.push_back(num[j]);
triplet.push_back(num[k]);
result.push_back(triplet);
j++;
k--;
while (j < k && num[j] == num[j-1]) {
j++;
}
while (j < k && num[k] == num[k+1]) {
k--;
}
} else if (num[j] + num[k] < diff) {
j++;
} else {
k--;
}
}
}
return result;
}
};
| true |
7fd0707a48916025fbd5fb2d94e52dcd854ba87a | C++ | KoheiHisatsune/cpp_ezoe | /chapter3/iostream/iotest.cpp | UTF-8 | 195 | 2.71875 | 3 | [] | no_license | #include "all.h"
int main()
{
std::cout
<< "Integer : "s << 3 + 5 << " "s << 3 - 5 << " "s
<< 3 * 5 << " "s << 3 / 5 << " "s << 3 % 5 << "\n"s
<< "Floating Point : "s << 3.14 << "\n"s;
} | true |
091e5781e707e05639592661c323ca41bd1b5806 | C++ | bell0136/TIL | /C23/StructOperation.cpp | UHC | 336 | 3.34375 | 3 | [] | no_license | #include <stdio.h>
struct point
{
int xpos;
int ypos;
};
int main()
{
struct point pos1 = {1,2};
struct point pos2;
pos2 = pos1;
printf("%d\n", sizeof(pos1)); //sizeof(pos1) ڷ* 8=4*2
printf("[%d %d]\n", pos1.xpos, pos1.ypos);
printf("%d\n", sizeof(pos2));
printf("[%d %d]\n", pos2.xpos, pos2.ypos);
} | true |
6f446ccb77939e05d2843719b7f1f45bd1c35712 | C++ | danhrubec/Academic-Projects | /CS 251/Labs/Lab 6/test.cpp | UTF-8 | 4,027 | 3.21875 | 3 | [] | no_license | /*test.cpp*/
//
// An AVL unit test based on Catch framework
//
#include <iostream>
#include <vector>
#include <string>
#include "avl.h"
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
using namespace std;
TEST_CASE("(1) AVL tree with 4 nodes")
{
avltree<int, int> avl;
//
// build a simple BST tree with 4 nodes:
//
avl.insert(100, -100);
avl.insert(50, -50);
avl.insert(150, -150);
avl.insert(125, -125);
//
// Tests:
//
vector<int> keys, values, heights;
keys = avl.inorder_keys();
values = avl.inorder_values();
heights = avl.inorder_heights();
REQUIRE(avl.size() == 4);
REQUIRE(avl.height() == 2);
REQUIRE(keys[0] == 50);
REQUIRE(heights[0] == 0);
REQUIRE(keys[1] == 100);
REQUIRE(heights[1] == 2);
REQUIRE(keys[2] == 125);
REQUIRE(heights[2] == 0);
REQUIRE(keys[3] == 150);
REQUIRE(heights[3] == 1);
}
TEST_CASE("(2) Empty AVL Tree")
{
avltree<int,int> avl;
REQUIRE(avl.size() == 0);
REQUIRE(avl.height() == -1);
vector<int> keys, values, heights;
keys = avl.inorder_keys();
values = avl.inorder_values();
heights = avl.inorder_heights();
REQUIRE(keys.empty() == true);
REQUIRE(values.empty() == true);
REQUIRE(heights.empty() == true);
}
TEST_CASE("(3) AVL with 1 node")
{
avltree<int,int> avl;
avl.insert(50,10);
REQUIRE(avl.size()==1);
REQUIRE(avl.height()==0);
vector<int> keys, values, heights;
keys = avl.inorder_keys();
values = avl.inorder_values();
heights = avl.inorder_heights();
REQUIRE(keys[0] == 50);
REQUIRE(values[0] == 10);
REQUIRE(heights[0] == 0);
}
TEST_CASE("(4) AVL height of root as LL")
{
avltree<int,int> avl;
avl.insert(0,10);
avl.insert(10,20);
avl.insert(20,30);
avl.insert(30,40);
avl.insert(40,50);
avl.insert(50,60);
avl.insert(60,70);
avl.insert(70,80);
REQUIRE(avl.size() == 8);
REQUIRE(avl.height() == 7);
vector<int> heights;
heights = avl.inorder_heights();
REQUIRE(heights[0] == 7);
}
TEST_CASE("(5) small AVL Tree")
{
avltree<int,int> avl;
avl.insert(50,1);
avl.insert(30,2);
avl.insert(20,3);
avl.insert(35,4);
avl.insert(75,5);
avl.insert(70,6);
avl.insert(80,8);
REQUIRE(avl.size() == 7);
REQUIRE(avl.height() == 2);
vector<int> keys, values, heights;
keys = avl.inorder_keys();
values = avl.inorder_values();
heights = avl.inorder_heights();
REQUIRE(keys[0] == 20);
REQUIRE(values[0] == 3);
REQUIRE(heights[0] == 0);
REQUIRE(keys[1] == 30);
REQUIRE(values[1] == 2);
REQUIRE(heights[1] == 1);
REQUIRE(keys[2] == 35);
REQUIRE(values[2] == 4);
REQUIRE(heights[2] == 0);
REQUIRE(keys[3] == 50);
REQUIRE(values[3] == 1);
REQUIRE(heights[3] == 2);
REQUIRE(keys[4] == 70);
REQUIRE(values[4] == 6);
REQUIRE(heights[4] == 0);
}
TEST_CASE("(6) AVL with different data types")
{
avltree<char,char> avl;
avl.insert('d','z');
avl.insert('a', 'y');
avl.insert('n', 'w');
vector<int> heights;
vector<char> keys, values;
keys = avl.inorder_keys();
values = avl.inorder_values();
heights = avl.inorder_heights();
REQUIRE(keys[0] == 'a');
REQUIRE(values[0] == 'y');
REQUIRE(heights[0] == 0);
REQUIRE(keys[1] == 'd');
REQUIRE(values[1] == 'z');
REQUIRE(heights[1] == 1);
REQUIRE(keys[2] == 'n');
REQUIRE(values[2] == 'w');
REQUIRE(heights[2] == 0);
}
TEST_CASE("(7) Larger AVL")
{
avltree<int,int> avl;
int i;
//tree with 100 elements
for(i=0;i<100;i++)
{
avl.insert(i,i);
}
REQUIRE(avl.size() == 100);
REQUIRE(avl.height() == 99);
vector<int> keys, values, heights;
keys = avl.inorder_keys();
values = avl.inorder_values();
heights = avl.inorder_heights();
REQUIRE(keys[42] == 42);
REQUIRE(values[42] == 42);
REQUIRE(heights[42] == 57);
}
TEST_CASE("(8) Duplicates in AVL")
{
avltree<int,int> avl;
avl.insert(20,5);
avl.insert(20,4);
avl.insert(20,4);
avl.insert(20,4);
avl.insert(20,4);
avl.insert(20,4);
avl.insert(20,4);
avl.insert(20,4);
REQUIRE(avl.size() == 1);
REQUIRE(avl.height() == 0);
}
| true |
7d4f4f34731f253753f728d3011846c597f0a916 | C++ | vyalich/Course_Nosov | /CourseNosov/Game.cpp | WINDOWS-1251 | 6,813 | 2.53125 | 3 | [] | no_license | #include "Game.h"
bool Compare(Entity* A, Entity* B) {
return A->y < B->y;
}
//-------------------------
int Game::Init()
{
//
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, u8"", u8" SDL2. .", NULL);
SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, u8" SDL 2, : %s", SDL_GetError());
return -10;
}
atexit(SDL_Quit);
//
if (TTF_Init() < 0)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, u8"", u8" TTF. .", NULL);
SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, u8" TTF, : %s", TTF_GetError());
return -20;
}
atexit(TTF_Quit);
//
if (IMG_Init(IMG_INIT_PNG) < 0)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, u8"", u8" TTF. .", NULL);
SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, u8" TTF, : %s", TTF_GetError());
return -20;
}
atexit(IMG_Quit);
//
Window = SDL_CreateWindow("Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIN_W, WIN_H, SDL_WINDOW_SHOWN);
if (Window == 0)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, u8"", u8" . .", NULL);
SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, u8" , : %s", SDL_GetError());
return -30;
}
//
Render = SDL_CreateRenderer(Window, -1, SDL_RENDERER_ACCELERATED);
if (Render == NULL)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, u8"", u8" . .", NULL);
SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, u8" , : %s", SDL_GetError());
return -40;
}
//
if (Drawer::LoadFonts() < 0)
return -50;
//
if (Map::LoadStatic(Render, "tileset.png") < 0)
return -60;
//
if (Player::player.Load("player.png", Render) < 0)
return -70;
//
if (Enemy::LoadStatic(Render) < 0)
return -80;
// GUI
if (GUI::GUIControl.Load(Render) < 0)
return -90;
//
if (Spell::LoadStatic(Render) < 0)
return -100;
//Initialize renderer color
SDL_SetRenderDrawColor(Render, 0, 0, 0, 0xFF);
floor = 0;
srand(time(0));
return 0;
}
int Game::LevelInit()
{
//
Map::MapControl.Load();
_level = true;
floor++;
enemy_cnt = 20 * floor;
Player::player.LevelInit();
Entity::OnScreen.push_back(&Player::player);
//
Enemy* temp;
for (int i = 0; i < enemy_cnt; i++) {
temp = new Enemy;
Enemy::EnemyList.push_back(temp);
Enemy::EnemyList[i]->Load();
}
return 0;
}
void Game::LevelClear()
{
Map::MapControl.ClearLevel();
Entity::OnScreen.clear();
for (int i = 0; i < enemy_cnt; i++)
{
Enemy::EnemyList[i]->Clear();
delete Enemy::EnemyList[i];
}
Enemy::EnemyList.clear();
for (auto spell : Spell::SpellCasted)
{
delete spell;
}
Spell::SpellCasted.clear();
}
//-------------------------
void Game::Clear()
{
Map::MapControl.Clear();
TTF_Quit();
SDL_Quit();
}
//-------------------------
int Game::MainCycle()
{
if (Init() < 0)
return -100;
SDL_Event e;
while (_running == GAME_RUNNING)
{
LevelInit();
MainCycleTimerID = SDL_AddTimer(1000 / 60, MainCycleTimerCallback, this);
while (_level) {
while (SDL_PollEvent(&e))
{
Handle(&e);
}
}
SDL_RemoveTimer(MainCycleTimerID);
LevelClear();
}
Clear();
}
//-------------------------
Uint32 Game::MainCycleTimerCallback(Uint32 interval, void* data)
{
Game* game_obj = static_cast<Game*>(data);
if(game_obj->Process())
game_obj->Draw();
return interval;
}
//-------------------------
void Game::Handle(SDL_Event* e)
{
switch (e->type)
{
case SDL_QUIT:
_running = GAME_OVER;
_level = false;
break;
case SDL_KEYDOWN:
switch (e->key.keysym.sym)
{
case SDLK_f: _level = false; SDL_RemoveTimer(MainCycleTimerID);
}
break;
case SDL_MOUSEBUTTONDOWN:
if (e->button.button == SDL_BUTTON_LEFT)
{
Player::player.SetSpeed(e->button.x + Map::MapControl.GetX() - 32, e->button.y + Map::MapControl.GetY() - 32);
}
if (e->button.button == SDL_BUTTON_RIGHT)
{
Spell::AddCasted(e->button.x, e->button.y);
}
break;
case SDL_MOUSEMOTION:
if (e->button.button == SDL_BUTTON_LEFT)
{
Player::player.SetSpeed(e->button.x + Map::MapControl.GetX() - 32, e->button.y + Map::MapControl.GetY() - 32);
}
break;
case SDL_MOUSEBUTTONUP:
if (e->button.button == SDL_BUTTON_LEFT)
{
Player::player.Stop();
}
break;
}
}
//-------------------------
bool Game::Process()
{
if (!Player::player.Process())
{
_level = false;
if (!Player::player.Alive())
_running = GAME_OVER;
SDL_RemoveTimer(MainCycleTimerID);
return false;
}
double TarX = Player::player.GetX();
double TarY = Player::player.GetY();
int CamX = Map::MapControl.GetX();
int CamY = Map::MapControl.GetY();
//Map::MapControl.Draw(Render);
for (int i = 0; i < enemy_cnt; i++)
Enemy::EnemyList[i]->Process(TarX, TarY, CamX, CamY, Render);
for (auto spell = Spell::SpellCasted.begin(); spell != Spell::SpellCasted.end();)
{
(*spell)->Process();
if (!(*spell)->Exist())
{
delete (*spell);
spell = Spell::SpellCasted.erase(spell);
}
else
spell++;
}
Entity::OnScreen.sort(Compare);
return true;
}
//-------------------------
void Game::Draw()
{
Map::MapControl.Draw(Render);
for (auto entity : Entity::OnScreen) {
entity->Draw(Render);
}
for (auto spell : Spell::SpellCasted) {
spell->Draw(Render, Map::MapControl.GetX(), Map::MapControl.GetY());
}
GUI::GUIControl.Draw(Render);
SDL_RenderPresent(Render);
}
int main(int argc, char* argv[])
{
Game game;
return game.MainCycle();
} | true |
9e81d02195b8feabb1edd60b6d03f0a85f7edf3a | C++ | aisenn/CPP_Piscine | /d01/ex05/Human.hpp | UTF-8 | 263 | 2.625 | 3 | [] | no_license | #ifndef HUMAN_HPP
# define HUMAN_HPP
#include "Brain.hpp"
#include <string>
class Human
{
private:
const Brain _brain;
public:
Human( void );
~Human( void );
std::string identify( void ) const;
const Brain &getBrain() const;
};
#endif //HUMAN_HPP | true |
92126b9935c2a76ae1cdc670cb093090211440ae | C++ | Nuytemans-Dieter/CarGame | /cpp/Factories/SDL/SDLTextOverlay.cpp | UTF-8 | 1,750 | 2.859375 | 3 | [] | no_license |
#include "../../../Headers/Factories/SDL/SDLTextOverlay.h"
SDLTextOverlay::SDLTextOverlay(SDLRenderer* rend) {
start(rend, 30);
}
SDLTextOverlay::SDLTextOverlay(SDLRenderer * rend, int height) {
start(rend, height);
}
void SDLTextOverlay::start(SDLRenderer* rend, int height) {
renderer = rend;
fontsize = height;
textColor = { 215, 11 , 11}; //RED
// Open the font.
font = TTF_OpenFont( "..//Resources//Fonts//roundFont.ttf", fontsize );
if( font == NULL )
{
printf( "SDL_ttf Error: %s\n", TTF_GetError() );
}
// Set texture filtering to linear.
if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
{
printf( "Warning: Linear texture filtering not enabled!" );
}
}
SDLTextOverlay::~SDLTextOverlay() {
free();
}
void SDLTextOverlay::setPosition(int x, int y) {
xPosition = x; yPosition = y;
}
void SDLTextOverlay::free() {
if (texture.getTexture() != NULL)
{
SDL_DestroyTexture(texture.getTexture());
texture.setTexture(NULL, 0, 0);
texture.free();
}
}
void SDLTextOverlay::setText(std::string txt) {
//Get rid of preexisting texture
free();
SDL_Surface* surfaceMessage = TTF_RenderText_Solid(font, txt.c_str(), textColor);
SDL_Texture* message = SDL_CreateTextureFromSurface(renderer->getSDL_Renderer(), surfaceMessage);
texture.setTexture(message, surfaceMessage->h, surfaceMessage->w);
SDL_FreeSurface(surfaceMessage);
}
void SDLTextOverlay::render() {
renderer->render(&texture, xPosition, yPosition);
}
int SDLTextOverlay::getTextWidth() {
return texture.getWidth();
}
//
// Created by Dieter on 25/03/2019.
//
#include "../../../Headers/Factories/SDL/SDLTextOverlay.h"
| true |
4003fc3dc5001175c3f93b7b56b8645e36327b02 | C++ | AnnalisaRapthap/Lab-2 | /answer7.cpp | UTF-8 | 220 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
int main()
{
float a,b,c;
cout << "Enter two angles of a triangle="<< endl;
cin >> a;
cin >> b;
c=180-(a+b);
cout << "The third angle=" << c;
return 0;
}
| true |
f6de41f7d9d1bc716382c90e9f1a0943103f3a81 | C++ | EmileRomon/SFMetroid | /src/Zoomer.cpp | UTF-8 | 1,676 | 2.59375 | 3 | [] | no_license | #include "Zoomer.hpp"
Zoomer::Zoomer(const sf::Texture &texture, const sf::Vector2f &position, const float limitRange) : bodySprite(sf::seconds(0.5f)),
collisionBounds(0.f, 0.f, 16.f, 16.f),
speed(105.f, 0.f)
{
animationBody.setSpriteSheet(texture);
animationBody.addFrame(sf::IntRect(186, 10, 23, 16));
animationBody.addFrame(sf::IntRect(218, 10, 23, 16));
animationBody.addFrame(sf::IntRect(250, 10, 23, 16));
bodySprite.setAnimation(animationBody);
bodySprite.setPosition(position);
leftLimit = position.x - limitRange;
rightLimit = position.x + limitRange;
movement.x = speed.x;
}
void Zoomer::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
target.draw(bodySprite);
}
void Zoomer::update(const sf::Time &deltaTime)
{
if (getPosition().x > rightLimit)
{
movement.x = -speed.x;
}
else if (getPosition().x < leftLimit)
{
movement.x = speed.x;
}
if (animationBody.getSize() != bodySprite.getAnimation()->getSize())
{
bodySprite.setAnimation(animationBody);
}
bodySprite.update(deltaTime);
}
const sf::Vector2f &Zoomer::getPosition() const
{
return bodySprite.getPosition();
}
void Zoomer::move(const sf::Vector2f &offset)
{
bodySprite.move(offset);
}
sf::FloatRect Zoomer::getGlobalBounds()
{
sf::Vector2f pos = bodySprite.getPosition();
collisionBounds.top = pos.y;
collisionBounds.left = pos.x;
return collisionBounds;
} | true |
f2eb294681c08187b66649aa00a8617a9b1c8486 | C++ | Kkoding/Practice_Algorithm | /code/practice_algorithm/practice_algorithm/10Gray code.cpp | WINDOWS-1252 | 940 | 3.390625 | 3 | [] | no_license | /*
Write a program that displays the normal binary representations,
Gray code representations, and decoded Gray code values for all 5-bit numbers.
*/
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 15; //0000 0101
vector<int> v;
vector<int> gray_answer;
vector<int> originla_answer;
while (n != 0)
{
v.push_back(n & 1);
n = n >> 1;
}
v.push_back(0);
reverse(v.begin(), v.end());
/////////////////
gray_answer.push_back(v[0]);
for (int i = 0; i < v.size()-1; ++i) {
gray_answer.push_back(v[i] ^ v[i + 1]);
}
cout << n << " Gray Code : ";
for (auto&d : gray_answer)
cout << d << ' ';
cout << endl;
originla_answer.push_back(gray_answer[0]);
for (int i = 0; i < v.size() - 1; ++i) {
originla_answer.push_back(originla_answer[i] ^ gray_answer[i + 1]);
}
cout << n << " Original Code : ";
for (auto&d : originla_answer)
cout << d << ' ';
cout << endl;
} | true |
490eaa1fdd06735e50460f7a06da89c6143a8376 | C++ | turshp/Programming_Language | /The_C_PL/OJ_回文串的判断/OJ_回文串的判断/源.cpp | UTF-8 | 1,206 | 2.828125 | 3 | [] | no_license | //#include<stdio.h>
//#include<string.h>
//int main() {
// int i, j;
// char s1[22], s2[22], s3[22];
// int a, b, c;
// while (scanf("%s", s1) != EOF) {
// a = strlen(s1);
// /*if (a == 1) {
// printf("YES\n");
// break;
// }
// else if (a % 2 == 0 && a != 1) {
// b = a / 2;
// for (i = 0; i < b; i++) {
// s2[i] = s1[i];
// }
// s2[b] = '\0';
// puts(s2);*/
// for (i = a - 1, j = 0; i >= (a) / 2; i--, j++) {
// s3[j] = s1[i];
// // s3[a] = '\0';
// puts(s3);
// }
// //}
//
// }
//}
//#include<stdio.h>
//#include<string.h>
//int main() {
// char s[100];
// int a=0, n;
// scanf("%d", &n);
// for (int i = 0; i < n;i++){
// scanf("%s", s);
// int num = strlen(s);
// for (int i = 0; i < num / 2; i++) {
// if (s[i] != s[num - 1 - i]) {
// a = 1;
// }
// }
// if (a == 1 ) printf("NO\n");
// else printf("YES\n");
// }
//
// return 0;
//
//}
#include<stdio.h>
#include<string.h>
int main()
{
int n;
scanf("%d", &n);
while (n--) {
int c = 0, a = 0, i;
char ch[1000];
scanf("%s", &ch);
a = strlen(ch);
for (i = 0; i<a; i++)
{
if (ch[i] != ch[a - i - 1])
c++;
}
if (c == 0) printf("YES\n");
else printf("NO\n");
}
return 0;
}
| true |
d1d16f059e2318d315555bff7b01c5231c425287 | C++ | Yurazast/StringList | /string_list.cpp | UTF-8 | 4,810 | 3.515625 | 4 | [] | no_license | #include "string_list.h"
void SwapStrings(char** a, char** b);
void SelectionSort(char** list);
void StringListInit(char*** list)
{
if (list == NULL)
{
puts("Passed NULL instead of address of the list to be initialized");
return;
}
if (*list != NULL)
{
puts("String list is already initialized");
return;
}
*list = (char**) malloc(sizeof(char*) * 2);
if (*list == NULL)
{
puts("Memory allocation problem");
exit(1);
}
(*list)[0] = NULL;
(*list)[1] = NULL;
}
void StringListDestroy(char*** list)
{
if (list == NULL)
{
puts("Passed NULL instead of address of the list to be destroyed");
return;
}
if (*list == NULL)
{
puts("String list is already destroyed");
return;
}
char** next_ptr;
do
{
next_ptr = (char**) (*list)[NEXT];
free((*list)[VALUE]);
free(*list);
*list = next_ptr;
} while (next_ptr != NULL);
*list = NULL;
}
void StringListAdd(char** list, String str)
{
if (list == NULL)
{
puts("String list is not initialized");
return;
}
char* new_str = (char*) malloc(sizeof(char) * strlen(str) + 1);
if (new_str == NULL)
{
puts("Cannot allocate memory for new string");
return;
}
strcpy_s(new_str, sizeof(char) * (strlen(str) + 1), str);
if (list[VALUE] == NULL)
{
list[VALUE] = new_str;
return;
}
char** new_el = (char**) malloc(sizeof(char*) * 2);
if (new_el == NULL)
{
puts("Cannot allocate memory for new list element");
free(new_str);
return;
}
new_el[VALUE] = new_str;
new_el[NEXT] = NULL;
char** next_ptr = list;
while (next_ptr[NEXT] != NULL)
next_ptr = (char**) next_ptr[NEXT];
next_ptr[NEXT] = (char*) new_el;
}
void StringListRemove(char*** list, String str)
{
if (list == NULL || *list == NULL || (*list)[VALUE] == NULL)
{
puts("String list is not initialized or is empty");
return;
}
char** save_ptr = *list;
for (char** next_ptr = (char**) (*list)[NEXT], **prev_ptr = NULL; ; next_ptr = (char**) next_ptr[NEXT])
{
if (strcmp((*list)[VALUE], str) == 0)
{
free((*list)[VALUE]);
if (prev_ptr != NULL)
prev_ptr[NEXT] = (char*) next_ptr;
else
save_ptr = next_ptr;
free(*list);
}
else
{
prev_ptr = *list;
}
if (next_ptr == NULL) break;
*list = next_ptr;
}
*list = save_ptr;
}
int StringListSize(char** list)
{
if (list == NULL || list[VALUE] == NULL) return 0;
int n = 0;
for ( ; list != NULL; list = (char**) list[NEXT])
++n;
return n;
}
int StringListIndexOf(char** list, String str)
{
if (list == NULL || list[VALUE] == NULL)
{
puts("String list is not initialized or is empty");
return -1;
}
int i = 0;
for ( ; list != NULL; list = (char**) list[NEXT])
{
if (strcmp(list[VALUE], str) == 0)
return i;
++i;
}
return -1;
}
void StringListRemoveDuplicates(char** list)
{
if (StringListSize(list) < 2)
{
puts("String list size is less then 2");
return;
}
for (char** el_to_cmp = list; el_to_cmp != NULL && el_to_cmp[NEXT] != NULL; el_to_cmp = (char**) el_to_cmp[NEXT])
{
list = (char**) el_to_cmp[NEXT];
for (char** next_ptr = (char**) list[NEXT], **prev_ptr = el_to_cmp; ; next_ptr = (char**) next_ptr[NEXT])
{
if(strcmp(el_to_cmp[VALUE], list[VALUE]) == 0)
{
free(list[VALUE]);
free(list);
prev_ptr[NEXT] = (char*) next_ptr;
}
else
{
prev_ptr = list;
}
if (next_ptr == NULL) break;
list = next_ptr;
}
}
}
void StringListReplaceInStrings(char** list, String before, String after)
{
if (list == NULL || list[VALUE] == NULL)
{
puts("String list is not initialized or is empty");
return;
}
const int len = strlen(after) + 1;
while (list != NULL)
{
if (strcmp(list[VALUE], before) == 0)
{
list[VALUE] = (char*) realloc(list[VALUE], sizeof(char) * len);
if (list[VALUE] == NULL)
{
puts("Cannot reallocate memory for string");
return;
}
strcpy_s(list[VALUE], sizeof(char) * len, after);
}
list = (char**) list[NEXT];
}
}
void StringListSort(char** list)
{
if (StringListSize(list) < 2)
{
puts("String list size is less then 2");
return;
}
SelectionSort(list);
}
void StringListPrint(char** list)
{
if (list == NULL || list[VALUE] == NULL)
{
puts("String list is empty");
return;
}
puts("String list:");
while (list != NULL)
{
printf("> %s\n", list[VALUE]);
list = (char**) list[NEXT];
}
}
void SwapStrings(char** a, char** b)
{
if (a == b) return;
char* temp = a[VALUE];
a[VALUE] = b[VALUE];
b[VALUE] = temp;
}
void SelectionSort(char** list)
{
for (char** el_to_cmp = list, **min_el; el_to_cmp[NEXT] != NULL; el_to_cmp = (char**) el_to_cmp[NEXT])
{
for (min_el = el_to_cmp, list = (char**) el_to_cmp[NEXT]; list != NULL; list = (char**) list[NEXT])
{
if (strcmp(list[VALUE], min_el[VALUE]) < 0)
min_el = list;
}
SwapStrings(el_to_cmp, min_el);
}
}
| true |
5db88c214a63b4c6816aa928d4318dadf879b693 | C++ | emaldonadogamedev/MeshRenderer_Lite | /MeshRenderer_Lite_Framework/MeshRenderer_Lite_Framework/Src/Systems/Graphics/Components/SimpleCloth/SimpleClothComponent.cpp | UTF-8 | 8,581 | 2.625 | 3 | [] | no_license | #include <Utilities/precompiled.h>
#include <Systems/Graphics/Components/SimpleCloth/SimpleClothComponent.h>
#include <Systems/Input/InputSystem.h>
#include <Systems/Input/Keyboard.h>h
#include <Systems/Graphics/DX11Renderer/DX11Renderer.h>
#include <Systems/Graphics/GraphicsUtilities/VertexTypes.h>
using namespace DirectX;
SimpleClothComponent::SimpleClothComponent(const GameObject* owner, float width, float height, int numParticlesWidth, int numParticlesHeight)
:IComponent(ComponentType::PHYSICS_SIMPLE_CLOTH, owner)
, m_numParticlesWidth(numParticlesWidth)
, m_numParticlesHeight(numParticlesHeight)
{
particles.resize(numParticlesWidth*numParticlesHeight); //I am essentially using this vector as an array with room for numParticlesWidth*numParticlesHeight particles
// creating particles in a grid of particles from (0,0,0) to (width,height,0)
for (int x = 0; x < numParticlesWidth; x++)
{
for (int y = 0; y < numParticlesHeight; y++)
{
const XMVECTOR pos = XMVectorSet(width * (x / (float)numParticlesWidth),
-height * (y / (float)numParticlesHeight),
0,
1.0f);
particles[y*numParticlesWidth + x] = Particle(pos); // insert particle in column x at y'th row
}
}
// Connecting immediate neighbor particles with constraints (distance 1 and sqrt(2) in the grid)
for (int x = 0; x < numParticlesWidth; x++)
{
for (int y = 0; y < numParticlesHeight; y++)
{
if (x < numParticlesWidth - 1)
makeConstraint(getParticle(x, y), getParticle(x + 1, y));
if (y < numParticlesHeight - 1)
makeConstraint(getParticle(x, y), getParticle(x, y + 1));
if (x < numParticlesWidth - 1 && y < numParticlesHeight - 1)
makeConstraint(getParticle(x, y), getParticle(x + 1, y + 1));
if (x < numParticlesWidth - 1 && y < numParticlesHeight - 1)
makeConstraint(getParticle(x + 1, y), getParticle(x, y + 1));
}
}
// Connecting secondary neighbors with constraints (distance 2 and sqrt(4) in the grid)
for (int x = 0; x < numParticlesWidth; x++)
{
for (int y = 0; y < numParticlesHeight; y++)
{
if (x < numParticlesWidth - 2)
makeConstraint(getParticle(x, y), getParticle(x + 2, y));
if (y < numParticlesHeight - 2)
makeConstraint(getParticle(x, y), getParticle(x, y + 2));
if (x < numParticlesWidth - 2 && y < numParticlesHeight - 2)
makeConstraint(getParticle(x, y), getParticle(x + 2, y + 2));
if (x < numParticlesWidth - 2 && y < numParticlesHeight - 2)
makeConstraint(getParticle(x + 2, y), getParticle(x, y + 2));
}
}
// making the upper left most three and right most three particles unmovable
for (int i = 0; i < 3; i++)
{
getParticle(i, 0)->offsetPos(XMVectorSet(0.5f, 0.f, 0.f, 0.f)); // moving the particle a bit towards the center, to make it hang more natural - because I like it ;)
getParticle(i, 0)->makeUnmovable();
getParticle(i, 0)->offsetPos(XMVectorSet(-0.5f, 0.f, 0.f, 0.f)); // moving the particle a bit towards the center, to make it hang more natural - because I like it ;)
getParticle(numParticlesWidth - 1 - i, 0)->makeUnmovable();
}
m_spherePos = XMVectorSet(0, -3.0f, -9.f, 1.0f);
}
SimpleClothComponent::~SimpleClothComponent()
{
}
void SimpleClothComponent::timeStep(const float dt)
{
std::vector<Constraint>::iterator constraint;
for (int i = 0; i < s_CONSTRAINT_ITERATIONS; i++) // iterate over all constraints several times
{
for (constraint = constraints.begin(); constraint != constraints.end(); constraint++)
{
(*constraint).satisfyConstraint(); // satisfy constraint.
}
}
std::vector<Particle>::iterator particle;
for (particle = particles.begin(); particle != particles.end(); particle++)
{
(*particle).timeStep(dt); // calculate the position of each particle at the next time step.
}
if (m_spherePos.m128_f32[2] > 10.0f)
{
m_sphereMoveDirection = -1.0f;
}
else if (m_spherePos.m128_f32[2] < -10.0f)
{
m_sphereMoveDirection = 1.0f;
}
m_spherePos.m128_f32[2] += m_sphereMoveDirection * m_sphereMoveSpeed * dt;
ballCollision(m_spherePos, m_sphereRadius);
}
void SimpleClothComponent::addForce(const XMVECTOR& direction)
{
std::vector<Particle>::iterator particle;
for (particle = particles.begin(); particle != particles.end(); particle++)
{
particle->addForce(direction); // add the forces to each particle
}
}
void SimpleClothComponent::windForce(const XMVECTOR& direction)
{
for (int x = 0; x < m_numParticlesWidth - 1; x++)
{
for (int y = 0; y < m_numParticlesHeight - 1; y++)
{
addWindForcesForTriangle(getParticle(x + 1, y), getParticle(x, y), getParticle(x, y + 1), direction);
addWindForcesForTriangle(getParticle(x + 1, y + 1), getParticle(x + 1, y), getParticle(x, y + 1), direction);
}
}
}
void SimpleClothComponent::ballCollision(const XMVECTOR& center, const float radius)
{
std::vector<Particle>::iterator particle;
for (particle = particles.begin(); particle != particles.end(); particle++)
{
const XMVECTOR particleToCenter = particle->getPos() - center;
const float lengthSquared = XmVec_LengthSquared(particleToCenter);
if (lengthSquared < radius * radius) // if the particle is inside the ball
{
//only use sqrt when we need it
const float length = sqrt(lengthSquared);
particle->offsetPos(XMVector3Normalize(particleToCenter) * (radius - lengthSquared)); // project the particle to the surface of the ball
}
}
}
void SimpleClothComponent::generateVertexBuffers(DX11Renderer* renderContext)
{
std::vector<VertexAnimation> vertices(particles.size());
std::vector<unsigned int> indices;// ((m_numParticlesWidth - 1) * (m_numParticlesHeight - 1) * 12);
for (int p = 0; p < particles.size(); ++p)
{
DirectX::XMStoreFloat3(&vertices[p].position, particles[p].getPos());
}
for (int j = 0; j < m_numParticlesHeight - 1; ++j)
{
for (int i = 0; i < m_numParticlesWidth - 1; ++i)
{
//face 2 of quad
indices.emplace_back(GetParticleIndex(i, j));
indices.emplace_back(GetParticleIndex(i + 1, j + 1));
indices.emplace_back(GetParticleIndex(i, j + 1));
//face 1 of quad
indices.emplace_back(GetParticleIndex(i, j));
indices.emplace_back(GetParticleIndex(i + 1, j));
indices.emplace_back(GetParticleIndex(i + 1, j + 1));
}
}
m_indexCount = indices.size();
renderContext->CreateVertexBuffer(m_drawPointsVB, BufferUsage::USAGE_DEFAULT, sizeof(VertexAnimation) * vertices.size(), vertices.data());
renderContext->CreateIndexBuffer(m_drawPointsIB, BufferUsage::USAGE_DEFAULT, sizeof(unsigned int) * indices.size(), indices.data());
}
int SimpleClothComponent::GetParticleIndex(int x, int y) const
{
return y * m_numParticlesWidth + x;
}
Particle* SimpleClothComponent::getParticle(int x, int y)
{
return &particles[GetParticleIndex(x,y)];
}
void SimpleClothComponent::makeConstraint(Particle *p1, Particle *p2)
{
constraints.emplace_back(std::move(Constraint(p1, p2)));
}
XMVECTOR SimpleClothComponent::calcTriangleNormal(Particle *p1, Particle *p2, Particle *p3) const
{
XMVECTOR& pos1 = p1->getPos();
XMVECTOR& pos2 = p2->getPos();
XMVECTOR& pos3 = p3->getPos();
const XMVECTOR v1 = pos2 - pos1;
const XMVECTOR v2 = pos3 - pos1;
return XmVec_Cross(v1,v2);
}
void SimpleClothComponent::addWindForcesForTriangle(Particle *p1, Particle *p2, Particle *p3, const XMVECTOR& direction)
{
const XMVECTOR normalRaw = calcTriangleNormal(p1, p2, p3);
const XMVECTOR nowNormalized = XMVector3Normalize(normalRaw);
const XMVECTOR force = normalRaw * XmVec_Dot(nowNormalized,direction);
p1->addForce(force);
p2->addForce(force);
p3->addForce(force);
}
float SimpleClothComponent::XmVec_Dot(const XMVECTOR& a, const XMVECTOR& b) const
{
return (a.m128_f32[0] * b.m128_f32[0]) + (a.m128_f32[1] * b.m128_f32[1]) + (a.m128_f32[2] * b.m128_f32[2]);
}
XMVECTOR SimpleClothComponent::XmVec_Cross(const XMVECTOR& a, const XMVECTOR& b) const
{
return DirectX::XMVector3Cross(a, b);
//XMVECTOR result;
//
//result.m128_f32[0] = (a.m128_f32[1] * b.m128_f32[2]) - (b.m128_f32[1] * a.m128_f32[2]);
//result.m128_f32[1] = -((a.m128_f32[0] * b.m128_f32[2]) - (b.m128_f32[0] * a.m128_f32[2]));
//result.m128_f32[2] = (a.m128_f32[0] * b.m128_f32[1]) - (b.m128_f32[0] * a.m128_f32[1]);
//
//return result;
}
float SimpleClothComponent::XmVec_Length(const XMVECTOR& a) const
{
return sqrt(XmVec_LengthSquared(a));
}
float SimpleClothComponent::XmVec_LengthSquared(const XMVECTOR& a) const
{
return (a.m128_f32[0] * a.m128_f32[0]) + (a.m128_f32[1] * a.m128_f32[1]) + (a.m128_f32[2] * a.m128_f32[2]);
}
const int SimpleClothComponent::s_CONSTRAINT_ITERATIONS = 100;
| true |
4f7bd9cb1ac1be1fa8984ef4cbcc6030a822841e | C++ | VoidClient/WindowsNT-Handle-Scanner | /OpenProcess/OpenProcess.cpp | UTF-8 | 1,010 | 3.140625 | 3 | [] | no_license | // OpenProcess.cpp : Defines the entry point for the console application.
//
#include <Windows.h>
#include <TlHelp32.h>
#include <string>
DWORD FindProcessId(const std::wstring processName)
{
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (processSnapshot == INVALID_HANDLE_VALUE)
return 0;
Process32First(processSnapshot, &processInfo);
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processSnapshot);
return processInfo.th32ProcessID;
}
while (Process32Next(processSnapshot, &processInfo))
{
if (!processName.compare(processInfo.szExeFile))
{
CloseHandle(processSnapshot);
return processInfo.th32ProcessID;
}
}
CloseHandle(processSnapshot);
return 0;
}
int main()
{
DWORD Id = FindProcessId(L"chrome.exe");
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, Id);
if (hProcess) {
printf("Handle opened!\n");
getchar();
}
return 0;
}
| true |
a58637afba82a3efce711cc3784c3edac70e973c | C++ | pierfale/Cliff | /include/cliff/shared/HashString.h | UTF-8 | 3,392 | 3.109375 | 3 | [] | no_license | #ifndef _CLIFF_HASH_STRING_H
#define _CLIFF_HASH_STRING_H
#include <cstring>
namespace cliff {
typedef unsigned int Hash;
class HashGenerator {
public:
static constexpr Hash base_offset = 2166136261;
static constexpr Hash prime_number = 16777619;
static constexpr Hash execute(const char* str) {
return _execute(str, base_offset);
}
private:
static constexpr Hash _execute(const char* str, Hash current_hash) {
return *str == '\0' ? current_hash : _execute(str+1, current_hash*base_offset ^ (Hash)*str);
}
};
template<typename T>
class ExternalPointerPolicy {
public:
T* constructor(T* ptr) {
return ptr;
}
void destructor(T* ptr) {
}
};
template<typename T>
class CopyPointerPolicy {
public:
T* constructor(T* ptr) {
_ptr = new T(*ptr);
return _ptr;
}
void destructor(T* ptr) {
delete _ptr;
}
private:
T* _ptr;
};
template<typename T>
class TransferPointerPolicy {
public:
T* constructor(T* ptr) {
_ptr = ptr;
return _ptr;
}
void destructor(T* ptr) {
delete _ptr;
}
private:
T* _ptr;
};
template<typename T>
class CopyPointerArrayPolicy {
public:
typedef typename std::remove_const<T>::type TNonConst;
CopyPointerArrayPolicy(T* array, unsigned int size) {
_ptr = new TNonConst[size];
_size = size;
move_mem(array, size);
}
CopyPointerArrayPolicy(CopyPointerArrayPolicy&& that) : _ptr(that._ptr), _size(that.size()) {
that._ptr = nullptr;
that._size = 0;
}
~CopyPointerArrayPolicy() {
delete[] _ptr;
}
T* get() {
return _ptr;
}
const T* get() const {
return _ptr;
}
unsigned int size() const {
return _size;
}
private:
template<class Q = T>
typename std::enable_if<std::is_scalar<Q>::value>::type
move_mem(T* array, unsigned int size) {
std::memcpy(_ptr, array, size*sizeof(T));
}
template<class Q = T>
typename std::enable_if<!std::is_scalar<Q>::value>::type
move_mem(T* array, unsigned int size) {
std::copy(array, array+size, _ptr);
}
TNonConst* _ptr;
unsigned int _size;
};
template<template<typename> class PointerArrayPolicy>
class HashString {
public:
constexpr HashString(const char* str) : _string(str, std::strlen(str)+1), _hash(HashGenerator::execute(str)) {
}
HashString(HashString<PointerArrayPolicy>&& that) : _string(std::move(that._string)), _hash(std::move(that._hash)) {
}
const char* string() const {
return _string.get();
}
unsigned int size() const {
return _string.size()-1;
}
Hash hash() const {
return _hash;
}
bool operator==(const HashString& that) const {
return _hash == that._hash && std::strcmp(_string.get(), that._string.get()) == 0;
}
bool operator!=(const HashString& that) const {
return _hash != that._hash || std::strcmp(_string.get(), that._string.get()) != 0;
}
bool operator<(const HashString& that) const {
return _hash < that._hash || (_hash == that._hash && std::strcmp(_string.get(), that._string.get()) < 0);
}
protected:
PointerArrayPolicy<const char> _string;
Hash _hash;
};
typedef HashString<CopyPointerArrayPolicy> CopyHashString;
}
#endif
| true |
b633be201e2a3f915f8af0c65add3a6bbf416862 | C++ | hamote505/ESP8266-FastLED | /mqtt-sine/mqtt-sine.ino | UTF-8 | 12,909 | 2.640625 | 3 | [] | no_license | /* mqtt-sine
*
* By: Andrew Tuline
*
* Date: January, 2017
*
* Update: July, 2019 (MQTT Update)
*
* What can you do with a sine wave? LOTS!!
*
* Forget using delay() statements or counting pixels up and down the strand of LED's. That's for chumps.
* This example demonstrates just a bit of what can be done using basic high school math by using a simple sinewave.
*
* You can use a sine wave to go back and forth up a strand of LED's. You can shift the phase of a sine wave to move along a strand. You can clip the top of that sine wave
* to just display a certain value (or greater). You can add palettes to that sine wave so that you aren't stuck with CHSV values and so much more.
*
* It shows that you don't neeed a pile of for loops, delays or counting pixels in order to come up with a decent animation. The display routine is SHORT.
*
* Oh, and look. It now contains MQTT functionality so that you can control a pile of variables with your phone. You can even support multiple devices.
*
*
* MQTT Topics/Controls include:
*
* Widget Topic Payload
* Combo Box sine/device 0 = ALL Devices or 1-9
* Slider sine/bri 0 - 255
* Slider sine/hue 0 - 255
* Slider sine/speed -5 - 5
* Slider sine/rot 16
* Slider sine/cent 0 - NUM_LEDS
*
*
* Note: You can configure a topic prefix of "sine/".
*
* The Android phone application used is called 'IoT MQTT Panel Pro'.
*
*/
// Use qsuba for smooth pixel colouring and qsubd for non-smooth pixel colouring
#define qsubd(x, b) ((x>b)?b:0) // Digital unsigned subtraction macro. if result <0, then => 0. Otherwise, take on fixed value.
#define qsuba(x, b) ((x>b)?x-b:0) // Analog Unsigned subtraction macro. if result <0, then => 0
#include <ESP8266WiFi.h> // Should be included when you install the ESP8266.
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient
#include "FastLED.h"
#if FASTLED_VERSION < 3001000
#error "Requires FastLED 3.1 or later; check github for latest code."
#endif
// WiFi Authentication -------------------------------------------------------------------------
const char* ssid = "SM-G965W4004"; // WiFi configuration for Android tethering network. The Android IP address is hard coded at 192.168.43.1.
const char* password = "afng2036";
// MQTT Authentication -------------------------------------------------------------------------
// My Phone as a tethered device (working) // MQTT Broker application on Android credentials - using the Android tethered WiFi.
const char* mqttServer = "192.168.43.1";
const int mqttPort = 1883;
const char* mqttUser = "wmabzsy";
const char* mqttPassword = "GT8Do3vkgWP5";
const char* mqttID ="12"; // Must be UNIQUE for EVERY display!!!
const uint8_t STRANDID = 12; // Choose 1 to 99. Where 0 = all. 100 - 255 reserved for future use.
const char *prefixtopic = "sine/";
const char *subscribetopic[] = {"device", "bri", "hue", "speed", "rot", "cent"};
char message_buff[100];
WiFiClient espClient;
PubSubClient client(espClient);
uint8_t mydevice = 0; // This is our STRANDID
uint8_t mypayload = 0; // MQTT message received.
// Fixed definitions cannot change on the fly.
#define LED_DT D5 // Serial data pin for WS2812 or WS2801.
#define LED_CK 11 // Serial clock pin for WS2801 or APA102.
#define COLOR_ORDER GRB // Are they GRB for WS2812 and GBR for APA102
#define LED_TYPE WS2812 // What kind of strip are you using? WS2812, APA102. . .
#define NUM_LEDS 40 // Number of LED's.
uint8_t max_bright = 128; // Overall brightness definition. It can be changed on the fly.
struct CRGB leds[NUM_LEDS]; // Initialize our LED array.
// Initialize changeable global variables. Play around with these!!!
int8_t thisspeed = 2; // You can change the speed of the wave, and use negative values.
int thisphase = 0; // Phase change value gets calculated.
int thisdelay = 20; // You can change the delay. Also you can change the allspeed variable above.
uint8_t thisrot = 16;
const uint8_t phasediv = 4; // A divider so that the speed has a decent range.
uint8_t thiscenter = NUM_LEDS / 2;
// Palette definitions
CRGBPalette16 currentPalette;
TBlendType currentBlending = LINEARBLEND;
void setup() {
Serial.begin(115200); // Initialize serial port for debugging.
delay(1000); // Soft startup to ease the flow of electrons.
// LEDS.addLeds<LED_TYPE, LED_DT, LED_CK, COLOR_ORDER>(leds, NUM_LEDS); //WS2801 and APA102
LEDS.addLeds<LED_TYPE, LED_DT, COLOR_ORDER>(leds, NUM_LEDS); // WS2812
FastLED.setBrightness(max_bright);
FastLED.setMaxPowerInVoltsAndMilliamps(5, 500); // FastLED Power management set at 5V, 500mA.
currentPalette = LavaColors_p;
client.setServer(mqttServer, mqttPort); // Initialize MQTT service. Just once is required.
client.setCallback(callback); // Define the callback service to check with the server. Just once is required.
} // setup()
void loop () {
networking(); // We need to run this continually in case we disconnect from the MQTT broker.
EVERY_N_MILLISECONDS(thisdelay) { // FastLED based non-blocking delay to update/display the sequence.
one_sine_phase(); // The value is used as a color index.
}
FastLED.show();
} // loop()
void one_sine_phase() { // This is the heart of this program. Sure is short.
uint8_t thisindex = millis() / thisrot;
thisphase += thisspeed; // You can change direction and speed individually.
for (int k = 0; k < NUM_LEDS - 1; k++) { // For each of the LED's in the strand, set a brightness based on a wave as follows:
// int thisbright = cubicwave8((k * allfreq) + thisphase * k / phasediv); // Brightness based on lots of variables.
int thisbright = cubicwave8((thisphase * k) / phasediv); // Brightness based on lots of variables.
if ((thiscenter + k) < NUM_LEDS) leds[(thiscenter + k) % NUM_LEDS] = ColorFromPalette( currentPalette, thisindex, thisbright, currentBlending); // Let's now add the foreground colour with centering.
if ((thiscenter - k) >= 0 ) leds[(thiscenter - k) % NUM_LEDS] = ColorFromPalette( currentPalette, thisindex, thisbright, currentBlending); // Let's now add the foreground colour with centering.
thisindex += 256 / NUM_LEDS;
thisindex += thisrot;
} // for k
} // one_sine_phase()
void callback(char *topic, byte *payload, unsigned int length) { // MQTT Interrupt routine because we just got a message!
Serial.print("Topic: ["); Serial.print(topic); Serial.println("]"); // Prints out anything that's arrived from broker and from the topics that we've subscribed to.
int i; for (i = 0; i < length; i++) message_buff[i] = payload[i]; message_buff[i] = '\0'; // We copy payload to message_buff because we can't make a string out of byte payload.
String msgString = String(message_buff); // Finally, converting our payload to a string so we can compare it.
Serial.print("Payload: ["); Serial.print(msgString); Serial.println("]");
mypayload = msgString.toInt();
if (strcmp(topic, "sine/device") == 0) { // Device selector
mydevice = msgString.toInt();
Serial.print("device: "); Serial.println(mydevice);
}
// if (mydevice == GROUPID || mydevice == STRANDID) {
if (strcmp(topic, "sine/bri") == 0) { // Brightness
max_bright = msgString.toInt();
Serial.print("mybri: "); Serial.println(max_bright);
FastLED.setBrightness(max_bright);
}
if (strcmp(topic, "sine/hue") == 0) { // Hue
uint8_t baseC = msgString.toInt();
Serial.print("baseC: "); Serial.println(baseC);
currentPalette = CRGBPalette16(CHSV(baseC + random8(128), 255, random8(128, 255)),
CHSV(baseC + random8(64), 255, random8(128, 255)),
CHSV(baseC + random8(128), 64, random8(128, 255)),
CHSV(baseC + random8(32), 255, random8(128, 255)));
}
if (strcmp(topic, "sine/speed")== 0) { // Speed 1 to 10
thisspeed = msgString.toInt();
Serial.print("thisspeed: "); Serial.println(thisspeed);
}
if (strcmp(topic, "sine/rot")== 0) {
thisrot = msgString.toInt();
Serial.print("thisrot: "); Serial.println(thisrot); // rot 0 - 255 (was 16)
}
if (strcmp(topic, "sine/cent")== 0) {
thiscenter = msgString.toInt() % NUM_LEDS;
Serial.print("thiscenter: "); Serial.println(thiscenter); // thiscenter - NUM_LEDS/2
}
// } // if mydevice
} // callback()
void networking() { // Asynchronous network connect routine with MQTT connect and re-connect. The trick is to make it re-connect when something breaks.
static long lastReconnectAttempt = 0;
static bool wifistart = false; // State variables for asynchronous wifi & mqtt connection.
static bool wificonn = false;
if (wifistart == false) {
WiFi.begin(ssid, password); // Initialize WiFi on the ESP8266. We don't care about actual status.
wifistart = true;
}
if (WiFi.status() == WL_CONNECTED && wificonn == false) {
Serial.print("IP address:\t"); Serial.println(WiFi.localIP()); // This should just print once.
wificonn = true;
}
if (WiFi.status() != WL_CONNECTED) wificonn = false; // Toast the connection if we've lost it.
if (!client.connected() && WiFi.status() == WL_CONNECTED) { // Non-blocking re-connect to the broker. This was challenging.
if (millis() - lastReconnectAttempt > 5000) {
lastReconnectAttempt = millis();
if (reconnect()) { // Attempt to reconnect.
lastReconnectAttempt = 0;
}
}
} else {
client.loop();
}
} // networking()
boolean reconnect() { // Here is where we actually connect/re-connect to the MQTT broker and subscribe to our topics.
if (client.connect(mqttID, mqttUser, mqttPassword )) {
Serial.println("MQTT connected.");
// client.publish("LED1", "Hello from ESP8266!"); // Sends topic and payload to the MQTT broker.
for (int i = 0; i < (sizeof(subscribetopic)/sizeof(int)); i++) { // Subscribes to list of topics from the MQTT broker. This whole loop is well above my pay grade.
String mypref = prefixtopic; // But first, we need to get our prefix.
mypref.concat(subscribetopic[i]); // Concatenate prefix and the topic together with a little bit of pfm.
client.subscribe((char *) mypref.c_str()); // Now, let's subscribe to that concatenated and converted mess.
Serial.println(mypref); // Let's print out each subscribed topic, just to be safe.
}
} // if client.connected()
return client.connected();
} // reconnect()
| true |
a5fa8b6a072efe7ba7279167074d7518e76de267 | C++ | ShiliXu1997/ACM_Code | /ACM-ICPC_2017_Asia_Urumqi/G.cpp | UTF-8 | 2,400 | 3 | 3 | [] | no_license | //******************************************************************************
// File Name: G.cpp
// Author: Shili_Xu
// E-Mail: shili_xu@qq.com
// Created Time: 2018年07月29日 星期日 13时00分34秒
//******************************************************************************
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
typedef long long ll;
const double EPS = 1e-8;
int sgn(double x)
{
if (fabs(x - 0) < EPS) return 0;
return (x < 0 ? -1 : 1);
}
struct point {
double x, y;
point(double _x = 0, double _y = 0) : x(_x), y(_y) {}
bool operator<(const point &another) const
{
return (x < another.x) || (x == another.x && y < another.y);
}
bool operator==(const point &another) const
{
return sgn(x - another.x) == 0 && sgn(y - another.y) == 0;
}
};
typedef point vec;
vec operator+(vec a, vec b)
{
return vec(a.x + b.x, a.y + b.y);
}
vec operator-(point a, point b)
{
return vec(a.x - b.x, a.y - b.y);
}
vec operator*(vec a, double p)
{
return vec(a.x * p, a.y * p);
}
vec operator/(vec a, double p)
{
return vec(a.x / p, a.x / p);
}
double dot(vec a, vec b)
{
return a.x * b.x + a.y * b.y;
}
double det(vec a, vec b)
{
return a.x * b.y - a.y * b.x;
}
double length(vec a)
{
return sqrt(dot(a, a));
}
struct polygon {
vector<point> p;
polygon() {}
polygon(vector<point> v)
{
p = v;
}
double area()
{
double ans = 0;
for (int i = 1; i < p.size() - 1; i++)
ans += det(p[i] - p[0], p[i + 1] - p[0]);
return fabs(ans / 2);
}
};
polygon convex_hull(vector<point> all)
{
polygon ans;
vector<point> &v = ans.p;
sort(all.begin(), all.end());
for (int i = 0; i < all.size(); i++) {
while (v.size() > 1 && sgn(det(v.back() - v[v.size() - 2], all[i] - v[v.size() - 2])) <= 0)
v.pop_back();
v.push_back(all[i]);
}
int k = v.size();
for (int i = all.size() - 2; i >= 0; i--) {
while (v.size() > k && sgn(det(v.back() - v[v.size() - 2], all[i] - v[v.size() - 2])) <= 0)
v.pop_back();
v.push_back(all[i]);
}
if (all.size() > 1) v.pop_back();
return ans;
}
int t, n;
vector<point> p;
polygon pol;
int main()
{
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
p.clear();
for (int i = 1; i <= n; i++) {
double x, y;
scanf("%lf %lf", &x, &y);
p.push_back(point(x, y));
}
pol = polygon(p);
printf("%.6f\n", pol.area());
}
return 0;
}
| true |
6d286ecb1fb5bb42505d52cb0d8eef7392963480 | C++ | LexaHoods/Ultimate-Community-Finder | /Ultimate-Community-Finder/Graph.cpp | UTF-8 | 2,409 | 3.171875 | 3 | [] | no_license | #include "Graph.h"
#include <iostream>
#include<time.h>
using namespace std;
//Basic functions
int Graph::degree(int v) {
return vertices[v].size();
}
vector<int> Graph::neighbours(int v) {
return vertices[v];
}
//Random generation functions
void Graph::random(int nVertices, float p) {
v = nVertices;
//Generate vertices vector
vertices = vector<vector<int>>(v, vector<int>());
float r = 0;
srand(time(NULL));
for (int i = 0; i < v; i++) {
for (int j = i + 1; j < v; j++) {
r = (float)rand() / RAND_MAX;
if (r <= p) {
vertices[i].push_back(j);
vertices[j].push_back(i);
}
}
}
}
void Graph::barabasiAlbert(int nVertices, int m, int m0) {
//1) Initialization
v = nVertices;
//Generate vertices vector
for(int i=0; i<v; i++) {
vertices.push_back(vector<int>());
}
int degSum = 0;
int degMarkedVertices = 0;
vector<int>degVector;
vector<int>markedVertices;
int random;
srand(time(NULL));
//2) Clique creation
for (int i = 0; i < m0; i++) {
for (int j = i + 1; j < m0; j++) {
vertices[i].push_back(j);
vertices[j].push_back(i);
}
degVector.push_back(m0 - 1);
}
degSum = m0 * (m0 - 1);
//3) Add edges
//Consider new vertex v
for (int i = m0; i < v; i++) {
//Reset marked vertices
markedVertices.clear();
degMarkedVertices = 0;
//Consider new edge e starting from v
for (int j = 0; j < m; j++) {
random = rand() % (degSum - degMarkedVertices);
int temp = 0;
int k = 0;
//Looking for new destination vertex
do{
bool conflict = false;
//Checking conflicts with already marked vertices
for (long unsigned int l = 0; l < markedVertices.size(); l++) {
if(markedVertices[l] == k) {
conflict = true;
break;
}
}
if(!conflict)
temp += degVector[k];
k++;
}while(temp <= random);
k--;
//At this point, vertex k found
degVector[k]++;
degSum++;
markedVertices.push_back(k);
degMarkedVertices += degVector[k];
vertices[i].push_back(k);
vertices[k].push_back(i);
}
//Adding new vertex and updating degSum with edges' other hand
degVector.push_back(m);
degSum += m;
}
}
//Testing functions
void Graph::print() {
for (long unsigned int i = 0; i < vertices.size(); i++) {
cout << i << ":";
for (long unsigned int j = 0; j < vertices[i].size(); j++) {
cout << " " << vertices[i][j];
}
cout << endl;
}
}
| true |
b6fd38e6a2c2937bcbc0845f368be09179daef80 | C++ | ryujt/ryulib-arduino | /libraries/RyuLib/Examples/Chapter 07. Game/_05._RyuGame Library/_01._RyuGame_Tutorial/Basic_09/Basic_09.ino | UTF-8 | 967 | 2.625 | 3 | [] | no_license | #include <RyuGame.h>
#include <cheetah.h>
int pin_fire = 12;
class Cheetah : public GameControlBase
{
private:
int _TickCount = 0;
int _Index = 0;
public:
void start()
{
x = (84 - CHEETAH_WIDTH ) / 2;
y = (48 - CHEETAH_HEIGHT) / 2;
}
void update(unsigned long tick)
{
_LCD->drawBitmap(x, y, cheetah_image[_Index], CHEETAH_WIDTH, CHEETAH_HEIGHT, BLACK);
_LCD->setTextSize(1);
_LCD->setCursor(0, 0);
_LCD->println(_Index);
if (_TickCount < 500) _TickCount = _TickCount + tick;
}
void incIndex()
{
if (_TickCount < 500) return;
_TickCount = 0;
_Index++;
if (_Index >= CHEETAH_COUNT) _Index = 0;
}
};
GameEngine gameEngine(13, 2, 3, 4, 5, 6);
Cheetah cheetah;
void setup() {
pinMode(pin_fire, INPUT_PULLUP);
gameEngine.addControl(&cheetah);
gameEngine.start();
}
void loop() {
if (digitalRead(pin_fire) == LOW) cheetah.incIndex();
gameEngine.update();
}
| true |
14a9d5435bc0480e1e527ae3d9be49929bcf9db6 | C++ | Gowtham-369/InterviewBitMasterSolutions | /BackTracking/Generate_all_parenthesis.cpp | UTF-8 | 743 | 3.171875 | 3 | [] | no_license | void solve(int open, int closed, int n, string temp, vector<string> &ans)
{
if (open == n && closed == n)
{
ans.push_back(temp);
return;
}
if (open < n)
{
temp.push_back('(');
solve(open + 1, closed, n, temp, ans);
temp.pop_back();
if (closed < open)
{
temp.push_back(')');
solve(open, closed + 1, n, temp, ans);
}
}
else if (closed < n)
{
temp.push_back(')');
solve(open, closed + 1, n, temp, ans);
}
return;
}
vector<string> Solution::generateParenthesis(int n)
{
int open = 0, closed = 0;
vector<string> ans;
string temp = "";
solve(open, closed, n, temp, ans);
return ans;
}
| true |
36c5f5061012d280375811601184b3b8df24f1fa | C++ | MDE4CPP/MDE4CPP | /src/examples/benchmarks/UMLBenchmark/src/UMLBenchmark/main.cpp | UTF-8 | 2,594 | 2.578125 | 3 | [
"EPL-1.0",
"MIT"
] | permissive | #include <chrono>
#include <iostream>
#include <string>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include "abstractDataTypes/SubsetUnion.hpp"
#include "uml/umlFactory.hpp"
#include "uml/umlPackage.hpp"
#include "uml/Package.hpp"
#include "uml/Class.hpp"
#include "uml/Property.hpp"
#include "umlReflection/UMLPackage.hpp"
#define SSTR( x ) static_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
using namespace std;
int main(int argc, char *argv[])
{
cout << "Hello World!" << endl;
for (int i=0; i<1; i++){
shared_ptr<uml::umlFactory> umlFactory = uml::umlFactory::eInstance();
cout << "factory created " << umlFactory << endl;
shared_ptr<UML::UMLPackage> umlPackage = UML::UMLPackage::eInstance();
cout << "package created " << umlPackage << endl;
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
{
shared_ptr<uml::Package> package = umlFactory->createPackage_as_packagedElement_in_Package(umlPackage);
cout << "package created" << endl;
package->setName(std::string("Benchmark UML"));
cout << package->getName() << endl;
char buffer [33];
start = std::chrono::high_resolution_clock::now();
for (int i=0; i<10000; i++)
{
shared_ptr<uml::Class> classObject = umlFactory->createClass_as_packagedElement_in_Package(package);
classObject->setName("Class " + sprintf (buffer, "%i", i));
shared_ptr<uml::Property> property = umlFactory->createProperty_as_ownedAttribute_in_Class(classObject);
property->setName("A" + sprintf (buffer, "%i", i));
classObject->getOwnedAttribute()->push_back(property);
}
end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end-start).count() << std::endl;
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << std::endl;
std::cout << std::chrono::duration_cast<std::chrono::seconds>(end-start).count() << std::endl;
std::cout << "count: " << package->getPackagedElement()->size() << std::endl;;
std::cout << "time for delete" << std::endl;
start = std::chrono::high_resolution_clock::now();
}
end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end-start).count() << std::endl;
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << std::endl;
std::cout << std::chrono::duration_cast<std::chrono::seconds>(end-start).count() << std::endl;
}
// Sleep( 10000000 );
return 0;
}
| true |
ce38e73bbcf7226fce2d8b84b30b5388ca8576d3 | C++ | SigridHo/CodingEx | /paint/paint/paint.cpp | UTF-8 | 1,695 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
using namespace std;
char init[18][18] = {0};
int mid[18][18] = {0};
int answer[18][18] = {0};
int a[18] = {0};
int MIN = 10000;
int binary[18] = {0};
void change(int n);
void firststate(int n)
{
for(int i = 0; i < binary[n]; ++ i)
{
int temp = i;
memset(answer, 0, sizeof(answer));
memset(mid, 0, sizeof(answer));
for(int j = 1; j <= n; ++j)
{
a[j] = temp & 1;
answer[1][j] = a[j];
temp = temp >> 1;
}
for(int j = 1; j <= n; ++j)
for(int k = 1; k <= n; ++k)
{
if(init[j][k] == 'w') mid[j][k] = 0;
else mid[j][k] = 1;
}
change(n);
}
}
void change(int n)
{
int number = 0;
for(int i = 1; i <= n; ++i)
{
for(int j = 1; j <= n; ++j)
{
if(answer[i][j] == 1)
{
mid[i - 1][j] = mid[i - 1][j] ^ 1;
mid[i + 1][j] = mid[i + 1][j] ^ 1;
mid[i][j] = mid[i][j] ^ 1;
mid[i][j - 1] = mid[i][j - 1] ^ 1;
mid[i][j + 1] = mid[i][j + 1] ^ 1;
number++;
if(number > MIN) return;
}
}
for(int j = 1; j <= n; ++j)
{
if(mid[i][j] == 0) answer[i + 1][j] = 1;
}
}
for(int i = 1; i <= n; ++i)
{
if(mid[n][i] == 0) return;
}
if(number < MIN) MIN = number;
}
int main() {
int t;
cin >> t;
int temp = 1;
binary[0] = 1;
for(int i = 1 ; i < 18; ++i)
{
temp *= 2;
binary[i] = temp;
}
for(int i = 0; i < t; ++i)
{
int n;
cin >> n;
memset(init, 0, sizeof(init));
for(int j = 1; j <= n; ++j)
for(int k = 1; k <= n; ++k)
cin >> init[j][k];
memset(answer, 0, sizeof(answer));
firststate(n);
if(MIN == 10000) cout << "inf" << endl;
else cout << MIN << endl;
MIN = 10000;
}
system("pause");
return 0;
}
| true |
cd0ed06ac950d6ced2de19d8b8deb176f8e988eb | C++ | yusuke-matsunaga/minimaleda | /libraries/libym_cec/FraigSig.h | UTF-8 | 8,485 | 2.734375 | 3 | [] | no_license | #ifndef LIBYM_AIG_FRAIGSIG_H
#define LIBYM_AIG_FRAIGSIG_H
/// @file libym_aig/FraigSig.h
/// @brief FraigSig のヘッダファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// $Id: FraigSig.h 2203 2009-04-16 05:04:40Z matsunaga $
///
/// Copyright (C) 2005-2010 Yusuke Matsunaga
/// All rights reserved.
#include "ym_aig/aig_nsdef.h"
#include "ym_utils/RandGen.h"
BEGIN_NAMESPACE_YM_AIG
//////////////////////////////////////////////////////////////////////
/// @class FraigSig FraigSig.h "FraigSig.h"
/// @brief Fraig のノードを区別するためのシグネチャを表すクラス
/// @note ハッシュ値の計算時には,1ビット目(最下位ビット)が0になるよう
/// に調節している.
//////////////////////////////////////////////////////////////////////
class FraigSig
{
public:
/// @brief コンストラクタ
/// @param[in] size サイズ
explicit
FraigSig(ymuint size);
/// @brief コピーコンストラクタ
FraigSig(const FraigSig& src);
/// @brief デストラクタ
~FraigSig();
public:
/// @brief サイズを得る.
ymuint
size() const;
/// @brief ハッシュ値の計算時に反転していたら true を返す.
bool
inv() const;
/// @brief 1 の数を返す.
ymuint
one_count() const;
/// @brief 0 の数を返す.
ymuint
zero_count() const;
/// @brief 内容を得る.
/// @param[in] pos 位置番号 ( 0 <= pos < size() )
ymuint32
pat(ymuint pos) const;
/// @brief 内容を設定する.
/// @note サイズがあっていることを前提としている.
void
set(const vector<ymuint32>& src);
/// @brief 内容をランダムにセットする.
void
set_random(RandGen& randgen);
/// @brief ファンインのシグネチャから計算する.
void
calc(const FraigSig& right,
bool right_inv,
const FraigSig& left,
bool left_inv);
/// @brief 等価比較
bool
operator==(const FraigSig& right) const;
/// @brief 否定したものが等価かどうか調べる.
bool
ncomp(const FraigSig& right) const;
/// @brief 大小比較 (lt)
bool
operator<(const FraigSig& right) const;
/// @brief ハッシュ値を返す.
ymuint
hash() const;
/// @brief 内容を出力する.
void
dump(ostream& s) const;
private:
/// @brief ハッシュ値を計算する.
void
calc_hash();
/// @brief pat 中の 1 の数を数える.
ymuint
count_ones(ymuint32 pat);
private:
//////////////////////////////////////////////////////////////////////
// データメンバ
//////////////////////////////////////////////////////////////////////
// サイズ
ymuint32 mSize;
// 本体
ymuint32* mBody;
// ハッシュ値
ymuint32 mHash;
// 1 の数
ymuint32 mOne;
// ハッシュ用の素数配列
static
ymuint32 mPrimes[128];
};
/// @relates FraigSig
/// @brief 非等価比較
bool
operator!=(const FraigSig& left,
const FraigSig& right);
/// @relates FraigSig
/// @brief 大小比較 (gt)
bool
operator>(const FraigSig& left,
const FraigSig& right);
/// @relates FraigSig
/// @brief 大小比較 (le)
bool
operator<=(const FraigSig& left,
const FraigSig& right);
/// @relates FraigSig
/// @brief 大小比較 (ge)
bool
operator>=(const FraigSig& left,
const FraigSig& right);
//////////////////////////////////////////////////////////////////////
// インライン関数の定義
//////////////////////////////////////////////////////////////////////
// @brief コンストラクタ
// @param[in] size サイズ
inline
FraigSig::FraigSig(ymuint size) :
mSize(size << 1),
mBody(new ymuint32[size]),
mHash(0)
{
}
// @brief コピーコンストラクタ
inline
FraigSig::FraigSig(const FraigSig& src) :
mSize(src.mSize),
mBody(new ymuint32[mSize]),
mHash(src.mHash)
{
for (ymuint i = 0; i < mSize; ++ i) {
mBody[i] = src.mBody[i];
}
}
// @brief デストラクタ
inline
FraigSig::~FraigSig()
{
delete [] mBody;
}
// @brief サイズを得る.
inline
ymuint
FraigSig::size() const
{
return mSize >> 1;
}
// @brief ハッシュ値の計算時に反転していたら true を返す.
inline
bool
FraigSig::inv() const
{
return static_cast<bool>(mSize & 1U);
}
// @brief 1 の数を返す.
inline
ymuint
FraigSig::one_count() const
{
return mOne;
}
// @brief 0 の数を返す.
inline
ymuint
FraigSig::zero_count() const
{
return (size() * 32) - mOne;
}
// @brief 内容を得る.
// @param[in] pos 位置番号 ( 0 <= pos < size() )
inline
ymuint32
FraigSig::pat(ymuint pos) const
{
return mBody[pos];
}
// @brief 内容を設定する.
// @note サイズがあっていることを前提としている.
inline
void
FraigSig::set(const vector<ymuint32>& src)
{
for (ymuint i = 0; i < size(); ++ i) {
mBody[i] = src[i];
}
calc_hash();
}
// @brief 内容をランダムにセットする.
inline
void
FraigSig::set_random(RandGen& randgen)
{
for (ymuint i = 0; i < size(); ++ i) {
mBody[i] = randgen.int32();
}
mBody[0] &= ~1U;
calc_hash();
}
// @brief ファンインのシグネチャから計算する.
inline
void
FraigSig::calc(const FraigSig& right,
bool right_inv,
const FraigSig& left,
bool left_inv)
{
if ( right_inv ) {
if ( left_inv ) {
for (ymuint i = 0; i < size(); ++ i) {
mBody[i] = ~(right.mBody[i] | left.mBody[i]);
}
}
else {
for (ymuint i = 0; i < size(); ++ i) {
mBody[i] = ~right.mBody[i] & left.mBody[i];
}
}
}
else {
if ( left_inv ) {
for (ymuint i = 0; i < size(); ++ i) {
mBody[i] = right.mBody[i] & ~left.mBody[i];
}
}
else {
for (ymuint i = 0; i < size(); ++ i) {
mBody[i] = right.mBody[i] & left.mBody[i];
}
}
}
calc_hash();
}
// @brief 等価比較
inline
bool
FraigSig::operator==(const FraigSig& right) const
{
for (ymuint i = 0; i < size(); ++ i) {
if ( mBody[i] != right.mBody[i] ) {
return false;
}
}
return true;
}
// @brief 否定したものが等価かどうか調べる.
inline
bool
FraigSig::ncomp(const FraigSig& right) const
{
for (ymuint i = 0; i < size(); ++ i) {
if ( mBody[i] != ~right.mBody[i] ) {
return false;
}
}
return true;
}
// @relates FraigSig
// @brief 非等価比較
inline
bool
operator!=(const FraigSig& left,
const FraigSig& right)
{
return !left.operator==(right);
}
// @brief 大小比較
inline
bool
FraigSig::operator<(const FraigSig& right) const
{
for (ymuint i = 0; i < size(); ++ i) {
if ( mBody[i] < right.mBody[i] ) {
return true;
}
}
return false;
}
// @relates FraigSig
// @brief 大小比較 (gt)
inline
bool
operator>(const FraigSig& left,
const FraigSig& right)
{
return right.operator<(left);
}
// @relates FraigSig
// @brief 大小比較 (le)
inline
bool
operator<=(const FraigSig& left,
const FraigSig& right)
{
return !right.operator<(left);
}
// @relates FraigSig
// @brief 大小比較 (ge)
inline
bool
operator>=(const FraigSig& left,
const FraigSig& right)
{
return !left.operator<(right);
}
// @brief ハッシュ値を返す.
inline
ymuint
FraigSig::hash() const
{
return mHash;
}
// @brief ハッシュ値を計算する.
inline
void
FraigSig::calc_hash()
{
mHash = 0;
mOne = 0;
if ( mBody[0] & 1U ) {
// 逆相
for (ymuint i = 0; i < size(); ++ i) {
mHash ^= (~mBody[i]) * mPrimes[i];
mOne += count_ones(mBody[i]);
}
mSize |= 1U;
}
else {
for (ymuint i = 0; i < size(); ++ i) {
mHash ^= mBody[i] * mPrimes[i];
mOne += count_ones(mBody[i]);
}
}
}
// @brief pat 中の 1 の数を数える.
inline
ymuint
FraigSig::count_ones(ymuint32 pat)
{
const ymuint32 mask1 = 0x55555555;
const ymuint32 mask2 = 0x33333333;
const ymuint32 mask4 = 0x0f0f0f0f;
const ymuint32 mask8 = 0x00ff00ff;
const ymuint32 mask16 = 0x0000ffff;
pat = (pat & mask1) + ((pat >> 1) & mask1);
pat = (pat & mask2) + ((pat >> 2) & mask2);
pat = (pat & mask4) + ((pat >> 4) & mask4);
pat = (pat & mask8) + ((pat >> 8) & mask8);
pat = (pat & mask16) + ((pat >> 16) & mask16);
return pat;
}
// @brief 内容を出力する.
inline
void
FraigSig::dump(ostream& s) const
{
for (ymuint i = 0; i < size(); ++ i) {
s << hex << mBody[i];
}
s << dec;
}
END_NAMESPACE_YM_AIG
#endif // LIBYM_AIG_FRAIGSIG_H
| true |
69784ba191b59737c8ea0a772c6734ab67d57df9 | C++ | jeffreypersons/CS153-Compilers | /Materials/C++ Code/CH16/wci/backend/compiler/generators/CompoundGenerator.h | UTF-8 | 1,111 | 2.609375 | 3 | [] | no_license | /**
* <h1>CompoundGenerator</h1>
*
* <p>Generate code for a compound statement.</p>
*
* <p>Copyright (c) 2017 by Ronald Mak</p>
* <p>For instructional purposes only. No warranties.</p>
*/
#ifndef COMPOUNDGENERATOR_H_
#define COMPOUNDGENERATOR_H_
#include <string>
#include "StatementGenerator.h"
#include "../CodeGenerator.h"
#include "../../../intermediate/ICodeNode.h"
namespace wci { namespace backend { namespace compiler { namespace generators {
using namespace std;
using namespace wci::intermediate;
using namespace wci::backend::compiler;
class CompoundGenerator : public StatementGenerator
{
public:
/**
* Constructor.
* @param the parent executor.
*/
CompoundGenerator(CodeGenerator *parent);
/**
* Generate code for a statement.
* To be overridden by the specialized statement executor subclasses.
* @param node the root node of the statement.
* @throw a string message if an error occurred.
*/
void generate(ICodeNode *node) throw (string);
};
}}}} // namespace wci::backend::compiler::generators
#endif /* COMPOUNDGENERATOR_H_ */
| true |
83673f3bc9d8e018b56d8e9207863529a6ef8493 | C++ | qooldeel/adonis | /sparse/gprime.cc | UTF-8 | 7,113 | 2.53125 | 3 | [] | no_license |
#include <iostream>
#include <vector>
#include <set>
#include <cassert>
#include <string>
/**
* \brief Compute G' = aI - bhS'
* This is only for square matrices. Actually, the sizes of the sparsity
* patterns for both the Jacobian S' and G' are equal; the only difference lies in the fact
* that G' posseses non-vanishing diagonal entries, thus the sets of each row differ by
* at most one entry.
*
*/
template<class PATT, class VEC, class T>
inline void create_G_prime(VEC& Gprime, const VEC& Jac, const PATT& pattNewt, const PATT& pattJac, const T& h, const T& a = 1, const T& b = 1){
assert(pattNewt.size() == pattJac.size());
typedef std::size_t SizeType;
typedef typename PATT::value_type SetType;
typedef typename SetType::const_iterator ConstSetIterType;
bool sameSize = false;
T bh = b*h;
SizeType k = 0; //positioin in G'
SizeType diffsz = 0;
ConstSetIterType pattJacIt,
setIt;
SizeType idx;
for(SizeType i = 0; i < pattNewt.size(); ++i){
pattJacIt = pattJac[i].begin();
(pattNewt[i].size() != pattJac[i].size()) ? sameSize = false : sameSize = true;
for(setIt = pattNewt[i].begin(); setIt != pattNewt[i].end(); ++setIt){
if(i == *setIt){
diffsz += pattNewt[i].size() - pattJac[i].size(); //either zero or one
if(!sameSize){
Gprime[k] = a*1;
}
else{
Gprime[k] = a*1 - bh*Jac[k-diffsz];
}
}
else{
Gprime[k] = -bh*Jac[k-diffsz];
}
k++;
}
}
}
template<class SVEC>
inline void print_pattern(const SVEC& p, const std::string& s = std::string()){
typedef typename SVEC::value_type SetType;
typedef typename SetType::const_iterator SetItType;
if(s.size() != 0)
std::cout << "Sparsity pattern \""<< s << "\":"<< std::endl;
for(std::size_t i = 0; i < p.size(); ++i){
std::cout << i << ".) ";
for(SetItType it = p[i].begin(); it != p[i].end(); ++it){
std::cout << *it << " ";
}
std::cout << std::endl;
}
}
template<class OBJ>
inline void print_me(const OBJ& obj, const std::string& str = std::string()){
if(str.size() != 0)
std::cout << str << " = ";
std::cout << "[ ";
for(typename OBJ::const_iterator it = obj.begin(); it != obj.end(); ++it)
std::cout << *it << " ";
std::cout<<"]"<< std::endl;
}
template<class SVEC>
inline void form_diag(SVEC& p){
for(std::size_t i = 0; i < p.size(); ++i){
p[i].insert(i); //no double insertion possible
}
}
using namespace std;
int main(){
cout << "Test Me:" << endl;
int m = 4,
nnzJac = 7,
nnz = 8; //in G'
typedef vector<double> ValVecType;
typedef vector<set<size_t> > VecSetType;
VecSetType pattJac1(4), pattNewt;
pattJac1[0].insert(0); pattJac1[0].insert(1);
pattJac1[2].insert(1); pattJac1[2].insert(2); pattJac1[2].insert(3);
pattJac1[3].insert(1); pattJac1[3].insert(3);
cout << endl;
print_pattern(pattJac1,"pattJac1");
pattNewt = pattJac1;
form_diag(pattNewt);
print_pattern(pattNewt,"pattNewt");
double a[] = {4.5,-1.5, 0.5, 2.95, -0.75, 2.65, -0.95};
ValVecType jac(a,a+nnzJac),
Gprime(nnz);
double h = 1./4;
create_G_prime(Gprime, jac, pattNewt,pattJac1,h);
double tst[] = {1-h*4.5, -h*(-1.5), 1, -h*0.5, 1-h*2.95, -h*(-0.75), -h*2.65,1-h*(-0.95)};
ValVecType test1(tst,tst+nnz);
print_me(Gprime, "G'");
print_me(test1, "a ");
cout << endl << "------------------ TEST 2 --------------------"<<endl;
m = 4;
nnzJac = 6;
nnz = 8; //in G'
VecSetType pattJac2(4), pattNewt2;
pattJac2[0].insert(1);
pattJac2[2].insert(1); pattJac2[2].insert(2); pattJac2[2].insert(3);
pattJac2[3].insert(1); pattJac2[3].insert(3);
cout << endl;
print_pattern(pattJac2,"pattJac2");
pattNewt2 = pattJac2;
form_diag(pattNewt2);
print_pattern(pattNewt2,"pattNewt2");
double a2[] = {-1.5, 0.5, 2.95, -0.75, 2.65, -0.95};
ValVecType jac2(a2,a2+nnzJac),
Gprime2(nnz);
create_G_prime(Gprime2, jac2, pattNewt2,pattJac2,h);
double tst2[] = {1,-h*(-1.5), 1, -h*0.5, 1-h*2.95, -h*(-0.75), -h*2.65,1-h*(-0.95)};
ValVecType test2(tst2,tst2+8);
print_me(Gprime2, "G'");
print_me(test2, "a ");
cout << endl << "------------------ TEST 3 --------------------"<<endl;
m = 6;
nnzJac = 13;
nnz = 17; //in G'
VecSetType pattJac3(m), pattNewt3;
pattJac3[0].insert(2); pattJac3[0].insert(4);
pattJac3[1].insert(1); pattJac3[1].insert(3);
pattJac3[2].insert(0); pattJac3[2].insert(3); pattJac3[2].insert(4);pattJac3[2].insert(5);
pattJac3[3].insert(1); pattJac3[3].insert(2);
pattJac3[4].insert(4);
pattJac3[5].insert(0); pattJac3[5].insert(2);
cout << endl;
print_pattern(pattJac3,"pattJac3");
pattNewt3 = pattJac3;
form_diag(pattNewt3);
print_pattern(pattNewt3,"pattNewt3");
double a3[] = {0.45, 3.5, -5.6, 8.5, 0.75, 0.005, -0.75, 6.23, 9.01, -3.4, -0.7, 1.4, 0.3};
ValVecType jac3(a3,a3+nnzJac),
Gprime3(nnz);
create_G_prime(Gprime3, jac3, pattNewt3,pattJac3,h);
double tst3[] = {1, -h*a3[0], -h*a3[1],
1-h*a3[2], -h*a3[3],
-h*a3[4], 1, -h*a3[5], -h*a3[6], -h*a3[7],
-h*a3[8],-h*a3[9],1,
1-h*a3[10],
-h*a3[11], -h*a3[12], 1};
ValVecType test3(tst3,tst3+nnz);
print_me(Gprime3, "G'");
print_me(test3, "a ");
cout << endl << "------------------ TEST 4 --------------------"<<endl;
m = 4;
nnzJac = 4;
nnz = 6; //in G'
VecSetType pattJac4(m), pattNewt4;
pattJac4[0].insert(0); pattJac4[0].insert(1);
pattJac4[3].insert(0); pattJac4[3].insert(3);
cout << endl;
print_pattern(pattJac4,"pattJac4");
pattNewt4 = pattJac4;
form_diag(pattNewt4);
print_pattern(pattNewt4,"pattNewt4");
double a4[] = {-2.5, 14.23, -0.44, 3.05};
ValVecType jac4(a4,a4+nnzJac),
Gprime4(nnz);
create_G_prime(Gprime4, jac4, pattNewt4,pattJac4,h);
double tst4[] = {1-h*a4[0],-h*a4[1],
1,
1,
-h*a4[2], 1-h*a4[3]};
ValVecType test4(tst4,tst4+nnz);
print_me(Gprime4, "G'");
print_me(test4, "a ");
cout << endl << "------------------ TEST 5 --------------------"<<endl;
m = 5;
nnzJac = 6;
nnz = 9; //in G'
VecSetType pattJac5(m), pattNewt5;
pattJac5[1].insert(1); pattJac5[1].insert(4);
pattJac5[3].insert(0); pattJac5[3].insert(1); pattJac5[3].insert(3); pattJac5[3].insert(4);
cout << endl;
print_pattern(pattJac5,"pattJac5");
pattNewt5 = pattJac5;
form_diag(pattNewt5);
print_pattern(pattNewt5,"pattNewt5");
double a5[] = {0.07, 1.32, -0.91, 0.31, 11.9, -5.32};
ValVecType jac5(a5,a5+nnzJac),
Gprime5(nnz);
create_G_prime(Gprime5, jac5, pattNewt5,pattJac5,h);
double tst5[] = {1,
1-h*a5[0], -h*a5[1],
1,
-h*a5[2], -h*a5[3], 1-h*a5[4],-h*a5[5],
1};
ValVecType test5(tst5,tst5+nnz);
print_me(Gprime5, "G'");
print_me(test5, "a ");
return 0;
}
| true |
7d9d7c194ecd80ec0c4a7dd7b246e2cc7e3ea1b1 | C++ | developer0hye/Algo-0hye | /problems/11048_이동하기/boj_11048.cpp | UTF-8 | 952 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main()
{
int N, M;
cin >> N >> M;
vector<vector<int>> candy_maze(N + 1, vector<int>(M+1));
vector<vector<int>> dp_table(N + 1, vector<int>(M+1));
for(int n = 1; n <= N; n++)
for(int m = 1; m <= M; m++)
cin >> candy_maze[n][m];
for(int n = 1; n <= N; n++)
for(int m = 1; m <= M; m++)
{
if(n==1 && m ==1)
{
dp_table[1][1] = candy_maze[1][1];
}
else
{
int temp = 0;
if(n > 1) temp = dp_table[n-1][m];
if(m > 1) temp = max(temp, dp_table[n][m-1]);
if(m > 1 && m > 1) temp = max(temp, dp_table[n-1][m-1]);
dp_table[n][m] = temp + candy_maze[n][m];
}
}
cout << dp_table[N][M];
return 0 ;
}
| true |
b8eb12da8136738e39934a62bab96a94db2820b2 | C++ | Himura2la/Arduino | /TSL2561/TSL2561.ino | UTF-8 | 1,538 | 2.59375 | 3 | [] | no_license | /* SFE_TSL2561
!!! 3V3 !!!
SDA -> A4
SCL -> A5
For more information see the hookup guide at:
*/
#include <SFE_TSL2561.h>
#include <Wire.h>
SFE_TSL2561 light;
boolean gain = 0; //0 = X1, 1 = X16;
// If time = 0, integration will be 13.7ms
// If time = 1, integration will be 101ms
// If time = 2, integration will be 402ms
// If time = 3, use manual start / stop to perform your own integration
unsigned char time = 1;
unsigned int ms; // Integration ("shutter") time in milliseconds
void setup() {
Serial.begin(9600);
light.begin();
light.setTiming(gain, time, ms);
light.setPowerUp();
}
void loop() {
delay(ms);
unsigned int data0, data1;
if (light.getData(data0, data1)) {
double lux; // Resulting lux value
if (light.getLux(gain, ms, data0, data1, lux))
Serial.println(lux);
else {
Serial.print(lux);
Serial.println(" [Over range]");
}
}
else { // getData() returned false because of an I2C error, inform the user.
byte error = light.getError();
printError(error);
}
}
void printError(byte error) {
Serial.print("[ERROR ");
Serial.print(error, DEC);
Serial.print("]");
switch(error) {
case 0: Serial.println("success"); break;
case 1: Serial.println("data too long for transmit buffer"); break;
case 2: Serial.println("received NACK on address (disconnected?)"); break;
case 3: Serial.println("received NACK on data"); break;
case 4: Serial.println("other error"); break;
default: Serial.println("unknown error");
}
}
| true |
6852e533cbafd55f9524408cba69fca9bfcc663b | C++ | sunset1995/ACM_ICPC_prac | /ACM-ICPC/Tehran2014/B.cpp | UTF-8 | 1,175 | 2.953125 | 3 | [] | no_license | #include <cstdio>
using namespace std;
long long dis2(long long r1, long long g1, long long b1,
long long r2, long long g2, long long b2) {
long long r = r1 - r2;
long long g = g1 - g2;
long long b = b1 - b2;
return r*r + g*g + b*b;
}
int main() {
const char colorName[16][20] = {
"White",
"Silver",
"Gray",
"Black",
"Red",
"Maroon",
"Yellow",
"Olive",
"Lime",
"Green",
"Aqua",
"Teal",
"Blue",
"Navy",
"Fuchsia",
"Purple"
};
long long c[16][3] = {
{255, 255, 255},
{192, 192, 192},
{128, 128, 128},
{0, 0, 0 },
{255, 0, 0 },
{128, 0, 0 },
{255, 255, 0 },
{128, 128, 0 },
{0, 255, 0 },
{0, 128, 0 },
{0, 255, 255},
{0, 128, 128},
{0, 0, 255},
{0, 0, 128},
{255, 0, 255},
{128, 0, 128}
};
int r, g, b;
while( scanf("%d%d%d", &r, &g, &b)!=EOF ) {
if( r==-1 && g==-1 && b==-1 )
break;
int minid = 0;
long long mind = dis2(c[0][0], c[0][1], c[0][2], r, g, b);
for(int i=1; i<16; ++i) {
long long nowd = dis2(c[i][0], c[i][1], c[i][2], r, g, b);
if( nowd < mind ) {
mind = nowd;
minid = i;
}
}
puts(colorName[minid]);
}
return 0;
}
| true |
5e5c34e2ba845f02825cdb0706eda06a870ba766 | C++ | IslamAhmed1092/PaintForKids | /Actions/SelectAction.cpp | UTF-8 | 1,379 | 2.609375 | 3 | [] | no_license | #include "SelectAction.h"
#include "..\ApplicationManager.h"
#include "..\GUI\input.h"
#include "..\GUI\Output.h"
SelectAction::SelectAction(ApplicationManager *pApp):Action(pApp)
{
}
void SelectAction::ReadActionParameters()
{
Output* pOut = pManager->GetOutput();
Input* pIn = pManager->GetInput();
pOut->PrintMessage("select a figure");
do
{
pIn->GetPointClicked(p.x, p.y);
}while (p.y<UI.ToolBarHeight);
pOut->ClearStatusBar();
}
//Execute the action
void SelectAction::Execute()
{
//This action needs to read some parameters first
ReadActionParameters();
CFigure* selected = pManager->GetFigure(p.x, p.y);
Output* pOut = pManager->GetOutput();
if(selected == NULL)
{
if(pManager->GetSelected() != NULL)
{
pOut->ClearStatusBar();
pManager->GetSelected()->SetSelected(false);
pManager->SelectFig(NULL);
}
}
else
{
if(pManager->GetSelected() == NULL)
{
selected->SetSelected(true);
pManager->SelectFig(selected);
selected->PrintInfo(pOut);
}
else
{
if (selected == pManager->GetSelected())
{
selected->SetSelected(false);
pManager->SelectFig(NULL);
pOut->ClearStatusBar();
}
else
{
pManager->GetSelected()->SetSelected(false);
selected->SetSelected(true);
pManager->SelectFig(selected);
selected->PrintInfo(pOut);
}
}
}
}
SelectAction::~SelectAction(void)
{
}
| true |
e5bcfe73bfc106c45810d8553081e223f1f5d6fe | C++ | xiaoguozhi/The-Cpp-Workshop | /Chapter10/Chapter10_Examples_Test.cpp | UTF-8 | 2,045 | 3.328125 | 3 | [
"MIT"
] | permissive | //Chapter 10 : Example 1
#include "pch.h"
#include <iostream>
#include <memory>
#include "gtest/gtest.h"
using namespace std;
std::ostringstream out;
class MyBaseClass
{
public:
virtual void PrintMessage()
{
out << "Hello ";
}
};
class MyDerivedClass : public MyBaseClass
{
public:
void PrintMessage() override
{
out << "World!";
}
};
std::string TestCase() {
MyDerivedClass obj;
obj.PrintMessage();
return out.str();
}
TEST(Chapter10, Example1) {
EXPECT_EQ("World!", TestCase());
}
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
// Chapter 10 : Example 2
#include "pch.h"
#include <iostream>
#include <memory>
#include "gtest/gtest.h"
using namespace std;
std::ostringstream out;
class MyBaseClass
{
public:
virtual void PrintMessage()
{
out << "Hello ";
}
};
class MyDerivedClass : public MyBaseClass
{
public:
void PrintMessage() override
{
MyBaseClass::PrintMessage();
out << "World!";
}
};
std::string TestCase() {
MyDerivedClass obj;
obj.PrintMessage();
return out.str();
}
TEST(Chapter10, Example2) {
EXPECT_EQ("Hello World!", TestCase());
}
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
//Chapter 10 : Example 3
#include "pch.h"
#include <iostream>
#include <memory>
#include "gtest/gtest.h"
using namespace std;
std::ostringstream out;
class MyClassA
{
public:
virtual std::string GetString() = 0;
};
class MyClassB : public MyClassA
{
public:
std::string GetString() override
{
return "Hello ";
}
};
class MyClassC : public MyClassA
{
public:
std::string GetString() override
{
return " world!";
}
};
std::string TestCase() {
MyClassA* myClass = new MyClassB();
out << myClass->GetString();
myClass = new MyClassC();
out << myClass->GetString();
return out.str();
}
TEST(Chapter10, Example3) {
EXPECT_EQ("Hello world!", TestCase());
}
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | true |
5206b4e25bd155a39a0988b6c2537eb97cbf6046 | C++ | SemyonTelegin/LABAS | /Laba7.cpp | UTF-8 | 2,162 | 3.515625 | 4 | [] | no_license | #include <stdio.h>
#include <malloc.h>
int** allocate_matrix(int height, int width);
void print_matrix(int** matrix, int height, int width);
void input_matrix(int** matrix, int height, int width);
void free_RAM(int** M, int height, int width);
void exchange_valules(int* x, int* y);
void sort(int** M, int height, int width);
int main()
{
printf("Set the height of the matrix:");
int height, width;
scanf_s("%d", &height);
printf("Set the width of the matrix:");
scanf_s("%d", &width);
int** Mamix = allocate_matrix(height, width);
input_matrix(Mamix, height, width);
sort(Mamix, height, width);
print_matrix(Mamix, height, width);
free_RAM(Mamix, height, width);
return 0;
}
int** allocate_matrix(int height, int width)
{
int** matrix = (int**)malloc(height * sizeof(int));
for (int i = 0; i < height; ++i)
{
matrix[i] = (int*)malloc(width * sizeof(int));
}
if (NULL == matrix) printf("NO MATRIX!!!\n");
return matrix;
}
void input_matrix(int** matrix, int height, int width)
{
printf("Set the matrix size of %d * %d:\n", height, width);
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
scanf_s("%d", &matrix[i][j]);
}
}
}
void print_matrix(int** matrix, int height, int width)
{
printf("Changed matrix is:\n");
for (int i = 0; i < height; ++i)
{
if (0 == i % 2)
{
for (int j = 0; j < width; ++j)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
else
{
for (int j = width - 1; j > -1; j -= 1)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
}
void free_RAM(int** M, int height, int width)
{
for (int i = 0; i < height; ++i)
{
free(M[i]);
}
free(M);
}
void exchange_valules(int* x, int* y)
{
*x = *x + *y;
*y = *x - *y;
*x = *x - *y;
}
void sort(int** M, int height, int width)
{
for (int i = 0; i < height * width - 1; i++)
{
for (int j = 0; j < height * width - 1 - i; ++j)
if (M[j / width][j % width] > M[(j + 1) / width][(j + 1) % width])
exchange_valules(&M[j / width][j % width], &M[(j + 1) / width][(j + 1) % width]);
}
}
| true |
2803425fdb5fa947d0372d2afe614b24cd35fda5 | C++ | mitDarkMomo/bancor | /src/bancor.cpp | UTF-8 | 15,501 | 2.71875 | 3 | [] | no_license | #include <eosiolib/eosio.hpp>
#include <eosiolib/print.hpp>
#include <eosiolib/asset.hpp>
#include <eosiolib/action.hpp>
#include <eosiolib/symbol.hpp>
#include <math.h>
#include <eosio.token/eosio.token.hpp>
using namespace eosio;
using namespace std;
class [[eosio::contract]] bancor : public eosio::contract {
public:
using contract::contract;
//进行 eos 与 inve 的转换
[[eosio::action]]
void transfer(name from, name to, asset quantity, string memo) {
//1. 判断 to 为自己;本人交易;交易量大于 0
print("transfer ", quantity, " from: ", from, "\t\t");
if(from == _self) { //若是自己转账的通知则放行
return;
}
if(from == name("intervalue11") && memo == "charge") {
return;
}
eosio_assert(to == _self, "should transfer to 'bancor'");
require_auth(from); //必须是调用者本人
eosio_assert(quantity.amount > 0, "show me the money" );
//2. 根据 asset 判断转入的是 eos 还是 inve
//3. 若为 eos,则买 inve
//4. 若为 inve,则卖 inve
if(quantity.symbol == symbol("EOS", 4)) {
buy(from, quantity);
} else if(quantity.symbol == symbol("INVE",4)) {
sell(from, quantity);
} else {
print("can only accept 'EOS' or 'INVE'\t\t");
return;
}
}
//更新 CW 的action:
[[eosio::action]]
void setratio(uint64_t cw) {
//1. 参数验证
require_auth(_self); //必须是合约账户
eosio_assert(cw <= 1000, "ratio should be less than 1000!");
//2. 更新
auto balance = token::get_balance(name("eosio.token"), _self, symbol_code("EOS")).amount;
//设置 cw 之前必须给 bancor 转入 eos
eosio_assert(balance > 0, "should charge eos before setratio!");
auto supply = token::get_balance(name("intervalue11"), _self, symbol_code("INVE")).amount;
asset inve = asset(supply, symbol("INVE", 4));
ratio_index ratios(_self, _self.value);
auto ratio = ratios.find(0);
if(ratio == ratios.end()) { //若未设置过 CW
ratios.emplace(_self, [&](auto& r) {
r.ratioid = ratios.available_primary_key();
r.value = cw;
r.supply = inve;
});
}else { //若已经设置过 CW
ratios.modify(ratio, _self, [&](auto &r) {
r.value = cw;
});
}
}
//充值 eos 或者 inve
[[eosio::action]]
void charge(name payer, asset quantity) {
//1. 判断 payer 为调用者本人且仅为 intervalue11;交易量大于 0
require_auth(payer); //必须是调用者本人
eosio_assert(payer == name("intervalue11"), "only 'intervalue11' can charge");
eosio_assert(quantity.amount > 0, "show me the money" );
//2. 根据 asset 判断转入的是 eos 还是 inve,并通过内联调用转账
name account = name("");
if(quantity.symbol == symbol("EOS", 4)) {
account = name("eosio.token");
} else if(quantity.symbol == symbol("INVE",4)) {
account = name("intervalue11");
// 增加 inve 供应量
ratio_index ratios(_self, _self.value);
auto ratio = ratios.find(0);
asset oldsupply = ratio -> supply;
auto newamount = oldsupply.amount + quantity.amount;
ratios.modify(ratio, _self, [&](auto &r) {
r.supply = asset(newamount, symbol("INVE", 4));
});
}
if(account != name("")) {
action(
permission_level{ payer, name("active")},
account,
name("transfer"),
std::make_tuple(
payer,
_self,
quantity,
std::string("charge"))
).send();
print("successfully charge ", quantity, " by ", payer);
}
}
//初始化数据表
// [[eosio::action]]
// void setinit() {
// ratio_index ratios(_self, _self.value);
// for(auto itr = ratios.begin(); itr != ratios.end();) {
// itr = ratios.erase(itr);
// }
// }
private:
//购买 token 的action:
void buy(name buyer, asset deposit) {
//1. 参数验证
print("buy token from: ", buyer, " of ", deposit, "\t\t");
//2. 计算兑换数量
double balance = 0;
double supply = 0;
double deposit_amount = deposit.amount;
uint64_t cw = 0;
//查询 bancor 合约中的 eos 抵押总量
auto eos = token::get_balance(name("eosio.token"), _self, symbol_code("EOS"));
balance = eos.amount;
eosio_assert(balance > 0, "should charge eos before buy inve");
print("balance of eos in bancor is: ", eos, "\t\t");
// //查询 inve 合约中的 inve 发行总量
// auto inve = token::get_supply(name("intervalue11"), symbol_code("INVE"));
// supply = inve.amount;
// print("supply of INVE is: ", inve, "\t\t");
ratio_index ratios(_self, _self.value);
auto ratio = ratios.find(0);
//必须先设置 CW
eosio_assert(ratio != ratios.end(), "set ratio first!");
cw = ratio -> value;
print("ratio of bancor is: ", cw, "\t\t");
//查询 bancor 合约中的 inve 供应量
supply = (ratio -> supply).amount;
eosio_assert(supply > 0, "should charge inve before buy inve");
print("supply of INVE is: ", supply, "\t\t");
//计算出购买的 token 数量
double smart_token = calculate_purchase_return(balance, deposit_amount, supply, cw);
print("purchased token amount is: ", smart_token, "\t\t");
// //3. 增发智能 token
// if(smart_token > 0) {
// //增发 token
// asset inve = asset(smart_token, symbol("INVE", 4));
// action(
// permission_level{ name("intervalue11"), name("active")},
// name("intervalue11"),
// name("issue"),
// std::make_tuple(
// buyer,
// inve,
// std::string("issue by bancor"))
// ).send();
// print("successfully bought ", inve, " with ", deposit);
// }
//3. 增发智能 token
auto amount = supply + smart_token;
ratios.modify(ratio, _self, [&](auto &r) {
r.supply = asset(amount, symbol("INVE", 4));
});
//4. 若 bancor 合约中 inve 足够,则转出 inve;否则从 intervalue11获取
if(smart_token > 0) {
auto inve_in_bancor = token::get_balance(name("intervalue11"), _self, symbol_code("INVE"));
auto inve_amount = inve_in_bancor.amount;
//转出 token
asset inve = asset(smart_token, symbol("INVE", 4));
if(inve_amount >= smart_token) { // bancor 合约中有足够的 inve
action(
permission_level{ _self, name("active")},
name("intervalue11"),
name("transfer"),
std::make_tuple(
_self,
buyer,
inve,
std::string("for buy inve"))
).send();
}else {
action(
permission_level{ name("intervalue11"), name("active")},
name("intervalue11"),
name("transfer"),
std::make_tuple(
name("intervalue11"),
buyer,
inve,
std::string("for buy inve"))
).send();
}
print("successfully bought ", inve, " with ", deposit);
}
}
//卖出 token 的action:
void sell(name seller, asset sell) {
//1. 参数验证
print("sell token from: ", seller, " of ", sell, "\t\t");
//2. 计算兑换数量
double balance = 0;
double supply = 0;
double sell_amount = sell.amount;
uint64_t cw = 0;
//查询 bancor 合约中的 eos 抵押总量
auto eos = token::get_balance(name("eosio.token"), _self, symbol_code("EOS"));
balance = eos.amount;
eosio_assert(balance > 0, "should charge eos before sell inve");
eosio_assert(sell.symbol == symbol("INVE", 4), "can only sell INVE");
print("balance of eos in bancor is: ", eos, "\t\t");
// //查询 inve 合约中的 inve 发行总量
// auto inve = token::get_supply(name("intervalue11"), symbol_code("INVE"));
// supply = inve.amount;
// print("supply of INVE is: ", inve, "\t\t");
ratio_index ratios(_self, _self.value);
auto ratio = ratios.find(0);
//必须先设置 CW
eosio_assert(ratio != ratios.end(), "set ratio first!");
cw = ratio -> value;
print("ratio of bancor is: ", cw, "\t\t");
//查询 bancor 合约中的 inve 供应量
supply = (ratio -> supply).amount;
eosio_assert(supply > 0, "should charge inve before buy inve");
print("supply of INVE is: ", supply, "\t\t");
//计算出卖出 token 获得的 eos 数量
double eos_token = calculate_sale_return(balance, sell_amount, supply, cw);
eosio_assert(balance >= eos_token, "not enough eos for sell inve");
print("returned eos amount is: ", eos_token, "\t\t");
// //3. 销毁 inve 并转账 eos
// if(eos_token > 0) {
// //将要销毁的 token 转给发行者
// if(seller != name("intervalue11")) { //不能转给自己
// action(
// permission_level{ _self, name("active")},
// name("intervalue11"),
// name("transfer"),
// std::make_tuple(
// _self,
// name("intervalue11"), //issuer of inve token
// sell,
// std::string("send inve to be retired to issuer!\t\t"))
// ).send();
// }
// //销毁 token
// action(
// permission_level{ name("intervalue11"), name("active")},
// name("intervalue11"),
// name("retire"),
// std::make_tuple(
// sell,
// std::string("retire by bancor\t\t"))
// ).send();
// //转账 EOS
// asset eos = asset(eos_token, symbol("EOS", 4));
// action(
// permission_level{ _self, name("active")},
// name("eosio.token"),
// name("transfer"),
// std::make_tuple(
// _self,
// seller,
// eos,
// std::string("for sell inve"))
// ).send();
// print("successfully sold ", eos, " of ", sell);
// }
//3. 减少智能 token 供应量
auto amount = supply - sell_amount;
eosio_assert(amount > 0, "inve exceeds supply!");
ratios.modify(ratio, _self, [&](auto &r) {
r.supply = asset(amount, symbol("INVE", 4));
});
//3. 转账 eos
if(eos_token > 0) {
//转账 EOS
asset eos = asset(eos_token, symbol("EOS", 4));
action(
permission_level{ _self, name("active")},
name("eosio.token"),
name("transfer"),
std::make_tuple(
_self,
seller,
eos,
std::string("for sell inve"))
).send();
print("successfully sold ", eos, " of ", sell);
}
}
double calculate_purchase_return(double balance, double deposit_amount, double supply, uint64_t ratio) {
double R(supply);
double C(balance - deposit_amount);
double F = (float)ratio / 1000.0;
double T(deposit_amount);
double ONE(1.0);
double E = R * (pow(ONE + T / C, F) - ONE);
return E;
}
double calculate_sale_return(double balance, double sell_amount, double supply, uint64_t ratio) {
double R(supply);
double C(balance);
double F = 1000.0 / (float)ratio;
double E(sell_amount);
double ONE(1.0);
double T = C * (pow(ONE + E/R, F) - ONE);
return T;
}
//任务认领相关的表:
struct [[eosio::table]] ratio {
uint64_t ratioid;
uint64_t value; //cw 的实际值,取值范围[0-1000],表示千分之几
asset supply; //记录的 inve 供应量
uint64_t primary_key() const {
return ratioid;
}
EOSLIB_SERIALIZE(ratio, (ratioid)(value)(supply))
};
typedef eosio::multi_index<name("ratio"), ratio> ratio_index;
};
#define EOSIO_DISPATCH_CUSTOM(TYPE, MEMBERS) \
extern "C" { \
void apply( uint64_t receiver, uint64_t code, uint64_t action ) { \
auto self = receiver; \
if( \
(code == self && action != name("transfer").value ) || \
(code == name("eosio.token").value && action == name("transfer").value) || \
action == name("onerror").value || \
(code == name("intervalue11").value && action == name("transfer").value)) \
{ \
switch( action ) { \
EOSIO_DISPATCH_HELPER( TYPE, MEMBERS ) \
} \
/* does not allow destructor of this contract to run: eosio_exit(0); */ \
} \
} \
} \
// EOSIO_DISPATCH_CUSTOM(bancor, (transfer)(setratio)(charge)(setinit))
EOSIO_DISPATCH_CUSTOM(bancor, (transfer)(setratio)(charge)) | true |
8f47e1baa9541b6dccd9c5499024cc5109b0ee40 | C++ | trunghai95/MyCPCodes | /Kattis/digitsum.cpp | UTF-8 | 608 | 3.046875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll sumofdigits(ll n)
{
if (n < 10) return n;
return sumofdigits(n/10) + (n%10);
}
ll digitsum(ll n)
{
if (n < 10)
return (n * (n + 1) / 2);
ll res = (n/10) * 45 + digitsum(n % 10);
res += ((n % 10) + 1) * sumofdigits(n/10) + digitsum(n/10 - 1) * 10;
return res;
}
int main()
{
int test;
ll a, b;
cin >> test;
while (test--)
{
cin >> a >> b;
ll x = digitsum(b);
ll y = digitsum(a-1);
cout << digitsum(b) - digitsum(a-1) << endl;
}
return 0;
}
| true |
cd7a7ae6f2524082aae4b1c0cae2924c8630b278 | C++ | azureitstepkharkov/33pr11gitserver | /Exam/Работы_для_проверки/Evgeniy Vanyan/Adress/Adress/AdressInfo.h | UTF-8 | 567 | 3.125 | 3 | [] | no_license | #pragma once
#include <string>
using namespace std;
class AdressInfo
{
private:
AdressInfo(const AdressInfo& obj) {};
protected:
string city;
string street;
string home_number;
int office_number;
public:
AdressInfo() {};
AdressInfo(string city, string street, string home_number, int office_number);
friend ostream& operator<<(ostream& os, AdressInfo info)
{
os << "City: " << info.city << " Street: "
<< info.street << " Home Number: "
<< info.home_number << " Office Number: "
<< info.office_number << endl;
return os;
}
};
| true |
eaeeba9e9ed8fcc85e65693654d936f2a1a5f062 | C++ | mohitjaisal/Competitive-Programing-Submissions | /atcoder/abc167/B.cpp | UTF-8 | 560 | 2.953125 | 3 | [
"Apache-2.0"
] | permissive | #include <bits/stdc++.h>
using namespace std;
int main() {
// input 1
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout << fixed << setprecision(15);
// definign variables
int a, b, c, k;
// input in variables
cin >> a >> b >> c >> k;
// logical execution
int sum = 0;
for (int i = 0; i < k; ++i) {
// if else looping
if (a > 0) {
++sum;
--a;
// el-if cond.
} else if (b > 0) {
--b;
} else {
--sum;
}
}
// print answe
cout << sum << '\n';
// return value
return 0;
} | true |
59507bde40b8d95963e99a7e8e659799073a4698 | C++ | Aniganesh/100daysofcode | /Sum_Primes.cpp | UTF-8 | 878 | 2.78125 | 3 | [] | no_license | // https://www.hackerearth.com/practice/math/number-theory/basic-number-theory-2/practice-problems/algorithm/sum-of-primes-7/
// 20-05-2020 Medium
#include<bits/stdc++.h>
#define MOD % 1000000007
typedef long long ll;
using namespace std;
int main(){
vector<bool> isPrime(9999999, true);
vector<ll> sumPrimes(9999999, 0);
ll tempSum = 0;
for(int i = 2; i < 9999999; ++i){
if(isPrime[i]){
tempSum += i;
for(int j = 2; j*i < 9999999; ++j){
isPrime[j*i] = false;
}
}
sumPrimes[i] = tempSum;
}
ll numQueries;
scanf("%lld", &numQueries);
while(numQueries--){
ll left, right;
scanf("%lld %lld", &left, &right);
// cout << sumPrimes[right] << " " << sumPrimes[left-1] << endl;
printf("%lld\n", sumPrimes[right]-sumPrimes[left-1]);
}
} | true |
20b19c75535f888ae230162736434aaa3e08193d | C++ | dreamJarvis/Problem_Solving | /string/test.cpp | UTF-8 | 2,449 | 3.1875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
// longest common subsequences
// recursive solution
int lcs(string str1, string str2){
if(str1.length()==0 || str2.length()==0)
return 0;
char ch1 = str1[0];
char ch2 = str2[0];
int count = 0;
if(ch1 == ch2) count = lcs(str1.substr(1), str2.substr(1)) + 1;
else count = max( lcs(str1.substr(1), str2), lcs(str1, str2.substr(1)) );
return count;
}
// memoisation : storing the repating values
int lcsMemo(string a, string b, int i, int j, unordered_map<string, int> &visited){
string key = to_string(i) + to_string(j);
if(i >= a.length() || j >= b.length())
return 0;
if(visited.count(key))
return visited[key];
char ch1 = a[i];
char ch2 = b[j];
int count = 0;
if(ch1 == ch2) count = lcsMemo(a, b, i+1, j+1, visited) + 1;
else count = max(lcsMemo(a, b, i+1, j, visited), lcsMemo(a, b, i, j+1, visited));
visited[key] = count;
return count;
}
int lcsMemoUTIL(string a, string b){
unordered_map<string, int> visited;
if(a.length() < b.length())
swap(a, b);
return lcsMemo(a, b, 0, 0, visited);
}
// dp solution
int lcsDP(string a, string b){
if(a.length() < b.length()){
swap(a, b);
}
int aLength = a.length();
int bLength = b.length();
vector<vector<int>> dp(bLength+1, vector<int>(aLength+1, 0)); // dp table
// fiiling the 1st row
for(int i = 0; i <= aLength; i++)
dp[0][i] = 0;
// filling the 1st column
for(int i = 0; i <= bLength; i++)
dp[i][0] = 0;
for(int i = 1; i <= bLength; i++){
for(int j = 1; j <= aLength; j++){
if(b[i-1] == a[j-1]) dp[i][j] = dp[i-1][j-1]+1;
else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
return dp[bLength][aLength];
}
// Driver program
int main(){
string a = "abcdefpppopoiqp";
string b = "cbfdlepoipipoqwepop";
// string a = "abcdef";
// string b = "hfcdle";
clock_t t1 = clock();
cout << lcs(a, b) << endl;
t1 = clock() - t1;
cout << "recursive : " << t1/60 << endl;
clock_t t2 = clock();
cout << lcsMemoUTIL(a, b) << endl;
t2 = clock() - t2;
cout << "memoisation : " << t2/60 << endl;
clock_t t3 = clock();
cout << lcsDP(a, b) << endl;
t3 = clock() - t3;
cout << "DP : " << t3/60 << endl;
return 0;
}
| true |
ce4f728a0925b196c28d271994695d74cedb3be2 | C++ | sakshamsomani2345/c-plus-plus-practice | /c++/cinget.cpp | UTF-8 | 436 | 2.859375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
char c;
int a=0;
int b=0;
c=cin.get();
int node=0;
while(c!='$'){
if(c>='a' && c<='z'){
a++;
}
if(c>='0' && c<='9'){
b++;
}
else if (c== ' ' || c =='\n' || c == '\t')
{ node++;}
c=cin.get();
}
cout<<a<<" "<<b<<" "<<node;
} | true |
79cc198ecd812e72e67d16fb534aee8a9848e968 | C++ | caseycelestin/cpsc427_hw_1 | /geocoord.cpp | UTF-8 | 1,020 | 3.421875 | 3 | [] | no_license | #include "geocoord.hpp"
#include <cmath>
#include <string>
#include <sstream>
using std::string;
using std::istringstream;
using std::acos;
using std::cos;
using std::sin;
namespace geocoord
{
Coordinate::Coordinate()
{
lat = 0.0;
lon = 0.0;
}
Coordinate::Coordinate(string x, string y)
{
lat = coordinate_converter(x);
lon = coordinate_converter(y);
}
double Coordinate::geo_distance(Coordinate end)
{
double a, b, C, angle, d;
a = 1.570796 - lat;
b = 1.570796 - end.lat;
C = lon - end.lon;
angle = acos( cos(a) * cos(b) + sin(a) * sin(b) * cos(C) );
d = angle * 3959;
return d;
}
double Coordinate::coordinate_converter(string coord_in)
{
double coord_out;
double deg, min, sec;
istringstream sin{coord_in};
sin >> deg >> min >> sec;
if(coord_in.front() == '-')
{
min = min * -1;
sec = sec * -1;
}
coord_out = deg + min / 60 + sec / 3600;
coord_out = coord_out * 3.14159 / 180; //Converts degrees to radians
return coord_out;
}
}
| true |
801491f412a115196ed959e470c8eb3148e987a6 | C++ | nfarnesi4/BertSummerCamp2015 | /BertCampRobot/examples/summerCamp2015MainCode/summerCamp2015MainCode.ino | UTF-8 | 1,670 | 3.0625 | 3 | [] | no_license | /*
This is the code for the 2015 Bishop Eustace Robotics Summer camp.
*/
//libs:
#include <RedBot.h>
#include <NewPing.h>
//IR Sensors vars:
//create the variables for which pins the left and right ir sensors
//are wired too.
const unsigned int kLeftIRPin = 9;
const unsigned int kRightIRPin = 10;
//Driving vars:
//change these to fine tune how your robot follows the light
const int kForwardDriveSpeed = 200; //speed that robot goes once it sees the light
const int kSpinSpeed = 90; //the speed that the robot spins at to look for the ir light
const int kTurnSpeed = 150; //the speed that the robot turns with to align itself with the light
//create the motors variable to
RedBotMotors motors;
void setup(){
//start coms with the computer
Serial.begin(9600);
//setup the left and right ir pins as inputs
pinMode(kLeftIRPin, INPUT);
pinMode(kRightIRPin, INPUT);
}
void loop(){
//read the IR sensor values
boolean left = !digitalRead(kLeftIRPin);
boolean right = !digitalRead(kRightIRPin);
//both see nothing drive in a circle to look for the light
if(!left && !right){
motors.leftDrive(kSpinSpeed);
motors.rightDrive(-kSpinSpeed);
}
//both see the light drive straight!
else if(left && right){
motors.drive(kForwardDriveSpeed);
}
//the left sees the light but not the right
//slow down the left and speed up the right
else if(left){
motors.leftBrake();
motors.rightDrive(kTurnSpeed);
}
//the right sees the light but the left does not
//slow down the right and speed up the left
else{
motors.rightBrake();
motors.leftDrive(kTurnSpeed);
}
}
| true |
35de0ff895d49e76f896af11f3c99656172f27e0 | C++ | cms-externals/coral | /MySQLAccess/tests/NIPP/nipp.cpp | UTF-8 | 1,242 | 2.75 | 3 | [] | no_license | #include "../../src/NamedInputParametersParser.h"
#include <string>
#include <iostream>
int main( int, char** )
{
try
{
std::string input1( "UPDATE COOL_SVEN.\"COOLTEST_NODES_SEQ\" SET \"CURRENT_VALUE\"=:\"newvalue\", \"LASTMOD_DATE\"=DATE_FORMAT(now(),'%Y-%m-% d_%H:%i:%s.000000000 GMT')" );
std::string input2( "INSERT INTO T ( ID, sc ) VALUES ( :\"ID\", :\"sc\", :\"uc\" )" );
std::string orig = input1;
coral::MySQLAccess::NamedInputParametersParser nipp;
nipp.bindVariable( "newvalue", "0", input1 );
std::cout << "Original input1: " << orig << std::endl;
std::cout << "Updated input: " << input1 << std::endl;
orig = input2;
nipp.bindVariable( "ID", "0" , input2 );
nipp.bindVariable( "sc", "'\\\\'" , input2 );
nipp.bindVariable( "uc", "255" , input2 );
std::cout << "Original input2: " << orig << std::endl;
std::cout << "Updated input: " << input2 << std::endl;
}
catch( const std::exception& e )
{
std::cerr << "Standard excption has been caught: " << e.what() << std::endl;
return 1;
}
catch( ... )
{
std::cerr << "Ooops, the real problem here, unknown exception has been caught..." << std::endl;
return 2;
}
return 0;
}
| true |
5452c1b3705c72f0136c7ae572730c39e2dfa24e | C++ | oubine/algorithme_trie | /NF16/NF16TP4P18-master/tp4.cpp | UTF-8 | 4,112 | 3.453125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include "tp4.h"
T_Arbre initABR(){
T_Arbre abr = malloc(sizeof (T_Noeud));
abr=NULL;
return abr;
}
T_Noeud* creerNoeud(int cle){
T_Noeud* noeud = malloc(sizeof (T_Noeud));
noeud->cle=cle;
noeud->nb_occurrence=1;
noeud->droite=NULL;
noeud->gauche=NULL;
return noeud;
}
void ajouterElement(T_Arbre* abr, int entier){
if (*abr==NULL){
*abr = creerNoeud(entier);
}
else {
T_Noeud* temp = *abr;
while (temp->cle!=entier){
if (temp->cle>entier){
if (temp->gauche!=NULL){
temp = temp->gauche;
}
else {
temp->gauche=creerNoeud(entier);
break;
}
}
else {
if (temp->cle<entier){
if (temp->droite!=NULL){
temp = temp->droite;
}
else {
temp->droite=creerNoeud(entier);
break;
}
}
}
}
if (temp->cle==entier) temp->nb_occurrence++;
}
}
void afficher_t(T_Arbre abr){ //tableau ordre croissant
if (abr!=NULL){
afficher_t(abr->gauche);
printf("\t%d, %d", abr->cle, abr->nb_occurrence);
afficher_t(abr->droite);
}
}
/*void afficher_a(T_Arbre abr){
if (abr!=NULL){
printf("\n%d, %d\t", abr->cle, abr->nb_occurrence);
printf("fils gauche:");
afficher_a(abr->gauche);
printf("fils droit:");
afficher_a(abr->droite);
}
}
*/
T_Noeud* rechercherElement(T_Arbre abr, int entier){
if(abr==NULL) return NULL;
if(abr->cle==entier) return abr;
if (abr->cle>entier) rechercherElement(abr->gauche, entier);
else rechercherElement(abr->droite, entier);
}
T_Noeud* pere(T_Arbre noeud, T_Noeud* n){
if (rechercherElement(noeud, n->cle)!=NULL){
if (noeud->cle==n->cle) return noeud;
while (noeud->gauche!=n && noeud->droite!=n ){
if (noeud->cle<n->cle) noeud=noeud->droite;
if (noeud->cle>n->cle) noeud=noeud->gauche;
}
return noeud;
}
else
{
printf("Le noeud de cle %d n'est pas dans l'ABR!!", n->cle);
return NULL;
}
}
T_Noeud* successeur(T_Arbre abr, T_Noeud* n){
if (rechercherElement(abr, n->cle)!=NULL){
if (n->droite!=NULL) n=n->droite;
while (n->gauche!=NULL){
n=n->gauche;
}
return n;
}
// On ne traite pas le cas ou on doit remonter l'ABR pour trouver le successeur car dans supprimer lorsque on a besoin de faire appel au successeur c'est seulement dans le cas où le noeud a un fils droit
else return NULL;
}
void supprimerNoeud(T_Arbre* abr, T_Noeud* noeud){
if (abr==NULL || noeud==NULL) printf("TG tu as foiré qqpart");
else {
if (noeud->gauche==NULL && noeud->droite==NULL){
T_Noeud* papa=pere(abr,noeud);
if (papa->gauche==noeud) papa->gauche=NULL;
else papa->droite=NULL;
free(noeud);
noeud=NULL;
}
if (noeud->gauche==NULL || noeud->droite==NULL){
T_Noeud* fils;
if (noeud->gauche==NULL) fils=noeud->droite;
else fils=noeud->gauche;
T_Noeud* papa=pere(abr,noeud);
if (papa->gauche==noeud) papa->gauche=fils;
else papa->droite=fils;
free(noeud);
noeud=NULL;
}
if (noeud->gauche!=NULL && noeud->droite!=NULL){
T_Noeud* succ=successeur(abr, noeud);
noeud->cle=succ->cle;
supprimerNoeud(abr, succ);
}
}
}
void decrementerElement (T_Arbre* abr, int entier){
T_Noeud* n=rechercherElement(*abr, entier);
if (n==NULL) printf("yo La valeur %d n'est pas dans le tableau!!\n", entier);
else {
n->nb_occurrence--;
if (n->nb_occurrence==0) {
supprimerNoeud(abr, n);
}
}
}
| true |
94400682b1fa6c85a9ab0bb2b96a7e3d5d05bd48 | C++ | berryzplus/githubpr | /src/generic.cpp | UTF-8 | 3,986 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "StdAfx.h"
#include "generic.h"
// get environment variable.
std::wstring getEnvStr(_In_z_ LPCWSTR pszVarName)
{
size_t requiredSize = 0;
::_wgetenv_s(&requiredSize, NULL, 0, pszVarName);
if (0 < requiredSize)
{
std::wstring varStr(requiredSize - 1, '\0');
::_wgetenv_s(&requiredSize, &*varStr.begin(), requiredSize, pszVarName);
if (0 < requiredSize)
{
varStr.assign(varStr.c_str(), requiredSize - 1);
return std::move(varStr);
}
}
return std::wstring();
}
// set environment variable.
void setEnvStr(_In_z_ LPCWSTR pszVarName, _In_z_ LPCWSTR pszValue)
{
// set environment variable.
if (::_wputenv_s(pszVarName, pszValue))
{
THROW_APP_EXCEPTION("can't set environment value.");
}
}
// load string from resource.
std::wstring loadString(_In_ WORD wStringResourceId)
{
//文字列の実体は文字列テーブルとしてバンドルされるので、
//wStringResourceIdIdをバンドルIDに変換し、リソース検索する。
//詳細についてはMSDN FindResourceEx関数の説明を参照。
//この処理はLoadString関数内部で行われているものと同じ。
const WORD wBundleId = wStringResourceId / 16 + 1;
const WORD wBundleOffset = wStringResourceId & 0x0F;
HRSRC hres = ::FindResource(NULL, MAKEINTRESOURCE(wBundleId), RT_STRING);
if (!hres) {
THROW_APP_EXCEPTION("resource not found.");
}
//文字列テーブルを読み込む
HGLOBAL hResData = ::LoadResource(NULL, hres);
if (!hResData)
{
THROW_APP_EXCEPTION("load resource has failed.");
}
//戻り値を用意する
std::wstring content;
//文字列テーブルをロックする
LPCWSTR pResData = static_cast<LPWSTR>(::LockResource(hResData));
if (pResData)
{
//文字列テーブルの先頭が返るのでwStringResourceIdのところまでポインタを進める
LPCWSTR pwRsrc = pResData;
for (WORD i = 0; i < wBundleOffset; i++)
{
pwRsrc = &pwRsrc[*pwRsrc + 1];
}
//文字列をコピーして戻り値を準備する
content = std::wstring(&pwRsrc[1], *pwRsrc);
//ロックを解除する
//※↓の名前のWindowsAPIは存在しない。
// LockするのにUnlockしないのは奇妙なので、形式的に記述しておく。
UnlockResource(pResData);
}
//開放処理を行う
//※実行モジュールは仮想メモリ空間に展開されたままなので、
// 取得した文字列ポインタはそのまま利用しつづけて問題ない。
::FreeResource(hResData);
if (!pResData)
{
THROW_APP_EXCEPTION("lock resource has failed.");
}
return std::move(content);
}
// convert multi-byte string to wide string.
std::wstring convertMbsToWString(_In_reads_z_(cchMbString) LPCSTR pszMbString, _In_ SIZE_T cchMbString)
{
if (INT_MAX < cchMbString) {
throw std::invalid_argument("cchMbString is too large.");
}
const int nwChars = ::MultiByteToWideChar(
CP_ACP, 0,
pszMbString, static_cast<int>(cchMbString),
nullptr, 0
);
if (0 == nwChars) {
return std::wstring();
}
std::wstring content(nwChars, '\0');
const int nwRet = ::MultiByteToWideChar(
CP_ACP, 0,
pszMbString, static_cast<int>(cchMbString),
&*content.begin(), static_cast<int>(content.capacity())
);
content.assign(content.c_str(), nwRet);
return std::move(content);
}
// convert wide string to multi-byte string.
std::string convertWcsToString(_In_reads_z_(cchWcString) LPCWSTR pszWcString, _In_ SIZE_T cchWcString)
{
if (INT_MAX < cchWcString) {
throw std::invalid_argument("cchWcString is too large.");
}
const int nChars = ::WideCharToMultiByte(
CP_ACP, 0,
pszWcString, static_cast<int>(cchWcString),
nullptr, 0,
NULL, NULL
);
if (0 == nChars) {
return std::string();
}
std::string content(nChars, '\0');
const int nRet = ::WideCharToMultiByte(
CP_ACP, 0,
pszWcString, static_cast<int>(cchWcString),
&*content.begin(), static_cast<int>(content.capacity()),
NULL, NULL
);
content.assign(content.c_str(), nRet);
return std::move(content);
}
| true |
7b8ea143f29995d8ddfe0f9fa9cc1ed028c483b8 | C++ | ddltger/DDLTG | /Common/DDLTGFont/src/DDLTGFaceCollection.cpp | UTF-8 | 1,364 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "DDLTGFaceCollection.h"
namespace Ddltg {
FaceCollection LoadFaces(FT_Library ft, const vector<string> &face_names) {
FaceCollection faces;
for (auto &face_name : face_names) {
FT_Face face;
if (FT_New_Face(ft, face_name.c_str(), 0, &face)) {
fprintf(stderr, "Could not load font\n");
exit(EXIT_FAILURE);
}
if (FT_HAS_COLOR(face)) {
if (FT_Select_Size(face, 0)) {
fprintf(stderr, "Could not request the font size (fixed)\n");
exit(EXIT_FAILURE);
}
} else {
if (FT_Set_Pixel_Sizes(face, kFontPixelWidth, kFontPixelHeight)) {
fprintf(stderr, "Could not request the font size (in pixels)\n");
exit(EXIT_FAILURE);
}
}
// The face's size and bbox are populated only after set pixel
// sizes/select size have been called
FT_Long width, height;
if (FT_IS_SCALABLE(face)) {
width = FT_MulFix(face->bbox.xMax - face->bbox.xMin,
face->size->metrics.x_scale) >>
6;
height = FT_MulFix(face->bbox.yMax - face->bbox.yMin,
face->size->metrics.y_scale) >>
6;
} else {
width = (face->available_sizes[0].width);
height = (face->available_sizes[0].height);
}
faces.push_back(make_tuple(face, (int)width, (int)height));
}
return faces;
}
}
| true |
6150e9fe237e6f6165baa8cef09200a85595fee6 | C++ | sdustlug/OpenJudge | /QuestionAns/wfb/1359.cc | UTF-8 | 1,139 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <deque>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
deque<string> D;
int n;
int op;
string ch;
cin>>n;
while(n--) {
cin>>op;
if(op == 1) {
cin>>ch;
D.push_front(ch);
}else if(op == 2) {
cin>>ch;
D.push_back(ch);
}else if(op == 3) {
if(D.empty()) cout<<"-1"<<endl;
else cout<<D.back()<<endl;
}else if(op == 4) {
if(D.empty()) cout<<"-1"<<endl;
else cout<<D.front()<<endl;
}else if(op == 5) {
if(D.empty()) cout<<"-1"<<endl;
else D.pop_back();
}else if(op == 6) {
if(D.empty()) cout<<"-1"<<endl;
else D.pop_front();
}else if(op == 0) {
D.clear();
}
}
return 0;
}
/**************************************************************
Problem: 1359
User: 201601011420
Language: C++
Result: Accepted
Time:0 ms
Memory:1268 kb
****************************************************************/
| true |
7b1a590f8a4f0bae02b9efa41d3a38af709b84a2 | C++ | mkassjanski/c- | /4.cpp | UTF-8 | 255 | 3.046875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
string haslo;
cout << "Podaj hasło" << endl;
cin >> haslo;
if(haslo == "Jakub"){
cout << "Haslo poprawne" << endl;
}
else{
cout << "Hasło niepoprawne!" << endl;
}
return 0;
}
| true |
54efee3faa5c05aecf695779e8ad518ac828ca37 | C++ | Saunak626/HUAWEI-CODE | /华为上机/字符串替代aaa.cpp | GB18030 | 1,645 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
//ܳ3
void convert(char *input,char *output)
{
char *p=output;
int len = strlen(input);
int i=0;
int count=1;
for(int j=i+1;j<=len;)
{
while(input[i]==input[j])
{
count++;
j++;
}
if(count==1)
{
if(input[i]=='z')
*p++=input[i]-25;
else
*p++=input[i]+1;
}
else if(count==2)
{
if(input[i]=='y')
{
*p++=input[i]+1;
*p++=input[i]-24;
}else if(input[i]=='z')
{
*p++=input[i]-25;
*p++=input[i]-24;
}else{
*p++=input[i]+1;
*p++=input[i]+2;
}
count=1;
}
else if(count==3)
{
if(input[i]=='x')
{
*p++=input[i]+1;
*p++=input[i]+2;
*p++=input[i]-23;
}else if(input[i]=='y')
{
*p++=input[i]+1;
*p++=input[i]-24;
*p++=input[i]-23;
}else if(input[i]=='z')
{
*p++=input[i]-25;
*p++=input[i]-24;
*p++=input[i]-23;
} else{
*p++=input[i]+1;
*p++=input[i]+2;
*p++=input[i]+3;
}
count=1;
}
i=j;
j=i+1;
}
*p='\0';
}
void main()
{
char a[1024];
char result[1024]={'\0'};
while(cin>>a){
convert(a,result);
cout<<result<<endl<<endl;
}
} | true |
47cbbbd6ccd1acdb61f1dc3b14c52921d0af2d63 | C++ | beatabb/My_University | /Semester_3/ProjectOK/jobshopd/jobshop.cpp | UTF-8 | 9,464 | 3.046875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <limits>
#include <chrono>
#include <ctime>
#include <algorithm>
#include <cstdlib>
using namespace std;
#define NR 10
string fileName;
int max (int a, int b)
{
return a > b ? a : b;
}
struct Instance
{
int jobs, machines, activities;
vector<vector<int>> order, pTime;
};
/*struct Ans
{
};*/
void printInstance(Instance &instance)
{
int jobs = instance.jobs;
int machines = instance.machines;
vector<vector<int>> order = instance.order;
vector<vector<int>> pTime = instance.pTime;
cout << "Jobs: " << jobs << "\nMachines: " << machines << endl;
for (int i = 0; i < order.size(); i++)
{
cout << "Job " << i << ":\t";
for (int j = 0; j < order[i].size(); j++)
{
cout<< order[i][j] <<"/" << pTime[i][j] <<"\t";
}
cout << endl;
}
}
Instance initBeasley(string fileName)
{
ifstream file;
int jobs, machines;
int x, y;
file.open(fileName.c_str());
if (!file.good())
{
cout << "ERROR: File not opened" << endl;
}
file >> jobs >> machines;
vector<vector<int>> order(jobs); // for Jobs
vector<vector<int>> pTime(jobs); // for Jobs
for (int i = 0; i < jobs; i++)
{
pTime[i].resize(machines);
order[i].resize(machines);
for (int j = 0; j < machines; j++)
{
file >> order [i][j] >> pTime [i][j];
}
}
file.close();
int activities = jobs * machines;
Instance instance;
instance.jobs = jobs;
instance.machines = machines;
instance.pTime = pTime;
instance.order = order;
instance.activities = activities;
return instance;
}
Instance initTaillard(string fileName)
{
ifstream file;
int jobs, machines;
file.open(fileName.c_str());
if (!file.good())
{
cout<<"ERROR: File not opened"<<endl;
}
file >> jobs >> machines;
file.ignore(numeric_limits<streamsize>::max(), '\n');
file.ignore(numeric_limits<streamsize>::max(), '\n');
vector<vector<int>> pTime(jobs);
for (int i = 0; i < jobs; i++)
{
pTime[i].resize(machines);
for (int j = 0; j < machines; j++)
{
file >> pTime[i][j];
}
}
file.ignore(numeric_limits<streamsize>::max(), '\n');
file.ignore(numeric_limits<streamsize>::max(), '\n');
vector<vector<int>> order(jobs);
for (int i = 0; i < jobs; i++)
{
order[i].resize(machines);
for (int j = 0; j < machines; j++)
{
int x;
file >> x;
order[i][j] = x - 1;
}
}
int activities = jobs * machines;
Instance instance;
instance.jobs = jobs;
instance.machines = machines;
instance.pTime = pTime;
instance.order = order;
instance.activities = activities;
return instance;
}
class Solver
{
const Instance * instance;
vector<int> jProgT, jProg, machProgT;
vector<int> sol, bestSol, finalSol;
public:
Solver(const Instance * inst) : instance(inst)
{
if (jProgT.size() == 0)
jProgT.resize(instance->jobs);
if (jProg.size() == 0)
jProg.resize(instance->jobs);
if (machProgT.size() == 0)
machProgT.resize(instance->machines);
}
void schedule()
{
for (int i = 0; i < instance->activities; i++)
{
int job = chooseJob();
scheduleNext(job);
}
}
int schedule2()
{
for (int i = 0; i < instance->activities; i++)
{
int job = rand() % instance->jobs;
sol.push_back(job);
scheduleNext(job);
}
int temp = makeSpan();
cout << temp << endl;
return temp;
}
void solve2()
{
int bestMakeSpan;
for (int i = 0; i < instance->machines; i++)
{
bestMakeSpan = numeric_limits<int>::max();
for (int j = 0; j < NR; j++)
{
int temp = schedule2();
if (temp < bestMakeSpan)
{
bestMakeSpan = temp;
bestSol = sol;
}
restart();
}
for (int k = 0; k < instance->jobs; k++)
{
finalSol.push_back(bestSol[finalSol.size()+k]);
}
}
if (finalSol.size() != instance->activities) throw string("ERROR: Saving final solution failed.");
saveAns(finalSol, bestMakeSpan);
}
void saveAns(vector<int> finalSol, int bestMakeSpan)
{
restart();
vector<vector<int>> solution;
solution.resize(instance->jobs);
for (int i = 0; i < finalSol.size(); i++)
{
int job = finalSol[i];
int machine = nextMachine(job);
int start = max (jProgT[job], machProgT[machine]);
solution[job].push_back(start);
scheduleNext(job);
}
int mkspn = makeSpan();
if (mkspn != bestMakeSpan)
{
throw string("ERROR: Makespans don't match.");
}
//file << mkspn << endl;
cout << mkspn << endl;
for (int j = 0; j < solution.size(); j++)
{
for (int k = 0; k < solution[j].size(); k++)
{
//file << solution [j][k];
cout << solution [j][k];
if (k < (solution[j].size()-1))
{
//file << "\t";
cout << "\t";
}
}
//file << endl;
cout << endl;
}
//file.close();
}
void restart()
{
jProgT.clear();
jProgT.resize(instance->jobs);
jProg.clear();
jProg.resize(instance->jobs);
machProgT.clear();
machProgT.resize(instance->machines);
sol.clear();
}
int makeSpan()
{
return *max_element(machProgT.begin(), machProgT.end());
}
void solve()
{
ofstream file; //file.open("output.txt");
//fstream results; results.open("results.txt", ios::app)
vector<vector<int>> solution;
solution.resize(instance->jobs);
int index = fileName.find_last_of("/\\");
string fileName2 = fileName.substr(index+1);
string str = "output/out_";
str.append(fileName2);
file.open(str.c_str());
for (int i = 0; i < instance->activities; i++)
{
int job = chooseJob();
int machine = nextMachine(job);
int start = max (jProgT[job], machProgT[machine]);
//cout << job << " " << start << endl;
solution[job].push_back(start);
scheduleNext(job);
}
int mkspn = makeSpan();
file << mkspn << endl;
cout << mkspn << endl;
for (int j = 0; j < solution.size(); j++)
{
for (int k = 0; k < solution[j].size(); k++)
{
file << solution [j][k];
cout << solution [j][k];
if (k < (solution[j].size()-1))
{
file << "\t";
cout << "\t";
}
}
file << endl;
cout << endl;
}
file.close();
}
private:
bool hasNextActivity(int job)
{
return jProg [job] < instance->machines;
}
int nextMachine(int job)
{
int nextActivity = jProg[job];
if (nextActivity == instance->machines) return -1;
return instance->order[job][nextActivity];
}
int chooseJob()
{
int earliestStart = numeric_limits<int>::max();
int selectedJob;
for (int job = 0; job < instance->jobs; job++)
{
if (!hasNextActivity(job)) continue;
int machine = nextMachine(job);
int start = max(jProgT[job], machProgT[machine]);
if (start < earliestStart)
{
earliestStart = start;
selectedJob = job;
}
}
return selectedJob;
}
int nextActivityEnd(int job)
{
int nextActivity = jProg[job];
int machine = instance->order[job][nextActivity];
int duration = instance->pTime[job][nextActivity];
int start = max (jProgT[job], machProgT[machine]);
return start + duration;
}
void scheduleNext(int job)
{
int machine = nextMachine(job);
int end = nextActivityEnd(job);
jProg[job]++;
machProgT[machine] = end;
jProgT[job] = end;
return;
}
};
int main(int argc, char ** argv)
{
srand(time(NULL));
if (argc != 3)
{
printf("Usage: %s <format> <inputfile>\nWhere <format> is b for beasley and t for tailard\n", argv[0]);
}
int format = *argv[1];
fileName = argv[2];
Instance instance;
if (format == 'b')
{
instance = initBeasley(fileName);
}
else if (format == 't')
{
instance = initTaillard(fileName);
}
else
{
printf("ERROR: Wrong format!\n");
}
Solver solver(&instance);
/*try
{
solver.solve2();
}
catch(string e)
{
cout<<e<<endl;
return -1;
}*/
//solver.solve();
} | true |
02fff51cf4a9a478e5dbcedba6a7bc8c540efe3c | C++ | ElijahWandimi/SchoolWork | /C++/Evans/main.cpp | UTF-8 | 336 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main(){
int numberOfStudent;
string courseName;
string units[8];
cout<<("Enter course name: ")<<endl;
cin>>courseName;
cout<<("Enter number of students: ")<<endl;
cin>>numberOfStudent;
for(int i=0; i<=8;i++)
{
cout<<"Enter units"<<endl;
cin>>units[i];
}
return 0;
}
| true |
139f647567d4264c1090afd25385a408e2b47fec | C++ | megakoko/m-system | /src/therapeutist/examcontainer.h | UTF-8 | 2,311 | 2.65625 | 3 | [] | no_license | #pragma once
#include "examwidget.h"
class QLabel;
class QGridLayout;
class ExaminationEditWidget;
/*
Контейнер для других ExamWidget'ов.
*/
class ExamContainer : public ExamWidget
{
Q_OBJECT
public:
ExamContainer(const int examId, const QString& textid, const bool topLevel = false);
void setExaminationEditWidget(ExaminationEditWidget* widget);
// Определенные чисто виртуальные функции.
bool valueIsNull() const;
QString value() const;
void init();
bool save(const int examId);
QMap<int, QVariant> data() const;
QLabel* label() const;
QWidget* widget() const;
protected:
void setLabelText(const QString &labelText, const QString& shortLabelText);
private:
// Возвращает значение всех элементов, содержащихся в контейнере
// с textid = containerTextId.
QStringList containerValueFromDatabase(const QString& containerTextId) const;
// То же самое, что и containerValueFromDatabase, только возвращает данные в виде
// карты QMap.
QMap<int, QVariant> containerDataFromDatabase(const QString& containerTextId) const;
void expandContainer(const bool expanded);
static const int m_indicatorWidth;
static const QString labelAndValueDelimiter;
const bool m_topLevel;
// Виджет, который содержит заголовок контейнера и контейнер.
QWidget* m_widget;
// Индикатор "свернутости" в заголовке контейнера.
QLabel* m_headerIndicator;
// Текст в заголовоке контейнера.
QLabel* m_headerText;
// Собственно сам контейнер, виджет, который будет хранить в себе другие виджеты.
QWidget* m_container;
// Layout для контейнера.
QGridLayout* m_containerLayout;
// Список виджетов, которых содержит контейнер.
QList<ExamWidget*> m_items;
// Указатель на главный виджет осмотра. Его мы спросим о возрасте пациента.
ExaminationEditWidget* m_examinationEditWidget;
private slots:
void updateHeader();
void expandContainer();
};
| true |
641627b1cdc4d60771a11ae7beb400249a29df14 | C++ | HSchmale16/KneeThingy | /implementation.cpp | UTF-8 | 4,661 | 2.921875 | 3 | [] | no_license | /** Implementation.cpp
* @author Henry J Schmale
* @date January 25, 2015
* Contains the implementation of functions defined in default.h
*/
#include <cstdlib>
#include <unistd.h>
#include <sqlite3.h>
#include <ctime>
#include <cstdio>
#include "default.h"
// Externs declared in header are here
BMA180Accelerometer * g_Accel0; //!< Left Leg Accel
BMA180Accelerometer * g_Accel1; //!< Right Leg Accel
gnublin_gpio gpio;
Accel3d g_A3d0;
Accel3d g_A3d1;
int HallEffectSensorVal; //!< The current value of the hall sensor
int initHallEffectSensorVal; //!< The initial value of the hall sensor
bool isRunning; //!< Is the board currently listening for data
time_t rawtime;
// File scope global variables
//static sqlite3 *db;
// FWD Declarations of functions used in this file and declared later.
#include <iostream>
// inits the program
int init()
{
using namespace std;
isRunning = true;
// init the pins for use
gpio.pinMode(PIN_ON_OFF_SW, "INPUT");
gpio.pinMode(PIN_RUNNING_LED, "OUTPUT");
gpio.pinMode(PIN_WARN_LED, "OUTPUT");
gpio.digitalWrite(PIN_RUNNING_LED, HIGH);
gpio.digitalWrite(PIN_WARN_LED, LOW);
// Init the hall effect sensor for distance measurement
initHallEffectSensor();
// Init I2C for all devices here
// init first accelerometer
g_Accel0 = new BMA180Accelerometer(ACC0_I2C_BUS, ACC0_I2C_ADDY);
g_Accel0->setRange(PLUSMINUS_1_G);
g_Accel0->setBandwidth(BW_150HZ);
// init 2nd accelerometer
g_Accel1 = new BMA180Accelerometer(ACC1_I2C_BUS, ACC1_I2C_ADDY);
g_Accel1->setRange(PLUSMINUS_1_G);
g_Accel1->setBandwidth(BW_150HZ);
// init DB
int rc = 0; // sqlite3_open(DB_FILE_PATH.c_str(), &db);
if(rc)
{
exit(0);
}
return 0;
}
/** This function contains the commands that should be
* carried out every iteration of the event loop.
* This function is equilvilent to the arduino `loop()`
* function.
*/
int eventLoop()
{
/*if(gpio.digitalRead(PIN_ON_OFF_SW)){
isRunning = true;
gpio.digitalWrite(PIN_RUNNING_LED, HIGH);
}else{
isRunning = false;
gpio.digitalWrite(PIN_RUNNING_LED, LOW);
}*/
// Update the data
updateAccel3d(g_Accel0, &g_A3d0); // update left leg
//updateAccel3d(g_Accel1, &g_A3d1); // update right leg
/// \todo add a magnetic check
// TEST the values to make sure there within the acceptable range
bool accelsOk = testAccel3ds(&g_A3d0, &g_A3d1);
bool distsOk = testHallEffectSensor();
// Output the data
if(isRunning == true){
time(&rawtime);
std::cout << "[" << rawtime << "]\t"
<< g_A3d0.m_roll << "\t"
<< g_A3d0.m_pitch << "\t"
<< g_A3d0.m_xAcc << "\t"
<< g_A3d0.m_yAcc << "\t"
<< g_A3d0.m_zAcc << std::endl;
if((accelsOk) | (distsOk)){
// This is not good, tell the user about it
gpio.digitalWrite(PIN_WARN_LED, HIGH);
}else{
gpio.digitalWrite(PIN_WARN_LED, LOW);
}
}
usleep(UPDATE_WAIT_T); // sleep for a couple of microsecs
return 0;
}
// ====================================================================
// Updaters and testers
// --------------------------------------------------------------------
// Hall Effect Sensor Functions
// inits hall effect sensor
void initHallEffectSensor()
{
}
// updates hall effect sensor
void updateHallEffectSensor()
{
}
// check if the hall effect is still in the good range
bool testHallEffectSensor()
{
return false; // it's all good take no action
}
// --------------------------------------------------------------------
// Accelerometer Functions
// accel update function
void updateAccel3d(BMA180Accelerometer *accel,
Accel3d *a3d)
{
accel->readFullSensorState();
a3d->m_roll = accel->getRoll();
a3d->m_pitch = accel->getPitch();
a3d->m_xAcc = accel->getAccelerationX();
a3d->m_yAcc = accel->getAccelerationY();
a3d->m_zAcc = accel->getAccelerationZ();
}
// inits an accel3d instance
void initAccel3d(BMA180Accelerometer *accel,
Accel3d *a3d)
{
accel->readFullSensorState();
a3d->m_initRoll = accel->getRoll();
a3d->m_initPitch = accel->getPitch();
a3d->m_initX = accel->getAccelerationX();
a3d->m_initY = accel->getAccelerationY();
a3d->m_initZ = accel->getAccelerationZ();
}
// Performs a test on the accelerometers
bool testAccel3ds(Accel3d *aLeft, Accel3d *aRight)
{
if((aLeft->m_yAcc > aLeft->m_xAcc) && (aLeft->m_xAcc > 0)){
return false;
}
if((aRight->m_yAcc > aRight->m_xAcc) && (aRight->m_xAcc > 0)){
return false;
}
return false; // all is right in the world
}
| true |
e1d225db310e1cdc091ca941c16a2cd3df837c15 | C++ | psettle/sudoku | /src/sdk/rules/ExclusiveTupleRule.cpp | UTF-8 | 2,434 | 3.140625 | 3 | [
"MIT"
] | permissive | /**
* ExclusiveTupleRule.hpp - Exclusive Tuple Rule
*
* If N cells consist of N possible digits, those digits cannot exist
* in any other cells
*/
#include "sdk/rules/ExclusiveTupleRule.hpp"
using namespace sdk::rules;
using ::sdk::data::Cell;
using ::sdk::data::Collection;
using ::sdk::data::Digit;
/**
* CollectionRule ctor
*/
ExclusiveTupleRule::ExclusiveTupleRule(uint8_t order) : order_(order), listener_(nullptr) {}
/**
* Set a listener for exclusive tuple progress
*/
void ExclusiveTupleRule::SetListener(interfaces::IExclusiveTupleListener* listener) {
if (listener) {
listener_ = listener;
}
}
/**
* Apply the exclusive tubple rule to the provided collection
*/
bool ExclusiveTupleRule::Apply(Collection& collection) {
bool progress = false;
// Initialize a set of iterators, we will be running through all combinations
utility::SelectionIterator<Collection::iterator> it(collection.begin(), collection.end(), order_);
do {
// Add up the total number of digits represented by the selected combination
Digit count = data::kN;
for (Collection::iterator& el : it.GetSelection()) {
count.Add(**el);
}
if (count.PossibleValues() == order_) {
// The currently selected tuple contains order_ unique values, so the values
// represented by count cannot exist in the rest of the collection
for (Cell* cell : collection) {
// If cell is not in the exclusive tuple, remove all values from it
// that are in the exclusive tuple
bool found = false;
for (Collection::iterator& el : it.GetSelection()) {
if (*el == cell) {
found = true;
}
}
if (!found && cell->Remove(count)) {
progress = true;
SendProgress(it, count, *cell);
}
}
}
} while (it.Increment());
return progress;
}
/**
* Send a notification describing the logical progress that was made to listener
*/
void ExclusiveTupleRule::SendProgress(
utility::SelectionIterator<Collection::iterator> const& exclusive_tuple,
Digit const& exclusive_values, Cell const& removed_from) const {
// Copy tuple from iterator into vector for listener interface
std::vector<Cell const*> tuple;
for (auto& it : exclusive_tuple.GetSelection()) {
tuple.push_back(*it);
}
if (listener_) {
listener_->OnExclusiveTupleProgress(tuple, exclusive_values, removed_from);
}
}
| true |
d79bc263dd4c0ebb2ee1750b5246d5ef47f4dc19 | C++ | Game-Tek/Game-Tek-Standard-Library | /GTSL/Thread.hpp | UTF-8 | 4,066 | 2.625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Core.h"
#include "Delegate.hpp"
#include "Tuple.hpp"
#include "Algorithm.hpp"
#if (_WIN64)
#include <Windows.h>
#undef ERROR
#elif __linux__
#include <pthread.h>
#endif
namespace GTSL
{
class Thread {
public:
Thread() = default;
template<class ALLOCATOR, typename T, typename... ARGS>
Thread(ALLOCATOR allocator, const uint8 threadIdParam, Delegate<T> delegate, ARGS... args) noexcept
{
uint64 allocatedSize;
this->dataSize = static_cast<uint32>(sizeof(FunctionCallData<T, ARGS...>));
allocator.Allocate(this->dataSize, 8, &this->data, &allocatedSize);
new(this->data) FunctionCallData<T, ARGS...>(threadIdParam, delegate, GTSL::ForwardRef<ARGS>(args)...);
this->handle = createThread(&Thread::launchThread<T, ARGS...>, this->data);
}
~Thread() = default;
static uint32 ThisTreadID() noexcept { return threadId; }
enum class Priority : uint8 {
LOW, LOW_MID, MID, MID_HIGH, HIGH
};
void SetPriority(Priority threadPriority) const noexcept {
#if (_WIN64)
int32 priority{ THREAD_PRIORITY_NORMAL };
switch (threadPriority)
{
case Priority::LOW: priority = THREAD_PRIORITY_LOWEST; break;
case Priority::LOW_MID: priority = THREAD_PRIORITY_BELOW_NORMAL; break;
case Priority::MID: priority = THREAD_PRIORITY_NORMAL; break;
case Priority::MID_HIGH: priority = THREAD_PRIORITY_ABOVE_NORMAL; break;
case Priority::HIGH: priority = THREAD_PRIORITY_HIGHEST; break;
default: return;
}
SetThreadPriority(handle, priority);
#elif __linux__
#endif
}
void static SetThreadId(const uint8 id) { threadId = id; }
template<class ALLOCATOR>
void Join(ALLOCATOR allocator) noexcept {
this->join(); //wait first
allocator.Deallocate(this->dataSize, 8, this->data); //deallocate next
}
void Detach() noexcept { handle = nullptr; }
[[nodiscard]] uint32 GetId() const noexcept {
#if (_WIN64)
return GetThreadId(handle);
#elif __linux__
return pthread_self();
#endif
}
[[nodiscard]] bool CanBeJoined() const noexcept { return !handle; }
static uint8 ThreadCount() {
#if (_WIN64)
SYSTEM_INFO system_info;
GetSystemInfo(&system_info);
return static_cast<uint8>(system_info.dwNumberOfProcessors);
#elif __linux__
return sysconf(_SC_NPROCESSORS_ONLN);
#endif
}
explicit operator bool() const {
return handle;
}
private:
template<typename FT, typename... ARGS>
struct FunctionCallData {
FunctionCallData(const uint8 tId, Delegate<FT> delegate, ARGS&&... args) : ThreadId(tId), delegate(delegate), Parameters(GTSL::ForwardRef<ARGS>(args)...)
{
}
uint8 ThreadId;
Delegate<FT> delegate;
Tuple<ARGS...> Parameters;
};
void* handle{ nullptr };
void* data;
uint32 dataSize;
#if (_WIN64)
template<typename FT, typename... ARGS>
static unsigned long launchThread(void* data) {
FunctionCallData<FT, ARGS...>* functionData = static_cast<FunctionCallData<FT, ARGS...>*>(data);
threadId = functionData->ThreadId;
Call(functionData->delegate, GTSL::MoveRef(functionData->Parameters));
return 0;
}
#elif __linux__
template<typename FT, typename... ARGS>
static void* launchThread(void* data) {
FunctionCallData<FT, ARGS...>* functionData = static_cast<FunctionCallData<FT, ARGS...>*>(data);
threadId = functionData->ThreadId;
Call(functionData->delegate, GTSL::MoveRef(functionData->Parameters));
return 0;
}
#endif
#if (_WIN64)
static void* createThread(unsigned long(*function)(void*), void* data) noexcept {
return CreateThread(0, 0, function, data, 0, nullptr);
#elif __linux__
static void* createThread(void*(*function)(void*), void* data) noexcept {
pthread_t handle = 0;
pthread_create(&handle, nullptr, function, data);
return reinterpret_cast<void*>(handle);
#endif
}
inline thread_local static uint8 threadId = 0;
void join() noexcept {
#if (_WIN64)
WaitForSingleObject(handle, INFINITE); handle = nullptr;
#elif __linux__
pthread_join((pthread_t)handle, nullptr);
#endif
}
};
}
| true |
12f415d29d1f4f5a7390b03cd6ed75d5f40a0d3d | C++ | Javi96/EDA | /Práctica 1/Racional.h | UTF-8 | 1,686 | 3.53125 | 4 | [] | no_license | #ifndef _RACIONAL_H
#define _RACIONAL_H
#include <iostream>
#include <string>
using namespace std;
class Racional {
public:
//Excepcion que se lanza cuando se trata de crear
//una fraccion con denominador 0
class EDenominadorCero {};
//Excepcion que se lanza cuando se produce una division
//por 0
class EDivisionPorCero {};
// Funcion que permite escribir una fraccion en un 'stream'
friend ostream& operator<<(ostream& out, const Racional& f);
//**** COMPLETAR
// Deben declararse los metodos publicos de la clase
bool operator==(const Racional& f) const{
return (float)_numer / (float)_denom == (float)f._numer / (float)f._denom;
}
void operator*=(const Racional& f){
_numer = _numer * f._numer;
_denom = _denom * f._denom;
reduce();
}
Racional operator-(const Racional& f){
long new_denom = mcm(f._denom, _denom);
long operando_1 = _numer*new_denom / _denom;
long operando_2 = f._numer*new_denom / f._denom;
Racional racional(operando_1 - operando_2, new_denom);
racional.reduce();
return racional;
}
void divideYActualiza(const Racional& f);
Racional();
Racional(long numer, long denom);
Racional suma(const Racional & f);
//****
private:
long _numer; // El numerador
long _denom; // El denominador
void reduce(); // Transforma la fraccion en una equivalente irreducible (es decir, una en la que
// el denominador es siempre positivo, y el unico divisor comun del numerador y el
// denominador es 1)
static long mcm(long v1, long v2); // Minimo comun multiplo de v1 y v2
static long mcd(long v1, long v2); // Maximo comun divisor de v1 y v2
};
#endif | true |
ecfcb4fd190efcd04ec1724e5b2f584ca374c779 | C++ | msrLi/portingSources | /ACE/ACE_wrappers/protocols/ace/TMCast/Protocol.hpp | UTF-8 | 1,897 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | // author : Boris Kolpackov <boris@dre.vanderbilt.edu>
#ifndef TMCAST_PROTOCOL_HPP
#define TMCAST_PROTOCOL_HPP
namespace ACE_TMCast
{
namespace Protocol
{
unsigned long const MEMBER_ID_LENGTH = 38;
struct MemberId
{
char id[MEMBER_ID_LENGTH];
/*
unsigned long ip;
unsigned short port;
*/
};
typedef unsigned short TransactionId;
typedef unsigned char TransactionStatus;
TransactionStatus const TS_BEGIN = 1;
TransactionStatus const TS_COMMIT = 2;
TransactionStatus const TS_ABORT = 3;
TransactionStatus const TS_COMMITED = 4;
TransactionStatus const TS_ABORTED = 5;
struct Transaction
{
TransactionId id;
TransactionStatus status;
};
// Transaction List (TL)
// unsigned long const TL_LENGTH = 1;
// typedef Transaction TransactionList[TL_LENGTH];
struct MessageHeader
{
unsigned long length;
unsigned long check_sum;
MemberId member_id;
Transaction current;
//TransactionList transaction_list;
};
unsigned long const MAX_MESSAGE_SIZE = 768;
unsigned long const
MAX_PAYLOAD_SIZE = MAX_MESSAGE_SIZE - sizeof (MessageHeader);
// Protocol timing
//
//
unsigned long const SYNC_PERIOD = 30000; // in mks
unsigned short const VOTING_FRAME = 4; // in SYNC_PERIOD's
unsigned short const SEPARATION_FRAME = 5; // in SYNC_PERIOD's
// FATAL_SILENCE_FRAME in SYNC_PERIOD's
// Generally it's a good idea to set it to < VOTING_FRAME + SEPARATION_FRAME
//
short const FATAL_SILENCE_FRAME = VOTING_FRAME + SEPARATION_FRAME - 2;
// short const FATAL_SILENCE_FRAME = 10000;
// Helpers
// std::string
// tslabel (Protocol::TransactionStatus s);
// std::ostream&
// operator << (std::ostream& o, Transaction const& t);
}
}
#endif // TMCAST_PROTOCOL_HPP
| true |
b08a17dda4f0fb717e48eeb863633eed9c877519 | C++ | jalesnunes/cs235 | /Insertion Sort/Insertion Sort/src/node.h | UTF-8 | 4,430 | 3.671875 | 4 | [] | no_license | /***********************************************************************
* Program:
* Assignment 06, Linked List
* Brother Kirby, CS 235
* Author:
* Jales Nunes, Davi Neves
* Summary:
* This program defines the Class Node.
************************************************************************/
#ifndef NODE_H
#define NODE_H
#include <cassert> // because I am paranoid
#include <iostream> // for CIN and COUT
using namespace std;
namespace custom
{
/************************************************
* NODE
* A class that holds stuff
***********************************************/
template <class T>
class Node
{
public:
T data;
Node <T> * pNext;
Node <T> * pPrev;
// constructors
Node();
Node(const T& t);
};
/*******************************************
* NODE - insert
* This is how elements are added to a
* linked list.
*******************************************/
template <class T>
Node <T>* insert(Node <T>* pCurrent, const T& t, bool after = false)
{
Node <T>* pNew = new Node <T>(t); //new node
if (pCurrent != NULL && after == false)
{
//Changing pointer in order to keep a list
pNew->pNext = pCurrent;
pNew->pPrev = pCurrent->pPrev;
pCurrent->pPrev = pNew;
if (pNew->pPrev)
{
pNew->pPrev->pNext = pNew;
}
}
else if (pCurrent != NULL && after == true)
{
//Changing pointer in order to keep a list
pNew->pNext = pCurrent->pNext;
pNew->pPrev = pCurrent;
if (pCurrent->pNext)
{
pCurrent->pNext->pPrev = pNew;
}
pCurrent->pNext = pNew;
}
return pNew; //returning a new node
}
/*******************************************
* NODE - find
* This is how elements are found to a
* linked list.
*******************************************/
template <class T>
Node <T>* find(Node <T>* pHead, const T& t)
{
Node <T>* p;
//Going through a list
for (p = pHead; p != NULL; p = p->pNext)
{
//condition if data equal to element
if (p->data == t)
{
return p;
}
}
return NULL;
}
/*******************************************
* NODE - clear
* Delete an entire list..
*******************************************/
template <class T>
void freeData(Node <T>*& pHead)
{
Node <T>* pDelete;
while (pHead != NULL)
{
pDelete = pHead;
pHead = pHead->pNext;
delete pDelete;
}
}
/*******************************************
* NODE - copy
* makes a copy of each and every node in
* the source linked list into a new
* linked list.
*******************************************/
template <class T>
Node <T>* copy(const Node <T>* pSource)
{
Node <T>* pDestination = new Node <T>(pSource->data); // creating new node
const Node <T>* pSrc;
Node <T>* pDes = pDestination;
for (pSrc = pSource->pNext; pSrc != NULL; pSrc = pSrc->pNext)
{
pDes = insert(pDes, pSrc->data, true);
}
return pDestination;
}
/*******************************************
* NODE - remove
* Delete a single node from a linked list
*******************************************/
template <class T>
Node <T>* remove(const Node <T>* pRemove)
{
Node <T>* pReturn = NULL;
if (pRemove == NULL)
{
return pReturn;
}
if (pRemove->pPrev)
{
pRemove->pPrev->pNext = pRemove->pNext;
}
if (pRemove->pNext)
{
pRemove->pNext->pPrev = pRemove->pPrev;
}
if (pRemove->pPrev)
{
pReturn = pRemove->pPrev;
}
else
{
pReturn = pRemove->pNext;
}
delete pRemove;
return pReturn;
}
/*****************************************
* DISPLAY
****************************************/
template <class T>
ostream & operator << (ostream & out, const Node <T> * pSource)
{
const Node <T> * p = pSource;
if(p != NULL)
{
out << p->data;
for(p = pSource->pNext; p; p = p->pNext)
out << ", " << p->data;
}
return out;
}
/********************************************
* CONSTRUCTOR
*******************************************/
template <class T>
Node <T> ::Node()
{
this->pNext = NULL;
this->pPrev = NULL;
}
/********************************************
* CONSTRUCTOR: NON-DEFAULT
*******************************************/
template <class T>
Node <T> ::Node(const T& t)
{
this->data = t;
this->pNext = NULL;
this->pPrev = NULL;
}
}; // namespace custom
#endif /* NODE_H */
| true |
14eb861301cd4528325cc7d053b7a76023d28768 | C++ | brandonl/Flow | /src/Core/ShaderSource.h | UTF-8 | 432 | 2.703125 | 3 | [] | no_license | #ifndef __SHADER_SOURCE_H__
#define __SHADER_SOURCE_H__
#include "Resource.h"
#include <memory>
namespace flow
{
class ShaderSource : public Resource
{
public:
ShaderSource( const std::string& fn );
ShaderSource& operator=( ShaderSource&& m );
const std::string& getSource() const;
private:
std::string source;
};
inline const std::string& ShaderSource::getSource() const
{
return source;
}
};
#endif | true |
89f8f25a807780ba5886da1a455b6c33783a5e0a | C++ | Draf09/TP3OrgArq | /OperadorBits.cpp | UTF-8 | 1,084 | 3.5 | 4 | [] | no_license | #include <string>
using namespace std;
class OperadorBits
{
public:
//move os N primeiros bits de entrada para o parâmetro de saída (remove esses bits do binário de entrada)
static void ExtrairBinario(string &binario_entrada, string &binario_saida, int numero_bits)
{
string buffer;
for(char i : binario_entrada)
{
buffer = i;
binario_saida += buffer;
if(binario_saida.size() == numero_bits) break;
}
binario_entrada.erase(0, numero_bits);
}
//shift dos binário
static void ShiftLeft(string &binario, int numero_shifts)
{
while(binario.size() < binario.size() + numero_shifts) binario = binario + "0";
}
//trunca binário
static void Trunc(string &binario, int bits_cortados)
{
binario.erase(0, bits_cortados);
}
//Operações da ULA
static string OperaAnd(string A, string B){ return "";}
static string OperaOr(string A, string B){ return "";}
static string OperaAdd(string A, string B){ return "";}
static string OperaSub(string A, string B){return "";}
static string OperaSetOnLess(string A, string B){return "";}
};
| true |
68c737960b2dcc7f625f46f7f16a651de64ad743 | C++ | saumitrabajpai98/DSA-Cpp- | /lnkdlstinsbeg.cpp | UTF-8 | 592 | 3.453125 | 3 | [] | no_license | #include<iostream>
using namespace std;
class node{
public:
int data;
node *next;
};
node *head;
void innsatbeg(int x)
{
node *temp=new node();
temp->data=x;
temp->next=head;
head=temp;
}
void print()
{
node *temp2=head;
//cout<<"\nList ";
while(temp2!=NULL)
{
cout<<temp2->data<<" ";
temp2=temp2->next;
}
cout<<endl;
}
int main()
{
head=NULL;
cout<<"How many numbers u want to entr ";
int n,count=1,x;
cin>>n;
for(int i=0;i<n;i++)
{
cout<<"\nEnter the number:"<<count<<" ";
cin>>x;
innsatbeg(x);
count++;
cout<<"\nList is::";
print();
}
return 0;
}
| true |
70a3c258429fc0d5d2b6b0c0adc2e912cee3a790 | C++ | felsamps/overlap-spm-sim | /src/ExternalMemory.cpp | UTF-8 | 432 | 2.75 | 3 | [] | no_license | #include "../inc/ExternalMemory.h"
ExternalMemory::ExternalMemory() {
this->numOfReadBU = 0;
this->numOfPageAct = 0;
}
void ExternalMemory::read(Int burstLengthInBU) {
this->numOfReadBU += burstLengthInBU;
}
void ExternalMemory::report() {
cout << "EXTERNAL MEMORY REPORT" << endl;
cout << "READ_BU:\t" << this->numOfReadBU << endl;
cout << "READ_MB:\t" << this->numOfReadBU * (BU_SIZE*BU_SIZE) / (1024.0*1024.0) << endl;
} | true |
f37f701ddfafd3d6e793d22d91ebca635d6c47bb | C++ | zpoint/Reading-Exercises-Notes | /The_C++_Standard_Library/Algorithm/permutation.cpp | UTF-8 | 1,053 | 3.625 | 4 | [] | no_license | #include "algostuff.hpp"
int main()
{
/*
* https://stackoverflow.com/questions/11483060/stdnext-permutation-implementation-explanation
*/
std::vector<int> coll;
INSERT_ELEMENTS(coll, 1, 3);
PRINT_ELEMENTS(coll, "on entry: " );
// permute elements until they are sorted
// - run through all permutations because the elements are sorted now
while (std::next_permutation(coll.begin(), coll.end()))
PRINT_ELEMENTS(coll, " ");
PRINT_ELEMENTS(coll, "afterward: ");
// permute until descending sorted
// - this is the next permutation after ascending sorting
// - so the loop ends immediately
while (std::prev_permutation(coll.begin(), coll.end()))
PRINT_ELEMENTS(coll, " ");
PRINT_ELEMENTS(coll, "now: ");
// permute elements until they are sorted in descending order
// - run through all permutations because the elements are sorted in descending order now
while (std::prev_permutation(coll.begin(), coll.end()))
PRINT_ELEMENTS(coll, " ");
PRINT_ELEMENTS(coll, "afterward: ");
return 0;
}
| true |
79cd70ee8cf4f69bd4be65c377b764afc24c7729 | C++ | haruka-mt/paiza | /Rank_C/C039.cpp | UTF-8 | 611 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main(void)
{
string str;
cin >> str;
vector<int> num(1);
int index = 0;
for (int i = 0; i < str.size(); ++i)
{
if (str[i] == '+')
{
num.resize(num.size() + 1);
index++;
}
else if (str[i] == '<')
{
num[index] += 10;
}
else if (str[i] == '/')
{
num[index] += 1;
}
}
int ans = 0;
for (int i = 0; i < num.size(); ++i)
{
ans += num[i];
}
cout << ans << endl;
return 0;
} | true |
dd743ea1b3bbe3f48263b70961da1a0757535ef2 | C++ | yclizhe/acm | /POJ/1950/1950.cpp | UTF-8 | 1,030 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
const char op[3] = {'+','-','.'};
char ans[20];
int numofans;
int N;
void print() {
cout << 1;
for(int i=2; i<=N; i++)
cout << " " << ans[i-2] << " " << i;
cout << endl;
}
void dfs(int depth, int sum, int lastnum, char lastop) {
if(depth==N-1) {
if(lastop=='+')
sum += lastnum;
else
sum -= lastnum;
if(sum == 0 && ++numofans <= 20)
print();
return;
}
for(int i=0; i<3; i++) {
// int psum = sum, plastnum = lastnum, plastop = lastop;
int nsum = sum, nnum = lastnum, nop = lastop;
ans[depth] = op[i];
if(i<2) {
if(lastop=='+')
nsum = sum +lastnum;
else
nsum = sum -lastnum;
nop = op[i];
nnum = depth + 2;
}
else {
if(depth < 8)
nnum = lastnum*10 + (depth+2);
else
nnum = lastnum*100 + (depth+2);
}
if(nsum>10000000)
continue;
if(nnum>10000000)
continue;
dfs(depth+1, nsum, nnum, nop);
}
}
int main() {
cin >> N;
numofans = 0;
dfs(0,0,1,'+');
cout << numofans <<endl;
}
| true |
3d6282ae160b9e1fad8d79bd237247a8fc086476 | C++ | brian-jordan/ThreadLibrary | /test20.cc | UTF-8 | 13,709 | 2.765625 | 3 | [] | no_license | #include <stdlib.h>
#include <iostream>
#include "thread.h"
#include <assert.h>
#include <string.h>
#include <stdio.h>
using namespace std;
int maxOrdersOnBoard;
int numOrdersOnBoard;
int prevMadeSandwich;
int numCashiers;
unsigned int deliLock; //main lock
unsigned int makerCV; //maker condition variable
bool* arr;
unsigned int initialNumCashiers;
struct BoardListNode {
unsigned int cashierNumber; //unsigned int for lock
int sandwichNumber;
struct BoardListNode* next;
};
struct CashierInfo {
FILE* file_ptr;
unsigned int id;
};
BoardListNode* startBoardList;
BoardListNode* endBoardList;
void print_freelist() {
BoardListNode* freelist_head = startBoardList;
while(freelist_head != NULL) {
fprintf(stderr, "\tFreelist cashier numb:%d, sandwich Number:%d, Next:%p\t \n",
freelist_head->cashierNumber,
freelist_head->sandwichNumber,
freelist_head->next);
freelist_head = freelist_head->next;
}
}
int checkSandwhich(BoardListNode* start, unsigned int ID) {
BoardListNode* temp = start;
while(temp->sandwichNumber!=1001){
if(temp->cashierNumber==ID){
return 1;
}
else{
temp=temp->next;
}
}
return 0;
}
bool canSignalThisCashier(unsigned int ID) {
return arr[ID];
}
void turnCashierToFalse(unsigned int ID){
arr[ID] = false;
}
void turnCashierToTrue(unsigned int ID){
arr[ID] = true;
}
//get sandwhich take it off the board
void take_off() {
//BoardListNode* temp = ((struct BoardListNode*)(malloc(sizeof(struct BoardListNode))));
BoardListNode* temp = startBoardList->next;
//BoardListNode* removeTempNode = temp;
//temp->cashierNumber = 0; //************change from NULL
//temp->sandwichNumber = 0;
//temp->next = startBoardList;
// fprintf(stderr, "take_off: entering takeoff method\n");
// fprintf(stderr, "take_off: this prevMadeSandwich value is %d\n", prevMadeSandwich);
// fprintf(stderr, "take_off: this is the boardlist before the takeoff\n");
// print_freelist();
BoardListNode* removeNode=startBoardList->next;
int minDiff=10000;
BoardListNode* before= startBoardList;
BoardListNode* finalBefore;
while(temp->sandwichNumber!=1001){
//fprintf(stderr, "take off: entering the while loop\n");
int diff=abs((temp->sandwichNumber) - prevMadeSandwich);
//fprintf(stderr, "take off: diff is %d\n",diff);
if(diff<minDiff){
//fprintf(stderr, "take off: if: diff (%d) is less than minDiff (%d) \n",diff, minDiff);
minDiff=diff;
removeNode=temp;
finalBefore=before;
// fprintf(stderr, "take off: if: finalbefore is \n \tcashier numb:%d, sandwich Number:%d, Next:%p\t \n",
// finalBefore->cashierNumber,
// finalBefore->sandwichNumber,
// finalBefore->next);
// fprintf(stderr, "take off: if: removeNode is \n \tcashier numb:%d, sandwich Number:%d, Next:%p\t \n",
// removeNode->cashierNumber,
// removeNode->sandwichNumber,
// removeNode->next);
}
before=before->next;
temp = temp->next;
}
// fprintf(stderr, "take off: exited while loop and these are my node values \n");
// fprintf(stderr, "take off: if: finalbefore is \n \tcashier numb:%d, sandwich Number:%d, Next:%p\t \n",
// finalBefore->cashierNumber,
// finalBefore->sandwichNumber,
// finalBefore->next);
// fprintf(stderr, "take off: if: removeNode is \n \tcashier numb:%d, sandwich Number:%d, Next:%p\t \n",
// removeNode->cashierNumber,
// removeNode->sandwichNumber,
// removeNode->next);
finalBefore->next=removeNode->next;
// fprintf(stderr, "take off: removed the node and so this is my list now\n");
// print_freelist();
unsigned int madeCashierID = removeNode->cashierNumber;
int madeSandwichNumber = removeNode->sandwichNumber;
prevMadeSandwich = madeSandwichNumber;
numOrdersOnBoard--;
// fprintf(stderr, "take_off: after the takeoff the prevMadeSandwich value is %d\n", prevMadeSandwich);
// fprintf(stderr, "take_off: after the takeoff the numOrdersOnBoard value is %d\n", numOrdersOnBoard);
// fprintf(stderr, "take_off: after the takeoff the madeCashierID/cashier that will be signalled is %d\n", madeCashierID);
cout << "READY: cashier " << madeCashierID << " sandwich " << madeSandwichNumber << std::endl;
free(removeNode);
//free(removeTempNode);
// Print Made Sandwich info here
thread_signal(deliLock, madeCashierID);
}
int submitOrder(CashierInfo* info){
//fprintf(stderr, "submitOrder: just entered submit order function\n");
// fprintf(stderr, "Beginning of submitOrder method \n");
int fileReadResult;
int done = fscanf(info->file_ptr, "%d", &fileReadResult);
// fprintf(stderr, "File was read from \n");
// fprintf(stderr, "submitOrder: the done value is %d\n", done);
if(done == EOF){ //if there is no more sandwhiches to read, KILL IT
//fprintf(stderr, "submitOrder: if: entering first if DONE ==EOF %d\n", EOF);
numCashiers--; //decrement number of cashiers
//fprintf(stderr, "submitOrder: if: numCashiers is %d\n", numCashiers);
//fprintf(stderr, "submitOrder: if: returning from first if statement to kill thread\n");
int killThread=1;
return killThread;
}
else{ //more sandwhiches to read from this cashier so its NOT done
//add sandwhich to board
//fprintf(stderr, "submitOrder: else: entering else. cashier has more sandwiches\n");
BoardListNode* newOrder = ((struct BoardListNode*)(malloc(sizeof(struct BoardListNode))));
newOrder->cashierNumber = info->id;
newOrder->sandwichNumber = fileReadResult;
// fprintf(stderr, "submitOrder: this is the new order to submite \n");
// fprintf(stderr, "submitOrder: newOrder is \n \tcashier numb:%d, sandwich Number:%d, Next:%p\t \n",
// newOrder->cashierNumber,
// newOrder->sandwichNumber,
// newOrder->next);
BoardListNode* temp = startBoardList;
//fprintf(stderr, "submitOrder: else: while: entering while\n");
while(temp->sandwichNumber!=1001){ //last temp will be 1001 //check this through
if(temp->next->sandwichNumber>=fileReadResult){
// fprintf(stderr, "submitOrder: else: while: if: the sandwhich should go here in the list\n");
// fprintf(stderr, "submitOrder: else: while: if: this is the prev node aka temp\n");
// fprintf(stderr, "submitOrder: temp is\n \tcashier numb:%d, sandwich Number:%d, Next:%p\t \n",
// temp->cashierNumber,
// temp->sandwichNumber,
// temp->next);
// fprintf(stderr, "submitOrder: else: while: if: this is the next node aka temp->next\n");
// fprintf(stderr, "submitOrder: temp->next is\n \tcashier numb:%d, sandwich Number:%d, Next:%p\t \n",
// temp->next->cashierNumber,
// temp->next->sandwichNumber,
// temp->next->next);
newOrder->next = temp->next;
temp->next = newOrder;
break;
}
temp = temp->next;
}
// fprintf(stderr, "Sandwich was added to board \n");
numOrdersOnBoard++;
// fprintf(stderr, "submitOrder: this is the numOrdersOnBoard %d\n", numOrdersOnBoard);
// fprintf(stderr, "submitOrder: added the node and so this is my list now\n");
// print_freelist();
cout << "POSTED: cashier " << newOrder->cashierNumber << " sandwich " << newOrder->sandwichNumber << std::endl;
int killThread=0;
return killThread;
}
}
// Cashier Method for adding orders
void cashier(void* arg){ //unsigned int for lock??
// fprintf(stderr, "Cashier method starting \n");
CashierInfo* myInfo = ((CashierInfo*) arg);
//fprintf(stderr, "cashier: cashierNumber %d: enter cashier\n", myInfo->id);
while(1){
//fprintf(stderr, "cashier: cashierNumber %d: trying to acquire lock\n", myInfo->id);
thread_lock(deliLock);
//fprintf(stderr, "cashier: cashierNumber %d: has lock\n", myInfo->id);
// unsigned int x = myInfo->id;
// unsigned int y = checkSandwhich(startBoardList, myInfo->id);
// fprintf(stderr, "%u ", x);
// fprintf(stderr, "\n");
// fprintf(stderr, "%u ", y);
// fprintf(stderr, "\n");
// fprintf(stderr, "%u ", numOrdersOnBoard);
// fprintf(stderr, "\n");
while(numOrdersOnBoard == maxOrdersOnBoard || checkSandwhich(startBoardList, myInfo->id)){
//unsigned int x = myInfo->id
//fprintf(stderr, "cashier: cashierNumber %d: while:enter while loop to wait\n", myInfo->id);
thread_wait(deliLock, myInfo->id);
}
// fprintf(stderr, "cashier: out of wait while loop \n");
// fprintf(stderr, "Cashier Adding Order\n");
//fprintf(stderr, "cashier: cashierNumber %d: woken up, left wait + calling submitOrder\n", myInfo->id);
int killThread = submitOrder(myInfo);
if(killThread == 1){
//fprintf(stderr, "cashier: cashierNumber %d: killing this thread, signalling maker CV + unlocking\n", myInfo->id );
// fprintf(stderr, "max orders on board is %d\n", maxOrdersOnBoard);
turnCashierToFalse(myInfo->id);
//update largePoss number (since num chashiers aka live threads is diff)
if(numCashiers<maxOrdersOnBoard){
//fprintf(stderr, "cashier: if: if: enter if statement. numCashiers (%d) is < maxOrdersOnBoard (%d) \n", numCashiers, maxOrdersOnBoard);
maxOrdersOnBoard = numCashiers;
//fprintf(stderr, "======Signalling Maker \n");
thread_signal(deliLock, makerCV);
}else{
//fprintf(stderr, "cashier: if: else: signalling other cashiers. numCashiersis %d and maxOrdersOnBoard is %d\n", numCashiers, maxOrdersOnBoard);
for(unsigned int i=0;i<initialNumCashiers;i++){
if(arr[i]==true){
//fprintf(stderr, "im signalling cashier %u\n", i);
thread_signal(deliLock, i);
}
}
}
//signal maker so it can pick another cashier’s sandwhich
//cout << "Cashier thread exiting\n";
//fprintf(stderr, "cashier: cashierNumber %d: unlocking\n", myInfo->id);
thread_unlock(deliLock);
return;
}
//fprintf(stderr, "cashier: cashierNumber %d: signalling makerCV2 + unlocking\n", myInfo->id );
//fprintf(stderr, "======Signalling Maker \n");
thread_signal(deliLock, makerCV);
thread_unlock(deliLock);
}
}
// Maker Method for making orders
void maker(void* arg) {
// fprintf(stderr, "maker: enter maker\n");
// fprintf(stderr, "Beginning of maker method \n");
char **argv = (char **)(arg);
unsigned int counter = 0;
for (int i = 2; i < numCashiers + 2; i++){
//fprintf(stderr, "%s \n",((char*) arg)+i );
// FILE* specificCashierFile_ptr = fopen(((char*) arg)+i, "r"); // File reader corresponding to cashier
FILE* specificCashierFile_ptr = fopen(argv[i], "r");
unsigned int cashierID = counter;
counter=counter+1;
// Stores file reader and cashier number into a struct to pass as one argument
CashierInfo* specificCashierInfo_ptr = ((struct CashierInfo*)(malloc(sizeof(struct CashierInfo))));
specificCashierInfo_ptr->file_ptr = specificCashierFile_ptr;
specificCashierInfo_ptr->id = cashierID;
//fprintf(stderr, "Calling thread_create for single cashier \n");
// Creates cashier thread
if (thread_create((thread_startfunc_t) cashier, ((void*) specificCashierInfo_ptr))){
cout << "thread_create failed\n";
exit(1);
}
turnCashierToTrue(cashierID);
}
while(1){
//fprintf(stderr, "maker: enter while loop\n");
thread_lock(deliLock);
//while the board isn't full or the number of orders
//isn't at it's max then we wait for the board to be full
//we give up the lock and wait for the makerCV to change
//so that we are woken up!
while(numOrdersOnBoard!=maxOrdersOnBoard){
//fprintf(stderr, "maker: start wait\n");
//fprintf(stderr, "maker: while: numOrdersOnBoard is %d and maxOrdersOnBoard is %d\n", numOrdersOnBoard, maxOrdersOnBoard);
thread_wait(deliLock,makerCV);
}
///fprintf(stderr, "maker: out of wait\n");
//fprintf(stderr, "Maker Removing order\n");
//we fall out of the while loop with the lock. so we
//have the lock and now we are going to take off a sandwhich and make it
if(numCashiers==0){
//fprintf(stderr, "maker: numCashiers is 0 so gonna kill the maker %d\n",numCashiers );
free(startBoardList);
free(endBoardList);
thread_unlock(deliLock);
return;
//TO DO: KILL IT ALL, END OF THE PROGRAM
}else{
//fprintf(stderr, "maker: numCashiers is not 0 so calling take_off %d\n",numCashiers );
take_off();
}
//job is done, unlock the thread
//fprintf(stderr, "maker: unlocking thread\n");
thread_unlock(deliLock);
}
}
int main(int argc, char* argv[]){
//******BRIAN TODO: ~~~~~INITILIZE HERE AND CREATE THREADS~~~~
//*********
///*********
// Initializes global variables
//fprintf(stderr, "main \n");
//fprintf(stderr, "Initializing Global Variables \n");
maxOrdersOnBoard = atoi(argv[1]);
numOrdersOnBoard = 0;
numCashiers = argc - 2;
prevMadeSandwich = -1;
deliLock = 0;
makerCV = (unsigned int)argc; // Number we know is greater than number of cashiers
arr = (bool*) malloc(numCashiers * sizeof(bool));
initialNumCashiers = numCashiers;
// fprintf(stderr, "Initializing Boarld List \n");
// Initializes first and last nodes of the board linked list
startBoardList = ((struct BoardListNode*)(malloc(sizeof(struct BoardListNode))));
startBoardList->cashierNumber = -1;
startBoardList->sandwichNumber = -1;
endBoardList = ((struct BoardListNode*)(malloc(sizeof(struct BoardListNode))));
startBoardList->next = endBoardList;
endBoardList->cashierNumber = 10001;
endBoardList->sandwichNumber = 1001;
endBoardList->next = NULL;
// fprintf(stderr, "Calling thread_libinit with maker method \n");
// Initiates maker thread with no argument
if (thread_libinit((thread_startfunc_t) maker, ((void*) argv))){
cout << "thread_libinit failed \n";
exit(1);
}
//fprintf(stderr, "last main \n");
}
| true |
228d40348a88347ee55286ba912ac3e49a39c668 | C++ | pillowpilot/problem_solving | /CodeForces/534A - Exam/code.cpp | UTF-8 | 557 | 3.390625 | 3 | [] | no_license | #include <cstdio>
using namespace std;
int f(int n){
switch(n){
case 1:
case 2:
return 1;
case 3:
return 2;
default:
return n;
}
}
void example(int n){
switch(n){
case 1:
case 2:
printf("1");
break;
case 3:
printf("1 3");
break;
case 4:
printf("2 4 1 3");
break;
default:
for( int i = 1; i <= n; i += 2 ) printf("%d ", i);
for( int i = 2; i <= n; i += 2 ) printf("%d ", i);
break;
}
}
int main(){
int n;
scanf("%d", &n);
printf("%d\n", f(n));
example(n);
return 0;
}
| true |
00ae33fd2a7ec3d0cd239fcb5ff1d6a8d46f88c4 | C++ | Therealchainman/LeetCode | /problems/make_the_string_great/solution.cpp | UTF-8 | 548 | 3.015625 | 3 | [] | no_license | class Solution {
public:
string makeGood(string s) {
vector <char> stk;
for (int i=0;i<s.length();i++) {
stk.push_back(s[i]);
while (stk.size() >= 2 && stk.at(stk.size()-1) != stk.at(stk.size()-2)
&& tolower(stk.at(stk.size()-1)) == tolower(stk.at(stk.size()-2))) {
stk.pop_back();
stk.pop_back();
}
}
ostringstream res;
copy(stk.begin(), stk.end(),ostream_iterator<char>(res,""));
return res.str();
}
}; | true |
14f7f764af22e9000cacad34cbe898fec6d72cc5 | C++ | SinghVikram97/Interview-Prep | /String/1. (IMP) Reverse string.cpp | UTF-8 | 408 | 3.453125 | 3 | [] | no_license | string reverseString(string s){
int start=0;
int end=s.length()-1;
/// No harm in putting = as character swapped with same character
while(start<=end){
swap(s[start],s[end]);
start++;
end--;
}
return s;
}
string reverseString(string s){
reverse(s.begin(),s.end());
return s;
}
Reverses a string between [first,last)
reverse(s.begin(),s.begin()+2);
| true |
c6c1222e2a0c92d43e91a87590cee3a1bf3e0b3a | C++ | eduardor626/CS3A | /Test1_Eduardo_Vu/fraction.cpp | UTF-8 | 6,481 | 3.5 | 4 | [] | no_license | #include "fraction.h"
//CONSTRUCTORS:
fraction::fraction()
{
whole = 0;
numer = 0;
denom = 1;
}
fraction::fraction( int a)
{
whole = 0;
numer = a;
denom = 1;
}
fraction::fraction ( int a, int b)
{
if (b == 0)
throw DENOMINATOR_EQUALS_TO_ZERO;
whole = 0;
numer = a;
denom = b;
reduce ();
}
fraction::fraction ( int a, int b, int c)
{
if (c == 0)
throw DENOMINATOR_EQUALS_TO_ZERO;
whole = a;
numer = abs(b);
denom = abs(c);
if (whole < 0)
numer = (whole * denom) - numer;
else
numer = (whole*denom) + numer;
reduce();
}
fraction::fraction (const fraction &other)
{
numer = other.numer;
denom = other.denom;
}
fraction::fraction (double a)
{
fraction A;
A = a ;
numer = A.numer;
denom = A.denom;
reduce();
}
fraction::fraction (double a, double b)
{
fraction A(a);
fraction B(b);
fraction C = A / B;
numer = C.getNumer();
denom = C.getDenom();
reduce();
}
//SETTERS and GETTERS:
void fraction::setNumer (int b)
{
numer = b;
}
void fraction::setDenom (int c)
{
if (c == 0)
throw DENOMINATOR_EQUALS_TO_ZERO;
denom = c;
}
int fraction::getNumer () const
{
return numer;
}
int fraction::getDenom () const
{
return denom;
}
//CLASS FUNCTIONS:
void fraction::reduce()
{
int c = gcd (numer, denom);
numer /= c;
denom /= c;
if (double(numer)/denom < 0)
{
numer = -(abs(numer));
denom = abs(denom);
}else{
numer = abs(numer);
denom = abs(denom);
}
}
int fraction::gcd (int a, int b)
{
return ( a % b == 0) ? b : gcd(b, a % b);
}
void fraction::display()
{
if (numer == 0)
{
cout << 0 << endl;
return;
}
if (denom == 1)
{
cout << numer << endl;
}else
{
cout << numer << "/" << denom << endl;
}
}
void fraction::copy(const fraction &other)
{
numer = other.numer;
denom = other.denom;
}
//fraction friends.cpp ------
fraction operator+(const fraction &first, const fraction &second)
{
int numer, denom;
numer = first.numer * second.denom + first.denom * second.numer;
denom = first.denom * second.denom;
fraction third(numer,denom);
return third;
}
fraction operator-(const fraction &first, const fraction &second)
{
int numer, denom;
numer = first.numer * second.denom - first.denom * second.numer;
denom = first.denom * second.denom;
fraction third(numer, denom);
return third;
}
fraction operator*(const fraction &first, const fraction &second)
{
int numer, denom;
numer = first.numer * second.numer;
denom = first.denom * second.denom;
fraction third(numer, denom);
return third;
}
fraction operator/(const fraction &first, const fraction &second)
{
if (second != 0)
{
int numer, denom;
numer = first.numer * second.denom;
denom = first.denom * second.numer;
fraction third(numer, denom);
return third;
}else{
throw DEVIDED_BY_ZERO;
}
}
//FRIEND I/O OPERATORS:
istream& operator>>(istream &in, fraction &me)
{
char crap;
in>>me.numer >> crap >> me.denom;
if(me.getDenom() == 0)
me.setDenom(1);
me.reduce();
return in;
}
ostream& operator<<(ostream &out, const fraction &me)
{
if(me.denom == 0)
throw DENOMINATOR_EQUALS_TO_ZERO;
out << me.numer;
if(me.denom != 1 && me.denom !=0)
out << '/' <<me.denom;
return out;
}
//FRIEND LOGICAL OPERATORS:
bool operator==(const fraction &first, const fraction &second)
{
return (first.numer*second.denom == first.denom*second.numer);
}
bool operator!=(const fraction &first, const fraction &second)
{
return !(first == second);
}
bool operator>=(const fraction &first, const fraction &second)
{
return (first.numer*second.denom >= first.denom*second.numer);
}
bool operator<=(const fraction &first, const fraction &second)
{
return (first.numer*second.denom <= first.denom*second.numer);
}
bool operator>(const fraction &first, const fraction &second)
{
return !(first.numer*second.denom <= first.denom*second.numer);
}
bool operator<(const fraction &first, const fraction &second)
{
return !(first.numer*second.denom >= first.denom*second.numer);
}
//FRIEND LOGICAL OVERLOAD OPERATORS:
bool operator==(const fraction &first, int a)
{
return (first.getNumer() == (a*first.getDenom()));
}
bool operator!=(const fraction &first, int a)
{
return !(first==a);
}
bool operator>=(const fraction &first, int a)
{
return (first.getNumer() >= a*first.getDenom());
}
bool operator<=(const fraction &first, int a)
{
return (first.getNumer() <= a*first.getDenom());
}
bool operator<(const fraction &first, int a)
{
return !(first >= a);
}
bool operator>(const fraction &first, int a)
{
return !(first <= a);
}
//fractionoperators.cpp ------
fraction& fraction::operator +=(const fraction &other)
{
this->numer = this->numer*other.denom + other.numer*this->denom;
this->denom = this->denom * other.denom;
this->reduce();
return *this;
}
fraction& fraction::operator -= (const fraction &other)
{
this->numer = this->numer*other.denom - other.numer*this->denom;
this->denom = this->denom * other.denom;
this->reduce();
return *this;
}
fraction& fraction::operator *= (const fraction &other)
{
this->numer *= other.numer;
this->denom *= other.denom;
this->reduce();
return *this;
}
fraction& fraction::operator /= (const fraction &other)
{
if(other.numer == 0 || this->numer == 0)
throw DEVIDED_BY_ZERO;
this->numer *= other.denom;
this->denom *= other.numer;
this->reduce();
return *this;
}
fraction& fraction::operator=(const fraction &other)
{
numer = other.numer;
denom = other.denom;
return *this;
}
fraction& fraction::operator=(int a)
{
numer = a;
denom = 1;
return *this;
}
fraction& fraction::operator=(double a)
{
int leftVal = (int)a;
const int MAX_DIGITS = 9;
int digits = 0;
while (leftVal != 0)
{
leftVal /=10;
digits++;
}
int digitAllows = MAX_DIGITS - digits;
int pow = 1;
for (int i = 0 ; i < digitAllows && (int)(a*pow)!= INT_MIN ; i++)
pow *=10;
numer = a*pow;
denom = pow;
if (abs(numer)%10 == 9)
numer += numer >= 0 ? 1 : -1;
reduce();
return *this;
}
| true |
717751cc775a206a42c199fc3cebbc994b5e15c3 | C++ | Lisoph/MyTracer | /PlaneEntity.cpp | UTF-8 | 1,929 | 2.78125 | 3 | [] | no_license | #include "PlaneEntity.hpp"
#include <SDL.h>
static Eigen::Matrix4f Mat3to4(Eigen::Matrix3f const &mat3)
{
Eigen::Matrix4f mat4 = Eigen::Matrix4f::Identity();
mat4.block(0, 0, 3, 3) = mat3.block(0, 0, 3, 3);
return mat4;
}
static Eigen::Matrix4f QuatRotMatrix4(Eigen::Quaternionf const &quat)
{
return Mat3to4(quat.toRotationMatrix());
}
namespace MyTracer
{
namespace Tracing
{
SceneEntity::IntersResult PlaneEntity::Intersects(Ray const &ray)
{
float denom = mNormal.dot(ray.GetDir());
if(std::abs(denom) > 0.0001f)
{
Eigen::Vector3f p0l0 = mPosition - ray.GetOrigin();
float t = p0l0.dot(mNormal) / denom;
//return (t >= 0);
if(t >= 0.0001f)
{
return {true, {ray.GetOrigin() + ray.GetDir() * t}};
}
return {false, {}};
}
return {false, {}};
}
Eigen::Vector3f PlaneEntity::GetDiffuseAt(Eigen::Vector3f const &relativePos)
{
Eigen::Vector3f texturePlaneOrtho = Eigen::Vector3f::UnitZ(); // The normal vector that is orthogonal to the 2D 'texture' plane.
Eigen::Vector3f rotationAxis = mNormal.cross(texturePlaneOrtho); // It determines on which axes the relativePos should be projected on.
float angle = std::acos(mNormal.dot(texturePlaneOrtho));
Eigen::Matrix4f rotMat = QuatRotMatrix4(Eigen::Quaternionf(Eigen::AngleAxisf(angle, rotationAxis)));
float const extraRot = SDL_GetTicks() / 1000.0f * 0.05f;
auto const extraRotMat = QuatRotMatrix4(Eigen::Quaternionf(Eigen::AngleAxisf(extraRot, Eigen::Vector3f::UnitY())));
rotMat *= extraRotMat;
auto v4 = Eigen::Vector4f(relativePos(0), relativePos(1), relativePos(2), 1);
auto vnew = rotMat * v4;
auto x = int(std::round(vnew(0) / 4));
auto y = int(std::round(vnew(1) / 4));
if((x + y) % 2 == 0)
return {0, 1, 0};
return {1, 1, 0};
}
}
} | true |
309e6bd4df2e4ab8962ccc3b1c8160f63becc5cd | C++ | LeoSalemann/UW_HCDE539 | /Class02/temperature-sensor/Temperature/Temperature.ino | UTF-8 | 2,321 | 3.515625 | 4 | [
"Unlicense"
] | permissive | /* Thermometer
ahdavidson
www.goldensection.cc
8/1/11
This program implements a simple thermometer by reading data from a temperature sensor.
It then displays the values in the serial monitor window.
*/
// this constant shows where we'll find the temp sensor
const int sensorPin = A1; // must be an analog pin !!
// these variables are used to calculate the temperature
int sensorValue; // raw analog data
int sensorMV; // corresponding voltage
float tempCent; // degrees Fahrenheit
float tempFahr; // degrees Centigrade
void setup() {
// setup the pin for the temp sensor input
pinMode(sensorPin, INPUT);
// setup the serial port for sending data to the serial monitor or host computer
Serial.begin(9600);
// display a startup message
Serial.println ("Thermometer");
}
void loop() {
// read the raw value of the temp sensor
sensorValue = analogRead(sensorPin);
// an analog sensor on the Arduino returns a value between 0 and 1023, depending on the strength
// of the signal it reads. (this is because the Arduino has a 10-bit analog to digital converter.)
// so we have to convert this value between 0-1023 into a temperature. the calculation is based on the
// voltage, and then the specs of the temperature sensor to convert that into degrees Celsius.
// if you're not interested in the details, you can just think of it as doing some math magic and skip down below
// first, convert the sensor reading to the right voltage level (5000 mV, since the Arduino port is +5V)
// the map function is just an efficient shortcut for some ratio math
sensorMV = map(sensorValue, 0, 1023, 0, 4999);
// now convert this voltage to degrees, both Fahrenheit and Centigrade
// this calculation comes from the spec of the specific sensor we are using
tempCent = (sensorMV - 500) / 10.0;
tempFahr = (tempCent * 9 / 5.0) + 32;
// write these temperatures out to the serial monitor so we can see them
Serial.print(tempFahr);
Serial.print(" deg F ");
Serial.print(tempCent);
Serial.print(" deg C");
Serial.println();
// since temperature doesn't change so rapidly, we can set the delay here until the next check
// this should also work with shorter delays, or none for ultra real-time (OK, 9600 baud...)
delay (500);
}
| true |
3b704cf6dd03ee834afb158786b7db824946b890 | C++ | kimlavoie/OS_TP2 | /simvirtmem/src/interpreter.cpp | UTF-8 | 3,630 | 2.921875 | 3 | [] | no_license | // Auteur: Yves Chiricota 11/11/2000
#include "stdafx.h"
#include "interpreter.h"
#include "MMU.h"
// --------------------------------------------------------------------------------
// Fonction: operator>>
//
// Par: Yves Chiricota
// Date: 12/11/00
// MAJ:
// --------------------------------------------------------------------------------
istream& operator>>(istream& is, Command& cmd)
{
string fcmd;
is >> fcmd;
is >> cmd.adr;
if ( fcmd == string("read") )
cmd.cmd = Command::READ;
else if ( fcmd == string("write") )
cmd.cmd = Command::WRITE;
else if ( fcmd == "") throw 0; //Kim Lavoie (Un bogue a été corrigé ici)
else throw string("Invalid command");
if ( cmd.cmd == Command::WRITE )
{
int i;
is >> i;
cmd.val = (byte) i;
}
return is;
}
// --------------------------------------------------------------------------------
// Fonction: operator==
//
// Par: Yves Chiricota
// Date: 12/11/00
// MAJ:
// --------------------------------------------------------------------------------
bool operator==(const Command& c0, const Command& c1)
{
return c0.adr == c1.adr && c0.cmd == c1.cmd && c0.val == c1.val ;
}
// --------------------------------------------------------------------------------
// Classe: Interpreter
// Description:
//
// Par: Yves Chiricota
// Date: 12/11/00
// MAJ:
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Fonction: Interpreter
//
// Par: Yves Chiricota
// Date: 12/11/00
// MAJ:
// --------------------------------------------------------------------------------
Interpreter::Interpreter(MMU* _mmu) :
mmu(_mmu)
{
}
// --------------------------------------------------------------------------------
// Fonction: ~Interpreter
//
// Par: Yves Chiricota
// Date: 12/11/00
// MAJ:
// --------------------------------------------------------------------------------
Interpreter::~Interpreter()
{
}
// --------------------------------------------------------------------------------
// Fonction: Process
//
// Par: Yves Chiricota
// Date: 12/11/00
// MAJ:
// --------------------------------------------------------------------------------
bool Interpreter::Process(ifstream* _f_in)
{
Command cmd;
if ( !_f_in )
throw;
f_in = _f_in;
while ( Fetch(cmd) )
{
Exec(cmd);
}
return true;
}
// --------------------------------------------------------------------------------
// Fonction: Fetch
//
// Par: Yves Chiricota
// Date: 12/11/00
// MAJ:
// --------------------------------------------------------------------------------
bool Interpreter::Fetch(Command& cmd)
{
if ( !f_in )
throw;
if ( f_in->eof() )
return false;
try
{
(*f_in) >> cmd;
}
catch (string const& s)
{
std::cerr << "Invalid command" << std::endl;
return false;
}
catch ( ... )
{
return false;
}
return true;
}
// --------------------------------------------------------------------------------
// Fonction: Exec
//
// Par: Yves Chiricota
// Date: 12/11/00
// MAJ:
// --------------------------------------------------------------------------------
void Interpreter::Exec(Command& cmd)
{
switch ( cmd.cmd )
{
case Command::READ:
mmu->read(cmd.adr);
break;
case Command::WRITE:
mmu->write(cmd.val, cmd.adr); // Kim Lavoie (adresse et valeur étaient inversées)
break;
default:
break;
}
}
| true |
e089ac8365847af973e3733aaee419788bd419c9 | C++ | mfiore/pomdp | /PriorityQueue.h | UTF-8 | 726 | 2.828125 | 3 | [] | no_license | /*
* File: PriorityQueue.h
* Author: mfiore
*
* Created on January 28, 2015, 10:17 AM
*/
#ifndef PRIORITYQUEUE_H
#define PRIORITYQUEUE_H
#include <map>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
class PriorityQueue {
public:
PriorityQueue();
PriorityQueue(const PriorityQueue& orig);
virtual ~PriorityQueue();
bool isEmpty();
void pushElement(pair<int, double> element);
void editElement(int index, double priority);
double getPriority(int index);
pair<int, double> pop();
int size();
void print();
private:
std::vector<pair<int, double>*> queue;
std::map<int, pair<int, double>*> indexs;
};
#endif /* PRIORITYQUEUE_H */
| true |
4c671da09db526137aa3685e84fb9ccfe7f505e7 | C++ | dmitriano/Awl | /Tests/Helpers/RwTest.h | UTF-8 | 1,106 | 2.5625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Product: AWL (A Working Library)
// Author: Dmitriano
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "Awl/Io/ReadWrite.h"
#include "Awl/Io/VectorStream.h"
#include "Awl/Testing/UnitTest.h"
using namespace awl::testing;
using namespace awl::io;
namespace awl::testing::helpers
{
template <class T>
void TestReadWrite(const TestContext& context, const T& sample)
{
AWT_ATTRIBUTE(size_t, iteration_count, 10);
std::vector<uint8_t> reusable_v;
VectorOutputStream out(reusable_v);
for (size_t i = 0; i < iteration_count; ++i)
{
Write(out, sample);
}
VectorInputStream in(reusable_v);
for (size_t i = 0; i < iteration_count; ++i)
{
T result;
Read(in, result);
AWT_ASSERT(sample == result);
}
AWT_ASSERT(in.End());
}
}
| true |
158feb8c0249242b498536f9b390b4a422722123 | C++ | davidlinn/BestASVCode | /libraries_old_old/main/PControl.cpp | UTF-8 | 2,167 | 2.984375 | 3 | [] | no_license | #include "PControl.h"
#include "Printer.h"
extern Printer printer;
inline float angleDiff(float a) {
while (a<-PI) a += 2*PI;
while (a> PI) a -= 2*PI;
return a;
}
PControl::PControl(void) {
}
void PControl::init(const int totalWayPoints_in, const int stateDims_in, double * wayPoints_in) {
totalWayPoints = totalWayPoints_in;
stateDims = stateDims_in;
wayPoints = wayPoints_in;
}
int PControl::getWayPoint(int dim) {
return wayPoints[currentWayPoint*stateDims+dim];
}
void PControl::calculateControl(state_t * state) {
updatePoint(state->x, state->y);
if (currentWayPoint == totalWayPoints) return; // stops motors at final point
// set up variables
int x_des = getWayPoint(0);
int y_des = getWayPoint(1);
yaw_des = atan2(y_des - state->y, x_des - state->x); //atan2 returns a value [-pi,pi]
yaw = state->heading;
u = Kp*angleDiff(yaw_des - yaw);
uL = max(0.0,min(255.0,(avgPower - u)*Kl));
uR = max(0.0,min(255.0,(avgPower + u)*Kr));
}
String PControl::printString(void) {
String printString = "PControl: Yaw_Des: " + String(yaw_des*180.0/PI)
+ " Yaw: " + String(yaw*180.0/PI)
+ " u: " + String(u);
return printString;
}
String PControl::printWaypointUpdate(void) {
String wayPointUpdate = "PControl: Current Waypoint: " + String(currentWayPoint)
+ " Distance from Waypoint: " + String(dist);
return wayPointUpdate;
}
void PControl::updatePoint(float x, float y) {
if (currentWayPoint == totalWayPoints) return; // don't check if finished
int x_des = getWayPoint(0);
int y_des = getWayPoint(1);
dist = sqrt(pow(x-x_des,2) + pow(y-y_des,2));
if (dist < SUCCESS_RADIUS && currentWayPoint < totalWayPoints) {
String changingWPMessage = "Got to waypoint " + String(currentWayPoint)
+ ", now directing to next point";
int cwpmTime = 20;
currentWayPoint++;
if (currentWayPoint == totalWayPoints) {
changingWPMessage = "Congratulations! You completed the path! Stopping motors.";
uR=0;
uL=0;
cwpmTime = 0;
}
printer.printMessage(changingWPMessage,cwpmTime);
}
}
| true |
a12698e8a2b18088486cabf421b8b329b66a0a97 | C++ | YLiuzz/Arduino | /light_senser2.ino | UTF-8 | 334 | 2.640625 | 3 | [] | no_license | //define
int value = 0;
int pin = A2;
int threshold = 500 ;
int led = 13;
//setup
void setup()
{
Serial.begin(9600);
pinMode(pin, INPUT);
}
//loop
void loop()
{
value analogRead(pin);
if(value>threshold){
digitalWrite(led, LOW);
}else{
digitalWrite(led, HIGH);
}
Serial.println(value);
delay(1000);
}
| true |
dadfe3ac2ad2909c9343587e41b51441035dc9b8 | C++ | EsunnyAPI/zcel2api_demo | /zcel2api_demo.cpp | GB18030 | 3,049 | 2.671875 | 3 | [] | no_license | #include "zcel2api/ZceLevel2ApiInterface.h"
#include <iostream>
#include <windows.h>
using namespace std;
//====================================================
//
// Ŀ
//
//Level2 IPַ
const char* ZCEL2_SERVICE_IP = "";
//Level2 ˿
const int ZCEL2_SERVICE_PORT = 0;
//Level2 û
const char* ZCEL2_SERVICE_USERNAME = "滻Ϊû";
//Level2
const char* ZCEL2_SERVICE_PASSWORD = "滻Ϊ";
//====================================================
// ʵIZCEL2QuoteNotifyӿڣڽLevel2API֪ͨ
class ZCEL2Quote : public IZCEL2QuoteNotify
{
public:
virtual void ZCEL2QUOTE_CALL OnRspLogin(const ZCEL2QuotRspLoginField& loginMsg)
{
if(loginMsg.ErrorCode == ZCEErrCode_Success)
{
cout << "½ɹ, ʱ䣺" << loginMsg.TimeStamp << endl;
}
else
{
cout << "½ʧ, ԭ" << loginMsg.ErrorCode << " , " << loginMsg.ErrorText << endl;
}
}
virtual void ZCEL2QUOTE_CALL OnRecvQuote(const ZCEL2QuotSnapshotField& snapshot)
{
cout << ":"
<< snapshot.TimeStamp << ","
<< snapshot.ContractID << ","
<< snapshot.LastPrice << ","
<< snapshot.BidPrice[0] << ","
<< snapshot.AskPrice[0] << ","
<< snapshot.BidLot[0] << ","
<< snapshot.AskLot[0] << ","
<< snapshot.TotalVolume << ","
<< snapshot.OpenInterest
<< endl;
}
virtual void ZCEL2QUOTE_CALL OnRecvCmbQuote(const ZCEL2QuotCMBQuotField& snapshot)
{
cout << ":"
<< snapshot.TimeStamp << ","
<< snapshot.ContractID << ","
<< snapshot.BidPrice << ","
<< snapshot.AskPrice << ","
<< snapshot.BidLot << ","
<< snapshot.AskLot << ","
<< endl;
}
virtual void ZCEL2QUOTE_CALL OnConnectClose()
{
cout << "ӶϿ" << endl;
}
};
int main()
{
//notify ʵ
ZCEL2Quote notify;
//ZCEL2QuotClientʵ
IZCEL2QuoteClient* pZCEL2QuoteClient = CreateZCEL2QuotClient(¬ify);
if(NULL == pZCEL2QuoteClient)
{
cerr << "ZCEL2APIʧ" <<endl;
return -1;
}
//鿴汾Ϣ
cout << "ZCEL2API Version:" << pZCEL2QuoteClient->GetAPIVersion() << endl;
ZCEINT4 iErr = ZCEErrCode_Success;
//÷IP
iErr = pZCEL2QuoteClient->SetService(ZCEL2_SERVICE_IP,ZCEL2_SERVICE_PORT);
if(ZCEErrCode_Success != iErr)
{
cerr << "SetService Err: "<< iErr << endl;
return -1;
}
//
iErr = pZCEL2QuoteClient->ConnectService();
if(ZCEErrCode_Success != iErr)
{
cerr << "ConnectService Err"<< endl;
return -1;
}
//½
ZCEL2QuotReqLoginField stUserMsg;
memset(&stUserMsg, 0, sizeof(stUserMsg));
strcpy(stUserMsg.UserNo, ZCEL2_SERVICE_USERNAME);
strcpy(stUserMsg.Password, ZCEL2_SERVICE_PASSWORD);
iErr = pZCEL2QuoteClient->Login(&stUserMsg);
if(ZCEErrCode_Success != iErr)
{
cerr << "Login Err: "<< iErr << endl;
return -1;
}
while(true)
{
Sleep(1000);
}
return 0;
} | true |
03b31bacf9510c81544839bf845dbe18f98b7ed7 | C++ | oydang/CS4701-pokemon-AI | /Tracer-VisualboyAdvance1.7.1/Tracer-VisualboyAdvance1.7.1/source/src/Pathlib.h | SHIFT_JIS | 1,508 | 2.609375 | 3 | [
"MIT"
] | permissive | //
// pXCuNX
//
#ifndef __CPATHLIB_INCLUDED__
#define __CPATHLIB_INCLUDED__
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <string>
using namespace std;
class CPathlib
{
public:
// pX{t@Cl[̃pX擾
static string SplitPath( LPCSTR lpszPath );
// pX{t@Cl[̃t@C擾(gqȂ)
static string SplitFname( LPCSTR lpszPath );
// pX{t@Cl[̃t@C擾(gq)
static string SplitFnameExt( LPCSTR lpszPath );
static string SplitExt( LPCSTR lpszPath );
// pXCt@C̃pX쐬(gq/Ȃp)
static string MakePath( LPCSTR lpszPath, LPCSTR lpszFname );
// pXCt@CCgq̃pX쐬(gqʂɎw)
static string MakePathExt( LPCSTR lpszPath, LPCSTR lpszFname, LPCSTR lpszExt );
// x[XpXljpX̎ނׂăpX쐬
// ljpXpXȂ̂܂܁CpXȂx[XpXɒlj
static string CreatePath( LPCSTR lpszBasePath, LPCSTR lpszPath );
// tH_I
static BOOL SelectFolder( HWND hWnd, LPCSTR lpszTitle, LPSTR lpszFolder );
protected:
static INT CALLBACK BffCallback( HWND hWnd, UINT uMsg, LPARAM lParam, WPARAM wParam );
private:
};
#endif // !__CPATHLIB_INCLUDED__
| true |
f615292bc864899a3c1a4e4a5323e5ac1b3c8b3b | C++ | zhubo240/870-oo-design | /p3/TwoWayMultiSprite.h | UTF-8 | 706 | 2.546875 | 3 | [] | no_license | /*
* TwoWaySprite.h
*
* Created on: Oct 13, 2015
* Author: zhubo
*/
#ifndef TWOWAYMULTISPRITE_H_
#define TWOWAYMULTISPRITE_H_
#include "multisprite.h"
class TwoWayMultiSprite: public MultiSprite {
public:
TwoWayMultiSprite(const string & name);
virtual ~TwoWayMultiSprite();
// TODO : even I know it is virtual, I still need to write those there
//why there are some link error, if I keep this virtual method in .h
//virtual void draw() const;
virtual void advanceFrame(Uint32 ticks);
virtual void move(Uint32 ticks);
protected:
enum Dir {LARGER, SMALLER};
//TODO : enum Dir or Dir
Dir dir;
//enum
int numFramesOneDir;
bool dirChanged;
};
#endif /* TWOWAYMULTISPRITE_H_ */
| true |
3e9214029cedc097b133bc7f9b3f7d459d5c03f8 | C++ | mjenrungrot/competitive_programming | /UVa Online Judge/v117/11797.cc | UTF-8 | 1,767 | 2.75 | 3 | [
"MIT"
] | permissive | /*=============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 11797.cc
# Description: UVa Online Judge - 11797
=============================================================================*/
#include <bits/stdc++.h>
using namespace std;
map<string, int> nameToIdx;
queue<string> Q[5];
int counter[5];
int M, N;
string name;
int main() {
nameToIdx["Ja"] = 0;
nameToIdx["Sam"] = 1;
nameToIdx["Sha"] = 2;
nameToIdx["Sid"] = 3;
nameToIdx["Tan"] = 4;
int T;
scanf("%d", &T);
for (int _i = 1; _i <= T; _i++) {
printf("Case %d:\n", _i);
memset(counter, 0, sizeof(counter));
for (int k = 0; k < 5; k++)
while (not Q[k].empty()) Q[k].pop();
scanf("%d %d", &M, &N);
cin >> name;
for (int k = 0; k < 5; k++) {
int x;
string tmp;
scanf("%d", &x);
for (int i = 1; i <= x; i++) {
cin >> tmp;
Q[k].push(tmp);
}
}
int curr = 0, curr_idx = nameToIdx[name];
while (curr < N) {
curr++;
counter[curr_idx]++;
if (curr == M) {
N -= M;
N -= 2;
curr = 0;
string new_person = Q[curr_idx].front();
Q[curr_idx].pop();
Q[curr_idx].push(new_person);
curr_idx = nameToIdx[new_person];
}
}
printf("Ja %d\n", counter[0]);
printf("Sam %d\n", counter[1]);
printf("Sha %d\n", counter[2]);
printf("Sid %d\n", counter[3]);
printf("Tan %d\n", counter[4]);
}
return 0;
} | true |
7db05814108999620d4ee65469429b53dc55fd1c | C++ | Celissa/Legacy-Base | /src/fire.cpp | UTF-8 | 12,853 | 2.546875 | 3 | [] | no_license | #include "system.h"
bool fireball_effect ( char_data*, char_data*, int );
/*
* SMOKE COMMAND
*/
void do_smoke( char_data* ch, char* argument )
{
obj_data* pipe;
obj_data* tobacco;
if( *argument == '\0' ) {
send( ch, "What do you want to smoke?\r\n" );
return;
}
if( ( pipe = one_object( ch, argument, "smoke", &ch->contents ) ) == NULL )
return;
if( pipe->pIndexData->item_type == ITEM_TOBACCO ) {
send( ch, "You need to put that in a pipe to smoke it.\r\n" );
return;
}
if( pipe->pIndexData->item_type != ITEM_PIPE ) {
send( ch, "That is not an item you can smoke.\r\n" );
return;
}
if( is_empty( pipe->contents ) ) {
send( ch, "%s contains nothing to smoke.\r\n", pipe );
return;
}
tobacco = object( pipe->contents[0] );
fsend( ch, "You smoke %s, inhaling the aroma from %s.", pipe, tobacco );
fsend( *ch->array, "%s smokes %s.", ch, pipe );
var_container = pipe;
if( execute_use_trigger( ch, tobacco, OPROG_TRIGGER_USE ) )
return;
tobacco->Extract( );
}
/*
* IGNITE
*/
void do_ignite( char_data* ch, char* argument )
{
affect_data affect;
obj_data* obj;
obj_data* source = NULL;
bool found = FALSE;
if( ch->shdata->race == RACE_TROLL ) {
send( ch, "Due to the natural attraction of flame and troll flesh and the associated\r\nchildhood nightmares burning things is not one of your allowed hobbies.\r\n" );
return;
}
if( ch->shdata->race == RACE_ENT ) {
send( ch, "Due to the natural attraction of flame and ent flesh and the associated\r\nchildhood nightmares burning things is not one of your allowed hobbies.\r\n" );
return;
}
if( ( obj = one_object( ch, argument, "ignite",
&ch->wearing, &ch->contents, ch->array ) ) == NULL )
return;
if( is_set( obj->extra_flags, OFLAG_BURNING ) ) {
send( ch, "%s is already burning.\r\n", obj );
return;
}
for( int i = 0; !found && i < *ch->array; i++ )
if( ( source = object( ch->array->list[i] ) ) != NULL
&& is_set( source->extra_flags, OFLAG_BURNING ) )
found = TRUE;
for( int i = 0; !found && i < ch->contents; i++ )
if( ( source = object( ch->contents[i] ) ) != NULL
&& is_set( source->extra_flags, OFLAG_BURNING ) )
found = TRUE;
if( !found ) {
send( ch, "You have nothing with which to ignite %s.\r\n", obj );
return;
}
if( obj->vs_fire( ) > 90 ) {
send( ch, "Depressingly %s doesn't seem inclined to burn.\r\n", obj );
return;
}
send( ch, "You ignite %s using %s.\r\n", obj, source );
send( *ch->array, "%s ignites %s using %s.\r\n", ch, obj, source );
affect.type = AFF_BURNING;
affect.duration = 1;
affect.level = 1;
affect.leech = NULL;
add_affect( obj, &affect );
}
/*
* FIRE DAMAGE ROUTINES
*/
int obj_data :: vs_fire( )
{
int save = 100;
int i;
for( i = 0; i < MAX_MATERIAL; i++ )
if( is_set( &pIndexData->materials, i ) )
save = min( save, material_table[i].save_fire );
if( pIndexData->item_type != ITEM_ARMOR
|| pIndexData->item_type != ITEM_WEAPON
|| pIndexData->item_type != ITEM_SHIELD )
return save;
return save+value[0]*(100-save)/(value[0]+2);
}
bool affected_cold( char_data* ch )
{
if( !is_set( ch->affected_by, AFF_FROST_SHIELD ) &&
!is_set( ch->affected_by, AFF_HOAR_SHIELD ) &&
!is_set( ch->affected_by, AFF_HOAR_FROST ) &&
!is_set( ch->affected_by, AFF_ABSOLUTE_ZERO ) )
return FALSE;
return TRUE;
}
/*
* FIRE BASED SPELLS
*/
bool spell_resist_fire( char_data* ch, char_data* victim, void*, int level, int duration )
{
spell_affect( ch, victim, level, duration, SPELL_RESIST_FIRE, AFF_RESIST_FIRE );
return TRUE;
}
bool spell_fire_shield( char_data* ch, char_data* victim, void*, int level, int duration )
{
if( is_submerged( victim ) ) {
fsend_all( victim->in_room, "The water around %s bubbles briefly.\r\n",
victim );
return TRUE;
}
if( !consenting( victim, ch, "fire shield" ) )
return FALSE;
if( affected_cold( victim ) ) {
send( victim, "The freezing shields protecting you dissipate.\r\n" );
send_seen( victim, "The freezing shields protecting %s dissipate.\r\n", victim );
return FALSE;
}
spoil_hide( victim );
spell_affect( ch, victim, level, duration, SPELL_FIRE_SHIELD, AFF_FIRE_SHIELD );
return TRUE;
}
bool spell_flame_shield( char_data* ch, char_data* victim, void*, int level, int duration )
{
if( is_submerged( victim ) ) {
fsend_all( victim->in_room, "The water around %s bubbles briefly.\r\n",
victim );
return TRUE;
}
if( !consenting( victim, ch, "shield of flame" ) )
return FALSE;
if( affected_cold( victim ) ) {
send( victim, "The freezing shields protecting you dissipate.\r\n" );
send_seen( victim, "The freezing shields protecting %s dissipate.\r\n", victim );
return FALSE;
}
spoil_hide( victim );
spell_affect( ch, victim, level, duration, SPELL_FLAME_SHIELD, AFF_FLAME_SHIELD );
return TRUE;
}
bool spell_fiery_shield( char_data* ch, char_data* victim, void*, int level, int duration )
{
if( is_submerged( victim ) ) {
fsend_all( victim->in_room, "The water around %s bubbles briefly.\r\n",
victim );
return TRUE;
}
if( !consenting( victim, ch, "fiery shield" ) )
return FALSE;
if( affected_cold( victim ) ) {
send( victim, "The freezing shields protecting you dissipate.\r\n" );
send_seen( victim, "The freezing shields protecting %s dissipate.\r\n", victim );
return FALSE;
}
spoil_hide( victim );
spell_affect( ch, victim, level, duration, SPELL_FIERY_SHIELD, AFF_FIERY_SHIELD );
return TRUE;
}
bool spell_inferno_shield( char_data* ch, char_data* victim, void*, int level, int duration )
{
if( is_submerged( victim ) ) {
fsend_all( victim->in_room, "The water around %s bubbles briefly.\r\n",
victim );
return TRUE;
}
if( !consenting( victim, ch, "shield of the inferno" ) )
return FALSE;
if( affected_cold( victim ) ) {
send( victim, "The freezing shields protecting you dissipate.\r\n" );
send_seen( victim, "The freezing shields protecting %s dissipate.\r\n", victim );
return FALSE;
}
spoil_hide( victim );
spell_affect( ch, victim, level, duration, SPELL_FIRE_SHIELD, AFF_FIRE_SHIELD );
return TRUE;
}
bool spell_ignite_weapon( char_data* ch, char_data*, void* vo, int level, int )
{
affect_data affect;
obj_data* obj = (obj_data*) vo;
if( null_caster( ch, SPELL_IGNITE_WEAPON ) )
return TRUE;
if( is_set( &obj->pIndexData->materials, MAT_WOOD ) ) {
fsend( ch, "%s you are carrying bursts into flames which quickly consume it.", obj );
fsend( *ch->array, "%s %s is carrying bursts into flames which quickly consume it.", obj, ch );
obj->Extract( 1 );
return TRUE;
}
affect.type = AFF_FLAMING;
affect.duration = level;
affect.level = level;
affect.leech = NULL;
add_affect( obj, &affect );
return TRUE;
}
/*
* DAMAGE SPELLS
*/
/*
bool spell_burning_hands( char_data* ch, char_data* victim, void*, int level, int )
{
if( null_caster( ch, SPELL_BURNING_HANDS ) )
return TRUE;
damage_fire( victim, ch, spell_damage( SPELL_BURNING_HANDS, level ), "*the burst of flame" );
return TRUE;
}
*/
bool spell_burning_hands( char_data* ch, char_data* victim, void* vo, int level, int duration )
{
obj_data* obj = (obj_data*) vo;
int save;
/* Quaff */
if( ch == NULL && obj == NULL ) {
fsend( victim, "You feel incredible pain as you combust from the liquid you consumed. Luckily you don't feel it for long." );
fsend_seen( victim, "%s grasps %s throat and spasms in pain - %s does not survive long.", victim, victim->His_Her( ), victim->He_She( ) );
death_message( victim );
death( victim, NULL, "burning to death" );
return TRUE;
}
/* Fill */
if( ch == NULL ) {
if( obj->metal( ) || is_set( &obj->materials, MAT_STONE ) )
return FALSE;
fsend( victim, "The fire burns its way through %s, which you quickly drop and watch disappear into nothing.\r\n", obj );
fsend( *victim->array, "%s quickly drops %s as %s destoryed by the liquid.", victim, obj, obj->selected > 1 ? "they are" : "it is" );
obj->Extract( obj->selected );
return TRUE;
}
/* Dip */
if( duration == -3 ) {
save = obj->vs_fire( );
if( number_range( 0,99 ) > save ) {
if( number_range( 0,99 ) > save ) {
send( *ch->array, "%s is consumed in flames.\r\n", obj );
obj->Extract( 1 );
return TRUE;
}
send( ch, "%s is partially destroyed.\r\n", obj );
}
return TRUE;
}
/* Throw-Cast */
damage_fire( victim, ch, spell_damage( SPELL_BURNING_HANDS, level ), "*the burst of flame" );
return TRUE;
}
bool spell_flame_strike( char_data* ch, char_data* victim, void*, int level, int )
{
damage_fire( victim, ch, spell_damage( SPELL_FLAME_STRIKE, level ), "*An incandescent spear of flame" );
return TRUE;
}
bool spell_conflagration( char_data* ch, char_data* victim, void*, int level, int )
{
damage_fire( victim, ch, spell_damage( SPELL_CONFLAGRATION, level ), "*A raging inferno" );
return TRUE;
}
/*
* FIREBALL
*/
bool spell_fireball( char_data* ch, char_data* victim, void*, int level, int )
{
if( null_caster( ch, SPELL_FIREBALL ) )
return TRUE;
if( fireball_effect( ch, victim, level ) )
return TRUE;
if( victim->in_room != ch->in_room )
return TRUE;
if( victim->mount != NULL )
fireball_effect( ch, victim->mount, level );
if( victim->rider != NULL )
fireball_effect( ch, victim->rider, level );
return TRUE;
}
bool fireball_effect( char_data *ch, char_data *victim, int level )
{
if( damage_fire( victim, ch, spell_damage( SPELL_FIREBALL,level ), "*The raging fireball" ) )
return TRUE;
if( victim->mount != NULL )
if( number_range( 0, 12*MAX_SKILL_LEVEL/10 ) > victim->get_skill( SKILL_RIDING ) ) {
send( "The blast throws you from your mount!\r\n", victim );
fsend_seen( victim, "%s is thrown from %s mount by the blast.", victim, victim->Him_Her() );
victim->mount->rider = NULL;
victim->mount = NULL;
victim->position = POS_RESTING;
set_delay(victim, 32);
return FALSE;
}
if( number_range( 0, SIZE_HORSE ) > victim->Size( ) && number_range( 0, 100 ) < 7 ) {
exit_data *exit = random_movable_exit(victim);
if (!exit)
return FALSE;
send( victim, "The blast throws you %s from the room!\r\n", dir_table[exit->direction].name );
fsend_seen( victim, "The blast throws %s %s from the room!", victim, dir_table[exit->direction].name );
// room_data *in_room = ch->in_room;
room_data *to_room = exit->to_room;
victim->From( );
victim->To( to_room );
fsend_seen( victim, "A large explosion flings %s in from %s!", victim, dir_table[ exit->direction ].arrival_msg );
send( "\r\n", victim );
do_look( victim, "");
}
return FALSE;
}
bool spell_inferno( char_data* ch, char_data* victim, void*, int level, int )
{
damage_element( victim, ch, spell_damage( SPELL_INFERNO, level ), "*the raging inferno", ATT_FIRE );
return TRUE;
}
/*
* Druid Fire Spells
*/
bool spell_summer_touch( char_data* ch, char_data* victim, void*, int level, int )
{
damage_element( victim, ch, spell_damage( SPELL_SUMMER_TOUCH, level ), "*The scorching summer heat", ATT_FIRE );
return TRUE;
}
bool spell_dancing_tallow( char_data* ch, char_data* victim, void*, int level, int )
{
damage_element( victim, ch, spell_damage( SPELL_DANCING_TALLOW, level ), "*The whip like tendril of fire", ATT_FIRE );
return TRUE;
}
bool spell_fire_ant( char_data* ch, char_data* victim, void*, int level, int )
{
damage_element( victim, ch, spell_damage( SPELL_FIRE_ANT, level ), "*The fire ants bite", ATT_FIRE );
return TRUE;
}
bool spell_river_magma( char_data* ch, char_data* victim, void*, int level, int )
{
damage_element( victim, ch, spell_damage( SPELL_RIVER_MAGMA, level ), "*The river of magma", ATT_FIRE );
return TRUE;
}
bool spell_sunburst( char_data* ch, char_data*, void*, int level, int duration )
{
char_data* rch;
if( null_caster( ch, SPELL_SUNBURST ) )
return TRUE;
for( int i = *ch->array-1; i >= 0; i-- )
if( ( rch = character( ch->array->list[i] ) ) != NULL && rch != ch && can_kill( ch, rch, false ) && rch->Seen( ch ) ) {
damage_element( rch, ch, spell_damage( SPELL_SUNBURST, level ), "*The raging sunburst", ATT_FIRE );
if( !makes_save( rch, ch, RES_MAGIC, SPELL_SUNBURST, level ) && rch->Can_See( ) )
spell_affect( ch, rch, level, duration, SPELL_SUNBURST, AFF_BLIND );
}
return TRUE;
}
| true |
4a7fd0764fd1c876680887d9a54d43e40926abb5 | C++ | iwasz/bajka | /library/trunk/src/tween/AtomicTween.cc | UTF-8 | 4,345 | 2.546875 | 3 | [] | no_license | /****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#include "AtomicTween.h"
#include "Manager.h"
namespace Tween {
void AtomicTween::Target::init ()
{
assertThrow (accessor, "AtomicTween::init : !accessor");
if (tween->type == AtomicTween::TO) {
startValue = accessor->getValue (tween->object);
}
else {
endValue = accessor->getValue (tween->object);
}
}
/****************************************************************************/
void AtomicTween::Target::update ()
{
double deltaValue = endValue - ((absolute) ? (startValue) : (0));
double comuted = tween->equation->compute (tween->currentMs, startValue, deltaValue, tween->durationMs);
accessor->setValue (tween->object, comuted);
}
/*##########################################################################*/
AtomicTween *to (void *targetObject, unsigned int durationMs, Ease ease)
{
AtomicTween *tween = Manager::getMain ()->newAtomicTween ();
tween->equation = Manager::getMain ()->getEase (ease);
tween->durationMs = durationMs;
tween->object = targetObject;
tween->type = AtomicTween::TO;
return tween;
}
/****************************************************************************/
AtomicTween *from (void *targetObject, unsigned int durationMs, Ease ease)
{
AtomicTween *tween = Manager::getMain ()->newAtomicTween ();
tween->equation = Manager::getMain ()->getEase (ease);
tween->durationMs = durationMs;
tween->object = targetObject;
tween->type = AtomicTween::FROM;
return tween;
}
/****************************************************************************/
void AtomicTween::initEntry (bool reverse) {}
void AtomicTween::initExit (bool reverse)
{
currentRepetition = repetitions;
// currentMs = ((forward) ? (0) : (durationMs));
for (TargetVector::iterator i = targets.begin (); i != targets.end (); ++i) {
(*i)->init ();
}
}
void AtomicTween::delayEntry (bool reverse)
{
currentMs = 0;
}
void AtomicTween::delayExit (bool reverse)
{
}
void AtomicTween::runEntry (bool reverse)
{
currentMs = ((forward ^ reverse) ? (0) : (durationMs));
}
void AtomicTween::runExit (bool reverse) {}
void AtomicTween::finishedEntry (bool reverse) {}
void AtomicTween::finishedExit (bool reverse)
{
currentRepetition = repetitions;
}
/****************************************************************************/
void AtomicTween::updateRun (int deltaMs, bool direction)
{
// Wylicz currentMs
if (direction) {
currentMs += deltaMs;
if (currentMs > durationMs) {
currentMs = durationMs;
}
}
else {
currentMs -= deltaMs;
if (currentMs < 0) {
currentMs = 0;
}
}
// Tweenuj
for (TargetVector::iterator i = targets.begin(); i != targets.end(); ++i) {
(*i)->update ();
}
}
/****************************************************************************/
bool AtomicTween::checkEnd (bool direction)
{
return (direction && currentMs >= durationMs) || (!direction && currentMs <= 0);
}
/****************************************************************************/
AtomicTween *AtomicTween::target (unsigned int property, double value, bool abs)
{
Target *target = Manager::getMain ()->newTarget ();
target->accessor = Manager::getMain ()->getAccessor (property);
if (type == TO) {
target->endValue = value;
}
else if (type == FROM) {
target->startValue = value;
}
target->absolute = abs;
target->tween = this;
targets.push_back (target);
return this;
}
} /* namespace Tween */
| true |
15580c0175f45f57c54eb4ebd1f9855f7b1f377b | C++ | NishantRaj/program_files | /stanly1.cpp | UTF-8 | 1,310 | 2.859375 | 3 | [] | no_license | /*
===================================================
Name :- Nishant Raj
Email :- raj.nishant360@gmail.com
College :- Indian School of Mines
Branch :- Computer Science and Engineering
Time :- 25 September 2015 (Friday) 21:48
===================================================*/
#include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n+9];
for(int i = 0 ; i < n ; i++){
cin>>arr[i];
}
for(int i = 1 , j = n-2 ; i < n/2-1 ;j--, i++){
if(arr[i-1]%2 ==0 && arr[i+1]%2==0)
{
if(abs(arr[j] - (arr[i-1] + arr[i+1])/2) > abs(arr[j] - arr[i]))
arr[i] = (arr[i-1] + arr[i+1])/2;
}
}
int start = (n%2 == 0 ? n/2 : n/2 + 1);
int start2 = n%2 == 0 ? start-1 : start-2;
for(int i = start , j =start2 ; i < n-1 ;j--, i++){
if(arr[i-1]%2 ==0 && arr[i+1]%2==0)
{
if(abs(arr[j] - (arr[i-1] + arr[i+1])/2) > abs(arr[j] - arr[i]))
arr[i] = (arr[i-1] + arr[i+1])/2;
}
}
long long ans = 0;
for(int i = 0 , j = n-1 ; i < n/2 ; i++ , j--)
ans += abs(arr[i] - arr[j]);
cout<<ans<<endl;
}
return 0;
}
| true |
e2f757b5f45d406bf816fc939846ec98c8e531b0 | C++ | alexandraback/datacollection | /solutions_1674486_0/C++/jefferson/A.cpp | UTF-8 | 1,387 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
typedef vector < int > vi;
typedef vector < vi > vvi;
typedef vector < double > vd;
typedef vector < vd > vvd;
typedef vector < string > vs;
bool dfs (const vector<vector<int> >& adj, vector<bool> &visited, int v,
vector<bool> &marked){
if (visited[v])
return true;
marked[v] = true;
visited[v] = true;
for (int i = 0; i < adj[v].size(); i++) {
if (!marked[adj[v][i]] && dfs(adj, visited, adj[v][i], marked))
return true;
}
marked[v] = false;
return false;
}
bool C2P (const vector< vector<int> >& adj, int v) {
vector<bool> visited (adj.size(), false);
vector<bool> marked (adj.size(), false);
return dfs (adj, visited, v, marked);
}
int main () {
int T, n, x; cin >> T;
for (int t = 1; t <= T; t++) {
int N; cin >> N;
vector< vector< int > > g (N, *new vector<int>());
for (int i = 0; i < N; i++) {
cin >> n;
for (int j = 0; j < n; j++) {
cin >> x;
g[i].push_back(x-1);
}
}
bool find = false;
for (int i = 0; i < N; i++) {
if ( C2P(g, i) ) {
find = true;
break;
}
}
cout << "Case #"<< t << ": " << (find ? "Yes" : "No") << endl;
}
return 0;
}
| true |
eed8ebae564b956d96c768388a2559227d4dbe37 | C++ | md143rbh7f/competitions | /topcoder/srm/492/TimeTravellingGardener.cpp | UTF-8 | 611 | 2.78125 | 3 | [] | no_license | #include <vector>
using namespace std;
int x[50];
struct TimeTravellingGardener
{
int determineUsage( vector<int> d, vector <int> h )
{
int n = h.size(), best = n-1;
for( int i = 1; i < n; i++ ) x[i] = x[i-1] + d[i-1];
for( int i = 0; i < n; i++ ) for( int j = i+1; j < n; j++ )
{
int bad = 0;
for( int k = 0; k < n; k++ ) if( k!=i )
{
int a = (h[k]-h[i])*(x[j]-x[i]);
int b = (h[j]-h[i])*(x[k]-x[i]);
int want = b + h[i]*(x[j]-x[i]);
if( want < 0 ) bad = n-1;
if( a < b ) bad = n-1;
if( a > b ) bad++;
}
if( bad < best ) best = bad;
}
return best;
}
};
| true |
756cf4f2a205075c6297bf5d3bf080f30ec13cd8 | C++ | tue-mdse/pgconvert | /include/pg.h | UTF-8 | 2,734 | 3.1875 | 3 | [] | no_license | #ifndef __PG_H
#define __PG_H
#include "vertex.h"
#include "parsers/dot.h"
#include <iostream>
namespace graph {
namespace pg {
/**
* @brief Enumerated constants to indicate parity game players.
*/
enum Player
{
even = 0,///< even
odd = 1 ///< odd
};
typedef size_t Priority; ///< Type of vertex priorities.
/**
* @brief Struct
typedef size_t VertexIndex;
typedef std::set<VertexIndex> VertexSet; ///< Type used to store adjacency lists.ure containing a node label.
*
* This class is provided to make it easier to adapt parity game reduction algorithms
* to work with Kripke structures too.
*/
struct Label
{
Priority prio; ///< The vertex priority
Player player; ///< The owner of the vertex
/// @brief Comparison to make Label a valid mapping index.
bool operator<(const Label& other) const
{
return (prio < other.prio)
or (prio == other.prio and player < other.player);
}
/// @brief Equality comparison.
bool operator==(const Label& other) const
{
return (prio == other.prio)
and (player == other.player);
}
};
/**
* @brief Struct
typedef size_t VertexIndex;
typedef std::set<VertexIndex> VertexSet; ///< Type used to store adjacency lists.ure containing a node label.
*
* This class is provided to make it easier to adapt parity game reduction algorithms
* to work with Kripke structures too.
*/
struct DivLabel
{
DivLabel() : div(0) {}
Priority prio; ///< The vertex priority
unsigned player : 2; ///< The owner of the vertex
unsigned div : 1;
/// @brief Comparison to make Label a valid mapping index.
bool operator<(const DivLabel& other) const {
return (prio < other.prio)
or (prio == other.prio and player < other.player)
or (prio == other.prio and player == other.player and div < other.div);
}
/// @brief Equality comparison.
bool operator==(const DivLabel& other) const {
return (prio == other.prio)
and (player == other.player)
and (div == other.div);
}
};
template <typename Vertex>
class VertexFormatter : public graph::Parser<Vertex, graph::dot>::VertexFormatter
{
public:
typedef Vertex vertex_t;
void format(std::ostream& s, size_t index, const vertex_t& vertex)
{
s << "shape=\"" << (vertex.label.player == odd ? "box" : "diamond") << "\", ";
s << "label=\"" << vertex.label.prio << "\"";
}
};
} // namespace pg
template <>
struct Vertex<pg::DivLabel>
{
public:
typedef pg::DivLabel label_t;
label_t label;
VertexSet out; ///< Set of indices of vertices to which this vertex has an outgoing edge.
VertexSet in; ///< Set of indices of vertices from which this vertex has an incoming edge.
void mark_scc() { label.div = 1; };
};
} // namespace graph
#endif // __PG_H
| true |
201c5a425c8674cab5b1d224da63ad04455dda69 | C++ | cmf41013/Aspose.PDF-for-C | /Examples/PdfCPP/Document/AddImage.cpp | UTF-8 | 970 | 2.53125 | 3 | [
"MIT"
] | permissive | #include "..\Aspose.Pdf.h"
using namespace System;
using namespace System::Drawing;
using namespace Aspose::Pdf;
using namespace Aspose::Pdf::Text;
void AddImage()
{
// ExStart:AddImage
auto doc = MakeObject<Document>();
auto pages = doc->get_Pages();
pages->Add();
auto page = pages->idx_get(1);
auto stream = MakeObject<IO::MemoryStream>();
SharedPtr<Bitmap> bitmap = MakeObject<Bitmap>(200, 200);
SharedPtr<Graphics> graphics = Graphics::FromImage(bitmap);
graphics->Clear(System::Drawing::Color::get_Yellow());
graphics->FillRectangle(Brushes::get_Blue(), System::Drawing::Rectangle(0, 0, 200, 100));
bitmap->Save(stream, Imaging::ImageFormat::get_Bmp());
double x = 100.0, y = 600.0, width = 200.0, height = 200.0;
auto rect = MakeObject<Aspose::Pdf::Rectangle>(x, y, x + width, y + height);
stream->Seek(0, System::IO::SeekOrigin::Begin);
page->AddImage(stream, rect);
doc->Save(u"..\\Data\\Document\\Document_out.pdf");
// ExEnd:AddImage
} | true |
8b82ac5d208e3d711033cb57bcb94c5413e98875 | C++ | nian0601/GfxEngine | /Solution/Engine/AssetContainer.cpp | UTF-8 | 2,436 | 2.515625 | 3 | [] | no_license | #include "stdafx.h"
#include "AssetContainer.h"
#include "Effect.h"
#include "Instance.h"
#include "FBXFactory.h"
#include "Texture.h"
namespace Easy3D
{
AssetContainer* AssetContainer::myInstance = nullptr;
AssetContainer* AssetContainer::GetInstance()
{
if (myInstance == nullptr)
{
myInstance = new AssetContainer();
}
return myInstance;
}
void AssetContainer::Destroy()
{
SAFE_DELETE(myInstance);
}
Instance* AssetContainer::LoadModel(const CU::String<64>& aModelPath, const CU::String<64>& aEffectPath)
{
EffectID effect = LoadEffect(aEffectPath);
if (myModelID.KeyExists(aModelPath) == false)
{
ModelData* modelData = myModelFactory->LoadModel(aModelPath, effect);
myModels[myNextModelID] = modelData;
myModelID[aModelPath] = myNextModelID;
++myNextModelID;
}
return new Instance(myModelID[aModelPath], effect);
}
Easy3D::ModelData* AssetContainer::GetModel(ModelID aID)
{
if (myModels.KeyExists(aID) == true)
{
return myModels[aID];
}
DL_ASSERT("Tried to Get an Invalid model");
return nullptr;
}
EffectID AssetContainer::LoadEffect(const CU::String<64>& aFilePath)
{
if (myEffectsID.KeyExists(aFilePath) == false)
{
Effect* effect = new Effect();
effect->Init(aFilePath);
myEffects[myNextEffectID] = effect;
myEffectsID[aFilePath] = myNextEffectID;
++myNextEffectID;
}
return myEffectsID[aFilePath];
}
Effect* AssetContainer::GetEffect(EffectID aID)
{
if (myEffects.KeyExists(aID) == true)
{
return myEffects[aID];
}
DL_ASSERT("Tried to Get an Invalid effect");
return nullptr;
}
Texture* AssetContainer::RequestTexture(const CU::String<64>& aFilePath)
{
if (myTextures.KeyExists(aFilePath) == false)
{
Texture* newTex = new Texture();
newTex->LoadTexture(aFilePath);
myTextures[aFilePath] = newTex;
}
return myTextures[aFilePath];
}
AssetContainer::AssetContainer()
: myModelFactory(new FBXFactory())
{
}
AssetContainer::~AssetContainer()
{
SAFE_DELETE(myModelFactory);
for (auto it = myEffects.Begin(); it != myEffects.End(); it = myEffects.Next(it))
{
SAFE_DELETE(it.Second());
}
myEffects.Clear();
for (auto it = myTextures.Begin(); it != myTextures.End(); it = myTextures.Next(it))
{
SAFE_DELETE(it.Second());
}
myTextures.Clear();
}
} | true |
c26affd7e6d034a5a3d0dadb74f5c0e96d33e36f | C++ | atsnyder/PhiProj | /src/test_mult_tbb_lambda.cpp | UTF-8 | 1,659 | 2.921875 | 3 | [] | no_license | #pragma offload_attribute (push,target(mic))
#include "tbb/parallel_for.h"
#include "tbb/blocked_range.h"
#include <iostream>
#pragma offload_attribute (pop)
#include <fstream>
#include "cilktime.h"
#include <vector>
using namespace std;
using namespace tbb;
#ifdef __MIC__
__attribute__((target(mic))) struct testStruct{
float* numArr;
} tS;
#else
struct testStruct{
float* numArr;
} tS;
#endif
int main(){
//File Input Begin
vector <float> numVect(0);
fstream reader("../input/testString.txt", ios_base::in);
if(!reader){
cout << "Error opening file" << endl;
return -1;
} else {
cout << "File Opened" << endl;
float temp;
while (reader >> temp){
numVect.push_back(temp);
}
cout << "File Copied to Vector" << endl;
reader.close();
}
//File Input End
int size = numVect.size();
tS.numArr = &numVect[0];
cout << "Vector reassigned to array" << endl;
cout << "Beginning calculation" << endl;
unsigned long long start_tick = cilk_getticks();
#pragma offload target(mic) in(size) inout(tS.numArr: length(size))
parallel_for(0,size,1, [&](int i){
tS.numArr[i] = tS.numArr[i]*7;
});
unsigned long long end_tick = cilk_getticks();
long total_time = (long) (end_tick-start_tick)/1000.f;
cout << total_time << " milliseconds" << endl;
cout << "Calculation Completed!" << endl;
cout << "Outputing to File" << endl;
//File Output Begin
ofstream writer("../output/testStringOut.txt");
if(!writer){
cout << "Error opening file" << endl;
return -1;
} else {
for(int i=0; i<size; i++){
writer << tS.numArr[i] << endl;
}
}
writer.close();
cout << "Output Complete!" << endl;
//File Output End
}
| true |
bec9dabcb4e22a010a85a3c263d02d607b8f5992 | C++ | mslawicz/PiBot | /PiBot/src/logger.cpp | UTF-8 | 2,050 | 3.15625 | 3 | [] | no_license | /*
* logger.cpp
*
* Created on: 7 sty 2019
* Author: Marcin
*/
#include "logger.h"
/*
* get instance of the logger singleton object
*/
Logger& Logger::getInstance(void)
{
// instantiated on the first use and guaranteed to be destroyed
static Logger instance;
return instance;
}
Logger::Logger()
{
// logger starts in info level
levelThreshold = MessageLevel::INFO;
pLoggerHandlerThread = nullptr;
exitHandler = true;
currentMessageLevel = MessageLevel::NONE;
}
Logger::~Logger()
{
}
/*
* logger output sink handler
*/
void Logger::sendMessage(std::string message)
{
if(sinks.find('c') != sinks.end())
{
std::cout << message << std::endl;
}
}
/*
* logger handler to be launched in a new thread
* it sends queued messages to sinks
*/
void Logger::handler(void)
{
logEvent(INFO, "logger handler started");
do
{
std::this_thread::yield();
std::unique_lock<std::mutex> lock(loggerHandlerMutex);
queueEvent.wait(lock, [this]() {return (!eventQueue.empty() || exitHandler); });
lock.unlock();
while(!eventQueue.empty())
{
eventContainer event;
{
std::lock_guard<std::mutex> lock(queueMutex);
event = eventQueue.front();
eventQueue.pop();
}
if(std::get<0>(event) <= levelThreshold)
{
sendMessage(std::get<1>(event));
}
}
} while (!exitHandler);
}
/*
* starts logger
*/
void Logger::start(MessageLevel level)
{
levelThreshold = level;
if(level != MessageLevel::NONE)
{
exitHandler = false;
pLoggerHandlerThread = new std::thread(&Logger::handler, this);
}
}
/*
* stops the logger
*/
void Logger::stop(void)
{
logEvent(INFO, "logger stop request");
exitHandler = true;
queueEvent.notify_one();
pLoggerHandlerThread->join();
delete pLoggerHandlerThread;
}
| true |
f41fe6c90f01a44f6bb81009a1d87e8c4856e3e2 | C++ | GreekPanda/leetcode | /Integer/KthLargestElement/KthLargestElement.cc | UTF-8 | 712 | 3.8125 | 4 | [] | no_license | class KthLargestElement {
public:
int kthLargestElement(vector<int> nums, int k) {
if(nums == null || num.size() == 0)
return -1;
int result = qSort(nums, 0, nums.size() - 1, k);
return result;
}
private:
int qSort(vector<int> nums, int start, int end, int k) {
if(start > end)
return nums[end];
int m = start;
for(int i = start; i < end; i++) {
if(nums[i] > nums[start]) {
m++;
swap(nums, i, start);
}
}
swap(nums, m, start);
if(m + 1 == k) {
return nums[m];
} else if(m + 1 >k) {
return qSort(nums, start, m - 1, k);
} else {
return qSort(nums, m + 1, end, k);
}
}
} | true |
382115ad16d66e72a53176665b839e957affe68c | C++ | raiselove/The-data-structure | /HashTable/HashTable_OP.h | UTF-8 | 7,918 | 3.28125 | 3 | [] | no_license | #include <vector>
//template<class K>
//size_t DefaultFunc(const K *str)
//{
// register size_t hash = 0;
// while (size_t ch = (size_t)*str++)
// {
// hash = hash * 131 + ch;
// }
// return hash;
//}
template<class K,class V>
struct HashTableNode
{
K _key;
V _value;
HashTableNode* _next;
HashTableNode( const K & key, const V & value)
:_key( key)
, _value( value)
, _next( NULL)
{}
};
template <class K, class V>
class HashTable
{
typedef HashTableNode <K, V> Node;
public:
//拷贝构造
HashTable()
:_table( NULL)
, _size(0)
{}
//拷贝构造
HashTable( const HashTable & ht)
{
_table.resize( ht._table.size());
for (int i = 0; i < ht._table.size(); i++)
{
Node* cur = ht ._table[i];
while (cur)
{
Node* tmp = new Node(cur->_key, cur->_value);
tmp->_next = _table[i];
_table[i] = tmp;
_size++;
cur = cur->_next;
}
}
}
//赋值运算符的重载
HashTable<K , V> operator=( HashTable<K ,V> ht)
{
if (this != &ht)
{
swap(_table, ht._table);
swap(_size, ht._size);
}
return *this ;
}
//析构函数
~HashTable()
{
if (_table.size())
{
for (int i = 0; i < _table.size(); i++)
{
Node* cur = _table[i];
while (cur)
{
Node* del = cur;
cur = cur->_next;
delete del;
del = NULL;
}
}
}
}
bool Insert(const K& key, const V& value)
{
//是否需要扩容
if (_size == _table.size())
{
_ExpandCapatity();
}
size_t index = _HashFunc(key );
Node* cur = _table[index];
//防冗余
while (cur)
{
if (cur->_key == key )
{
return false ;
}
cur = cur->_next;
}
//插入节点
Node* tmp = new Node( key, value );
tmp->_next = _table[index];
_table[index] = tmp;
_size++;
return true ;
}
Node* Find(const K& key)
{
size_t index = _HashFunc(key );
Node* cur = _table[index];
while (cur)
{
if (cur->_key == key )
{
return cur;
}
cur = cur->_next;
}
return NULL ;
}
bool Remove(const K& key)
{
size_t index = _HashFunc(key );
Node* cur = _table[index];
Node* prev = NULL ;
//找到要删除的元素
while (cur)
{
if (cur->_key == key )
{
break;
}
prev = cur;
cur = cur->_next;
}
if (cur)
{
//头删
if (cur == _table[index])
{
_table[index] = cur->_next;
}
//删除中间元素
else
{
Node* next = cur->_next;
prev->_next = next;
}
delete cur;
cur = NULL;
_size--;
return true ;
}
return false ;
}
void Print()
{
for (int i = 0; i < _table.size(); i++)
{
Node* cur = _table[i];
cout << i << ":";
while (cur)
{
cout << cur->_key << " ";
cout << cur->_value << " ";
cur = cur->_next;
}
if (_table[i] == NULL )
{
cout << "NULL";
}
cout <<endl;
}
cout << endl;
}
protected:
//算出应该链接到哈希桶的那个位置
size_t _HashFunc(const K& key)
{
return key %_table.size();
}
//新的容量
size_t _NewSize()
{
// 使用素数表对齐做哈希表的容量,降低哈希冲突
const int _PrimeSize = 28;
static const unsigned long _PrimeList[_PrimeSize] =
{
53ul, 97ul, 193ul, 389ul, 769ul,
1543ul, 3079ul, 6151ul, 12289ul, 24593ul,
49157ul, 98317ul, 196613ul, 393241ul, 786433ul,
1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul,
50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul,
1610612741ul, 3221225473ul, 4294967291ul
};
for (int i = 0; i < _PrimeSize; i++)
{
if (_PrimeList[i]>_table.size())
{
return _PrimeList[i];//按照素数表来设置容量大小
}
}
//当需要的容量超过素数表的最大容量,我们就按照最大的来扩容
return _PrimeList[_PrimeSize - 1];
}
//哈希桶扩张容量
void _ExpandCapatity()
{
//开辟一个新的更大容量哈希桶
size_t newsize = _NewSize();
vector<Node *> newtable;
newtable.resize(newsize);
//把原来哈希桶中的元素再下来,插入到新的哈希桶
for (int i = 0; i < _table.size(); i++)
{
Node* cur = _table[i];
while (cur)
{
Node* tmp = cur;
int index = _HashFunc(tmp->_key);
//头插法
tmp->_next = newtable[index];
newtable[index] = tmp;
cur = cur->_next;
}
_table[i] = NULL;
}
_table.swap(newtable);
}
protected:
vector<Node *> _table;
size_t _size;//数据的多少
};
| true |
44b810b943876bb37e7a9c5e0473216e409ef73e | C++ | OmarLetona14/EDD_1S2020_PY1_201700377 | /src/MenuPrincipal.cpp | UTF-8 | 5,023 | 2.8125 | 3 | [] | no_license | #include "MenuPrincipal.h"
#include <iostream>
#include "ReadArchive.h"
#include "DoubleCircularListDiccionario.h"
#include "MenuJuego.h"
using namespace std;
MenuPrincipal::MenuPrincipal()
{
this->diccionario_palabras = new DoubleCircularListDiccionario();
}
void MenuPrincipal::desplegarMenu(){
MenuJuego* nuevo_juego = new MenuJuego();
do{
std::string file_string;
cout << "BIENVENIDO AL PROGRAMA" << endl;
cout << "Por favor seleccione una opcion" << endl;
cout << "1. Lectura de archivo" << endl;
cout << "2. Juego" << endl;
cout << "3. Reportes" << endl;
cout << "4. Salir" <<endl;
cin>>opcion;
try{
switch(opcion){
case 1:
dimension_tablero = 0;
cout<< "Por favor ingrese la ruta del archivo que desea leer"<< endl;
cin >> file_string;
if(file_string!=""){
reader = new ReadArchive(diccionario_palabras);
reader->readJSON(file_string);
dimension_tablero = reader->getDimension();
system("pause");
system("cls");
}
break;
case 2:
if(reader!=nullptr){
nuevo_juego->mostrarMenu(dimension_tablero, reader->getDiccionario(), reader->getCoordenadas());
}else{
cout<<"Debe leer un archivo de entrada antes de jugar "<<endl;
system("pause");
}
break;
case 3:
do{
cout<<"SELECCIONE EL REPORTE QUE DESEA VER"<<endl;
cout<<"1. Palabras del diccionario" << endl;
cout<<"2. Fichas disponibles en el juego" << endl;
cout<<"3. Jugadores disponibles"<<endl;
cout<<"4. Recorrido preorden del arbol binario de busqueda"<<endl;
cout<<"5. Recorrido inorden del arbol binario de busqueda"<<endl;
cout<<"6. Recorrido postorden del arbol binario de busqueda"<<endl;
cout<<"7. Historial de puntajes de un jugador"<<endl;
cout<<"8. Scoreboard general"<<endl;
cout<<"9. Salir"<<endl;
try{cin>>opcion;}catch(exception e){
system("cls");
cout<<"Debe introducir un numero "<<endl;
system("pause");
opcion = 10;
}
switch(opcion){
case 1:
if(diccionario_palabras->getSize()!=0){
diccionario_palabras->createDOT("diccionario.dot");
}else{
cout<<"Lista vacia"<<endl;
}
break;
case 2:
if(nuevo_juego->getColaFichas()!=nullptr){
nuevo_juego->getColaFichas()->generateDOT("colaFichas.dot");
}else{
cout<<"Aun no se han cargado fichas! "<<endl;
}
break;
case 3:
if(nuevo_juego->getJugadores()!=nullptr){
nuevo_juego->getJugadores()->GraphABB(nuevo_juego->getRoot());
}else {
cout<< "Aun no se han introducido jugadores! "<<endl;
}
break;
case 4:
if(nuevo_juego->getJugadores()!=nullptr){
nuevo_juego->getJugadores()->createDOT("JugadoresPreOrden.dot","preorder", nuevo_juego->getRoot());
}else {
cout<< "Aun no se han introducido jugadores! "<<endl;
}
break;
case 5:
if(nuevo_juego->getJugadores()!=nullptr){
nuevo_juego->getJugadores()->createDOT("JugadoresInOrden.dot","inorder", nuevo_juego->getRoot());
}else {
cout<< "Aun no se han introducido jugadores! "<<endl;
}
break;
case 6:
if(nuevo_juego->getJugadores()!=nullptr){
nuevo_juego->getJugadores()->createDOT("JugadoresPostOrden.dot","postorder", nuevo_juego->getRoot());
}else {
cout<< "Aun no se han introducido jugadores! "<<endl;
}
break;
}
case 7:
break;
case 8:
nuevo_juego->obtenerMejores();
break;
system("pause");
system("cls");
}while(opcion!=11);
break;
}
}catch(exception e){
system("cls");
cout<<"Debe introducir un numero "<<endl;
system("pause");
opcion = 10;
}
system("cls");
}while(opcion!=4);
}
| true |
27936a9298e10a83a77c33c6596a0ab40d087a0e | C++ | AlexMcClay/Uni | /2020/s2/oop/practical-02/function-2-3.cpp | UTF-8 | 1,372 | 4.03125 | 4 | [] | no_license | // function that print out a multiple of a matrix
#include <iostream>
#include <stdlib.h>
#include <cmath>
using namespace std;
int sum_elements(int integers[], int length)
{
int sum = 0;
if (length < 1)
{
return -1;
}
else
{
for (int i = 0; i < length; ++i)
{
sum = sum +integers[i];
}
return sum;
}
}
bool is_a_palindrome(int integers[], int length)
{
//initializing variables
int count = 0;
int mid = floor(float(length/2));
//checking if the size of the array is less than 1
if (length < 1)
{
return false;
}
//executing the rest of the code
else
{
if (length%2 ==0)
{
for (int i = (mid); i < length; i++)
{
if (integers[i] == integers[length-i-1])
{
count++;
}
}
}
else
{
for (int i = (mid+1); i < length; i++)
{
if (integers[i] == integers[length-i-1])
{
count++;
}
}
}
if (count == mid)
{
return true;
}
else
{
return false;
}
}
}
int sum_if_a_palindrome(int integers[], int length)
{
int sum;
bool check;
//check if palindrome
check = is_a_palindrome(integers, length);
if (length < 1)
{
return -1;
}
else
{
if (check == false)
{
return -2;
}
else
{
sum = sum_elements(integers, length);
return sum;
}
}
}
| true |
b3e7ab32303f3eff23e827aa5250bfd767652c59 | C++ | chingandy/cpp | /cpp_BST.cpp | UTF-8 | 7,122 | 3.8125 | 4 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
class node
{
private:
int data;
node *left;
node *right;
friend class binary_tree;
};
//typedef struct binary_tree node;
class binary_tree{
public:
binary_tree();
void insert(int value);
void inorder();
void preorder();
void postorder();
void ___delete(int value);
void find(int value);
private:
node *insert_node(node *root, int value);
void print_inorder(node *ptr);
void print_preorder(node *ptr);
void print_postorder(node *ptr);
void release(node *ptr);
node *search_node(node *ptr, int value);
node *find_node(node *ptr, int value);
node *find_parent(node *ptr, int value, int *pos);
node *delete_node(node *root, int value);
node *root;
node *ptr;
};
node *binary_tree::insert_node(node *root, int value)
{
node *new_node;
node *current;
node *parent;
new_node = (node *)malloc(sizeof(node));
new_node->data = value;
new_node->left = NULL;
new_node->right = NULL;
if(root == NULL)
{
return new_node;
}
else
{
current = root;
while(current != NULL)
{
parent = current;
if(current->data > value)
current = current->left;
else
current = current->right;
}
if(parent->data > value)
parent->left = new_node;
else
parent->right = new_node;
}
return root;
}
void binary_tree::print_inorder(node *ptr)
{
if(ptr != NULL)
{
print_inorder(ptr->left);
printf("%d ", ptr->data);
print_inorder(ptr->right);
}
}
void binary_tree::print_preorder(node *ptr)
{
if(ptr != NULL)
{
printf("%d ", ptr->data);
print_preorder(ptr->left);
print_preorder(ptr->right);
}
}
void binary_tree::print_postorder(node *ptr)
{
if(ptr != NULL)
{
print_postorder(ptr->left);
print_postorder(ptr->right);
printf("%d ", ptr->data);
}
}
void binary_tree::release(node *ptr)
{
if(ptr != NULL)
{
release(ptr->left);
release(ptr->right);
//printf("%d ", ptr->data);
delete ptr;
}
}
node *binary_tree::search_node(node *ptr, int value)
{
node *temp;
if(ptr != NULL)
{
if(ptr->data == value)
return ptr;
else
{
temp = search_node(ptr->left, value);
if(temp != NULL)
return temp;
temp = search_node(ptr->right, value);
if(temp != NULL)
return temp;
}
}
return NULL;
}
node *binary_tree::find_node(node *ptr, int value)
{
while(ptr != NULL)
{
if(ptr->data == value)
return ptr;
else
{
if(ptr->data > value)
ptr = ptr->left;
else
ptr = ptr->right;
}
}
return NULL;
}
// 找某值之父節點
node *binary_tree::find_parent(node *ptr, int value, int *pos)
{
node *parent;
parent = ptr; // 從ptr開始找
*pos = 0;
while(ptr != NULL)
{
if(ptr->data == value) // 找到目標
return parent; // 回傳此節點之父節點
else
{
parent = ptr;
if(ptr->data > value)
{
*pos = -1; // ptr在parent左子樹
ptr = ptr->left; // 往左找
}
else
{
*pos = 1; // ptr在parent右子樹
ptr = ptr->right; // 往右找
}
}
}
return NULL; // 找不到
}
// 刪除節點
node *binary_tree::delete_node(node *root, int value)
{
node *parent;
node *ptr;
node *next;
int pos;
parent = find_parent(root, value, &pos); // 從root開始,找value之父節點
if(parent != NULL) // 有找到, 準備刪除
{
switch(pos) // 判斷目前節點再父節點左邊或右邊
{
case -1:
ptr = parent->left;
break;
case 1:
ptr = parent->right;
break;
case 0:
ptr = parent;
break;
}
if(ptr->left == NULL) // 情況1: 節點沒有左子樹 如果要刪的是根節點
{
if(parent == ptr) // 如果要刪的是根節點
root = root->right;
else // 其他
{
if( pos == 1 )
{
//要刪除的節點在父節點右方,所以將父節點的右節點指向刪除節點的右節點
parent->right = ptr->right;
}
else
{
//要刪除的節點在父節點左方,所以將父節點的左節點指向刪除節點的右節點
parent->left = ptr->right;
}
}
delete ptr;
}
else if(ptr->right == NULL) // 情況2: 節點沒有右子樹
{
if(parent != ptr)
{
if( pos == 1 )
{
//要刪除的節點在父節點右方,所以將父節點的右節點指向刪除節點的左節點
parent->right = ptr->left;
}
else
{
//要刪除的節點在父節點左方,所以將父節點的左節點指向刪除節點的左節點
parent->left = ptr->left;
}
}
else
root = root->left;
delete ptr;
}
else // 情況3: 節點有左右子樹
{
parent = ptr;
next = ptr->left;//找取代點next,從左邊開始找
if(next->right != NULL) {
while(next->right != NULL)
{ // 往左子節點之右子樹找最大值當取代點
parent = next; //parent為next父節點
next = next->right;
} // 繞過next節點
parent->right = next->left;
}
else {
ptr->left = NULL;
}
ptr->data = next->data; // 取代!!
delete next;
}
}
return root; // 回傳此樹
}
//binary_tree public member
binary_tree::binary_tree(){
root = NULL ;
}
void binary_tree::insert(int value){
root = insert_node(root, value);
}
void binary_tree::inorder(){
print_inorder(root);
cout << endl;
}
void binary_tree::preorder(){
print_preorder(root);
cout << endl;
}
void binary_tree::postorder(){
print_postorder(root);
cout << endl;
}
void binary_tree::___delete(int value){
ptr = find_node(root, value);
if(ptr!=NULL){
root = delete_node(root, value);
cout << "delete "<<value << " ok" << endl;
}
else{
cout << "cannot delete"<<endl;
}
}
void binary_tree::find(int value){
ptr = find_node(root, value);
if(ptr!=NULL){
cout << "found: " << ptr->data << endl;
}
else{
cout << "Not found" ;
}
}
int main()
{
int op;
int value;
binary_tree b1;
//node *root = NULL, *ptr;
while(1){
/*
cout << "1 insert data"<<endl;
cout << "2 inorder print"<<endl;
cout << "3 preorder print"<<endl;
cout << "4 postorder print"<<endl;
cout << "5 delete node"<<endl;
cout << "6 find node"<<endl;
cout << "8 exit"<<endl;
*/
cin >> op ;
switch(op){
case 1:
cin >> value ;
b1.insert(value);
break;
case 2:
b1.inorder();
break;
case 3:
b1.preorder();
break;
case 4:
b1.postorder();
break;
case 5:
cin >> value ;
b1.___delete(value);
break;
case 6:
cin >> value ;
b1.find(value);
break;
case 8:
return 0;
break;
}
}
return 0;
}
| true |
dcfa1f283115978071fe6b851bc4622f01b38395 | C++ | Shivam0001/Competitive-Programming | /Question Bank with Solution/Sheet_8 Linked List/5median.cpp | UTF-8 | 767 | 3.34375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
void display(Node *head)
{
while(head!=NULL)
{
cout<<head->data<<" ";
head=head->next;
}
cout<<endl;
}
void median(Node *head1)
{
Node *ptr1=head1,*ptr2=head1;
while(ptr2!=NULL && ptr2->next!=NULL )
{
ptr1=ptr1->next;
ptr2=ptr2->next->next;
}
cout<<ptr1->data;
return ;
}
void insertinfirst(Node **head,int value)
{
Node *temp=new Node();
temp->data=value;
temp->next=*head;
*head=temp;
return ;
}
int main()
{
Node *head1=NULL;
int n,i,value;
cin>>n;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
for(i=n-1;i>=0;i--)
{
insertinfirst(&head1,a[i]);
}
median(head1);
}
| true |
07ebf29274cfca44cd2b97aaaf87197c67806904 | C++ | daltonmoore/classic-chess | /ChesterChess/Source/ChesterChess/PieceBishop.cpp | UTF-8 | 2,784 | 2.53125 | 3 | [] | no_license | // Fill out your copyright notice in the Description page of Project Settings.
#include "PieceBishop.h"
APieceBishop::APieceBishop(const FObjectInitializer& ObjectInitializer)
{
Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
static ConstructorHelpers::FObjectFinder<UStaticMesh>BishopM(TEXT("StaticMesh'/Game/StarterContent/Shapes/BishopWhite.BishopWhite'"));
UStaticMesh* PawnMesh = BishopM.Object;
Mesh->SetStaticMesh(PawnMesh);
PieceColor = 1;
PieceValue = 3;
pieceType = EBishop;
FirstMove = true;
//GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Constructor"));
}
TSet<int32> APieceBishop::CalculateMoves(TArray<APiece*> Pieces, int CurrentPos)
{
Super::CalculateMoves(Pieces, CurrentPos);
int tempCurrentPos = CurrentPos;
APiece* CurrentPiece = Pieces[CurrentPos];
TSet<int32> BishopMoves;
//Create and populate array with all movement directions for the Bishop
TArray<int> Directions;
Directions.SetNumUninitialized(4);
Directions.Add(9);
Directions.Add(-9);
Directions.Add(7);
Directions.Add(-7);
//For loop to check all directions
for (int i = 0; i < Directions.Num(); i++)
{
tempCurrentPos = CurrentPos; //Reset position to check from
CurrentPiece = Pieces[CurrentPos]; //Reset current piece being checked
//UE_LOG(LogTemp, Warning, TEXT("now checking for %d"), Directions[i]);
//UE_LOG(LogTemp, Warning, TEXT("from current position %d"), tempCurrentPos);
for (int j = 0; j < 7; j++)
{
bool RowDone = false;
//Check if the row that the piece is on is done
if (Directions[i] == 9 || Directions[i] == -7)
{
RowDone = ((tempCurrentPos + 1) % 8 == 0);
int rem = (tempCurrentPos + 1) % 8;
//UE_LOG(LogTemp, Error, TEXT("from current position %d"), rem);
}
else if (Directions[i] == -9 || Directions[i] == 7)
{
RowDone = (tempCurrentPos % 8 == 0);
}
tempCurrentPos += Directions[i];
//Make sure we never go out of bounds
if (tempCurrentPos < 64 && tempCurrentPos >= 0)
{
CurrentPiece = Pieces[tempCurrentPos];
//UE_LOG(LogTemp, Error, TEXT("from current position %d"), CurrentPiece->PieceColor);
if (!RowDone && (Pieces[tempCurrentPos] == nullptr || CurrentPiece->PieceColor != PieceColor))
{
//If there is a piece of different color, add the piece to the possible moves and break the loop
if (Pieces[tempCurrentPos] != nullptr && CurrentPiece->PieceColor != PieceColor)
{
BishopMoves.Add(tempCurrentPos);
UE_LOG(LogTemp, Warning, TEXT("adding position %d"), tempCurrentPos);
break;
}
BishopMoves.Add(tempCurrentPos);
UE_LOG(LogTemp, Warning, TEXT("adding position %d"), tempCurrentPos);
}
else
break;
}
else
break;
}
}
return BishopMoves;
} | true |