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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
63a70bc8d0212ea743a62c5403ee156ab3470d19 | C++ | InDieTasten/--EXP-old- | /src/Input/EventManager.cpp | UTF-8 | 8,588 | 2.65625 | 3 | [
"LicenseRef-scancode-other-permissive"
] | permissive | #include <Input\EventManager.hpp>
EventManager::EventManager(sf::RenderWindow& _target) :
EventPublisher(),
target(_target)
{
listening = false;
EXP::log("[Info]EventManager has been constructed: " + utils::tostring(this));
}
EventManager::~EventManager()
{
if (listening)
{
EXP::log("[Warning]Forcefully terminating EventManager");
terminate();
}
EXP::log("[Info]Forcefully disconnecting listeners");
mouseMove.clear();
mousePress.clear();
mouseRelease.clear();
mouseWheel.clear();
keyPress.clear();
keyRelease.clear();
textEnter.clear();
joyPress.clear();
joyRelease.clear();
joyConnect.clear();
joyDisconnect.clear();
joyMove.clear();
focusGained.clear();
focusLost.clear();
mouseEnter.clear();
mouseLeave.clear();
resize.clear();
any.clear();
EXP::log("[Info]EventManager has been destructed: " + utils::tostring(this));
}
void EventManager::listen(GUIManager* _guiManager)
{
EXP::log("[Info]EventManager starts listening");
confmtx.lock();
listening = true;
sf::Clock limiter;
sf::Time time(sf::milliseconds(1000.0f/300.0f));
while (listening)
{
confmtx.unlock();
sf::sleep(time - limiter.restart());
confmtx.lock();
sf::Event event;
any(this, &event);
while (target.pollEvent(event))
{
target.setView(target.getDefaultView());
_guiManager->handleEvent(target, &event);
switch (event.type)
{
case sf::Event::MouseMoved:
mouseMove(this, event.mouseMove);
break;
case sf::Event::MouseButtonPressed:
mousePress(this, event.mouseButton);
break;
case sf::Event::MouseButtonReleased:
mouseRelease(this, event.mouseButton);
break;
case sf::Event::MouseWheelMoved:
mouseWheel(this, event.mouseWheel);
break;
case sf::Event::KeyPressed:
keyPress(this, event.key);
break;
case sf::Event::KeyReleased:
keyRelease(this, event.key);
break;
case sf::Event::TextEntered:
textEnter(this, event.text);
break;
case sf::Event::JoystickButtonPressed:
joyPress(this, event.joystickButton);
break;
case sf::Event::JoystickButtonReleased:
joyRelease(this, event.joystickButton);
break;
case sf::Event::JoystickConnected:
joyConnect(this, event.joystickConnect);
break;
case sf::Event::JoystickDisconnected:
joyDisconnect(this, event.joystickConnect);
break;
case sf::Event::JoystickMoved:
joyMove(this, event.joystickMove);
break;
case sf::Event::GainedFocus:
focusGained(this, EventArgs());
break;
case sf::Event::LostFocus:
focusLost(this, EventArgs());
break;
case sf::Event::MouseEntered:
mouseEnter(this, EventArgs());
break;
case sf::Event::MouseLeft:
mouseLeave(this, EventArgs());
break;
case sf::Event::Resized:
resize(this, event.size);
break;
case sf::Event::Closed:
EXP::log("[Info]The application is requested to close itself...");
EXP::log("[Info]EventManager follows this request: " + utils::tostring(this));
terminate();
break;
default:
std::cout << event.type << std::endl;
EXP::log("[WARNING]Something strange happened");
}
}
}
EXP::log("[Info]EventManager stopped listening");
confmtx.unlock();
}
void EventManager::terminate()
{
if (!listening)
{
EXP::log("[Warning]Tried terminating already terminated EventManager");
return;
}
confmtx.lock();
listening = false;
confmtx.unlock();
sf::sleep(sf::seconds(0.05f));
confmtx.lock();
confmtx.unlock();
}
void EventManager::addMouseMove(Delegate<sf::Event::MouseMoveEvent> _delegate)
{
mouseMove += _delegate;
EXP::log("[Info]MouseMove listener registered");
}
void EventManager::removeMouseMove(Delegate<sf::Event::MouseMoveEvent> _delegate)
{
mouseMove -= _delegate;
EXP::log("[Info]MouseMove listener unregisterd");
}
void EventManager::addMousePress(Delegate<sf::Event::MouseButtonEvent> _delegate)
{
mousePress += _delegate;
EXP::log("[Info]MousePress listener registered");
}
void EventManager::removeMousePress(Delegate<sf::Event::MouseButtonEvent> _delegate)
{
mousePress -= _delegate;
EXP::log("[Info]MousePress listener unregistered");
}
void EventManager::addMouseRelease(Delegate<sf::Event::MouseButtonEvent> _delegate)
{
mouseRelease += _delegate;
EXP::log("[Info]MouseRelease listener registered");
}
void EventManager::removeMouseRelease(Delegate<sf::Event::MouseButtonEvent> _delegate)
{
mouseRelease -= _delegate;
}
void EventManager::addMouseWheel(Delegate<sf::Event::MouseWheelEvent> _delegate)
{
mouseWheel += _delegate;
EXP::log("[Info]MouseWheel listener registered");
}
void EventManager::removeMouseWheel(Delegate<sf::Event::MouseWheelEvent> _delegate)
{
mouseWheel -= _delegate;
}
void EventManager::addKeyPress(Delegate<sf::Event::KeyEvent> _delegate)
{
keyPress += _delegate;
EXP::log("[Info]KeyPress listener registered");
}
void EventManager::removeKeyPress(Delegate<sf::Event::KeyEvent> _delegate)
{
keyPress -= _delegate;
}
void EventManager::addKeyRelease(Delegate<sf::Event::KeyEvent> _delegate)
{
keyRelease += _delegate;
EXP::log("[Info]KeyRelease listener registered");
}
void EventManager::removeKeyRelease(Delegate<sf::Event::KeyEvent> _delegate)
{
keyRelease -= _delegate;
}
void EventManager::addTextEnter(Delegate<sf::Event::TextEvent> _delegate)
{
textEnter += _delegate;
EXP::log("[Info]TextEnter listener registered");
}
void EventManager::removeTextEnter(Delegate<sf::Event::TextEvent> _delegate)
{
textEnter -= _delegate;
}
void EventManager::addJoyPress(Delegate<sf::Event::JoystickButtonEvent> _delegate)
{
joyPress += _delegate;
EXP::log("[Info]JoyPress listener registered");
}
void EventManager::removeJoyPress(Delegate<sf::Event::JoystickButtonEvent> _delegate)
{
joyPress -= _delegate;
}
void EventManager::addJoyRelease(Delegate<sf::Event::JoystickButtonEvent> _delegate)
{
joyRelease += _delegate;
EXP::log("[Info]JoyRelease listener registered");
}
void EventManager::removeJoyRelease(Delegate<sf::Event::JoystickButtonEvent> _delegate)
{
joyRelease -= _delegate;
}
void EventManager::addJoyConnect(Delegate<sf::Event::JoystickConnectEvent> _delegate)
{
joyConnect += _delegate;
EXP::log("[Info]JoyConnect listener registered");
}
void EventManager::removeJoyConnect(Delegate<sf::Event::JoystickConnectEvent> _delegate)
{
joyConnect -= _delegate;
}
void EventManager::addJoyDisconnect(Delegate<sf::Event::JoystickConnectEvent> _delegate)
{
joyDisconnect += _delegate;
EXP::log("[Info]JoyDisconnect listener registered");
}
void EventManager::removeJoyDisconnect(Delegate<sf::Event::JoystickConnectEvent> _delegate)
{
joyDisconnect -= _delegate;
}
void EventManager::addJoyMove(Delegate<sf::Event::JoystickMoveEvent> _delegate)
{
joyMove += _delegate;
EXP::log("[Info]JoyMove listener registered");
}
void EventManager::removeJoyMove(Delegate<sf::Event::JoystickMoveEvent> _delegate)
{
joyMove -= _delegate;
}
void EventManager::addFocusGained(Delegate<EventArgs> _delegate)
{
focusGained += _delegate;
EXP::log("[Info]FocusGained listener registered");
}
void EventManager::removeFocusGained(Delegate<EventArgs> _delegate)
{
focusGained -= _delegate;
}
void EventManager::addFocusLost(Delegate<EventArgs> _delegate)
{
focusLost += _delegate;
EXP::log("[Info]FocusLost listener registered");
}
void EventManager::removeFocusLost(Delegate<EventArgs> _delegate)
{
focusLost -= _delegate;
}
void EventManager::addMouseEnter(Delegate<EventArgs> _delegate)
{
mouseEnter += _delegate;
EXP::log("[Info]MouseEnter listener registered");
}
void EventManager::removeMouseEnter(Delegate<EventArgs> _delegate)
{
mouseEnter -= _delegate;
}
void EventManager::addMouseLeave(Delegate<EventArgs> _delegate)
{
mouseLeave += _delegate;
EXP::log("[Info]MouseLeave listener registered");
}
void EventManager::removeMouseLeave(Delegate<EventArgs> _delegate)
{
mouseLeave -= _delegate;
}
void EventManager::addResize(Delegate<sf::Event::SizeEvent> _delegate)
{
resize += _delegate;
EXP::log("[Info]Resize listener registered");
}
void EventManager::removeResize(Delegate<sf::Event::SizeEvent> _delegate)
{
resize -= _delegate;
}
void EventManager::addAny(Delegate<sf::Event*> _delegate)
{
any += _delegate;
EXP::log("[Info]Any listener registered");
}
void EventManager::removeAny(Delegate<sf::Event*> _delegate)
{
any -= _delegate;
}
| true |
acb4c25f4a24c27c5fdc5bf642227a2d20fa75ea | C++ | tbydza/simple-chess-cpp | /src/Move.h | UTF-8 | 1,337 | 3.34375 | 3 | [
"MIT"
] | permissive | #ifndef MOVE_H
#define MOVE_H
#include "Position.h"
using namespace std;
/**
* Move class.
* This class represents one chess move.
* Move consist of source and destination Position
* and its properties.
*/
class Move
{
public:
/**
* Move class default constructor.
* this creates invalid move
*/
Move();
/**
* Move class constructor.
* @param src source Position of the Move
* @param dst destination Position of the Move
* @param capture move with capture of enemy figure.
* @param castling move is castling special move, default value is false.
*/
Move(const Position &src, const Position &dst, bool capture, bool castling = false);
/**
* Capture property getter
* @return value of capture property
*/
bool IsCapture() const;
/**
* Castling property getter
* @return value of castling property
*/
bool IsCastling() const;
/**
* Source Position getter
* @return source Position.
*/
Position GetSourcePosition() const;
/**
* Destination Position getter
* @return destination Position.
*/
Position GetDestinationPosition() const;
/**
* overloaded == operator
* @param other other Move
* @return true if source and destination positions equal
*/
bool operator==(const Move &other) const;
private:
Position src, dst;
bool castling, capture;
};
#endif | true |
7e0440c4dc737e9026297dbcf0f4cec6092d4f3a | C++ | fabba/BH2013-with-coach | /Src/Controller/Visualization/PaintMethods.h | UTF-8 | 677 | 2.703125 | 3 | [
"BSD-2-Clause"
] | permissive | /**
* @file Controller/Visualization/PaintMethods.h
* Declaration of class PaintMethods.
*
* @author <A href="mailto:juengel@informatik.hu-berlin.de">Matthias Jüngel</A>
* @author Colin Graf
*/
#pragma once
class DebugDrawing;
class QPainter;
/**
* @class PaintMethods
*
* Defines static methods to paint debug drawings to QPainters.
*/
class PaintMethods
{
public:
/**
* Paints a DebugDrawings to a QPainter.
* @param painter The graphics context the DebugDrawing is painted to.
* @param debugDrawing The DebugDrawing to paint.
* @param baseTrans A basic transformation.
*/
static void paintDebugDrawing(QPainter& painter, const DebugDrawing& debugDrawing, const QTransform& baseTrans);
};
| true |
9dc651ff30ec53e030583c9c32957e027b10fcf1 | C++ | lingjiankong/leetcode | /244. Shortest Word Distance II.cpp | UTF-8 | 2,425 | 3.875 | 4 | [] | no_license | // ***
//
// Design a class which receives a list of words in the constructor, and implements a method that takes two words word1
// and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly
// many times with different parameters.
//
// Example:
//
// Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
//
// Input: word1 = “coding”, word2 = “practice”
// Output: 3
//
// Input: word1 = "makes", word2 = "coding"
// Output: 1
//
// Note:
// You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
//
// Your WordDistance object will be instantiated and called as such:
// WordDistance obj = new WordDistance(words);
// int param_1 = obj.shortest(word1,word2);
//
// ***
// Straight forward solution, O(mn)
class WordDistance {
public:
WordDistance(vector<string>& words) {
for (int i = 0; i < words.size(); ++i) {
_wordToIndexes[words[i]].push_back(i);
}
}
int shortest(string word1, string word2) {
int minDis = INT_MAX;
for (int i : _wordToIndexes[word1]) {
for (int j : _wordToIndexes[word2]) {
minDis = min(minDis, abs(i - j));
}
}
return minDis;
}
private:
unordered_map<string, vector<int>> _wordToIndexes;
};
// Optimized solution, O(m+n)
class WordDistance {
public:
WordDistance(vector<string> words) {
for (int i = 0; i < words.size(); ++i) {
_wordToIndexes[words[i]].push_back(i);
}
}
int shortest(string word1, string word2) {
int i = 0, j = 0;
int minDis = INT_MAX;
while (i < _wordToIndexes[word1].size() && j < _wordToIndexes[word2].size()) {
minDis = min(minDis, abs(_wordToIndexes[word1][i] - _wordToIndexes[word2][j]));
// The trick is here.
// We know that in _wordToIndexes, each word's indexes in words are in ascending order. We want to comapre
// the current indexes pointed to by i and j, and increase the pointer which points to the smaller index, in
// order to get two indexes as close as possible and hopefully get a smaller minDis.
_wordToIndexes[word1][i] < _wordToIndexes[word2][j] ? ++i : ++j;
}
return minDis;
}
private:
unordered_map<string, vector<int>> _wordToIndexes;
};
| true |
6e945d8f1a807f1cf5cb8cc2aeefaa7fcb7e61b4 | C++ | sihan010/Tower-of-Hanoi | /tower of hanoi.cpp | UTF-8 | 692 | 3.640625 | 4 | [] | no_license | #include<iostream>
using namespace std;
int TOH(int disc,int source,int destination)
{
static int counter=0;
if(disc==1)
{
cout<<source<<" --> "<<destination<<endl;
counter++;
}
else
{
TOH(disc-1,source,1+2+3-source-destination);
cout<<source<<" --> "<<destination<<endl;
counter++;
TOH(disc-1,1+2+3-source-destination,destination);
}
return counter;
}
int main()
{
int disc,source,destination;
cout<<"Enter number of discs: "; cin>>disc;
cout<<"Enter Source: "; cin>>source;
cout<<"Enter Destination: "; cin>>destination;
cout<<"Total Moves: "<<TOH(disc,source,destination)<<endl;
}
| true |
d76eee564ae16769aad80041d39f282f7a099275 | C++ | NikolaJackova/ICPP1_2020 | /Exercise07/Exercise07/Source.cpp | UTF-8 | 1,270 | 3.390625 | 3 | [] | no_license | #include <ostream>
#include "Date.h"
#include "Address.h"
#include "Person.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define SIZE_OF_ARRAY 3
void save() {
Date d1(1, 1, 2010);
Date d2(1, 2, 2015);
Date d3(1, 3, 2020);
Address a1("Dvorska", "Pardubice", "12345");
Address a2("Pardubicka", "Pardubice", "12345");
Address a3("Hradecka", "Pardubice", "12345");
Person arrayOfPersons[SIZE_OF_ARRAY] = {
{"Jan", "Novak", a1, d1 },
{"Jan", "Novy", a2, d2},
{"Honza", "Novotny", a3, d3}
};
ofstream vystupniSoubor{};
vystupniSoubor.open("outputPersons.txt");
for (int i = 0; i < SIZE_OF_ARRAY; i++)
{
vystupniSoubor << arrayOfPersons[i] << endl;
}
vystupniSoubor.close();
}
Person* load() {
ifstream is{};
is.open("outputPersons.txt");
string line;
int sizeOfArray = 0;
if (is.is_open()) {
while (getline(is, line)) {
sizeOfArray++;
}
Person* arrayOfPersons = new Person[sizeOfArray];
is.clear();
is.seekg(0);
for (int i = 0; i < sizeOfArray; i++)
{
Person per;
is >> per;
arrayOfPersons[i] = per;
}
is.close();
return arrayOfPersons;
}
return nullptr;
}
int main() {
save();
Person* p = load();
for (int i = 0; i < SIZE_OF_ARRAY; i++)
{
cout << p[i] << endl;
}
} | true |
d3649fee09a685c2749e61925f533938dd409a4f | C++ | ddpub/cafe | /src/shared/vfd_display/customer_display.cpp | UTF-8 | 1,524 | 3.015625 | 3 | [] | no_license |
#include "customer_display.hpp"
void customer_display_t::writebyte(char ch) {
char buff[1] = {ch};
com_.write<char>(buff, 1);
}
void customer_display_t::pos_cursor(int x, int y) {
writebyte(0x1B);
writebyte(0x6C);
writebyte(x);
writebyte(y);
}
void customer_display_t::clear_all() {
writebyte(0x0C);
writebyte(0x1B);
writebyte(0x40);
}
void customer_display_t::clear_line(int num) {
pos_cursor(1, num);
writebyte(0x18);
}
void customer_display_t::print(int rownum, const std::string& str, const std::string& price, int align) {
int max = str.length() > 20 ? 20 : str.length();
std::string data = str.substr(0, max);
pos_cursor(1, rownum);
writebyte(0x18);
int st = 1;
if (align == 1) {
st = ((20 - data.length())/2) + 1;
}
else if (align == 2) {
st = 20 - data.length() + 1;
}
pos_cursor(st, rownum);
for (int i = 0; i <max; ++i) writebyte(data[i]);
if (align == 1 || align == 2 || !price.length()) return;
//pos_cursor(20, rownum);
for (int i = 0; i < price.length(); i++) {
pos_cursor(20 - i, rownum);
writebyte(price[price.length() - i - 1]);
}
}
void vfd_print(customer_display_t* const display, int rownum, const std::string& str, const std::string& price, int align) {
if (display == 0) return;
display->print(rownum, str, price, align);
}
void vfd_clear_all(customer_display_t* const display) {
if (display == 0) return;
display->clear_all();
}
void vfd_clear_line(customer_display_t* const display, int num) {
if (display == 0) return;
display->clear_line(num);
}
| true |
750205445ca37ae4cb67653acd1af5b8c27a40be | C++ | sourcehold/Sourcehold | /test/SurfaceTest.cpp | UTF-8 | 4,177 | 3.078125 | 3 | [
"MIT"
] | permissive | #include <gtest/gtest.h>
#include <array>
#include <numeric>
#include "Rendering/Surface.h"
#include "SDL/SDLHelpers.h"
using namespace Sourcehold::Rendering;
using namespace Sourcehold::SDL;
constexpr Vector2<int> size_k = {10, 10};
constexpr Color color = {0xFF, 0xFF, 0xFF};
TEST(Surface, DefaultIsNull) {
Surface surface;
ASSERT_EQ(static_cast<SDL_Surface*>(surface), nullptr);
}
TEST(Surface, CopyConstructFromDefaultIsNull) {
Surface surface;
auto surface2(surface);
ASSERT_EQ(static_cast<SDL_Surface*>(surface2), nullptr);
}
TEST(Surface, CopyAssignFromDefaultIsNull) {
Surface surface;
auto surface2 = surface;
ASSERT_EQ(static_cast<SDL_Surface*>(surface2), nullptr);
}
TEST(Surface, CopyConstructible) {
Surface surface({10, 10});
SDL_Surface* surface_ptr = surface;
for (int i = 0; i < 100; ++i) {
(static_cast<int*>(surface_ptr->pixels))[i] = i;
}
auto surface2(surface);
SDL_Surface* surface_ptr2 = surface2;
for (int i = 0; i < 100; ++i) {
ASSERT_EQ(static_cast<int*>(surface_ptr->pixels)[i],
static_cast<int*>(surface_ptr2->pixels)[i]);
}
}
TEST(Surface, CopyAssignmentConstructible) {
Surface surface({10, 10});
SDL_Surface* surface_ptr = surface;
for (int i = 0; i < 100; ++i) {
(static_cast<int*>(surface_ptr->pixels))[i] = i;
}
auto surface2 = surface;
SDL_Surface* surface_ptr2 = surface2;
for (int i = 0; i < 100; ++i) {
ASSERT_EQ(static_cast<int*>(surface_ptr->pixels)[i],
static_cast<int*>(surface_ptr2->pixels)[i]);
}
}
TEST(Surface, MoveConstructSourceIsNull) {
Surface surface({10, 10});
Surface surface2(std::move(surface));
ASSERT_EQ(surface, nullptr);
}
TEST(Surface, MoveAssignSourceIsNull) {
Surface surface({10, 10});
Surface surface2 = std::move(surface);
ASSERT_EQ(surface, nullptr);
}
TEST(Surface, MoveConstructDestinationIsValid) {
Surface surface({10, 10});
Surface surface2(std::move(surface));
ASSERT_NE(surface2, nullptr);
}
TEST(Surface, MoveAssignDestinationIsValid) {
Surface surface({10, 10});
Surface surface2 = std::move(surface);
ASSERT_NE(surface2, nullptr);
}
TEST(Surface, Set) {
Surface surface(size_k);
surface.Set({0, 0}, color);
ASSERT_EQ(At<Pixel>(surface, {0, 0}), color);
}
TEST(Surface, StdAlgorithm) {
Surface surface(size_k);
std::array<Pixel, size_k.x * size_k.y> groundtruth;
std::iota(std::begin(surface), std::end(surface), 0);
std::iota(std::begin(groundtruth), std::end(groundtruth), 0);
auto result = std::equal(std::begin(surface), std::end(surface),
std::begin(groundtruth));
ASSERT_TRUE(result);
}
TEST(Surface, Fill) {
Surface surface({10, 10});
surface.Fill(color);
for (const auto& pixel : surface) {
ASSERT_EQ(pixel, color);
}
}
TEST(Surface, Blit) {
Surface surface1({5, 5});
Surface surface2({10, 10});
std::fill(std::begin(surface1), std::end(surface1), Color{0, 0, 0});
std::iota(std::begin(surface2), std::end(surface2), 0);
std::array<Pixel, 100> groundtruth;
std::iota(std::begin(groundtruth), std::end(groundtruth), 0);
for (auto y = 0; y < 5; ++y) {
for (auto x = 0; x < 5; ++x) {
groundtruth[At({x, y}, 10)] = 0xFF;
}
}
surface2.Blit(surface1, {0, 0});
auto result = std::equal(std::begin(surface2), std::end(surface2),
std::begin(groundtruth));
ASSERT_TRUE(result);
}
TEST(Surface, BlitClipped) {
Surface surface1({5, 5});
Surface surface2({10, 10});
std::fill(std::begin(surface1), std::end(surface1), Color{0, 0, 0});
std::iota(std::begin(surface2), std::end(surface2), 0);
std::array<Pixel, 100> groundtruth;
std::iota(std::begin(groundtruth), std::end(groundtruth), 0);
constexpr Vector2<int> pos = {1, 2};
constexpr Rect<int> clip = {0, 0, 2, 4};
for (auto y = pos.y; y < clip.h + pos.y; ++y) {
for (auto x = pos.x; x < clip.w + pos.x; ++x) {
groundtruth[At({x, y}, 10)] = Color{0, 0, 0};
}
}
surface2.Blit(surface1, pos, clip);
auto result = std::equal(std::begin(surface2), std::end(surface2),
std::begin(groundtruth));
ASSERT_TRUE(result);
}
| true |
5735e344d1e051207367b957a096469f64fd9d44 | C++ | EFanZh/Archived | /Visual Studio/Misc/LeetCode OJ/324. Wiggle Sort II/Solution.h | UTF-8 | 1,178 | 3.46875 | 3 | [] | no_license | #pragma once
class Solution
{
static int getMedian(vector<int> &nums)
{
const auto it = nums.begin() + nums.size() / 2;
nth_element(nums.begin(), it, nums.end());
return *it;
}
public:
void wiggleSort(vector<int> &nums)
{
if (nums.size() < 2)
{
return;
}
const auto median = getMedian(nums);
auto i = vector<int>::size_type(0);
auto k = vector<int>::size_type(nums.size());
const auto getNum = [&](vector<int>::size_type i) -> int & {
const auto half = (nums.size() + 1) / 2;
return nums[i < half ? 2 * (half - 1 - i) : 2 * (nums.size() - 1 - i) + 1];
};
for (auto j = vector<int>::size_type(0); j < k;)
{
auto ¤t = getNum(j);
if (current < median)
{
swap(current, getNum(i));
++i;
++j;
}
else if (current == median)
{
++j;
}
else
{
--k;
swap(current, getNum(k));
}
}
}
};
| true |
0f14c1c261805f42a556b414ef85dfeb9e87bcfb | C++ | Jaycar-Electronics/WiFi-Datalogger | /datalog/datalog.ino | UTF-8 | 2,155 | 2.703125 | 3 | [] | no_license | #include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <SPI.h>
#include <ArduinoJson.h>
const char* WIFI_SSID = "wifiName";
const char* WIFI_PASS = "wifiPassword";
const char* URL = "http://maker.ifttt.com/trigger/EVENT_NAME_HERE/with/key/YOUR_KEY_HERE";
const int CS = D8;
StaticJsonDocument<300> doc;
const char msg_buffer[300] = "";
void setup() {
Serial.begin(115200);
// Serial.setDebugOutput(true);
Serial.println();
Serial.println();
Serial.println();
SPI.begin();
WiFi.begin(WIFI_SSID, WIFI_PASS);
while(WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println(" OK!");
pinMode(CS, OUTPUT);
}
void loop() {
for(short i = 0; i < 8; i++){
Serial.print( read(i) );
Serial.print(",");
}
Serial.println();
// send request with 3 vars
// you could also do multiple, by shifting by ten, IE:
// (read(0) << 10) | read(1);
// or putting in an array.
// but you would have to process it on the google sheets side.
// limitations ahoy;
// Maker/IFTTT expect something literally called "value1"
doc["value1"] = read(0);
doc["value2"] = read(1);
doc["value3"] = read(2);
//send vars, first convert to string, then POST out.
serializeJson(doc, (char*) msg_buffer, 300);
Serial.println(msg_buffer);
HTTPClient http;
http.begin(URL);
http.addHeader("Content-Type", "application/json"); //tell server it is json
int r = http.POST(msg_buffer);
if (r < 0){
Serial.println(http.errorToString(r));
}else{
http.writeToStream(&Serial); //write response back to serial,
}
http.end();
Serial.printf("\n[%d] status code\n\n", r);
delay(60000);
}
int read(short chan){
if ((chan > 7) || (chan < 0))
return -1;
//from page 22 of the MCP3008 datasheet.
short command = 0b11000000 | (chan << 3);
//SPI.beginTransaction( SPISettings(1000000, MSBFIRST, SPI_MODE0) );
digitalWrite(CS, LOW);
SPI.transfer(command);
int ret = SPI.transfer16(0);
digitalWrite(CS, HIGH);
//SPI.endTransaction();
return ret & 0x3FF;
}
| true |
38a6e791a64a7ed6dcfa1cfcd93738c24c7eee8d | C++ | nicebub/CPP_CrashCourse | /chptr1/sum.cpp | UTF-8 | 413 | 3.25 | 3 | [] | no_license | #include <cstdio>
int sum(int x, int y){
return x+y;
}
int main(){
int my_number = -10;
int my_number2 = 10;
int my_number3 = 255;
printf("The sum of %d and %d is %d\n", my_number, my_number2, sum(my_number,my_number2));
printf("The sum of %d and %d is %d\n", my_number, my_number3, sum(my_number,my_number3));
printf("The sum of %d and %d is %d\n", my_number2, my_number3, sum(my_number2,my_number3));
} | true |
63200320238663862f5a72d6ab35e3f8f8610409 | C++ | oberonlievens/computertechnologie-3 | /labo/2015-2016/08/02.ino | UTF-8 | 720 | 2.796875 | 3 | [] | no_license | #include <TM1636.h>
TM1636 disp(7,8);
const byte leds[] = {2, 3, 4, 5};
int8_t pr [] = {17,0,0,12};
short temp = 0;
void setup() {
Serial.begin(9600);
pinMode(14,INPUT);
for (byte i = 0; i < sizeof(leds) / sizeof(byte); i++) {
pinMode(leds[i], OUTPUT);
}
disp.init();
disp.display(pr);
}
int8_t getTemperature()
{
float temperature,resistance;
int a;
a = analogRead(14);
resistance = (float)(1023-a)*10000/a;
temperature = 1/(log(resistance/10000)/3975+1/298.15)-273.15;
return (int8_t)temperature;
}
void printTemp(int8_t t) {
pr[1] = t/10;
pr[2] = t % 10 ;
Serial.println(pr[2]),
disp.display(pr);
}
void loop() {
temp = getTemperature();
printTemp(temp);
delay(100);
}
| true |
205822ff99d38939ecfc09ada3674d00d0bfbed3 | C++ | christocs/ICT398 | /src/afk/render/Camera.cpp | UTF-8 | 2,921 | 2.75 | 3 | [
"ISC"
] | permissive | #include "afk/render/Camera.hpp"
#include <algorithm>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/matrix_decompose.hpp>
#include "afk/NumericTypes.hpp"
using glm::mat4;
using glm::vec2;
using glm::vec3;
using afk::render::Camera;
auto Camera::handle_mouse(f32 dx, f32 dy) -> void {
constexpr auto max_yaw = 89.0f;
this->angles.x += dx * this->sensitivity;
this->angles.y += -dy * this->sensitivity;
this->angles.y = std::clamp(this->angles.y, -max_yaw, max_yaw);
}
auto Camera::handle_key(Movement movement, f32 dt) -> void {
const auto velocity = this->speed * dt;
switch (movement) {
case Movement::Forward: {
this->position += this->get_front() * velocity;
} break;
case Movement::Backward: {
this->position -= this->get_front() * velocity;
} break;
case Movement::Left: {
this->position -= this->get_right() * velocity;
} break;
case Movement::Right: {
this->position += this->get_right() * velocity;
} break;
}
}
auto Camera::get_view_matrix() const -> mat4 {
return glm::lookAt(this->position, this->position + this->get_front(), this->get_up());
}
auto Camera::get_projection_matrix(int width, i32 height) const -> mat4 {
const auto w = static_cast<f32>(width);
const auto h = static_cast<f32>(height);
const auto aspect = h > 0 ? w / h : 0;
return glm::perspective(glm::radians(this->fov), aspect, this->near, this->far);
}
auto Camera::get_front() const -> vec3 {
auto front = vec3{};
front.x = std::cos(glm::radians(this->angles.x)) *
std::cos(glm::radians(this->angles.y));
front.y = std::sin(glm::radians(this->angles.y));
front.z = std::sin(glm::radians(this->angles.x)) *
std::cos(glm::radians(this->angles.y));
front = glm::normalize(front);
return front;
}
auto Camera::get_right() const -> vec3 {
return glm::normalize(glm::cross(this->get_front(), this->WORLD_UP));
}
auto Camera::get_up() const -> vec3 {
return glm::normalize(glm::cross(this->get_right(), this->get_front()));
}
auto Camera::get_position() const -> vec3 {
return this->position;
}
auto Camera::get_angles() const -> vec2 {
return this->angles;
}
auto Camera::set_position(glm::vec3 v) -> void {
this->position = v;
}
auto Camera::set_angles(glm::vec2 v) -> void {
this->angles = v;
}
auto Camera::get_key(Movement movement) const -> bool {
return this->key_states.at(movement);
}
auto Camera::set_key(Movement movement, bool down) -> void {
this->key_states.at(movement) = down;
}
auto Camera::get_near() const -> f32 {
return this->near;
}
auto Camera::get_far() const -> f32 {
return this->far;
}
auto Camera::set_raycast_entity(OptionalEntity entity) -> void {
this->raycast_entity = entity;
}
auto Camera::get_raycast_entity() const -> OptionalEntity {
return this->raycast_entity;
}
| true |
930dd190cec9b53f96e6f664de4c2a5647dec578 | C++ | drlongle/leetcode | /algorithms/problem_1124/other2.cpp | UTF-8 | 538 | 2.671875 | 3 | [] | no_license | class Solution {
public:
int longestWPI(vector<int>& hours) {
int res = 0, cnt = 0, n = hours.size();
for (int i = 0; i < n; ++i) {
if (hours[i] > 8) ++cnt;
if (cnt * 2 > i + 1) res = i + 1;
int left = 0, curCnt = cnt;
while (left < i && curCnt * 2 <= i - left + 1) {
if (hours[left] > 8) --curCnt;
++left;
if (curCnt * 2 > i - left + 1) res = max(res, i - left + 1);
}
}
return res;
}
};
| true |
f42c8480f5b6246dc645ff01eee0b0d14299e311 | C++ | paulzik/Mortal-Kombat | /MortalCombat/MortalCombat/Animator/Animator/MovingPathAnimator.cpp | UTF-8 | 1,605 | 2.515625 | 3 | [] | no_license | #include "MovingPathAnimator.h"
#include <iostream>
#include <math.h>
bool fall;
bool once;
void MovingPathAnimator::Progress(timestamp_t currTime) {
if (currTime > lastTime && currTime - lastTime >= anim->GetDelay()) {
int x = anim->GetDx();
if (fall) {
if (sprite->y < 150)
sprite->y += (float)sqrt((((1 - pow((sprite->x / 800), 2)))) / 10.0f) * 10;
else if (sprite->y < 200)
sprite->y += (float)sqrt((((1 - pow((sprite->x / 800), 2)))) / 10.0f) * 20;
else if (sprite->y < 250)
sprite->y += (float)sqrt((((1 - pow((sprite->x / 800), 2)))) / 10.0f) * 30;
else
sprite->y += (float)sqrt((((1 - pow((sprite->x / 800), 2)))) / 10.0f) * 40;
}
else {
if (sprite->y < 150)
sprite->y -= (float)sqrt((((1 - pow((sprite->x / 800), 2)))) / 10.0f) * 10;
else if (sprite->y < 200)
sprite->y -= (float)sqrt((((1 - pow((sprite->x / 800), 2)))) / 10.0f) * 20;
else if (sprite->y < 250)
sprite->y -= (float)sqrt((((1 - pow((sprite->x / 800), 2)))) / 10.0f) * 30;
else
sprite->y -= (float)sqrt((((1 - pow((sprite->x / 800), 2)))) / 10.0f) * 40;
}
sprite->Move(x, 0);
if (sprite->y < 100 && !once) {
once = true;
fall = true;
}
if (sprite->y >= 330) {
state = ANIMATOR_FINISHED;
sprite->y = 330;
NotifyStopped();
fall = false;
once = false;
return;
}
else {
lastTime += anim->GetDelay();
//Progress(currTime); // Recursion (make it a loop)
}
}
}
void MovingPathAnimator::Render(SDL_Renderer * rend)
{
}
void MovingPathAnimator::SetLogicState(logic::StateTransitions & state)
{
state.SetState("Idle");
}
| true |
018eb2c48b82934add09c75441cd81d9ad0ac66a | C++ | Sharundaar/OpenGLSDL | /GraphicEngine/ShaderBank.cpp | UTF-8 | 438 | 2.75 | 3 | [] | no_license | #include "ShaderBank.h"
std::unordered_map<std::string, Shader*> ShaderBank::s_bank;
ShaderBank::ShaderBank()
{
}
ShaderBank::~ShaderBank()
{
for (auto elem : s_bank)
{
delete elem.second;
}
s_bank.clear();
}
Shader* ShaderBank::getShader(const char* _name)
{
if (s_bank.find(_name) == s_bank.end())
{
Shader* shader = new Shader(_name);
s_bank[_name] = shader;
return shader;
}
else
{
return s_bank[_name];
}
}
| true |
810774b2543445b9bc468317699980719b861e07 | C++ | elilitko/ArduinoStuff | /PSRAM/ESP_PSRAM64/examples/PutGetTest/PutGetTest.ino | UTF-8 | 2,363 | 3.171875 | 3 | [] | no_license | #include <Printing.h>
#define USE_PINOPS true
#include <ESP_PSRAM64.h>
class CAnekdot : public Printable {
char m_origin[16];
char m_body[100];
int m_id;
public:
CAnekdot(void) {}
CAnekdot(const int id, const char * origin, const char * body) {
strcpy(m_origin, origin);
strcpy(m_body, body);
m_id = id;
}
size_t printTo(Print& p) const {
return
p.print(m_id)
+ p.print(", (")
+ p.print(m_origin)
+ p.println(')')
+ p.println(m_body);
}
};
ESP_PSRAM64 psram;
void setup(void) {
Serial.begin(115200);
Serial.println("ESP PSRAM64H тест методов put и get\r\n");
delayMicroseconds(150);
psram.reset();
//
// Число с плавающей точкой
float pi = M_PI;
Serial << "Исходное число (float): " << pi << "\r\n";
psram.put(1234, pi); // запишем
pi = 0; // загадим
psram.get(1234, pi); // прочитаем
Serial << "Прочитанное число (float): " << pi << "\r\n\r\n";
//
// Число uint32_t
uint32_t f_cpu = F_CPU;
Serial << "Исходное число (uint32_t): " << f_cpu << "\r\n";
psram.put(1234, f_cpu); // запишем
f_cpu = 0; // загадим
psram.get(1234, f_cpu); // прочитаем
Serial << "Прочитанное число (uint32_t): " << f_cpu << "\r\n\r\n";
//
// Массив char[]
char str[] = "\"Жил один еврей, так он сказал, что всё проходит.\"";
Serial << "Исходный массив: " << str << "\r\n";
psram.put(1234, str); // запишем
str[0] = '\0'; // загадим
psram.get(1234, str); // прочитаем
Serial << "Прочитанный массив: " << str << "\r\n\r\n";
// Исходная структура (запишем её по адресу 1234)
CAnekdot source(321, "Одесса", "- Сёма, Вы таки куда?\r\n- Да, нет, я домой.");
psram.put(1234, source);
Serial.println("::: Исходная структура :::");
Serial.println(source);
// Прочитанная из PSRAM структура
CAnekdot dest;
psram.get(1234, dest);
Serial.println("::: Прочитанная структура :::");
Serial.println(dest);
Serial.println("=== Тест завершён ===");
}
void loop(void) {}
| true |
a88faefff2b5b48e038ae061957295a2e32087b1 | C++ | robertsdionne/textengine | /libraries/rsd/source/program.cpp | UTF-8 | 2,875 | 2.8125 | 3 | [] | no_license | #include <unordered_map>
#include <vector>
#include "checks.h"
#include "program.h"
#include "shader.h"
namespace rsd {
Program::Program() : shaders(), handle() {}
Program::~Program() {
if (handle) {
glDeleteProgram(handle);
handle = 0;
}
}
GLuint Program::get_handle() const {
return handle;
}
void Program::CompileAndLink() {
for (auto shader : shaders) {
shader->Compile();
glAttachShader(handle, shader->get_handle());
}
glLinkProgram(handle);
MaybeOutputLinkerError();
}
void Program::Create(const std::vector<Shader *> &&shaders) {
if (handle) {
glDeleteProgram(handle);
handle = 0;
}
this->shaders = shaders;
handle = glCreateProgram();
}
GLint Program::GetAttributeLocation(const std::string &name) {
return glGetAttribLocation(handle, name.c_str());
}
GLint Program::GetUniformLocation(const std::string &name) {
return glGetUniformLocation(handle, name.c_str());
}
void Program::MaybeOutputLinkerError() {
GLint success;
glGetProgramiv(handle, GL_LINK_STATUS, &success);
if (!success) {
GLchar info_log[Shader::kMaxInfoLogLength];
GLsizei length;
glGetProgramInfoLog(handle, Shader::kMaxInfoLogLength, &length, info_log);
if (length) {
FAIL(info_log);
} else {
FAIL(u8"Failed to link program.");
}
}
}
void Program::Uniforms(const std::unordered_map<std::string, int> &&uniforms) {
Use();
for (auto &uniform : uniforms) {
glUniform1i(GetUniformLocation(uniform.first), uniform.second);
}
}
void Program::Uniforms(const std::unordered_map<std::string, float> &&uniforms) {
Use();
for (auto &uniform : uniforms) {
glUniform1f(GetUniformLocation(uniform.first), uniform.second);
}
}
void Program::Uniforms(const std::unordered_map<std::string, glm::vec2> &&uniforms) {
Use();
for (auto &uniform : uniforms) {
glUniform2fv(GetUniformLocation(uniform.first), 1, &uniform.second[0]);
}
}
void Program::Uniforms(const std::unordered_map<std::string, glm::vec3> &&uniforms) {
Use();
for (auto &uniform : uniforms) {
glUniform3fv(GetUniformLocation(uniform.first), 1, &uniform.second[0]);
}
}
void Program::Uniforms(const std::unordered_map<std::string, glm::vec4> &&uniforms) {
Use();
for (auto &uniform : uniforms) {
glUniform4fv(GetUniformLocation(uniform.first), 1, &uniform.second[0]);
}
}
void Program::Uniforms(const std::unordered_map<std::string, const glm::mat4 *> &&uniforms) {
Use();
for (auto &uniform : uniforms) {
glUniformMatrix4fv(GetUniformLocation(uniform.first),
1, false, &uniform.second->operator[](0)[0]);
}
}
void Program::Use() {
glUseProgram(handle);
}
} // namespace rsd
| true |
57dd8827267532e72eb94c14e5422482a9a6687d | C++ | naddu77/ModernCppChallenge | /076_Deserializing_data_from_JSON/076_Deserializing_data_from_JSON.cpp | UTF-8 | 1,911 | 3.5 | 4 | [] | no_license | // 076_Deserializing_data_from_JSON.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다.
//
#include "pch.h"
#include <iostream>
#include <cassert>
#include <string_view>
#include <fstream>
#include <nlohmann/json.hpp>
struct casting_role
{
std::string actor;
std::string role;
};
struct movie
{
unsigned int id;
std::string title;
unsigned int year;
unsigned int length;
std::vector<casting_role> cast;
std::vector<std::string> directors;
std::vector<std::string> writers;
};
using movie_list = std::vector<movie>;
using json = nlohmann::json;
movie_list deserialize(std::string_view filepath)
{
movie_list movies;
std::ifstream ifile(filepath.data());
if (ifile.is_open())
{
json jdata;
try
{
ifile >> jdata;
if (jdata.is_object())
{
for (auto & element : jdata.at("movies"))
{
movie m;
m.id = element.at("id").get<unsigned int>();
m.title = element.at("title").get<std::string>();
m.year = element.at("year").get<unsigned int>();
m.length = element.at("length").get<unsigned int>();
for (auto & role : element.at("cast"))
{
m.cast.push_back(casting_role{
role.at("star").get<std::string>(),
role.at("name").get<std::string>() });
}
for (auto & director : element.at("directors"))
{
m.directors.push_back(director);
}
for (auto & writer : element.at("writers"))
{
m.writers.push_back(writer);
}
movies.push_back(m);
}
}
}
catch (std::exception const & ex)
{
std::cout << ex.what() << std::endl;
}
}
return movies;
}
int main()
{
auto movies = deserialize("movies.json");
assert(movies.size() == 2);
assert(movies[0].title == "The Matrix");
assert(movies[1].title == "Forrest Gump");
return 0;
} | true |
186ea7c7ea09c9bda2effc622b5cea457a21d170 | C++ | Cegard/Parallel_Matrices | /parallel_openmp.cpp | UTF-8 | 3,126 | 3.0625 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <omp.h>
#define PAD 2*sizeof(double)
using namespace std;
double** createMatrix(int dim, bool zeroes){
double **matrix = (double**) malloc(dim * sizeof(double*) * PAD);
for (int i = 0; i < dim; i++){
*(matrix + i) = (double*) malloc(dim * sizeof(double) + PAD);
for (int j = 0; j < dim; j++)
*(*(matrix + i) + j) = (zeroes)? 0.0 : (10.0*rand()/(RAND_MAX+1.0));
}
return matrix;
}
double** createMatrixWithZeroes(int dim){
return createMatrix(dim, 1);
}
int printMatrix(double **matrix, int dim){
for (int i = 0; i < dim; i++){
for (int j = 0; j < dim; j++)
printf("%.2f ", *(*(matrix + i) + j));
printf("\n");
}
printf("\n");
}
double ** createRandomMatrix(int dim){
return createMatrix(dim, 0);
}
void freeMatrix(double ***matrix, int dim){
for (int i = 0; i < dim; i++)
free(*(*matrix + i));
free(*matrix);
}
double** multiplyMatrix(double **matrixA, double **matrixB, double **matrixC, int dim, int threads){
double **answer = matrixC;
#pragma omp parallel num_threads(threads)
{
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < dim; i++){
for (int j = 0; j < dim; j++){
double cell = 0.0;
for (int n = 0; n < dim; n++)
cell += *(*(matrixA + i) + n) * *(*(matrixB + j) + n);
*(*(answer + i) + j) = cell;
}
}
}
return answer;
}
int main(){
int dim = 32;
int threads = 1;
printf("\n---------------------------------------------\n");
while (dim <= 2048){
double **matrixA = createRandomMatrix(dim);
double **matrixB = createRandomMatrix(dim);
double **matrixC = createMatrixWithZeroes(dim);
struct timeval start_time;
struct timeval end_time;
gettimeofday(&start_time, NULL);
matrixC = multiplyMatrix(matrixA, matrixB, matrixC, dim, threads);
gettimeofday(&end_time, NULL);
double seconds = (((1000.0*end_time.tv_sec) + (end_time.tv_usec/1000.0)) -
((1000.0*start_time.tv_sec) + (start_time.tv_usec/1000.0)))/1000.0;
//printf("\n");
//printf("matrix a\n");
//printMatrix(matrixA, dim);
//printf("matrix b\n");
//printMatrix(matrixB, dim);
//printf("matrix c\n");
//printMatrix(matrixC, dim);
printf("Taken time for a matrix of %dX%d with %d threads: %.5fs\n", dim, dim, threads, seconds);
freeMatrix(&matrixA, dim);
freeMatrix(&matrixB, dim);
freeMatrix(&matrixC, dim);
threads *= 2;
if (threads > 64){
printf("---------------------------------------------\n\n");
printf("---------------------------------------------\n");
threads = 1;
dim *= 2;
}
}
return 0;
}
| true |
b218085fa2c0adb23b79eb689ec9202eb2f2dd9a | C++ | PDcsc5/pd2503230 | /Homework/Assignment_2/Gaddis_ch3_prob15/main.cpp | UTF-8 | 697 | 3.359375 | 3 | [] | no_license | /*
* File: main.cpp
* Author: rcc
*Created on July 3, 2014, 1:04 PM
* Math Tutor
Write a program that can be used as a math tutor for a young student. The program
should display two random numbers to be added, such as
247
+ 129
The program should then pause while the student works on the problem. When the
student is ready to check the answer, he or she can press a key and the program will
display the correct solution:
247
+ 129
376
*/
#include <cstdlib>
#include <iostream>
using namespace std;
//User Defined Libraries
//Global Constants
//Function Prototypes
//Execution Begins Here
int main(int argc, char** argv) {
float
//Exit stage right
return 0;
} | true |
8c1fa8a01179bca0936294b7343a56840dc9ae3f | C++ | cenariusxz/ACM-Coding | /homework/CandC++/E31.cpp | UTF-8 | 320 | 2.984375 | 3 | [] | no_license | #include<stdio.h>
#define N 1000
int main()
{
int prim(int x);
int i,count=0;
for (i=2;i<=N;i++)
{
if (prim(i)==1)
{
printf("%d\t",i);
count++;
if (count%8==0) printf("\n");
}
}
return 0;
}
int prim(int x)
{
int m;
for (m=x-1;m>=1;m--)
{
if (x%m==0) break;
}
if (m==1) return 1;
return 0;
} | true |
434c2956d3256594caf42bd837effb881a086ac0 | C++ | dhbloo/light2D | /light2D/ShapeTriangle.h | UTF-8 | 967 | 3.09375 | 3 | [] | no_license | #pragma once
#include "shape.h"
class ShapeTriangle : public Shape {
private:
float bx, by, cx, cy;
float segment(float x, float y, float ax, float ay, float bx, float by) const {
float vx = x - ax, vy = y - ay, ux = bx - ax, uy = by - ay;
float t = fmaxf(fminf((vx * ux + vy * uy) / (ux * ux + uy * uy), 1.0f), 0.0f);
float dx = vx - ux * t, dy = vy - uy * t;
return sqrtf(dx * dx + dy * dy);
}
public:
ShapeTriangle(float ax, float ay, float bx, float by, float cx, float cy) : Shape(ax, ay), bx(bx), by(by), cx(cx), cy(cy) {}
virtual ~ShapeTriangle() {}
virtual float sdf(float x, float y) const {
float d = fminf(fminf(
segment(x, y, this->x, this->y, bx, by),
segment(x, y, bx, by, cx, cy)),
segment(x, y, cx, cy, this->x, this->y));
return (bx - this->x) * (y - this->y) > (by - this->y) * (x - this->x) &&
(cx - bx) * (y - by) > (cy - by) * (x - bx) &&
(this->x - cx) * (y - cy) > (this->y - cy) * (x - cx) ? -d : d;
}
}; | true |
4290a7b7ef67245d172059ca2292b477bf314b84 | C++ | mitchinator1/ColourCube | /ColourCube/Source/UI/Font/Word.cpp | UTF-8 | 363 | 2.96875 | 3 | [] | no_license | #include "Word.h"
namespace Text
{
Word::Word(float fontSize)
: m_FontSize(fontSize)
{
}
void Word::AddCharacter(Character& character)
{
m_Characters.emplace_back(character);
m_Width += character.xAdvance * m_FontSize;
}
std::vector<Character>& Word::GetCharacters()
{
return m_Characters;
}
float Word::GetWidth()
{
return m_Width;
}
} | true |
65049202289751ffd76cbdbe23cf1150571b7360 | C++ | FRC-3277/2018POWER-UP | /src/Commands/InvertDriverControlsCommand.cpp | UTF-8 | 1,081 | 2.6875 | 3 | [
"MIT"
] | permissive | #include "InvertDriverControlsCommand.h"
InvertDriverControlsCommand::InvertDriverControlsCommand() {
// No exclusive access required to drivetrain subsystem.
lumberJack.reset(new LumberJack());
}
// Called just before this Command runs the first time
void InvertDriverControlsCommand::Initialize() {
}
// Called repeatedly when this Command is scheduled to run
void InvertDriverControlsCommand::Execute() {
lumberJack->iLog("InvertDriverControlsCommand toggled");
if(Robot::driveTrain->ToggleInvertDriverControls())
{
lumberJack->iLog("Camera Reverse");
Robot::camera->CameraReverse();
}
else
{
lumberJack->iLog("Camera Forward");
Robot::camera->CameraForward();
}
}
// Make this return true when this Command no longer needs to run execute()
bool InvertDriverControlsCommand::IsFinished() {
return true;
}
// Called once after isFinished returns true
void InvertDriverControlsCommand::End() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void InvertDriverControlsCommand::Interrupted() {
}
| true |
ad8e9854f3b70e1f7291fd2ecda85450f14b1b00 | C++ | hthappiness/codebase | /src/util/tools.hpp | UTF-8 | 8,520 | 3.015625 | 3 | [] | no_license |
#include <iostream>
#include <chrono>
/*
The ulitity about time ,the function ,the class, the object, the operation, the variables
These resources are well organized by the c++ library.
1、基本功能的正交
2、好用、直观的接口
3、
OOP + template 的组织方式
std::chrono::stready_clock ;
std::chrono::system_clock ;
std::chrono::high_resolution_lock ;
Durations
They measure time spans, like: one minute, two hours, or ten milliseconds.
Time points
A reference to a specific point in time, like one’s birthday, today’s dawn, or when the next train passes.
Clocks
A framework that relates a time point to real physical time.
https://blog.csdn.net/mo4776/article/details/80116112
*/
#include <iostream>
#include <chrono>
#include <ratio>
#include <thread>
void f()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int test()
{
auto t1 = std::chrono::high_resolution_clock::now();
f();
auto t2 = std::chrono::high_resolution_clock::now();
// 整数时长:要求 duration_cast
auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
// 小数时长:不要求 duration_cast
std::chrono::duration<double, std::milli> fp_ms = t2 - t1;
std::cout << "f() took " << fp_ms.count() << " ms, "
<< "or " << int_ms.count() << " whole milliseconds\n";
}
//可能的输出:
//f() took 1000.23 ms, or 1000 whole milliseconds
class CTimeStat
{
public:
const char* m_tag;
std::chrono::steady_clock::time_point m_startTp = std::chrono::steady_clock::now();
public:
CTimeStat(const char* tag):
m_tag(tag){
}
~CTimeStat()
{
auto elapsedClk = std::chrono::stready_clock::now() - m_startTp;
auto elapsedTm = std::chrono::duration_cast<std::chrono::milliseconds>(elapsedClk);
std::cout<<m_tag<<"elapsed Time:"<<elapsedTm<<std::endl;
}
};
template <typename T>
class CPrintCfg
{
public:
using Handle = std::function<void(T&&)>;
private:
int iInterval;
int iIntervalCnt;
CPrintCfg(handle print)
{
m_print = print;
}
~CPrintCfg(){}
void operator() ()
{
iInterValCnt++;
if( iIntervalCnt % iInterval)
{
m_print();
}
}
Handle m_print;
};
template <typename T>
class CBufferConsumer : public boost::noncopyable
{
using Handler = std::function<void(T&&)>;
public:
CBufferConsumer(unsigned long ulCapacity)
:m_queue(ulCapacity)
{
}
void push(const T& value)
{
m_queue.push_back(value);
}
void push(T&& value)
{
m_queue.push_back(std::move(value));
}
void run(const Handler& handler, const std::function<void()>& pre = nullptr)
{
m_process = handler;
m_pre = pre;
m_thread = std::thread(&CBufferConsumer::work, this);
}
void join()
{
m_queue.close();
m_thread.join();
}
private:
void work()
{
if( m_pre )
{
m_pre();
}
while(true)
{
auto status = m_queue.wait_pull_front(m_buffer);
if ( boost::concurrency::queue_op_status::success == status )
{
m_process(std::move(m_buffer));
m_buffer = {};
}
else if ( boost::concurrency::queue_op_status::closed == status )
{
break;
}
}
}
private:
boost::concurrency::sync_bounded_queue<T> m_queue;
std::function<void()> m_pre;
Handler m_process;
std::thread m_thread;
T m_buffer;
};
class CFinalGuard
{
public:
CFinalGuard(const std::function<void()>& final)
:m_final(final)
{}
~CFinalGuard()
{
if ( false == m_bCanceled)
{
try{
m_final();
}
catch(...)
{
}
}
}
void cancel() noexcept;
private:
const std::function<void()> m_final;
bool m_bCanceled = false;
}
#ifndef ASIO_TIMER_H
#define ASIO_TIMER_H
typedef std::function<void()> ProcessFun;
//以steady_timer替代原来的deadline_timer
typedef boost::shared_ptr <boost::asio::steady_timer> pSteadyTimer;
struct STimerUnit
{
int id;
int seconds;
pSteadyTimer t;
ProcessFun fun;
};
typedef boost::shared_ptr<STimerUnit> TimerUnitPtr;
class CTimer
{
public:
CTimer() :m_ioWork(m_ioService), m_lID(0)
{
}
public:
//添加一个定时业务,f为业务处理函数,arg为自定义参数,seconds为超时秒数
//返回生成的ID
int AddTimerUnit(ProcessFun f,int seconds);
//每intervalSeconds秒数执行一次 f函数
int AddTimerIntervalUnit(ProcessFun f, int intervalSeconds);
//删除指定定时器
void RemoveTimerUnit(int id);
bool TimerisValid(int id);
void Run();
private:
void TimerProcess(int id, bool isIntervalTimer, const boost::system::error_code& e);
private:
std::map<int, TimerUnitPtr> m_mapTimerUnits;
private:
boost::asio::io_service m_ioService;
boost::asio::io_service::work m_ioWork;
private:
std::mutex m_mutexTimerUnit;
private:
//分配timer id
std::vector<int> m_vecTimerUnitIDs;
unsigned long long m_lID;
};
#endif
#include "log.h"
#include "asiotimer.h"
int CTimer::AddTimerUnit(ProcessFun f,int seconds)
{
TimerUnitPtr s(new STimerUnit);
s->seconds = seconds;
s->t.reset(new boost::asio::steady_timer(m_ioService, std::chrono::seconds(seconds)));
s->fun = f;
{
std::lock_guard<std::mutex> lock(m_mutexTimerUnit);
m_mapTimerUnits.insert(std::make_pair(++m_lID, s));
s->t->async_wait(boost::bind(&CTimer::TimerProcess, this, m_lID,false, boost::asio::placeholders::error));
return m_lID;
}
}
int CTimer::AddTimerIntervalUnit(ProcessFun f, int intervalSeconds)
{
TimerUnitPtr s(new STimerUnit);
s->seconds = intervalSeconds;
s->t.reset(new boost::asio::steady_timer(m_ioService, std::chrono::seconds(intervalSeconds)));
s->fun = f;
{
std::lock_guard<std::mutex> lock(m_mutexTimerUnit);
m_mapTimerUnits.insert(std::make_pair(++m_lID, s));
s->t->async_wait(boost::bind(&CTimer::TimerProcess, this, m_lID, false, boost::asio::placeholders::error));
return m_lID;
}
}
void CTimer::RemoveTimerUnit(int id)
{
std::lock_guard<std::mutex> lock(m_mutexTimerUnit);
std::map<int, TimerUnitPtr>::iterator It = m_mapTimerUnits.find(id);
if (It != m_mapTimerUnits.end())
{
It->second->t->cancel();
m_mapTimerUnits.erase(It);
return;
}
}
bool CTimer::TimerisValid(int id)
{
std::lock_guard<std::mutex> lock(m_mutexTimerUnit);
std::map<int, TimerUnitPtr>::iterator It = m_mapTimerUnits.find(id);
if (It != m_mapTimerUnits.end())
{
return true;
}
return false;
}
void CTimer::Run()
{
m_ioService.run();
}
void CTimer::TimerProcess(int id, bool isIntervalTimer, const boost::system::error_code& e)
{
if (e == boost::asio::error::operation_aborted)
{
return;
}
TimerUnitPtr pTimerUnit;
{
std::lock_guard<std::mutex> lock(m_mutexTimerUnit);
std::map<int, TimerUnitPtr>::iterator It = m_mapTimerUnits.find(id);
if (It != m_mapTimerUnits.end())
{
pTimerUnit = It->second;
if (!isIntervalTimer)
{
m_mapTimerUnits.erase(It);
}
}
//LOG_INFO << "=========>mapTimerUnits size " << m_mapTimerUnits.size() << std::endl;
}
if (pTimerUnit)
{
pTimerUnit->fun();
if (isIntervalTimer)
{
pTimerUnit->t->expires_at(pTimerUnit->t->expires_at() + std::chrono::seconds(pTimerUnit->seconds));
pTimerUnit->t->async_wait(boost::bind(&CTimer::TimerProcess, this, id,true, boost::asio::placeholders::error));
}
}
else
{
//LOG_INFO << "TimerUnit pointer is NULL" << std::endl;
}
}
| true |
d86c3b205370df09894fdae12648a88b44f5e1e5 | C++ | fg123/sea | /src/ASTPrinter.h | UTF-8 | 5,678 | 2.84375 | 3 | [] | no_license | #pragma once
#include "ASTVisitor.h"
#include "CompilationContext.h"
#include <ostream>
class ASTPrinter : public ASTVisitor {
size_t depth = 0;
std::ostream& out;
public:
virtual void PreVisitChildren() override {
depth += 1;
}
virtual void PostVisitChildren() override {
depth -= 1;
}
void PrintIndentation() {
if (depth > 0) {
for (size_t i = 0 ; i < depth - 1; i++) {
out << "| ";
}
out << "`-";
}
}
ASTPrinter(std::ostream& output) : out(output) { }
virtual bool PreVisit(CompilationUnit* base) override {
PrintIndentation();
out << "Compilation unit in file " << base->fileName << std::endl;
PrintIndentation();
for (auto& import : base->imports) {
out << "Import: " << import.import << std::endl;
}
return true;
}
virtual bool PreVisit(ClassDeclaration* base) override {
PrintIndentation();
out << "Class Declaration: " << base->id << std::endl;
depth++;
PrintIndentation();
out << (base->isPublic ? "PUBLIC" : "") << std::endl;
// if (base->extendsType.has_value()) {
// PrintIndentation();
// out << "Extends: " << (*base->extendsType).ToString() << std::endl;
// }
// for (auto& implement : base->implementsInterfaces) {
// PrintIndentation();
// out << "Implements: " << implement.ToString() << std::endl;
// }
depth--;
return true;
}
virtual bool PreVisit(InterfaceDeclaration* base) override {
PrintIndentation();
out << "Interface Declaration: " << base->id << std::endl;
depth++;
PrintIndentation();
out << (base->isPublic ? "PUBLIC" : "") << std::endl;
// for (auto& implement : base->extendsInterfaces) {
// PrintIndentation();
// out << "Extends: " << implement.ToString() << std::endl;
// }
depth--;
return true;
}
virtual bool PreVisit(FunctionDeclaration* base) override {
PrintIndentation();
out << "Function Declaration: " << base->id << std::endl;
depth++;
PrintIndentation();
out << (base->isPublic ? "PUBLIC" : "") << std::endl;
// for (auto& implement : base->extendsInterfaces) {
// PrintIndentation();
// out << "Extends: " << implement.ToString() << std::endl;
// }
depth--;
return true;
}
virtual bool PreVisit(LiteralExpression*) {
PrintIndentation();
out << "LiteralExpression" << std::endl;
return true;
}
virtual bool PreVisit(BinaryExpression*) {
PrintIndentation();
out << "BinaryExpression" << std::endl;
return true;
}
virtual bool PreVisit(BinaryTypeExpression*) {
PrintIndentation();
out << "BinaryTypeExpression" << std::endl;
return true;
}
virtual bool PreVisit(UnaryExpression*) {
PrintIndentation();
out << "UnaryExpression" << std::endl;
return true;
}
virtual bool PreVisit(IfExpression*) {
PrintIndentation();
out << "IfExpression" << std::endl;
return true;
}
virtual bool PreVisit(WhenExpression*) {
PrintIndentation();
out << "WhenExpression" << std::endl;
return true;
}
virtual bool PreVisit(InfixCallExpression*) {
PrintIndentation();
out << "InfixCallExpression" << std::endl;
return true;
}
virtual bool PreVisit(TryExpression*) {
PrintIndentation();
out << "TryExpression" << std::endl;
return true;
}
virtual bool PreVisit(ThisExpression*) {
PrintIndentation();
out << "ThisExpression" << std::endl;
return true;
}
virtual bool PreVisit(SuperExpression*) {
PrintIndentation();
out << "SuperExpression" << std::endl;
return true;
}
virtual bool PreVisit(NameExpression*) {
PrintIndentation();
out << "NameExpression" << std::endl;
return true;
}
virtual bool PreVisit(CallExpression*) {
PrintIndentation();
out << "CallExpression" << std::endl;
return true;
}
virtual bool PreVisit(NavigationExpression*) {
PrintIndentation();
out << "NavigationExpression" << std::endl;
return true;
}
virtual bool PreVisit(WhileStatement*) {
PrintIndentation();
out << "WhileStatement" << std::endl;
return true;
}
virtual bool PreVisit(ReturnStatement*) {
PrintIndentation();
out << "ReturnStatement" << std::endl;
return true;
}
virtual bool PreVisit(ForStatement*) {
PrintIndentation();
out << "ForStatement" << std::endl;
return true;
}
virtual bool PreVisit(BlockStatement*) {
PrintIndentation();
out << "BlockStatement" << std::endl;
return true;
}
virtual bool PreVisit(LocalVariableDeclarationStatement*) {
PrintIndentation();
out << "LocalVariableDeclarationStatement" << std::endl;
return true;
}
virtual bool PreVisit(ExpressionStatement*) {
PrintIndentation();
out << "ExpressionStatement" << std::endl;
return true;
}
}; | true |
380aa2bb13803ff73e9355d7b8d336d40f425e42 | C++ | linnitel/cpp_pool | /day04/ex03/AMateria.hpp | UTF-8 | 572 | 2.953125 | 3 | [] | no_license |
#ifndef AMATERIA_HPP
# define AMATERIA_HPP
# include <iostream>
class ICharacter;
# include "ICharacter.hpp"
# define XP_ICR 10
class AMateria {
private:
std::string const _type;
unsigned int _xp;
AMateria();
public:
AMateria(std::string const & type);
AMateria(AMateria const & materia);
virtual ~AMateria();
void operator=(const AMateria &AM);
std::string const & getType() const; //Returns the materia type
unsigned int getXP() const; //Returns the Materia's XP
virtual AMateria* clone() const = 0;
virtual void use(ICharacter& target);
};
#endif
| true |
9388a381d167bafec53169d2b5c1633e47dde71f | C++ | oudream/leetcode | /algorithms/cpp/6.zigzag_conversion.cpp | UTF-8 | 2,514 | 3.203125 | 3 | [] | no_license | #include "global.h"
using namespace std;
class SolutionLeetcode {
public:
string convert(string s, int nRows)
{
if (nRows == 1) return s;
vector<string> rows(min(nRows, int(s.size())));
int curRow = 0;
bool goingDown = false;
for (char c : s)
{
rows[curRow] += c;
if (curRow == 0 || curRow == nRows - 1) goingDown = !goingDown;
curRow += goingDown ? 1 : -1;
}
string ret;
for (string row : rows) ret += row;
return ret;
}
};
class SolutionLeetcode2 {
public:
// 按照与逐行读取 Z 字形图案相同的顺序访问字符串。
string convert(string s, int nRows)
{
if (nRows == 1) return s;
string ret;
int n = s.size();
int cycleLen = 2 * nRows - 2;
for (int i = 0; i < nRows; i++)
{
for (int j = 0; j + i < n; j += cycleLen)
{
ret += s[j + i];
if (i != 0 && i != nRows - 1 && j + cycleLen - i < n)
ret += s[j + cycleLen - i];
}
}
return ret;
}
};
class Solution {
public:
string convert(string s, int numRows)
{
if (numRows == 1) return s;
string ret;
int n = s.size();
int iCycleLen = 2 * numRows - 2;
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j + i < n; j += iCycleLen)
{
// rowBegin rowEnd rowMid.First
ret += s[j + i];
if (i != 0 && i != numRows - 1 && j + iCycleLen - i < n)
// rowMid.Second
ret += s[j + iCycleLen - i];
}
}
return ret;
}
};
int zigzag_conversion1(int argc, const char *argv[])
{
int nums[] = {2, 7, 11, 15};
int target = 9;
// Leetcode
SolutionLeetcode solutionLeetcode;
string r = solutionLeetcode.convert("PAYPALISHIRING", 3);
fn_print(fn_format("Leetcode.convert.return=%s !", r.c_str()));
// Leetcode
SolutionLeetcode2 solutionLeetcode2;
string r2 = solutionLeetcode2.convert("PAYPALISHIRING", 3);
fn_print(fn_format("Leetcode2.convert.return=%s !", r.c_str()));
// oudream
Solution solution;
string r3 = solution.convert("PAYPALISHIRING", 3);
fn_print(fn_format("oudream.convert.return=%s !", r3.c_str()));
return TRUE;
}
int fn_zigzag_conversion1 = fn_add_case("convert1", zigzag_conversion1);
| true |
2dc8d03ef042b1cecfc4cc6371b4b991f29dadfb | C++ | shubhanshusv/ALGORITHMS | /Dynamic Programming/longest_increasing_subsequence.cpp | UTF-8 | 1,264 | 3.59375 | 4 | [] | no_license | // Shubhanshu Verma
// Dynamic Programming
// Longest Increasing Subsequence
// For an array of n elements, let L(i) be the length of the LIS ending at index i such that arr[i] is the last element of the LIS.
// Then, L(i) can be recursively written as:
// L(i) = 1 + max( L(j) ) where 0 < j < i and arr[j] < arr[i]; or
// L(i) = 1, if no such j exists.
// max(L(i)) is the required answer
// Practise : https://www.hackerrank.com/challenges/longest-increasing-subsequent
#include <iostream>
#include <bits/stdc++.h>
#include <cmath>
#include <cstdio>
using namespace std;
long int longest_increasing_subsequence(long int a[], long int n);
int main(){
long int array[10] = {34,45,11,35,64,54,52,88,59,79};
long int x = longest_increasing_subsequence(a, 10);
cout << "Length of longest increasing subsequence is : " << x;
return 0;
}
long int longest_increasing_subsequence(long int a[], long int n){
long int l[n];
long int i,j;
long int max = 1;
for(i=0;i<n;i++){
l[i] = 1;
}
for(i=1;i<n;i++){
for(j=0;j<i;j++){
if(a[i] > a[j] && l[i] < l[j]+1){
l[i] = l[j] + 1;
}
}
}
for(i=0;i<n;i++){
if(max < l[i]){
max = l[i];
}
}
return max;
} | true |
28a410d186be6cf589398eda6c4447fa8b10a72d | C++ | TudorPavaluca7/Faculty | /Licenta/Semester 2/OOP/pet gui/Dog.h | UTF-8 | 868 | 3.09375 | 3 | [] | no_license | #pragma once
#include <iostream>
class Dog
{
private:
std::string breed;
std::string name;
int age;
int weight;
std::string source;
public:
Dog();
// constructor with parameters
Dog(const std::string& breed, const std::string& name,int age,const std::string& source,int weight);
std::string getBreed() const { return breed; }
std::string getName() const { return name; }
int getAge() const { return age; }
int getWeight() const { return weight; }
void setBreed(std::string breed);
void setAge(int varsta);
void setName(std::string name);
void setSource(std::string name);
void setWeight(int weight);
std::string getSource() const { return source; }
bool operator<(int value);
void show();
friend std::istream& operator>>(std::istream& is, Dog& d);
friend std::ostream& operator<<(std::ostream& os, const Dog& d);
std::string toString();
}; | true |
e3aace7e5945dfcdd198f60ff1f94b2633769e0b | C++ | hcthanhhh/UCC | /UCC_base/src/CColdFusionCounter.h | UTF-8 | 1,449 | 2.609375 | 3 | [
"Zlib",
"BSL-1.0",
"MIT"
] | permissive | //! Code counter class definition for the ColdFusion language.
/*!
* \file CColdFusionCounter.h
*
* This file contains the code counter class definition for the ColdFusion language.
*/
#ifndef CColdFusionCounter_h
#define CColdFusionCounter_h
#include "CTagCounter.h"
//! ColdFusion code counter class.
/*!
* \class CColdFusionCounter
*
* Defines the ColdFusion code counter class.
*/
class CColdFusionCounter : public CTagCounter
{
public:
CColdFusionCounter();
protected:
virtual int PreCountProcess(filemap* fmap);
int ParseFunctionName(const string &line, string &lastline, filemap &functionStack, string &functionName,
unsigned int &functionCount);
private:
// This class is NOT copied or assigned to.
// Avoid copying of this class. Avoid assignment of this class.
// Compiler will give an Error if a copy or assignment is done and those Errors do NOT happen.
// This avoids a VC++ -W4 or -Wall warning C4625, C4626
// Take care of warning C4625: 'CColdFusionCounter' : copy constructor could not be generated because a base class copy constructor is inaccessible
CColdFusionCounter(const CColdFusionCounter& rhs); // Declare without implementation
// Take care of warning C4626: 'CColdFusionCounter' : assignment operator could not be generated because a base class assignment operator is inaccessible
CColdFusionCounter operator=(const CColdFusionCounter); // Declare without implementation
};
#endif
| true |
47682f223606db24b14b81c1ee5887085250fc7a | C++ | Santirax/competitive-solutions | /UVa_online_judge/armyBuddies_(with_SET).cpp | UTF-8 | 2,032 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <set>
using namespace std;
int main ()
{
long long int S, B;
long long izq, der;
while (cin>>S && cin>>B && S != 0 && B != 0) {
set<int>conjunto; //declaracion del set, donde estan los soldados
for(int i=1; i<=S; i++){
conjunto.insert(i);
//cout<<i<<" ";
}
//it_i -> atacar izquierda
//it_d -> atacar derecha
for(int x = 1; x<=B; x++)
{
cin>>izq>>der;
set<int>::iterator it_i=conjunto.find(izq), it_d = conjunto.find(der);
set<int>::iterator aux_it_i = it_i, aux_it_d = it_d;
//cout<<"IT I = "<<*it_i<<endl;
//cout<<"IT D = "<<*it_d<<endl;
if(it_i == conjunto.begin())
cout<<"* ";
else
{
int impIzq = *(--it_i);
cout<<impIzq<<" ";
}
if(++it_d == conjunto.end())
cout<<"*\n";
else
{
//int impDer = *it_d;
cout<<*it_d<<"\n";
}
//cout<<"aux izq = "<<*aux_it_i<<endl;
//cout<<"aux der = "<<*aux_it_d<<endl;
int it_for = 0;
for(it_for = *aux_it_i; it_for != *aux_it_d; ++it_for){
conjunto.erase(it_for);
}
conjunto.erase(it_for);
/*cout<<"Tamaño del set = "<<conjunto.size()<<endl;
cout<<"Elementos del set: \n";
set <int>:: iterator it = conjunto.begin();
while (it != conjunto.end()) {
cout<<*it<<" ";
it++;
}
cout<<endl;*/
//for(int i = 1; i<S; i++)
//cout<<++(*conjunto)<<" ";
}
cout<<"-\n";
}//Fin del while
return 0;
}
| true |
9bbe7b1d492109fa854ede208626a2d94e9eb5aa | C++ | prateekbose/30-seconds-of-cpp | /snippets/vector/accumulate.cpp | UTF-8 | 230 | 2.75 | 3 | [
"MIT"
] | permissive | #include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int main(){
vector<int> num;
num.push_back(10);
num.push_back(15);
num.push_back(20);
cout << accumulate(num.begin(),num.end(),0);
}
| true |
02110361aa6ba98636265d2c14f72dd6634ff14c | C++ | gvenet/CPP | /Module_04/ex01/srcs/AWeapon.cpp | UTF-8 | 985 | 3.1875 | 3 | [] | no_license | #include "../inc/AWeapon.hpp"
//=================================COPLIAN================================================================
AWeapon::AWeapon(std::string const &name, int apcost, int damage) : _name(name), _apcost(apcost), _damage(damage)
{
std::cout << _name << "\t | apcost : " << _apcost << " | damage : " << _damage << std::endl;
}
AWeapon::AWeapon(AWeapon const &cpy) : _name(cpy._name), _apcost(cpy._apcost), _damage(cpy._damage)
{
std::cout << _name << "\t | apcost : " << _apcost << " | damage : " << _damage << std::endl;
}
AWeapon &AWeapon::operator=(AWeapon const &op)
{
_name = op._name;
_apcost = op._apcost;
_damage = op._damage;
return *this;
}
AWeapon::~AWeapon()
{
}
//==========================================GETTERS=======================================================
std::string const &AWeapon::getName() const
{
return _name;
}
int AWeapon::getAPCost() const
{
return _apcost;
}
int AWeapon::getDamage() const
{
return _damage;
}
| true |
3bf4b10d4cbda479044b603ec5b1856806fc6338 | C++ | xinwangcas/operating-systems | /hw5/race22.cpp | UTF-8 | 2,892 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <pthread.h>
#include <iomanip>
#include <stdlib.h>
#include <fstream>
using namespace std;
pthread_mutex_t mutex;
int main(int argc, char* argv[])
{
int n = 1000;//the initial amount ot bank account
int errno_create1, errno_create2, errno_create3;//error message of creating threads
int errno_join1, errno_join2, errno_join3;//error message of waiting for threads
const char filename[] = "bankaccount.txt";//the bank account file
ofstream o_file;
// ifstream i_file;
o_file.open(filename);//open and write amount to bank account file
o_file << n << endl;
o_file.close();//close the file after writing
pthread_attr_t attr;//attributes
pthread_attr_init(&attr);//initializing attributes
// pthread_attr_init(&attr2);
// pthread_attr_init(&attr3);
pthread_t thread1, thread2, thread3;// define three threads
int ret1, ret2, ret3; //return values of three threads
// void *thread1_func(void *);
// void *thread2_func(void *);
// void *thread3_func(void *);
void *thief(void *);
errno_create1 = pthread_create(&thread1, &attr, thief, NULL);//create thread1
if (errno_create1 != 0)
{
cout << "Creation of thread1 is unsuccessful." << endl;
}
errno_create2 = pthread_create(&thread2, &attr, thief, NULL);//create thread2
if (errno_create2 != 0)
{
cout << "Creation of thread2 is unsuccessful." << endl;
}
errno_create3 = pthread_create(&thread3, &attr, thief, NULL);//create thread3
if (errno_create3 != 0)
{
cout << "Creation of thread3 is unsuccessful." << endl;
}
errno_join1 = pthread_join(thread1, NULL);//wait for thread1
if (errno_join1 != 0)
{
cout << "Join of thread1 fails." << endl;
}
errno_join2 = pthread_join(thread2, NULL);//wait for thread2
if (errno_join2 != 0)
{
cout << "Join of thread2 fails." << endl;
}
errno_join3 = pthread_join(thread3, NULL);//wait for thread3
if (errno_join3 != 0)
{
cout << "Join of thread3 fails." << endl;
}
return 0;
}
void* thief (void *)//thief function which is operated by all three threads
{
int n = 0;//initialize own account to 0
int sum ;//sum of bank account
int total = 0;//threads' own balance
ifstream infile;
ofstream outfile;
while(1)
{
pthread_mutex_lock(&mutex);
infile.open("bankaccount.txt");//open the bank account
if (!infile.is_open())
{
cout << "Error opening file." << endl;
exit(1);
}
infile >> sum;//read the amount from bank account
infile.close();
if (sum > 0)//when the amount is larger than $1, steal one half to its own account
{
total = total + sum/2 + 1;
sum = sum - sum/2 - 1;
outfile.open("bankaccount.txt");
outfile << sum << endl;
outfile.close();
}
else
{
pthread_mutex_unlock(&mutex);
break;
}
pthread_mutex_unlock(&mutex);
}
n = total;
cout << "thread ID: " << pthread_self() << ". Total amount that have stolen:" << n << endl;
pthread_exit(NULL);
}
| true |
cd0ed670bfc4a9b021588ecb0e410e633ca2c18f | C++ | AlexeyKulbitsky/Shadow | /engine/source/video/VertexDeclaration.h | UTF-8 | 2,687 | 2.765625 | 3 | [] | no_license | #ifndef SHADOW_VERTEX_DECLARATION_INCLUDE
#define SHADOW_VERTEX_DECLARATION_INCLUDE
#include "../Globals.h"
namespace sh
{
namespace video
{
struct SHADOW_API Attribute
{
Attribute()
: semantic(AttributeSemantic::POSITION)
, type(AttributeType::FLOAT)
, componentsCount(3)
{}
Attribute(AttributeSemantic _semantic, AttributeType _type, size_t _componentsCount)
: semantic(_semantic)
, type(_type)
, componentsCount(_componentsCount)
{}
AttributeSemantic semantic;
AttributeType type;
// Attribute offset (in bytes)
size_t offset;
size_t componentsCount;
};
class SHADOW_API VertexDeclaration
{
public:
VertexDeclaration() {}
VertexDeclaration(const VertexDeclaration& other)
: m_attributes(other.m_attributes)
, m_stride(other.m_stride)
{
}
void AddAttribute(Attribute& attribute)
{
attribute.offset = CalculateAttributeOffset(attribute);
m_attributes.push_back(attribute);
m_stride += static_cast<size_t>(attribute.type) * attribute.componentsCount;
}
Attribute* GetAttribute(AttributeSemantic sematic)
{
for (size_t i = 0, sz = m_attributes.size(); i < sz; ++i)
{
if (m_attributes[i].semantic == sematic)
return &m_attributes[i];
}
return nullptr;
}
size_t GetStride() const { return m_stride; }
size_t GetAttributesCount() const { return m_attributes.size(); }
Attribute* GetAttribute(size_t attributeIndex) { return &m_attributes[attributeIndex]; }
VertexDeclaration& operator=(const VertexDeclaration& other)
{
m_attributes = other.m_attributes;
m_stride = other.m_stride;
return *this;
}
private:
size_t CalculateAttributeOffset(const Attribute& attribute)
{
size_t offset = 0U;
for (auto attr : m_attributes)
{
offset += static_cast<size_t>(attr.type) * attr.componentsCount;
}
return offset;
}
private:
std::vector<Attribute> m_attributes;
Attribute m_attribs[(size_t)AttributeSemantic::COUNT];
size_t m_stride = 0U;
};
struct SHADOW_API InputAttribute
{
AttributeSemantic semantic;
};
class SHADOW_API VertexInputDeclaration
{
public:
//virtual void Load(const pugi::xml_node &node){}
virtual void Init(){}
virtual VertexInputDeclarationPtr Clone() { return nullptr; }
virtual void Assemble(VertexDeclaration& declaration){}
virtual void SetShaderProgram(ShaderProgram* shaderProgram){}
virtual u32 GetAttributesCount() const { return 0U; }
virtual const InputAttribute& GetAttribute(u32 index) const = 0;
static VertexInputDeclarationPtr Create();
};
}
}
#endif // !SHADOW_VERTEX_DECLARATION_INCLUDE
| true |
ea806be1da7431f7404ef0d1b3db42741e977601 | C++ | 17342983498/zhuxu | /Code/AVLTree/23-4-30/AVLTree.h | GB18030 | 3,998 | 3.265625 | 3 | [] | no_license | #include <iostream>
using namespace std;
template<class K,class V>
struct AVTreeNode
{
AVTreeNode<K, V>* _pLeft;
AVTreeNode<K, V>* _pRight;
AVTreeNode<K, V>* _pParent;
pair<K, V> _kv;
int _bf;//ƽ
AVTreeNode(const pair<K,V> kv)
:_pLeft(nullptr), _pRight(nullptr), _pParent(nullptr)
, _kv(kv), _bf(0)
{}
};
template<class K, class V>
struct AVLtree
{
typedef AVTreeNode<K, V> Node;
public:
bool insert(const pair<K, V> kv)
{
if (_root == nullptr)
{
_root = new Node(kv);
return true;
}
Node* parent = nullptr;
Node* cur = _root;
while (cur)
{
if (cur->_kv.second < kv.second)
{
parent = cur;
cur = cur->_pRight;
}
else if (cur->_kv.second > kv.second)
{
parent = cur;
cur = cur->_pLeft;
}
else
{
return false;
}
}
//ҵҪλ
cur = new Node(kv);
if (cur->_kv.second < parent->_kv.second)
{
cur = parent->_pLeft;
}
else
{
cur = parent->_pRight;
}
//ҲҪ
cur->_pParent = parent;
//ƽ
while (parent)
{
if (cur == parent->_pLeft)
{
parent->_bf--;
}
else
{
parent->_bf++;
}
if (parent->_bf == 1 || parent->_bf == -1)
{
cur = parent;
parent = parent->_pParent;
}
else if (parent->_bf == 0)
{
break;
}
else if (parent->_bf == 2 || parent->_bf == -2)
{
//ת
if (parent->_bf == 2 && cur->_bf == 1)
{
_RotateL(parent);
}
else if (parent->_bf == -2 && cur->_bf == -1)
{
_RotateR(parent);
}
else if ()
{
}
else
{
}
break;
}
else
{
return false;
}
}
return true;
}
private:
void _RotateL(Node* pParent)
{
Node* pSubR = pParent->_pRight;
Node* pSubRL = pSubR->_pLeft;
pParent->_pRight = pSubRL;
if (pSubRL)
{
pSubRL->_pParent = pParent;
}
Node* ppParent = pParent->_pParent;
pSubR->_pLeft = pParent;
pParent->_pParent = pSubR;
if (ppParent == nullptr)
{
_root = pSubR;
pSubR->_pParent = nullptr;
}
else
{
if (ppParent->_pLeft == pParent)
{
ppParent->_pLeft = pSubR;
}
else
{
ppParent->_pRight = pSubR;
}
pSubR->_pParent = ppParent;
}
pParent->_bf = pSubR->_bf = 0;
}
void _RotateR(Node* pParent)
{
Node* pSubL = pParent->_pLeft;
Node* pSubLR = pSubL->_pRight;
pParent->_pLeft = pSubLR;
if (pSubLR)
{
pSubLR->_pParent = pParent;
}
Node* ppParent = pParent->_pParent;
pSubL->_pRight = pParent;
pParent->_pParent = pSubL;
if (ppParent == nullptr)
{
_root = pSubL;
pSubL->_pParent = nullptr;
}
else
{
if (ppParent->_pLeft == pParent)
{
ppParent->_pLeft = pSubL;
}
else
{
ppParent->_pRight = pSubL;
}
pSubL->_pParent = ppParent;
}
pParent->_bf = pSubL->_bf = 0;
}
//ҵ
void _RotateLR(Node* pParent)
{
Node* pSubL = pParent->_pLeft;
Node* pSubLR = pSubL->_pRight;
//ͨıĽڵƽô
int bf = pSubLR->_bf;
_RotateL(pSubL);
_RotateR(pParent);
if (bf == 1)
{
pParent->_bf = 0;
pSubL->_bf = -1;
pSubLR->_bf = 0;
}
else if (bf == -1)
{
pParent->_bf = 1;
pSubL->_bf = 0;
pSubLR->_bf = 0;
}
else if (bf == 0)
{
pParent->_bf = 0;
pSubL->_bf = 0;
pSubLR->_bf = 0;
}
else
{
assert(false);
}
}
//ҵ
void _RotateRL(Node* pParent)
{
Node* pSubR = pParent->_pRight;
Node* pSubRL = pSubR->_pLeft;
//ͨıĽڵƽô
int bf = pSubRL->_bf;
_RotateR(pSubR);
_RotateL(pParent);
if (bf == 1)
{
pParent->_bf = -1;
pSubR->_bf = 0;
pSubRL->_bf = 0;
}
else if (bf == -1)
{
pParent->_bf = 0;
pSubR->_bf = 1;
pSubRL->_bf = 0;
}
else if (bf == 0)
{
pParent->_bf = 0;
pSubR->_bf = 0;
pSubRL->_bf = 0;
}
else
{
assert(false);
}
}
private:
Node* _root = nullptr;
}; | true |
2a17efcbbfd0917a16491ddeffedd4b8ae0d2119 | C++ | Dwillnio/GameOfLife | /rule.h | UTF-8 | 530 | 2.953125 | 3 | [] | no_license | #ifndef RULE_H
#define RULE_H
#include <vector>
class rule
{
public:
virtual int calculate(const std::vector<int>& neighbours) = 0;
};
class rule_classic : public rule
{
public:
virtual int calculate(const std::vector<int>& neighbours);
};
class rule_lifelike : public rule
{
public:
rule_lifelike(std::vector<int> stay_, std::vector<int> born_) : rule(), stay(stay_), born(born_) {}
virtual int calculate(const std::vector<int>& neighbours);
private:
std::vector<int> stay, born;
};
#endif // RULE_H
| true |
a1ed5b3ed301d051d08e2cbb8d2f03dd15914d8e | C++ | magicrex/personal | /sort/httpserver/httpserver.cpp | UTF-8 | 14,292 | 2.765625 | 3 | [] | no_license | #include"httpserver.h"
#include"util.hpp"
namespace httpserver{
//将打印请求进行声明
void PrintRequest(const Context* context);
//解析请求的第一行,即方法和url
//主要是进行字符串的分割
int Parseline(std::string first_line,std::string* method,std::string* url){
std::vector<std::string> output;
common::StringUtil::Split(first_line," ",&output);
if(output.size()!=3){
LOG(ERROR)<<" first line loss";
return -1;
}
*method=output[0];
*url=common::UrlUtil::deescapeURL(output[1]);
return 1;
}
//解析请求的第一行的url部分,即目标文件和参数
//主要是字符串的分割
int Parseurl(const std::string url,std::string* url_argu,std::string* url_path){
int pos=url.find('?');
if(pos==0){
return -1;
}
(*url_path).assign(url,0,pos);
(*url_argu).assign(url,pos+1,url.size()-pos);
return 1;
}
//解析请求的第二部分通用首部
//主要是按行读取并使用冒号分割,并缓存到一个map数据结构中
int ParseHeadler(const std::string Headler_line , httpserver::Headlers* headler){
size_t pos=Headler_line.find(':');
if(pos==std::string::npos){
LOG(ERROR)<< " Headlers error";
return -1;
}
if(pos+2>=Headler_line.size()){
LOG(ERROR)<< " Headlers error";
return -1;
}
(*headler)[Headler_line.substr(0,pos)]
= Headler_line.substr(pos+2);
return 1;
}
//读取请求并解析
//是线程的第一步,进行读取请求,为后面处理作准备
int http_server::readrequest(Context* context)
{
Request* req=&context->request;
std::string first_line;
int ret =0;
ret=common::FileUtil::Readline(context->socket_fd,&first_line);
if(ret<0){
LOG(ERROR)<<"requset Readline error";
return -1;
}
ret = httpserver::Parseline(first_line,&req->method,&req->url);
if(ret<0)
{
LOG(INFO)<<"request Parseline error";
return -1;
}
ret=httpserver::Parseurl(req->url,&req->url_argu,&req->url_path);
if(ret<0){
LOG(INFO)<<"request Parseurl error";
return -1;
}
std::string headler_line;
while(1){
ret=common::FileUtil::Readline(context->socket_fd,&headler_line);
if(headler_line.empty()){
break;
}
ret=httpserver::ParseHeadler(headler_line,&req->headler);
if(ret<0){
LOG(ERROR)<<"ParseHeadler error";
return -1;
}
}
//分为get、post和其他类型
//get方法不需要读取主体,post读取主体,其他方法即位错误
if(req->method=="GET")
{
return 1;
}
else if(req->method=="POST")
{
//先读取长度,为后面读取内容做准备
//读取文件类型,根据类型判断是读到一个string或者缓存文件中
int contlen;
httpserver::Headlers::iterator it;
it =req->headler.find("Content-Length");
if(it!=req->headler.end()){
int n=std::stoi((*it).second);
contlen=n;
}else{
LOG(ERROR)<<" request error";
return -1;
}
it =req->headler.find("Content-Type");
if(it!=req->headler.end()){
std::vector<std::string> type;
common::StringUtil::Split(req->headler["Content-Type"],";",&type);
if(type.empty()){
LOG(ERROR)<<" request error";
return -1;
}else{
if(type[0]=="application/x-www-form-urlencoded"){
ret=common::FileUtil::ReadN(context->socket_fd,contlen,&req->body);
return 1;
}else if(type[0]=="multipart/form-data"){
//将内容读入一个缓存文件中,以sessid作为缓存文件名
it=req->headler.find("Cookie");
if(it!=req->headler.end()){
std::vector<std::string> cookie;
common::StringUtil::Split(req->headler["Cookie"],"=",&cookie);
common::FileUtil::ReadNFile(context->socket_fd,contlen,cookie[1]);
return 1;
}else{
LOG(ERROR)<<" request error";
return -1;
}
}else{
LOG(ERROR)<<" request error";
return -1;
}
}
}else{
LOG(ERROR)<<" request error"<<"\n";
return -1;
}
}else if(req->method=="DELETE"){
return 1;
}else
{
return -1;
}
return 1;
}//end readrequest
//线程处理的第三步,构造响应报文返回给浏览器
int http_server::writeresponse(Context* context)
{
const Response* resp=&context->response;
std::stringstream ss;
ss << "HTTP/1.1 " << resp->state << " "<<resp->message <<"\n";
if(resp->cgi_resp==""){
for(auto item : resp->headler){
ss<< item.first <<": " <<item.second<<"\n";
}
ss<<"\n";
ss<<resp->body;
}else{
ss<<resp->cgi_resp;
}
const std::string& str=ss.str();
write(context->socket_fd,str.c_str(),str.size());
return 1;
}
//构造绝对路径,将网络的路径参数构造成一个服务器绝对路径
//主要是默认文件的路径和一般文件的路径
void http_server::GetFilePath(std::string url_path,std::string* file_path){
*file_path="../wwwroot"+url_path;
if(common::FileUtil::IsDir(file_path->c_str())){
if(file_path->back()!='/'){
file_path->push_back('/');
}
*file_path=(*file_path)+"index.html";
}
}
//判断GET方法的处理
//判断文件是否存在,或是否可执行
int http_server::ProcessStaticFile(Context* context){
const Request* req=&context->request;
Response* resp=&context->response;
std::string file_path;
GetFilePath(req->url_path,&file_path);
if((access(file_path.c_str(),F_OK))!=-1){
if((access(file_path.c_str(),X_OK))!=-1){
ProcessCGI(context);
return 1;
}else{
int ret=common::FileUtil::ReadAll(file_path,&resp->body);
return 1;
}
}else{
return -1;
}
}
//请求的动态处理
int http_server::ProcessCGI(Context* context){
//1.如果是POST请求,父进程就要把body写入到管道中
// 阻塞式对去管道,尝试把子进程的结果读取出来,并放到Respponse中
// 对子进程进行进程等待
//2.fork,子进程流程
// 把标准输入输出进行重定向
//先获取到要替换的可执行文件
//由CGI可执行程序完成动态页面的计算,并且写回数据到管道
//先创建一对匿名管道全双工通信
const Request& req = context->request;
Response* resp=&context->response;
int fd1[2],fd2[2];
pipe(fd1);
pipe(fd2);
int father_write = fd1[1];
int father_read = fd2[0];
int child_write = fd2[1];
int child_read = fd1[0];
//GET 方法 QUERY_STRING 请求的参数
//POST 请求 CONTENT_LENGTH 长度
//fork 父子进程流程不同
pid_t ret=fork();
if(ret<0){
perror("fork");
goto END;
}else if(ret > 0){
//父进程
//父进程负责将post的body写入管道1
//将最后终结果从管2读出到response中
close(child_read);
close(child_write);
if(req.method=="POST"){
write(father_write,req.body.c_str(),req.body.size());
}
common::FileUtil::ReadAll(father_read,&resp->cgi_resp);
wait(NULL);
}else{
//子进程
//设置环境变量 METHOD请求方法
std::string env1="REQUEST_METHOD="+req.method;
std::string env2;
if(req.method=="GET"){
std::string file_path;
GetFilePath(req.url_path,&file_path);
if((access(file_path.c_str(),F_OK))!=-1){
if((access(file_path.c_str(),X_OK))==-1){
process404(context);
}
}else{
process404(context);
}
env2="QUERY_STRING="+req.url_argu;
char * const envp[] = {const_cast<char*>(env1.c_str()),const_cast<char*>(env2.c_str()), NULL};
close(father_read);
close(father_write);
dup2(child_read,0);
dup2(child_write,1);
if((execle(file_path.c_str(),file_path.c_str(),NULL,envp))==-1){
LOG(ERROR)<<"file_path:";
LOG(ERROR)<<"execle error";
}
}else{
LOG(INFO)<<"request error";
process404(context);
}
}
END:
close(father_read);
close(father_write);
close(child_read);
close(child_write);
if(ret<0)
return -1;
else
return 1;
}//end ProcessCGI
//线程的第二步,请求处理
//主要是进行判断,具体处理由cgi进行
int http_server::Handlerrequest(Context* context)
{
const Request* req=&context->request;
Response* resp=&context->response;
resp->state=200;
resp->message="OK";
if(req->method=="GET"){
return ProcessStaticFile(context);
}else if(req->method=="POST"){
return ProcessCGI(context);
}else if(req->method=="DELETE"){
return ProcessCGI(context);
}else{
LOG(ERROR)<<"Unsupport Method"<< req->method <<"\n";
return -1;
}
return 1;
}
//构造一个404页面,所有错误均使用404
void http_server::process404(Context* context)
{
Response* resp=&context->response;
resp->state=404;
resp->message="Not Found";
resp->body="<html><head><meta charset=\"utf8\"><title>NotFound</title></head><body><h1>页面出错</h1></body></html>";
std::stringstream ss;
ss << resp->body.size();
std::string size;
ss >> size;
resp->headler["Content-Length"]=size;
}
//打印请求方便记录
//并不打印body部分
void http_server::PrintRequest(const Context* context){
const Request* req=&context->request;
std::cout<<"HTTP1.1 "<<req->method<<" "<<req->url<<std::endl;
Headlers::const_iterator it=req->headler.begin();
for(;it!=req->headler.end();it++){
std::cout<<(*it).first<<": "<<(*it).second<<std::endl;
}
std::cout<<std::endl;
std::cout<<"body "<<std::endl;
std::cout<<req->body<<std::endl;
}
//线程入口函数,每个线程的主要逻辑
//分为读取、处理、返回三步
int threadcount=1;
void* http_server::ThreadEntry(void* con)
{
threadcount++;
Context* context =reinterpret_cast<Context*>(con);
int ret=context->service->readrequest(context);
if(ret<0)
{
context->service->process404(context);
goto END;
}
context->service->PrintRequest(context);
ret=context->service->Handlerrequest(context);
if(ret<0)
{
context->service->process404(context);
goto END;
}
END:
context->service->writeresponse(context);
delete context;
close(context->socket_fd);
return 0;
}
//整个服务器的主要流程
//将服务器启动,绑定端口并集进行监听
//使用多线程提高服务器的并发
int http_server::start(int argc,char* argv[])
{
if(argc!=3)
{
std::cout<<"user IP Port"<<std::endl;
return -1;
}
int sockt_fd=socket(AF_INET,SOCK_STREAM,0);
if(sockt_fd<0)
{
LOG(FATAL)<<"socket";
return 2;
}
//给socket加一个参数使得文件描述符重用,不至于出现大量的timw_wait
int opt=1;
setsockopt(sockt_fd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
sockaddr_in server_sock;
server_sock.sin_family=AF_INET;
server_sock.sin_port=htons(atoi(argv[2]));
server_sock.sin_addr.s_addr=inet_addr(argv[1]);
int ret=bind(sockt_fd,(sockaddr*)&server_sock,sizeof(server_sock));
if(ret<0)
{
LOG(FATAL)<<"bind";
return 3;
}
if(listen(sockt_fd,5)<0)
{
LOG(FATAL)<<"listen";
return 4;
}
while(1)
{
sockaddr_in client_addr;
socklen_t len=sizeof(client_addr);
int client_socket_fd =accept(sockt_fd,(sockaddr*)&client_addr,&len);
if(client_socket_fd<0)
{
LOG(INFO)<<"accept";
continue;
}
pthread_t tid;
Context* context=new Context();
context->addr =client_addr;
context->socket_fd=client_socket_fd;
pthread_create(&tid,NULL,ThreadEntry,reinterpret_cast<void*>(context));
pthread_detach(tid);
}
return 0;
}//end start
}//end namespace
| true |
e4a8268b1242b258231e9ffd1a019581b3f0442b | C++ | holoskii/RenderEngine | /RenderEngine.h | UTF-8 | 1,275 | 2.71875 | 3 | [] | no_license | /* Created: 29.04.2021
* Author: Makar Ivashko
* Short description: 3d rendering engine,
* projects polygons from 3d space into 2d screen
*/
#pragma once
#include "Util.h"
#include "SFML/Graphics.hpp"
class RenderEngine
{
public:
// because of OpenGL render inside window
// width and height does not have much effect on performance
int windowWidth = 1920;
int windowHeight = 1080;
sf::RenderWindow window; // widnow handle
mesh objectMesh; // object to be rendered
mat4x4 matProj; // world -> camere view projection
// vec4 vCamera = { -5, 1, 0 }; // camera location
vec4 vCamera = { -25, 1, 0 };
vec4 vLookDir; // camera direction
float fYaw = -45; // camera rotation in horizontal plane
float fTheta = 0; // object rotation
float frameTime = 0; // time between frames
int maxFrameRate = 60; // limit framerate
// create window with default size
RenderEngine();
// start render of given file
void run(const std::string& filename, const bool toRotate = false);
// render window content
void render(float fElapsedTime);
// draw triangle with SFML as 3 thin lines
void drawBlankTriange(polygon& poly);
// draw solid triangle with SFML, colored as in poly.color RGBA format
void drawColorTriange(polygon& poly);
};
| true |
eb6afd47dd5f4305b0672914496c64e247ff93b8 | C++ | kbigdelysh/FreePIE-HTCVive-Custom-Controller | /Lib/piefreespace/piefreespace.cpp | UTF-8 | 7,318 | 2.53125 | 3 | [] | no_license | /*
Author: Brant Lewis (brantlew@yahoo.com) - July 2012
piefreespace (PFS) is a proxy dll that is used to translate complex freespacelib
calls into a simple API for easy linking by the FreePIE FreeSpacePlugin. It sets up
the device connection, handles I/O reads, and converts quaternion vectors into
Euler angles. This simplifies the code in FreePIE instead of implementing and calling
a full C# libfreespace interface
It was developed against libfreespace-0.6
*/
#include "piefreespace.h"
#include <freespace/freespace.h>
#include <string.h>
#include <math.h>
#include <time.h>
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#include <stdio.h>
FreespaceDeviceId DeviceID = -1;
FreespaceDeviceInfo Device;
//----------------------------------------------------------------------------
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
//-----------------------------------------------------------------------------
int Connect() {
// Initialize the freespace library
int err = freespace_init();
if (err)
return err;
// Look for a single tracker
int num_devices;
err = freespace_getDeviceList(&DeviceID, 1, &num_devices);
if (err)
return err;
if (num_devices == 0)
return FREESPACE_ERROR_NO_DEVICE;
// Attach to the tracker
err = freespace_openDevice(DeviceID);
if (err) {
DeviceID = -1;
return err;
}
err = freespace_getDeviceInfo(DeviceID, &Device);
// Flush the message stream
err = freespace_flush(DeviceID);
if (err)
return err;
// Turn on the orientation message stream
freespace_message msg;
memset(&msg, 0, sizeof(msg));
if (Device.hVer >= 2) {
// version 2 protocol
msg.messageType = FREESPACE_MESSAGE_DATAMODECONTROLV2REQUEST;
msg.dataModeControlV2Request.packetSelect = 3; // User Frame (orientation)
msg.dataModeControlV2Request.modeAndStatus = 0; // operating mode == full motion
}
else {
// version 1 protocol
msg.messageType = FREESPACE_MESSAGE_DATAMODEREQUEST;
msg.dataModeRequest.enableUserPosition = 1;
msg.dataModeRequest.inhibitPowerManager = 1;
}
err = freespace_sendMessage(DeviceID, &msg);
if (err)
return err;
// Now the tracker is ready to read
return 0;
}
//-----------------------------------------------------------------------------
void Close() {
if (DeviceID >= 0) {
// Shut off the data stream
freespace_message msg;
memset(&msg, 0, sizeof(msg));
if (Device.hVer >= 2) {
msg.messageType = FREESPACE_MESSAGE_DATAMODECONTROLV2REQUEST;
msg.dataModeControlV2Request.packetSelect = 0; // No output
msg.dataModeControlV2Request.modeAndStatus = 1 << 1; // operating mode == sleep
}
else {
msg.messageType = FREESPACE_MESSAGE_DATAMODEREQUEST;
msg.dataModeRequest.enableUserPosition = 0;
msg.dataModeRequest.inhibitPowerManager = 0;
}
int err = freespace_sendMessage(DeviceID, &msg);
// Detach from the tracker
freespace_closeDevice(DeviceID);
DeviceID = -1;
}
freespace_exit();
}
//-----------------------------------------------------------------------------
int GetOrientation(float* yaw, float* pitch, float* roll) {
int duration = 0;
int timeout = 250; // 1/4 second max time in this function
long start = clock();
freespace_message msg;
while (duration < timeout) {
int err = freespace_readMessage(DeviceID, &msg, timeout - duration);
if (err == 0) {
// Check if this is a user frame message.
if (msg.messageType == FREESPACE_MESSAGE_USERFRAME) {
// Convert from quaternion to Euler angles
// Get the quaternion vector
float w = msg.userFrame.angularPosA;
float x = msg.userFrame.angularPosB;
float y = msg.userFrame.angularPosC;
float z = msg.userFrame.angularPosD;
// normalize the vector
float len = sqrtf((w*w) + (x*x) + (y*y) + (z*z));
w /= len;
x /= len;
y /= len;
z /= len;
// The Freespace quaternion gives the rotation in terms of
// rotating the world around the object. We take the conjugate to
// get the rotation in the object's reference frame.
w = w;
x = -x;
y = -y;
z = -z;
// Convert to angles in radians
float m11 = (2.0f * w * w) + (2.0f * x * x) - 1.0f;
float m12 = (2.0f * x * y) + (2.0f * w * z);
float m13 = (2.0f * x * z) - (2.0f * w * y);
float m23 = (2.0f * y * z) + (2.0f * w * x);
float m33 = (2.0f * w * w) + (2.0f * z * z) - 1.0f;
*roll = atan2f(m23, m33);
*pitch = asinf(-m13);
*yaw = atan2f(m12, m11);
return 0;
}
// any other message types will just fall through and keep looping until the timeout is reached
}
else
return err; // return on timeouts or serious errors
duration += clock() - start;
}
return FREESPACE_ERROR_TIMEOUT; // The function returns gracefully without values
}
//-----------------------------------------------------------------------------
int PFS_Connect() {
int err = Connect();
if (err)
Close(); // Shutdown on error
return err;
}
//-----------------------------------------------------------------------------
void PFS_Close() {
Close();
}
//-----------------------------------------------------------------------------
int PFS_GetOrientation(float* yaw, float* pitch, float* roll) {
int err = GetOrientation(yaw, pitch, roll);
if (err && (err != FREESPACE_ERROR_TIMEOUT))
Close(); // Shutdown on true error
return err;
}
//-----------------------------------------------------------------------------
#ifndef _USRDLL
// This section is strictly for development and testing as an EXE and is not
// compiled as part of the dll
#include <conio.h>
#define PI 3.141592654
#define RADIANS_TO_DEGREES(rad) ((float) rad * (float) (180.0 / PI))
int main(int argc, char* argv[]) {
int err = PFS_Connect();
if (err)
printf("Connect errored with %d", err);
else {
float yaw, pitch, roll;
while (!err && !_kbhit()) {
err = PFS_GetOrientation(&yaw, &pitch, &roll);
if (err) {
if (err == FREESPACE_ERROR_TIMEOUT) {
printf("wait timeout\n");
err = 0; // not a real error so keep looping
}
}
else {
yaw = RADIANS_TO_DEGREES(yaw);
pitch = RADIANS_TO_DEGREES(pitch);
roll = RADIANS_TO_DEGREES(roll);
printf("yaw=%g, pitch=%g, roll=%g\n", yaw, pitch, roll);
//Sleep(0);
}
}
if (err)
printf("Read errored with %d", err);
PFS_Close();
}
}
#endif
| true |
db3188a16cda0b177f66ed2ea7789a39faab9763 | C++ | alvin-me/MIVT | /tgt/progressbar.cpp | UTF-8 | 2,267 | 2.71875 | 3 | [] | no_license | #include "progressbar.h"
#include "logmanager.h"
#include "tgt_string.h"
namespace tgt {
std::string ProgressBar::loggerCat_ = "ProgressBar";
ProgressBar::ProgressBar(ProgressCallback callback)
: progress_(0)
, progressRange_(0.f, 1.f)
, printedErrorMessage_(false)
, callback_(callback)
{}
void ProgressBar::setProgress(float progress) {
if (!(progressRange_.x <= progressRange_.y && progressRange_.x >= 0.f && progressRange_.y <= 1.f)) {
LERROR("invalid progress range");
}
if (progress < 0.f) {
if (!printedErrorMessage_)
LWARNING("progress value " << progress << " out of valid range [0,1]");
printedErrorMessage_ = true;
progress = 0.f;
}
else if (progress > 1.f) {
if (!printedErrorMessage_)
LWARNING("progress value " << progress << " out of valid range [0,1]");
printedErrorMessage_ = true;
progress = 1.f;
}
else {
printedErrorMessage_ = false;
}
progress_ = progressRange_.x + progress*(progressRange_.y - progressRange_.x);
update();
}
float ProgressBar::getProgress() const {
return progress_;
}
void ProgressBar::setProgressMessage(const std::string& message) {
message_ = message;
update();
}
std::string ProgressBar::getProgressMessage() const {
return message_;
}
std::string ProgressBar::getMessage() const {
return message_;
}
void ProgressBar::setTitle(const std::string& title) {
title_ = title;
}
std::string ProgressBar::getTitle() const {
return title_;
}
void ProgressBar::setProgressRange(const glm::vec2& progressRange) {
if (!(progressRange.x <= progressRange.y && progressRange.x >= 0.f && progressRange.y <= 1.f)) {
LERROR("invalid progress range");
}
progressRange_ = progressRange;
}
glm::vec2 ProgressBar::getProgressRange() const {
return progressRange_;
}
void ProgressBar::show() {
forceUpdate();
}
void ProgressBar::hide() {
callback_("");
}
void ProgressBar::forceUpdate() {
std::string msg = title_ + ": " + message_ + "(" + tgt::itos((int)(progress_ * 100)) + "%)";
callback_(msg.c_str());
}
void ProgressBar::update() {
forceUpdate();
}
} // end namespace tgt
| true |
bfd4d8976cda708be3a189909d1d9beb11db8ec3 | C++ | ruankotovich/B-Tree | /src/debug.cpp | UTF-8 | 2,659 | 3.140625 | 3 | [] | no_license | #include "secondarybtree.hpp"
#include <iostream>
union BlockDerreference {
Block_t block;
SecondaryBTreeNode node;
};
void printAll(Block_t& block, FILE* indexFile, BlockDerreference* derreference)
{
int i = 0;
rewind(indexFile);
while (fread(&block, sizeof(Block_t), 1, indexFile)) {
std::cout << " --- At seek " << i << '\n';
std::cout << "Key Count : " << derreference->node.count << "\n";
std::cout << "Keys : {";
for (int j = 0; j < derreference->node.count; ++j) {
std::cout << derreference->node.keys[j].key << ',';
}
std::cout << "}\n";
std::cout << "Pointer Count : " << derreference->node.countPointers << "\n";
std::cout << "Pointers : {";
for (int j = 0; j < derreference->node.countPointers; ++j) {
std::cout << derreference->node.blockPointers[j] << ',';
}
std::cout << "}\n";
std::cout << "isLeaf() : " << derreference->node.isLeaf() << "\n";
std::cout << "hasRoom() : " << derreference->node.hasRoom() << "\n";
i++;
std::cout << "\n\n";
fseek(indexFile, sizeof(Block_t) * i, SEEK_SET);
}
}
int main()
{
Block_t block;
BlockDerreference* derreference;
derreference = (BlockDerreference*)█
FILE* indexFile = fopen("files/secondaryindex.block", "rb");
int toRead;
std::cout << "\n >> ";
while (std::cin >> toRead) {
if (toRead <= 0) {
printAll(block, indexFile, derreference);
std::cout << "\n --- \n >> ";
} else {
fseek(indexFile, sizeof(Block_t) * toRead, SEEK_SET);
fread(&block, sizeof(Block_t), 1, indexFile);
std::cout << "\n\n --- \n";
std::cout << " --- At seek " << toRead << '\n';
std::cout << "Key Count : " << derreference->node.count << "\n";
std::cout << "Keys : {";
for (int j = 0; j < derreference->node.count; ++j) {
std::cout << derreference->node.keys[j].key << ',';
}
std::cout << "}\n";
std::cout << "Pointer Count : " << derreference->node.countPointers << "\n";
std::cout << "Pointers : {";
for (int j = 0; j < derreference->node.countPointers; ++j) {
std::cout << derreference->node.blockPointers[j] << ',';
}
std::cout << "}\n";
std::cout << "isLeaf() : " << derreference->node.isLeaf() << "\n";
std::cout << "hasRoom() : " << derreference->node.hasRoom() << "\n";
std::cout << "\n --- \n >> ";
}
}
return 0;
} | true |
6cbef319f7086dae2c602a190f88535a33bd5f79 | C++ | QuantumBird/ACM_Team | /LZL/Data_structure/ST/HDU-1166.cpp | UTF-8 | 2,151 | 2.890625 | 3 | [] | no_license | //单点更新 区间查询 结点存区间数值和
#include<bits/stdc++.h>
using namespace std;
#define lson (q<<1)
#define rson (q<<1|1)
#define mid ((l+r)>>1)
const int maxn = 50000+10;
int book[maxn];
int segt[maxn<<2];
int T,m,n;
int flag;
void init(){
memset(book,0,sizeof(book));
memset(segt,0,sizeof(segt));
}
void push_up(int q){
segt[q] = segt[lson] + segt[rson];
}
void build(int q,int l,int r){
if(l == r){
segt[q] = book[l];
return;
}
int m = mid;
build(lson,l,m);
build(rson,m+1,r);
push_up(q);
}
void update_add(int q,int l,int r,int number,int k){
if(l == r){
segt[q] += k;
return;
}
int m = mid;
if(number <= m) update_add(lson,l,m,number,k);
else update_add(rson,m+1,r,number,k);
push_up(q);
}
void update_sub(int q,int l,int r,int number,int k){
if(l == r){
segt[q] -= k;
return;
}
int m = mid;
if(number <= m) update_sub(lson,l,m,number,k);
else update_sub(rson,m+1,r,number,k);
push_up(q);
}
int query(int q,int l,int r,int lhs,int rhs){
int sum = 0;
if(l >= lhs && r <= rhs){
sum += segt[q];
return sum;
}
int m = mid;
if(lhs<=m) sum+=query(lson,l,m,lhs,rhs);
if(rhs>m) sum+=query(rson,m+1,r,lhs,rhs);
return sum;
}
int main(){
std::ios::sync_with_stdio(false);
cin >> T;
while(T--){
cout << "Case " << ++flag << ":\n";
string str;
cin >> m;
init();
for(int i=1;i<=m;++i){
cin >> book[i];
}
build(1,1,m);
while(cin >> str && str!="End"){
if(str == "Query"){
int tmpa=0,tmpb=0;
cin >> tmpa >> tmpb;
cout << query(1,1,m,tmpa,tmpb) << endl;
}else if(str == "Add"){
int tmpa=0,tmpb=0;
cin >> tmpa >> tmpb;
update_add(1,1,m,tmpa,tmpb);
}else if(str == "Sub"){
int tmpa=0,tmpb=0;
cin >> tmpa >> tmpb;
update_sub(1,1,m,tmpa,tmpb);
}
}
}
return 0;
} | true |
0a541d78b945c166b062379fd04f731b34877067 | C++ | jordantonni/Design_Patterns | /6 Flyweight/flyweight.cpp | UTF-8 | 1,816 | 3.953125 | 4 | [] | no_license | #include <iostream>
#include <boost/bimap.hpp>
#include <ostream>
using namespace std;
using namespace boost;
/*
* ABSTRACT:
* Users can have the same names.
* We store the names in a static bi-directional map of the user class.
*
* When we add a new name it gets added to the map with the id of the object.
* Check if the name already exists in the constructor of each user object.
*
* The flyweight in this example is the key value that is used to find names in the list.
*/
struct User
{
User(const string& first_name, const string& last_name)
: first_name{ add(first_name) }
, last_name{ add(last_name) }
{}
const string& get_first_name() const
{
return names.left.find(first_name)->second;
}
const string& get_last_name() const
{
return names.left.find(last_name)->second;
}
friend std::ostream& operator<<(std::ostream& os, const User& obj)
{
return os
<< "first_name: " << obj.get_first_name() << " at index " << obj.first_name
<< " last_name: " << obj.get_last_name() << " at index " << obj.last_name;
}
protected:
static bimap<int, string> names;
static int user_seed;;
int first_name;
int last_name;
static int add(const string& name)
{
auto names_iterator = names.right.find(name);
if (names_iterator == names.right.end())
{
int id = ++user_seed;
names.insert(bimap<int, string>::value_type(id, name));
return id;
}
return names_iterator->second;
}
};
bimap<int, string> User::names {};
int User::user_seed = 0;
void test_flyweight()
{
User person1 { "John", "Smith" };
User person2 { "Peter", "Jefferson" };
cout << person1 << endl << person2 << endl;
}
| true |
cc6c878a9ed264e21523139b4e051f5b52ae5721 | C++ | Strider-7/code | /graph/find-mother-vertex.cpp | UTF-8 | 996 | 3.546875 | 4 | [
"MIT"
] | permissive | // A Mother Vertex is a vertex through which we can reach all the other vertices of the Graph.
#include <bits/stdc++.h>
using namespace std;
void dfsUtil(int u, vector<bool> &visited, vector<int> adj[])
{
visited[u] = true;
for (auto v : adj[u])
if (!visited[v])
dfsUtil(v, visited, adj);
}
int findMother(int V, vector<int> adj[])
{
vector<bool> visited(V, false);
int v = 0;
// track the last visited vertex.
for (int i = 0; i < V; i++)
{
if (visited[i] == false)
{
dfsUtil(i, visited, adj);
v = i;
}
}
fill(visited.begin(), visited.end(), false);
// starting from vertex v visit the whole graph
dfsUtil(v, visited, adj);
// if any vertex is unvisited then the node v is not mother vertex
// so on mother vertex is present
for (int i = 0; i < V; i++)
if (visited[i] == false)
return -1;
return v;
} | true |
bab18d2661624873c7d7faf1a9efffa9b4d8851b | C++ | sonyhome/DigitalIO | /Examples/1_Button_and_builtin_LED/1_Button_and_builtin_LED.ino | UTF-8 | 9,984 | 3.078125 | 3 | [
"MIT"
] | permissive | ////////////////////////////////////////////////////////////////////////////////
// A Digital IO Library for Arduino
// Copyright (c) 2015-2020 Dan Truong
////////////////////////////////////////////////////////////////////////////////
// Button_and_builtin_LED
//
// This simple demo declares push button and an LED. The LED turns on if you
// press the push-button.
//
// The code is set up for an Arduino Uno. Other boards may have different IO pin
// configurations. Some may not even have a built-in LED. For the UNO, Pin 7 is
// the AVR port D7. Pin 13 is the AVR port B5. Google Arduino <you board> to find
// a diagram of your board's pinout mapping.
//
// This library offers multiple ways to declare your pin variables. It makes
// trade offs between portability vs performance and compactness of the code.
// Comment/uncomment each of the ways to see the impact at compile time on code
// size. I'm putting detailed comments to explain what's what.
//
// Code size improvements on Arduino Uno up to 17%.
//
// 2422 digitalRead()/digitalWrite()
// 1% 2406 Arduino Pin
// 7% 2254 Arduino Pin + DIGITAL_IO_AVR_OPTIMIZED
// 15% 2066 AVR Port + DIGITAL_IO_AVR_DEFAULT
// 17% 2014 AVR Port
//
////////////////////////////////////////////////////////////////////////////////
// Wiring
////////////////////////////////////////////////////////////////////////////////
// The push-button should not conduct at rest and conduct when pressed. Wire it
// between pin 7 and the ground. The program will enable the pull-up resistor so
// that with the push-button at rest, the pin is pulled to 5V and reads HIGH.
// When you press the push-button, it grounds pin 7 and reads LOW.
// Wiring for digitalIo<7, HIGH>:
//
// -- Switch
// pin 7 ---o o---.
// |
// ---
// /// Gnd
//
// We use the built in LED on pin 13 so there's nothing more to wire.
// If you want to use your own LED on a different pin, wire it to an IO pin in
// series with a 200 Ohm resistor, and to the ground. When you write HIGH to the
// pin, it goes high
// Wiring for digitalIo<7, LOW> as output (control a low power LED):
// When you output HIGH, it turns on the LED
//
// 200 Ohm
// pin 7 ---====---.
// |
// V 23mA LED
// -
// |
// ---
// /// Gnd
////////////////////////////////////////////////////////////////////////////////
// Uncomment this definition to have the library print to the Serial console
// a bunch of debug information to show you what's going on under the hood.
// This must be defined before including the library to take effect.
//#define DIGITAL_IO_DEBUG 1
// Uncomment one of the led and button variables declaration pairs to see their
// effect on the size of the compiled code, and portability:
////////////////////////////////////////////////////////////////////////////////
// BEST COMPATIBILITY:
// This is the most portable version of the code. It should work for AVR and
// non AVR Arduino boards (ARM, Intel, etc.).
// This declares the button is attached to pin 7, and is in its default rest
// state when it is HIGH. When it is LOW, it means the button is on.
// It declares an LED is attached to pin 13, and that we turn it off when we set
// the level to LOW, and turn it on when we set thelevel to HIGH.
// Uno: 2406 bytes program storage, 190 bytes dynamic memory
#include <DigitalIO.hpp>
digitalIo<7, HIGH> button;
digitalIo<13, LOW> led;
////////////////////////////////////////////////////////////////////////////////
// This is as portable, but if the board is an AVR board, it applies some code
// optimizations. There's still an Arduino Pin to AVR Port conversion so it's
// not quite as compact as it could.
// Uno: 2254 bytes program storage, 190 bytes dynamic memory
//#define DIGITAL_IO_AVR_PINMODE DIGITAL_IO_AVR_OPTIMIZED
//#include <DigitalIO.hpp>
//digitalIo<7, HIGH> button;
//digitalIo<13, LOW> led;
////////////////////////////////////////////////////////////////////////////////
// BEST PERFORMANCE:
// This only compiles for AVR boards, and generates optimized code that should
// be as compact and fast as possible, as it avoids pin to port conversions. It
// should be more compact than if you were to code this yourself directly.
// Uno: 2014 bytes program storage, 190 bytes dynamic memory
//#include <DigitalIO.hpp>
//digitalIoAvr<D,7, HIGH> button;
//digitalIoAvr<B,5, LOW> led; // pin 13
////////////////////////////////////////////////////////////////////////////////
// This only compiles for AVR boards, and generates code that's more portable.
// If your board doesn't work with the optimal code version you could try this.
// Uno: 2066 bytes program storage, 190 bytes dynamic memory
//#define DIGITAL_IO_AVR_PORTMODE DIGITAL_IO_AVR_DEFAULT
//#include <DigitalIO.hpp>
//digitalIoAvr<D,7, HIGH> button;
//digitalIoAvr<B,5, LOW> led; // pin 13
////////////////////////////////////////////////////////////////////////////////
// native_loop Arduino calls to digitalRead() and digitalWrite()
// To test this, comment all button and led variables related code and uncomment
// the pinMode() and native_loop() code.
// Uno: 2422 bytes program storage, 188 bytes dynamic memory
////////////////////////////////////////////////////////////////////////////////
void setup() {
Serial.begin(9600);
// Activate the pull-up resistor for the button
button.inputPullupMode();
// Set the port as output for the LED to turn it on/off
led.outputMode();
// If you uncomment native_loop() below, you should uncomment this:
// pinMode(7, INPUT_PULLUP);
// pinMode(13, OUTPUT);
}
////////////////////////////////////////////////////////////////////////////////
void loop() {
// Here's equivalent loop bodies that perform the same task in different ways.
// Uncomment only one of them and try it, then read the code and description.
// Uses digitalIO class and traditional read/write interface
//read_write_loop();
// Uses digitalIO class and convenient routines for easy to read code
//isOn_isOff_loop();
// Uses digitalIO class flipped() debounce function to read the button
// (costs 108 bytes of program memory)
//flipped_loop();
// Uses digitalIO class triggered() debounce function to read spikes, and toggle()
// (costs 170 bytes of program memory)
triggered_loop();
// Doesn't use digitalIO but Arduino built-in digital IO methods
// native_loop();
}
////////////////////////////////////////////////////////////////////////////////
// The library also has more classic read()/write() methods.
// The code performs exactly the same task, but you'll notice it is harder to
// glance at it and understand what's happening.
////////////////////////////////////////////////////////////////////////////////
void read_write_loop() {
// When you press the button, the pin is grounded so it reads LOW.
if (button.read() == LOW) {
// When you write HIGH, the pin voltage goes to 5V and turns on.
led.write(HIGH);
} else {
led.write(LOW);
}
Serial.print(button.read());
Serial.println(led.read());
delay(500);
}
////////////////////////////////////////////////////////////////////////////////
// Code example with the convenience isOn()/isOff(), turnOn()/turnOff() methods.
// This takes advantage of the default state declarations we made when creating
// the variables, to simplify code reading.
////////////////////////////////////////////////////////////////////////////////
void isOn_isOff_loop() {
if (button.isOn()) {
led.turnOn();
} else {
led.turnOff();
}
Serial.print(button.isOn());
Serial.println(led.isOn());
delay(500);
}
////////////////////////////////////////////////////////////////////////////////
// Code example with the debounced flipped() method.
// This method returns 0 when button state has not changed, 1 if it was pressed
// and -1 if it was released. These 3 states allow us to not write to the LED
// port if the button has not changed state.
// Furthermore, the debounce of the button means we can use a mechanical button
// that causes noise on the line without having the code glitching.
////////////////////////////////////////////////////////////////////////////////
void flipped_loop() {
// notice: int8_t is signed. Unsigned, a release would be represented by 255.
const int8_t state = button.flipped();
if (state == 1) {
led.turnOn();
} else if (state == -1) {
led.turnOff();
}
Serial.print(button.isOn());
Serial.println(led.isOn());
delay(500);
}
////////////////////////////////////////////////////////////////////////////////
// Code example with the debounced triggered() method.
// The triggered method is for detecting brief spikes (i.e. knock sensor) so
// this loop function works differently. If a transition is detected on the
// button, it toggles the LED. This means if you press the button slowly, it
// will behave the same. However if you tap the button briefly it will toggle
// the LED. That's because triggered() doesn't track the HIGH or LOW level, but
// transitions on the pin (a spike or level change).
// triggered has debounce code to handle noisy spikes so the same spike doesn't
// trigger multiple times the code if it's noisy.
////////////////////////////////////////////////////////////////////////////////
void triggered_loop() {
if (button.triggered()) {
led.toggle();
Serial.print(button.isOn());
Serial.println(led.isOn());
}
delay(5);
}
////////////////////////////////////////////////////////////////////////////////
// Baseline loop without using the DigitalIO library.
////////////////////////////////////////////////////////////////////////////////
void native_loop()
{
if (digitalRead(7) == LOW) {
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
Serial.print(digitalRead(7));
Serial.println(digitalRead(13));
delay(500);
}
| true |
6a8712c515ca24f7cd47f0a58b3a396ae8396d33 | C++ | Rena7ssance/Database-Implementation | /SQL/headers/ExprTree.h | UTF-8 | 24,722 | 2.703125 | 3 | [] | no_license |
#ifndef SQL_EXPRESSIONS
#define SQL_EXPRESSIONS
#include "MyDB_AttType.h"
#include "MyDB_Catalog.h"
#include <string>
#include <vector>
#include <algorithm>
// create a smart pointer for database tables
using namespace std;
class ExprTree;
typedef shared_ptr <ExprTree> ExprTreePtr;
enum ExprType {
NUMBER_TYPE,
BOOL_TYPE,
STRING_TYPE,
ERROR_TYPE
};
// this class encapsules a parsed SQL expression (such as "this.that > 34.5 AND 4 = 5")
// class ExprTree is a pure virtual class... the various classes that implement it are below
class ExprTree : public enable_shared_from_this <ExprTree> {
public:
virtual string toString () = 0;
virtual ~ExprTree () {}
// Roy7wt
virtual bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses
) = 0;
virtual ExprType getType() = 0;
virtual void getAtt (vector <ExprTreePtr> &vec) {};
virtual bool isIdentifierAtt() {return false;}
virtual bool isAggregateAtt() {return false;}
virtual pair <string, string> getAggregateAtt() {return make_pair("", "");};
virtual bool isReferToTable (string tableAlais) {return false;}
virtual bool isEqOp() {return false;}
virtual ExprTreePtr getLhs() {return nullptr;}
virtual ExprTreePtr getRhs() {return nullptr;}
MyDB_AttTypePtr getAttType() {
return attType;
}
void setAttType(MyDB_AttTypePtr attTypeIn) {
attType = attTypeIn;
}
void setAttType () {
switch (getType()) {
case NUMBER_TYPE : {
attType = make_shared <MyDB_DoubleAttType> ();
break;
}
case STRING_TYPE : {
attType = make_shared <MyDB_StringAttType> ();
break;
}
case BOOL_TYPE : {
attType = make_shared <MyDB_BoolAttType> ();
break;
}
default: {
return;
}
}
}
string type2Str() {
switch (getType()) {
case NUMBER_TYPE : {
return "number";
}
case STRING_TYPE: {
return "string";
}
case BOOL_TYPE : {
return "bool";
}
default: {
return "nullptr";
}
}
}
protected :
MyDB_AttTypePtr attType;
};
class BoolLiteral : public ExprTree {
private:
bool myVal;
public:
BoolLiteral (bool fromMe) {
myVal = fromMe;
}
string toString () {
if (myVal) {
return "bool[true]";
} else {
return "bool[false]";
}
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// attType = make_shared <MyDB_BoolAttType> ();
setAttType();
return true;
}
ExprType getType() {
return BOOL_TYPE;
}
};
class DoubleLiteral : public ExprTree {
private:
double myVal;
public:
DoubleLiteral (double fromMe) {
myVal = fromMe;
}
string toString () {
return "double[" + to_string (myVal) + "]";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// attType = make_shared <MyDB_DoubleAttType> ();
setAttType();
return true;
}
ExprType getType() {
return NUMBER_TYPE;
}
~DoubleLiteral () {}
};
// this implement class ExprTree
class IntLiteral : public ExprTree {
private:
int myVal;
public:
IntLiteral (int fromMe) {
myVal = fromMe;
}
string toString () {
return "int[" + to_string (myVal) + "]";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// attType = make_shared <MyDB_IntAttType> ();
setAttType();
return true;
}
ExprType getType() {
return NUMBER_TYPE;
}
~IntLiteral () {}
};
class StringLiteral : public ExprTree {
private:
string myVal;
public:
StringLiteral (char *fromMe) {
fromMe[strlen (fromMe) - 1] = 0;
myVal = string (fromMe + 1);
}
string toString () {
return "string[" + myVal + "]";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// attType = make_shared <MyDB_StringAttType> ();
setAttType();
return true;
}
ExprType getType() {
return STRING_TYPE;
}
~StringLiteral () {}
};
class Identifier : public ExprTree {
private:
string tableName;
string attName;
string attType;
public:
Identifier (char *tableNameIn, char *attNameIn) {
tableName = string (tableNameIn);
attName = string (attNameIn);
attType = string ("");
}
Identifier (string tableNameIn, string attNameIn) {
tableName = string (tableNameIn);
attName = string (attNameIn);
attType = string ("");
}
string toString () {
if (tableName == "") {
return "[" + attName + "]";
} else {
return "[" + tableName + "_" + attName + "]";
}
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses) {
vector<string> tables;
catalog->getStringList("tables", tables);
string tableRealName;
for (auto table : tablesToProcess) {
if (table.second == tableName) {
// get the real name of table
tableRealName = table.first;
break;
}
}
if (tableRealName == "") { // the alias of table name is not in the catalog
cout << "[SemanticError: table alias (" << tableName << ")does not exist in the database]" << endl;
return false;
}
// check the attributes
vector<string> atts;
string key = tableRealName + ".attList";
catalog->getStringList(key, atts);
if (std :: find(atts.begin(), atts.end(), attName) != atts.end()) {
/* attName contains in the table*/
attType = "";
string attKey = tableRealName + "." + attName + ".type";
catalog->getString(attKey, attType);
} else {
/* attName does not contain in the table*/
cout << "[SemanticError: Attributes (" << attName << ") does not exist in (" << tableRealName << ") table]" << endl;
return false;
}
// check for the group when the identifier is in the valuesToSelect
if (!groupingClauses.empty()) {
/* this is an aggregation query*/
bool attInGroupAtt = false;
for (auto groupingClause : groupingClauses) {
if (groupingClause->toString() == toString()) {
attInGroupAtt = true;
break;
}
}
if (!attInGroupAtt) {
// in the case of an aggregation query, the att is not functions of grouping attributes
cout << "[SemanticError: In the case of an aggregation query, the selected attribute " << toString() << " is not functions of grouping attributes]" << endl;
return false;
}
}
setAttType();
return true;
}
ExprType getType() {
if (attType == "int" || attType == "double") return NUMBER_TYPE;
if (attType == "string") return STRING_TYPE;
if (attType == "bool") return BOOL_TYPE;
return ERROR_TYPE;
}
bool isIdentifierAtt() {
return true;
}
void getAtt(vector <ExprTreePtr> &vec) {
vec.push_back(shared_from_this());
}
bool isReferToTable(string tableAlais) {
return tableAlais == tableName;
}
~Identifier () {}
};
class MinusOp : public ExprTree {
private:
ExprTreePtr lhs;
ExprTreePtr rhs;
public:
MinusOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) {
lhs = lhsIn;
rhs = rhsIn;
}
string toString () {
return "- (" + lhs->toString () + ", " + rhs->toString () + ")";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// check for identifiers
if (!lhs->checkFunc(catalog, tablesToProcess, groupingClauses) || !rhs->checkFunc(catalog, tablesToProcess, groupingClauses)) {
// one of the identifiers is wrong
return false;
}
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == NUMBER_TYPE && rhsType == NUMBER_TYPE) {
setAttType();
return true;
} else if (lhsType == NUMBER_TYPE && rhsType != NUMBER_TYPE) {
cout << "[SemanticError: type mismatches that " << rhs->toString() << " is not number type]" << endl;
return false;
} else if (lhsType != NUMBER_TYPE && rhsType == NUMBER_TYPE) {
cout << "[SemanticError: type mismatches that " << lhs->toString() << " is not number type]" << endl;
return false;
} else {
cout << "[SemanticError: type mismatches that " << lhs->toString() << " and " << rhs->toString() << " are neither number type]" << endl;
return false;
}
}
ExprType getType() {
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == NUMBER_TYPE && rhsType == NUMBER_TYPE) {
return NUMBER_TYPE;
} else return ERROR_TYPE;
}
void getAtt(vector <ExprTreePtr> &vec) {
lhs->getAtt(vec);
rhs->getAtt(vec);
}
bool isReferToTable(string tableAlais) {
return lhs->isReferToTable(tableAlais) || rhs->isReferToTable(tableAlais);
}
~MinusOp () {}
};
class PlusOp : public ExprTree {
private:
ExprTreePtr lhs;
ExprTreePtr rhs;
public:
PlusOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) {
lhs = lhsIn;
rhs = rhsIn;
}
string toString () {
return "+ (" + lhs->toString () + ", " + rhs->toString () + ")";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// check for identifiers
if (!lhs->checkFunc(catalog, tablesToProcess, groupingClauses) || !rhs->checkFunc(catalog, tablesToProcess, groupingClauses)) {
// one of the identifiers is wrong
return false;
}
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == NUMBER_TYPE && rhsType == NUMBER_TYPE) {
setAttType();
return true;
}
if (lhsType == STRING_TYPE && rhsType == STRING_TYPE) {
setAttType();
return true;
}
cout << "[SemanticError: type mismatches that " << lhs->toString() << " and " << rhs->toString() << "]" << endl;
return false;
}
ExprType getType() {
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == NUMBER_TYPE && rhsType == NUMBER_TYPE) {
return NUMBER_TYPE;
} else if (lhsType == STRING_TYPE && rhsType == STRING_TYPE) {
return STRING_TYPE;
} else return ERROR_TYPE;
}
void getAtt(vector <ExprTreePtr> &vec) {
lhs->getAtt(vec);
rhs->getAtt(vec);
}
bool isReferToTable(string tableAlais) {
return lhs->isReferToTable(tableAlais) || rhs->isReferToTable(tableAlais);
}
~PlusOp () {}
};
class TimesOp : public ExprTree {
private:
ExprTreePtr lhs;
ExprTreePtr rhs;
public:
TimesOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) {
lhs = lhsIn;
rhs = rhsIn;
}
string toString () {
return "* (" + lhs->toString () + ", " + rhs->toString () + ")";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// check for identifiers
if (!lhs->checkFunc(catalog, tablesToProcess, groupingClauses) || !rhs->checkFunc(catalog, tablesToProcess, groupingClauses)) {
// one of the identifiers is wrong
return false;
}
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == NUMBER_TYPE && rhsType == NUMBER_TYPE) {
setAttType();
return true;
} else if (lhsType == NUMBER_TYPE && rhsType != NUMBER_TYPE) {
cout << "[SemanticError: type mismatches that " << rhs->toString() << " is not number type]" << endl;
return false;
} else if (lhsType != NUMBER_TYPE && rhsType == NUMBER_TYPE) {
cout << "[SemanticError: type mismatches that " << lhs->toString() << " is not number type]" << endl;
return false;
} else {
cout << "[SemanticError: type mismatches that " << lhs->toString() << " and " << rhs->toString() << " are neither number type]" << endl;
return false;
}
}
ExprType getType() {
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == NUMBER_TYPE && rhsType == NUMBER_TYPE) {
return NUMBER_TYPE;
} else return ERROR_TYPE;
}
void getAtt(vector <ExprTreePtr> &vec) {
lhs->getAtt(vec);
rhs->getAtt(vec);
}
bool isReferToTable(string tableAlais) {
return lhs->isReferToTable(tableAlais) || rhs->isReferToTable(tableAlais);
}
~TimesOp () {}
};
class DivideOp : public ExprTree {
private:
ExprTreePtr lhs;
ExprTreePtr rhs;
public:
DivideOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) {
lhs = lhsIn;
rhs = rhsIn;
}
string toString () {
return "/ (" + lhs->toString () + ", " + rhs->toString () + ")";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// check for identifiers
if (!lhs->checkFunc(catalog, tablesToProcess, groupingClauses) || !rhs->checkFunc(catalog, tablesToProcess, groupingClauses)) {
// one of the identifiers is wrong
return false;
}
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == NUMBER_TYPE && rhsType == NUMBER_TYPE) {
setAttType();
return true;
} else if (lhsType == NUMBER_TYPE && rhsType != NUMBER_TYPE) {
cout << "[SemanticError: type mismatches that " << rhs->toString() << " is not number type]" << endl;
return false;
} else if (lhsType != NUMBER_TYPE && rhsType == NUMBER_TYPE) {
cout << "[SemanticError: type mismatches that " << lhs->toString() << " is not number type]" << endl;
return false;
} else {
cout << "[SemanticError: type mismatches that " << lhs->toString() << " and " << rhs->toString() << " are neither number type]" << endl;
return false;
}
}
ExprType getType() {
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == NUMBER_TYPE && rhsType == NUMBER_TYPE) {
return NUMBER_TYPE;
} else return ERROR_TYPE;
}
void getAtt(vector <ExprTreePtr> &vec) {
lhs->getAtt(vec);
rhs->getAtt(vec);
}
bool isReferToTable(string tableAlais) {
return lhs->isReferToTable(tableAlais) || rhs->isReferToTable(tableAlais);
}
~DivideOp () {}
};
class GtOp : public ExprTree {
private:
ExprTreePtr lhs;
ExprTreePtr rhs;
public:
GtOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) {
lhs = lhsIn;
rhs = rhsIn;
}
string toString () {
return "> (" + lhs->toString () + ", " + rhs->toString () + ")";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// check for identifiers
if (!lhs->checkFunc(catalog, tablesToProcess, groupingClauses) || !rhs->checkFunc(catalog, tablesToProcess, groupingClauses)) {
// one of the identifiers is wrong
return false;
}
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == NUMBER_TYPE && rhsType == NUMBER_TYPE) {
setAttType();
return true;
}
if (lhsType == STRING_TYPE && rhsType == STRING_TYPE) {
setAttType();
return true;
}
cout << "[SemanticError: type mismatches that " << lhs->toString() << " and " << rhs->toString() << "]" << endl;
return false;
}
ExprType getType() {
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == NUMBER_TYPE && rhsType == NUMBER_TYPE) {
return BOOL_TYPE;
} else if (lhsType == STRING_TYPE && rhsType == STRING_TYPE) {
return BOOL_TYPE;
} else return ERROR_TYPE;
}
void getAtt(vector <ExprTreePtr> &vec) {
lhs->getAtt(vec);
rhs->getAtt(vec);
}
bool isReferToTable(string tableAlais) {
return lhs->isReferToTable(tableAlais) || rhs->isReferToTable(tableAlais);
}
~GtOp () {}
};
class LtOp : public ExprTree {
private:
ExprTreePtr lhs;
ExprTreePtr rhs;
public:
LtOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) {
lhs = lhsIn;
rhs = rhsIn;
}
string toString () {
return "< (" + lhs->toString () + ", " + rhs->toString () + ")";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// check for identifiers
if (!lhs->checkFunc(catalog, tablesToProcess, groupingClauses) || !rhs->checkFunc(catalog, tablesToProcess, groupingClauses)) {
// one of the identifiers is wrong
return false;
}
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == NUMBER_TYPE && rhsType == NUMBER_TYPE) {
setAttType();
return true;
}
if (lhsType == STRING_TYPE && rhsType == STRING_TYPE) {
setAttType();
return true;
}
cout << "[SemanticError: type mismatches that " << lhs->toString() << " and " << rhs->toString() << "]" << endl;
return false;
}
ExprType getType() {
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == NUMBER_TYPE && rhsType == NUMBER_TYPE) {
return BOOL_TYPE;
} else if (lhsType == STRING_TYPE && rhsType == STRING_TYPE) {
return BOOL_TYPE;
} else return ERROR_TYPE;
}
void getAtt(vector <ExprTreePtr> &vec) {
lhs->getAtt(vec);
rhs->getAtt(vec);
}
bool isReferToTable(string tableAlais) {
return lhs->isReferToTable(tableAlais) || rhs->isReferToTable(tableAlais);
}
~LtOp () {}
};
class NeqOp : public ExprTree {
private:
ExprTreePtr lhs;
ExprTreePtr rhs;
public:
NeqOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) {
lhs = lhsIn;
rhs = rhsIn;
}
string toString () {
return "!= (" + lhs->toString () + ", " + rhs->toString () + ")";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// check for identifiers
if (!lhs->checkFunc(catalog, tablesToProcess, groupingClauses) || !rhs->checkFunc(catalog, tablesToProcess, groupingClauses)) {
// one of the identifiers is wrong
return false;
}
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType != rhsType) {
cout << "[SemanticError: type mismatches that " << lhs->toString() << " and " << rhs->toString() << "]" << endl;
return false;
}
setAttType();
return true;
}
ExprType getType() {
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == rhsType) {
return BOOL_TYPE;
} else return ERROR_TYPE;
}
void getAtt(vector <ExprTreePtr> &vec) {
lhs->getAtt(vec);
rhs->getAtt(vec);
}
bool isReferToTable(string tableAlais) {
return lhs->isReferToTable(tableAlais) || rhs->isReferToTable(tableAlais);
}
~NeqOp () {}
};
class OrOp : public ExprTree {
private:
ExprTreePtr lhs;
ExprTreePtr rhs;
public:
OrOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) {
lhs = lhsIn;
rhs = rhsIn;
}
string toString () {
return "|| (" + lhs->toString () + ", " + rhs->toString () + ")";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// check for identifiers
if (!lhs->checkFunc(catalog, tablesToProcess, groupingClauses) || !rhs->checkFunc(catalog, tablesToProcess, groupingClauses)) {
// one of the identifiers is wrong
return false;
}
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType != BOOL_TYPE) {
cout << "[SemanticError: the left expression of OR that " << lhs->toString() << " is not a bool type]" << endl;
return false;
}else if (rhsType != BOOL_TYPE) {
cout << "[SemanticError: the right expression of OR that " << rhs->toString() << " is not a bool type]" << endl;
return false;
}
setAttType();
return true;
}
ExprType getType() {
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == BOOL_TYPE && rhsType == BOOL_TYPE) {
return BOOL_TYPE;
} else return ERROR_TYPE;
}
void getAtt(vector <ExprTreePtr> &vec) {
lhs->getAtt(vec);
rhs->getAtt(vec);
}
bool isReferToTable(string tableAlais) {
return lhs->isReferToTable(tableAlais) || rhs->isReferToTable(tableAlais);
}
~OrOp () {}
};
class EqOp : public ExprTree {
private:
ExprTreePtr lhs;
ExprTreePtr rhs;
public:
EqOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) {
lhs = lhsIn;
rhs = rhsIn;
}
string toString () {
return "== (" + lhs->toString () + ", " + rhs->toString () + ")";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// check for identifiers
if (!lhs->checkFunc(catalog, tablesToProcess, groupingClauses) || !rhs->checkFunc(catalog, tablesToProcess, groupingClauses)) {
// one of the identifiers is wrong
return false;
}
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType != rhsType) {
cout << "[SemanticError: type mismatches that " << lhs->toString() << " and " << rhs->toString() << "]" << endl;
return false;
}
setAttType();
return true;
}
ExprType getType() {
ExprType lhsType = lhs->getType();
ExprType rhsType = rhs->getType();
if (lhsType == rhsType) {
return BOOL_TYPE;
} else return ERROR_TYPE;
}
void getAtt(vector <ExprTreePtr> &vec) {
lhs->getAtt(vec);
rhs->getAtt(vec);
}
bool isReferToTable(string tableAlais) {
return lhs->isReferToTable(tableAlais) || rhs->isReferToTable(tableAlais);
}
bool isEqOp() {
return true;
}
ExprTreePtr getLhs() {
return lhs;
}
ExprTreePtr getRhs() {
return rhs;
}
~EqOp () {}
};
class NotOp : public ExprTree {
private:
ExprTreePtr child;
public:
NotOp (ExprTreePtr childIn) {
child = childIn;
}
string toString () {
return "!(" + child->toString () + ")";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
// check for identifiers
if (!child->checkFunc(catalog, tablesToProcess, groupingClauses)) {
// one of the identifiers is wrong
return false;
}
ExprType childType = child->getType();
if (childType != BOOL_TYPE) {
cout << "[SemanticError: the expression " << child->toString() << " is not bool type]" << endl;
return false;
}
setAttType();
return true;
}
ExprType getType() {
ExprType childType = child->getType();
if (childType == BOOL_TYPE) {
return BOOL_TYPE;
} else return ERROR_TYPE;
}
void getAtt(vector <ExprTreePtr> &vec) {
child->getAtt(vec);
}
bool isReferToTable(string tableAlais) {
return child->isReferToTable(tableAlais);
}
~NotOp () {}
};
class SumOp : public ExprTree {
private:
ExprTreePtr child;
public:
SumOp (ExprTreePtr childIn) {
child = childIn;
}
string toString () {
return "sum(" + child->toString () + ")";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
vector <ExprTreePtr> emptyVec;
// check for identifiers
if (!child->checkFunc(catalog, tablesToProcess, emptyVec)) {
// one of the identifiers is wrong
return false;
}
ExprType childType = child->getType();
if (childType != NUMBER_TYPE) {
cout << "[SemanticError: expression " << child->toString() << " is not number type, failing to sum]" << endl;
return false;
}
setAttType();
return true;
}
ExprType getType() {
ExprType childType = child->getType();
if (childType == NUMBER_TYPE) {
return NUMBER_TYPE;
} else return ERROR_TYPE;
}
void getAtt(vector <ExprTreePtr> &vec) {
child->getAtt(vec);
}
bool isAggregateAtt() {
return true;
}
pair <string, string> getAggregateAtt() {
return make_pair("sum", child->toString());
}
bool isReferToTable(string tableAlais) {
return child->isReferToTable(tableAlais);
}
~SumOp () {}
};
class AvgOp : public ExprTree {
private:
ExprTreePtr child;
public:
AvgOp (ExprTreePtr childIn) {
child = childIn;
}
string toString () {
return "avg(" + child->toString () + ")";
}
bool checkFunc(
MyDB_CatalogPtr catalog,
vector <pair <string, string>> tablesToProcess,
vector <ExprTreePtr> groupingClauses ) {
vector <ExprTreePtr> emptyVec;
// check for identifiers
if (!child->checkFunc(catalog, tablesToProcess, emptyVec)) {
// one of the identifiers is wrong
return false;
}
ExprType childType = child->getType();
if (childType != NUMBER_TYPE) {
cout << "[SemanticError: expression " << child->toString() << " is not number type, failing to sum]" << endl;
return false;
}
setAttType();
return true;
}
ExprType getType() {
ExprType childType = child->getType();
if (childType == NUMBER_TYPE) {
return NUMBER_TYPE;
} else return ERROR_TYPE;
}
void getAtt(vector <ExprTreePtr> &vec) {
child->getAtt(vec);
}
bool isAggregateAtt() {
return true;
}
pair <string, string> getAggregateAtt() {
return make_pair("avg", child->toString());
}
bool isReferToTable(string tableAlais) {
return child->isReferToTable(tableAlais);
}
~AvgOp () {}
};
#endif
| true |
dd2002c687f00352833551df47a163b2cb4c5b31 | C++ | DejotaFreitas/LANG-C-PLUS-PLUS | /SERVER-GAME/headers/Computer.hpp | UTF-8 | 3,338 | 2.515625 | 3 | [
"MIT"
] | permissive | //
// Computer.hpp
// server
//
// Created by Bruno Macedo Miguel on 10/12/16.
// Copyright © 2016 d2server. All rights reserved.
//
#ifndef Computer_hpp
#define Computer_hpp
#include <cstdlib>
#include <queue>
#include <boost/asio.hpp>
#include <iostream>
#include "Consts.hpp"
#include "Account.hpp"
#include "MemoryStream.hpp"
#include "MessageAction.hpp"
using boost::asio::ip::udp;
class Factory;
class MessageNotificationCenter;
class Computer
{
friend class LanHouse;
public:
// getters
const bool inUse(){return _userID != 0;}
const uint16_t& getUserID(){return _userID;}
const udp::endpoint getAddress(){return _address;}
// process and output message
bool update(DataBus*);
// Action to use objects
MessageNotificationCenter& getNotificationCenter(){return *_notificationCenter;}
Account& getAccount() {return _playerAccount;}
Factory& getFactory() {return *_factory;}
// write message
void writeMessage(MessageHeader header, void* data);
void forceDisconnection(){_state.active.forceRestart = true;}
protected:
// Dependencies manager
void installDependencies(MailBox* mailbox, MessageNotificationCenter* messageCenter, Factory* factory);
bool hasDependencies() {return (_mailBox && _notificationCenter && _factory);}
// Reset variables and recycle message (if exist)
void cleanState();
// Message processing
void addMessage(MessageParcel& incomingMessage); // receive message from LanHouse
void readMessage();
void sendMessage(bool force = false);
bool filterMessage(MessageParcel& message);
// State Manager
void setUserID (uint16_t uid) { _userID = uid; }
void setAddress (udp::endpoint address) {_address = address;}
// Activity Manager
bool isActive() {return _state.active.lastActivity + REQUIREDACTIVITYTIME > static_cast<uint64_t>(OTSYS_TIME()) && !_state.active.forceRestart;}
void updateActivity() {_state.active.lastActivity = static_cast<uint64_t>(OTSYS_TIME());}
private:
Computer() :
_userID(0),
_mailBox(nullptr),
_notificationCenter(nullptr),
_factory(nullptr),
_outputMessage(nullptr)
{}
~Computer(){}
// State
uint16_t _userID;
udp::endpoint _address;
// Dependencies
MailBox* _mailBox;
MessageNotificationCenter* _notificationCenter;
Factory* _factory;
// Player
std::unique_ptr<Action> _action;
Account _playerAccount;
// Memory Stream
OutputMemoryBitStream _writer;
InputMemoryBitStream _reader;
// Object Pool
Computer* getNext() {return _state.next;}
void setNext(Computer* next) {_state.next = next;}
// Messages
MessageParcel* _outputMessage;
std::queue<MessageParcel*> _receiveMessages;
union
{
struct
{
uint32_t lastSent;
uint32_t lastReceived;
uint64_t lastActivity;
bool forceRestart;
} active;
Computer* next;
} _state;
};
#endif /* Computer_hpp */
| true |
779a1c86484affd85ab43e93d1cf0436fd16fb35 | C++ | lijiaxin-dut/leetcode | /leetcode_train/Solution_536.cpp | GB18030 | 1,633 | 3.671875 | 4 | [] | no_license | #include<vector>
#include"TreeNode.h"
#include<string>
using namespace std;
//You need to construct a binary tree from a string consisting of parenthesis and integers.
//
//The whole input represents a binary tree.It contains an integer followed by zero, one or two pairs of parenthesis.The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure.
//
//You always start to construct the left child node of the parent first if it exists.
//
//Example:
//
//Input: "4(2(3)(1))(6(5))"
// Output : return the tree root node representing the following tree :
//
// 4
// / \
// 2 6
// / \ /
// 3 1 5
//
//
// Note:
//
// There will only be '(', ')', '-' and '0' ~'9' in the input string.
// An empty tree is represented by "" instead of "()".
class Solution {
public:
TreeNode* str2tree(string s) {
if (s.empty())
return NULL;
auto found = s.find('(');
int val = (found == string::npos) ? stoi(s) : stoi(s.substr(0, found));
TreeNode *cur = new TreeNode(val);
if (found == string::npos)
return cur;
int start = found, cnt = 0;
for (int i = start; i < s.size(); ++i) {
if (s[i] == '(')
++cnt;
else if (s[i] == ')')
--cnt;
if (cnt == 0 && start == found) {
//Ҫȥߵ
cur->left = str2tree(s.substr(start + 1, i - start - 1));
start = i + 1;
//i+1Ϊһŵλãѭͽ
}
else if (cnt == 0) {
cur->right = str2tree(s.substr(start + 1, i - start - 1));
}
}
return cur;
}
}; | true |
a4189b4764c7d119877d87bce4c5799060947546 | C++ | vitalbit/labApple | /TPlab1/TPlab1.cpp | WINDOWS-1251 | 2,488 | 3.25 | 3 | [] | no_license | // TPlab1.cpp: .
//
#include "stdafx.h"
#include <string>
#include <vector>
#include <time.h>
#include <iostream>
using namespace std;
class Apple
{
private:
bool ripe;
string color;
int seeds;
public:
Apple() {
ripe = true;
color = "red";
seeds = rand() % 11;
}
int getSeeds()
{
return seeds;
}
};
class Tree
{
private:
vector <Apple> tree;
int allSeeds;
bool blossom;
Tree(int n) {
allSeeds = 0;
if (n > 5000) n = 5000;
for (int i = 0; i < n; i++)
{
tree.push_back(*(new Apple()));
allSeeds += (tree.end()-1)->getSeeds();
}
}
public:
Tree() {
allSeeds = 0;
blossom = false;
}
int grow() {
int x = 0;
if (blossom) {
int high = 5000;
x=rand();
x=x-5000*(x/5000);
if ((int)tree.size()+x>5000) x=5000-tree.size();
for (int i=0; i!=x; i++)
{
tree.push_back(*(new Apple()));
allSeeds += (tree.end()-1)->getSeeds();
}
}
return x;
}
int shake() {
int x=rand();
x=x-5000*(x/5000);
if ((int)tree.size()-x < 0) x=tree.size();
for (int i=0; i<x; i++)
{
allSeeds-=(tree.end()-1)->getSeeds();
tree.pop_back();
}
return x;
}
int count() {
return tree.size();
}
int countSeeds() {
return allSeeds;
}
bool blossomTree() {
if (!blossom) {
blossom = true;
return true;
}
else return false;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
srand(time(NULL));
Tree *tr = new Tree();
string cmd="";
while (cmd!="quite")
{
cout << "Enter\ngrow -- for new apples\ncount -- for count of apples\nshake -- for apples down\nseeds -- for count of seeds\nblossom -- for blossomed tree\nquite -- for quite" << endl;
cin >> cmd;
if (cmd=="grow")
cout << "Has grown " << tr->grow() << " apples" << endl;
else if (cmd=="shake")
cout << tr->shake() << " apples have down" << endl;
else if (cmd=="count")
cout << "Tree has " << tr->count() << " apples" << endl;
else if (cmd=="seeds")
cout << "Count of seeds = " << tr->countSeeds() << endl;
else if (cmd=="blossom") {
if (tr->blossomTree())
cout << "Tree has blossomed" << endl;
else cout << "Tree has already blossomed" << endl;
}
else if (cmd!="quite") cout << "Wrong command!" << endl;
}
return 0;
}
//
//commit
//
//commit | true |
e91f5fcbe38e13d51a21cb9d1d7499ceff38498f | C++ | Ting2003/LDO | /util.h | UTF-8 | 793 | 2.625 | 3 | [] | no_license | #ifndef __UTIL_H__
#define __UTIL_H__
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>
using namespace std;
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
#define report_exit(a) _report_exit(AT,a)
#define fzero(a) (fabs(a)<FLOAT_ZERO)
#define feqn(a,b) (fzero((a)-(b)))
void _report_exit(const char *location, const char *msg);
double ** new_square_matrix(int n);
void delete_matrix(double **,int);
void output_matrix(double **,int);
string get_basename(char * filename);
void open_logfile(const char * logname);
void close_logfile();
// given a vector, copy its element to a basic array
template<class T>
void vector_to_array(vector<T> v, T * arr){
copy(v.begin(), v.end(), arr);
}
#endif
| true |
2571ab11c39a46a69c09e029458356db6703060b | C++ | RyanStonebraker/Snowball | /c++/test/neuralNetworkTests.cpp | UTF-8 | 5,640 | 2.84375 | 3 | [
"MIT"
] | permissive | #include "catch.hpp"
#include "WeightedNode.h"
#include "IOHandler.h"
#include <fstream>
#include "BranchTracker.h"
#include <vector>
#include "board.h"
#include <chrono>
using std::chrono::system_clock;
using std::chrono::duration;
#include "moveGenerator.h"
TEST_CASE ("Basic Gameplay") {
WeightedNode currentWeights;
currentWeights.kingingWeight = 0.5;
currentWeights.qualityWeight = 0.5;
currentWeights.availableMovesWeight = 0.5;
currentWeights.riskFactor = 0.5;
currentWeights.enemyFactor = 0.5;
currentWeights.depth = 2;
SECTION ("AI goes second as black") {
SECTION ("Basic IO") {
IOHandler ioHandler(true);
std::ofstream firstHandshakeWriter (ioHandler.getFirstHandshakeLocation().c_str(), std::ofstream::trunc);
firstHandshakeWriter << "1";
firstHandshakeWriter.flush();
ioHandler.startGame(ioHandler.setupGame());
std::ifstream checkHandshake(ioHandler.getSecondHandshakeLocation());
int handshakeCheck = -1;
checkHandshake >> handshakeCheck;
SECTION ("Valid Handshake") {
REQUIRE(handshakeCheck == 1);
}
std::ofstream writeZeroTurn (ioHandler.getCurrentGameDirectory() + "turn0.txt");
writeZeroTurn << "11111111111100000000222222222222";
writeZeroTurn.flush();
std::ofstream writeFirstTurn (ioHandler.getCurrentGameDirectory() + "turn1.txt");
std::string first_board = "11111111110110000000222222222222";
writeFirstTurn << first_board;
writeFirstTurn.flush();
ioHandler.updateFileName();
Board initBoard(ioHandler.readBoardState());
}
std::string first_board = "11111111110110000000222222222222";
Board initBoard(first_board);
REQUIRE(initBoard.getBoardStateString() == first_board);
BranchTracker potentialBranch(initBoard, currentWeights);
Board nextMove = potentialBranch.getBestMove(BranchTracker::Color::BLACK_PIECE);
std::vector <Board> validMoves {nextMove};
std::string boardToWrite = validMoves[0].getBoardStateString();
SECTION ("Move Generated") {
REQUIRE(validMoves.size() == 1);
SECTION ("Valid Move Generated") {
SECTION ("Wrote all pieces") {
REQUIRE (boardToWrite.size() == first_board.size());
}
SECTION ("Didn't move red") {
REQUIRE (boardToWrite.substr(0, 13) == first_board.substr(0, 13));
}
SECTION ("Moved white") {
REQUIRE(boardToWrite.substr(13, 32) != first_board.substr(13,32));
}
SECTION ("Valid Piece Count") {
REQUIRE(validMoves[0].getRedPieceCount() == 12);
REQUIRE(validMoves[0].getBlackPieceCount() == 12);
REQUIRE(validMoves[0].getRedKingCount() == 0);
REQUIRE(validMoves[0].getBlackKingCount() == 0);
}
}
}
SECTION ("Timing") {
SECTION ("Within time limit") {
WeightedNode timedWeights;
timedWeights.kingingWeight = 0.5;
timedWeights.qualityWeight = 0.5;
timedWeights.availableMovesWeight = 0.5;
timedWeights.riskFactor = 0.5;
timedWeights.enemyFactor = 0.5;
SECTION ("DEPTH OF 2") {
timedWeights.depth = 2;
MoveGenerator::totalMoveGens = 0;
auto startWeightTwo = system_clock::now();
BranchTracker potentialBranch(initBoard, timedWeights);
Board nextMove = potentialBranch.getBestMove(BranchTracker::Color::BLACK_PIECE);
auto endWeightTwo = system_clock::now();
duration<double> elapsedMoveGenTime = endWeightTwo - startWeightTwo;
REQUIRE (elapsedMoveGenTime.count() < 10);
SECTION ("Boards Per Second >= 100,000") {
double bps = MoveGenerator::totalMoveGens/elapsedMoveGenTime.count();
REQUIRE (bps >= 100000.0);
}
}
SECTION ("DEPTH OF 3") {
timedWeights.depth = 3;
MoveGenerator::totalMoveGens = 0;
auto startWeightTwo = system_clock::now();
BranchTracker potentialBranch(initBoard, timedWeights);
Board nextMove = potentialBranch.getBestMove(BranchTracker::Color::BLACK_PIECE);
auto endWeightTwo = system_clock::now();
duration<double> elapsedMoveGenTime = endWeightTwo - startWeightTwo;
REQUIRE (elapsedMoveGenTime.count() < 10);
SECTION ("Boards Per Second >= 100,000") {
REQUIRE (MoveGenerator::totalMoveGens/elapsedMoveGenTime.count() >= 100000);
}
}
SECTION ("DEPTH OF 5") {
timedWeights.depth = 5;
MoveGenerator::totalMoveGens = 0;
auto startWeightTwo = system_clock::now();
BranchTracker potentialBranch(initBoard, timedWeights);
Board nextMove = potentialBranch.getBestMove(BranchTracker::Color::BLACK_PIECE);
auto endWeightTwo = system_clock::now();
duration<double> elapsedMoveGenTime = endWeightTwo - startWeightTwo;
REQUIRE (elapsedMoveGenTime.count() < 10);
SECTION ("Boards Per Second >= 100,000") {
REQUIRE (MoveGenerator::totalMoveGens/elapsedMoveGenTime.count() >= 100000);
}
}
}
}
}
SECTION ("AI goes first as red") {
IOHandler ioHandler(true);
std::ofstream firstHandshakeWriter (ioHandler.getFirstHandshakeLocation());
firstHandshakeWriter << 0;
firstHandshakeWriter.flush();
ioHandler.startGame(ioHandler.setupGame());
std::ifstream checkHandshake(ioHandler.getSecondHandshakeLocation());
int handshakeCheck = -1;
checkHandshake >> handshakeCheck;
SECTION ("Valid Handshake") {
REQUIRE(handshakeCheck == 1);
}
}
}
| true |
8dec23fcc8eb910f3eadc86f8410099c5a2bd394 | C++ | aqfaridi/Competitve-Programming-Codes | /SPOJ/PARTY.cpp | UTF-8 | 1,531 | 2.703125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define MAX 2010
typedef unsigned long long int LL;
using namespace std;
int w[MAX],v[MAX];
int main()
{
int W,n,K;
while(1)
{
scanf("%d %d",&W,&n);
if(W==0 && n==0)
break;
for(int i=1;i<=n;i++)
scanf("%d %d",&w[i],&v[i]);
LL V[n+1][W+1],sum;
bool keep[n+1][W+1];
for(int j=0;j<=W;j++)
V[0][j] = 0;
for(int i=0;i<=n;i++)
V[i][0] = 0;
for(int i=1;i<=n;i++)//choosing i items for capacity j
{
for(int j=1;j<=W;j++)
{
if((w[i] <= j) && (v[i]+V[i-1][j-w[i]] >= V[i-1][j]))// w[i]<=j we choose ith item :::: j is subproblem limit
{
V[i][j] = v[i] + V[i-1][j-w[i]];
keep[i][j] = 1;
}
else
{
V[i][j] = V[i-1][j];
keep[i][j] = 0;
}
//cout<<V[i][j]<<" ";
}
//cout<<endl;
}
/**
K = W ;
sum = 0;
for(int i=n;i>=1;i--)
{
if(keep[i][K]==1)
{
sum += w[i] ;
K = K - w[i] ;
}
}**/
//dont need to keep track of all the choosen items
//in this question we have to only find out the minimum budget
//which give maximum fun
int i,best;
for( i=W,best=V[n][W];i>0;i--)
if(V[n][i] < best)
break;
cout<<i+1<<" "<<V[n][W]<<endl;
}
return 0;
}
| true |
da68f8d38d47f35149f06a6ff57a98939ad7a060 | C++ | davidvodnik/OptionalCoroutine | /src/optional_coroutine.h | UTF-8 | 1,417 | 3 | 3 | [] | no_license | #include <experimental/coroutine>
#include <optional>
template<typename T>
struct OptionalPromise {
auto initial_suspend() {
return std::experimental::suspend_never();
}
auto final_suspend() {
return std::experimental::suspend_never();
}
void unhandled_exception() {}
struct ReturnObject {
ReturnObject(OptionalPromise& promise) : promise_(promise) {}
operator std::optional<T>() {
return promise_.optional_;
}
OptionalPromise& promise_;
};
auto get_return_object() {
return ReturnObject(*this);
}
template<typename U>
struct Awaitable {
Awaitable(const std::optional<U>& optional) : optional_(optional) {}
bool await_ready() {
return false;
}
bool await_suspend(...) {
return !optional_;
}
auto await_resume() {
return optional_.value();
}
const std::optional<U>& optional_;
};
template<typename U>
auto await_transform(const std::optional<U>& optional) {
return Awaitable<U>(optional);
}
template<typename U>
void return_value(U value) {
optional_ = value;
}
std::optional<T> optional_;
};
template<typename T, typename... Args>
struct std::experimental::coroutine_traits<std::optional<T>, Args...> {
using promise_type = OptionalPromise<T>;
};
| true |
f5dd4e59cb060dbca1c99a47c35fb9e8f0ffb8b6 | C++ | AshrafTasin/UVA_ | /136-Ugly Numbers.cpp | UTF-8 | 732 | 2.53125 | 3 | [] | no_license | /*----------------------|
/ Author : Ashraf Tasin |
/ Date : 10.09.18 |
/----------------------*/
#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define ll long long
#define all v.begin(),v.end()
#define M it=m.begin(),it!=m.end(),it++
#define db double
#define show for(int i=0;i<v.size();i++) cout << v[i] << " ";
using namespace std;
int main()
{
ll i;
int counter=1;
for(i=2;;i++)
{
ll p=i;
if(p%2==0) while(p%2==0) p/=2;
if(p%3==0) while(p%3==0) p/=3;
if(p%5==0) while(p%5==0) p/=5;
if(p==1) counter++;
if(counter==1500) break;
}
// cout << "The 1500'th ugly number is 859963392." << endl;
cout << i << endl;
return 0;
}
| true |
da35389cd72cab07f21222943464b58cfc87371c | C++ | novikov-ilia-softdev/thinking_cpp | /tom_2/chapter_01/06/main.cpp | UTF-8 | 394 | 3.28125 | 3 | [] | no_license | #include <iostream>
class MyClass{
public:
MyClass()
{
std::cout << "MyClass::MyClass" << std::endl;
}
~MyClass()
{
std::cout << "MyClass::~MyClass" << std::endl;
throw 5;
}
};
int main()
{
try
{
MyClass* myClassPtr = new MyClass;
delete myClassPtr;
}
catch( ...)
{
std::cout << "exception!" << std::endl;
MyClass* myClassPtr = new MyClass;
delete myClassPtr;
}
}
| true |
6dcc9359a6b2b07f497b000d96e8b7ed2fbbd0d1 | C++ | IlyaOvodov/tensorflow-cc-inference | /lib/Inference.cc | UTF-8 | 3,147 | 2.875 | 3 | [
"MIT"
] | permissive | #include <fstream>
#include <sstream>
#include <exception>
#include "tensorflow_cc_inference/Inference.h"
using tensorflow_cc_inference::Inference;
/**
* Read a binary protobuf (.pb) buffer into a TF_Buffer object.
*
* Non-binary protobuffers are not supported by the C api.
* The caller is responsible for freeing the returned TF_Buffer.
*/
TF_Buffer* Inference::ReadBinaryProto(const std::string& fname) const
{
std::ostringstream content;
std::ifstream in(fname, std::ios::in | std::ios::binary); // | std::ios::binary ?
if(!in.is_open())
{
throw std::runtime_error("Unable to open file: " + std::string(fname));
}
// convert the whole filebuffer into a string
content << in.rdbuf();
std::string data = content.str();
return TF_NewBufferFromString(data.c_str(), data.length());
}
/**
* Tensorflow does not throw errors but manages runtime information
* in a _Status_ object containing error codes and a failure message.
*
* AssertOk throws a runtime_error if Tensorflow communicates an
* exceptional status.
*
*/
void Inference::AssertOk(const TF_Status* status) const
{
if(TF_GetCode(status) != TF_OK)
{
throw std::runtime_error(TF_Message(status));
}
}
/**
* Load a protobuf buffer from disk,
* recreate the tensorflow graph and
* provide it for inference.
*/
Inference::Inference(
const std::string& binary_graphdef_protobuffer_filename,
const std::string& input_node_name,
const std::string& output_node_name)
{
// init the 'trival' members
TF_Status* status = TF_NewStatus();
graph = TF_NewGraph();
// create a bunch of objects we need to init graph and session
TF_Buffer* graph_def = ReadBinaryProto(binary_graphdef_protobuffer_filename);
TF_ImportGraphDefOptions* opts = TF_NewImportGraphDefOptions();
TF_SessionOptions* session_opts = TF_NewSessionOptions();
// import graph
TF_GraphImportGraphDef(graph, graph_def, opts, status);
AssertOk(status);
// and create session
session = TF_NewSession(graph, session_opts, status);
AssertOk(status);
// prepare the constants for inference
// input
input_op = TF_GraphOperationByName(graph, input_node_name.c_str());
input = {input_op, 0};
// output
output_op = TF_GraphOperationByName(graph, output_node_name.c_str());
output = {output_op, 0};
// Clean Up all temporary objects
TF_DeleteBuffer(graph_def);
TF_DeleteImportGraphDefOptions(opts);
TF_DeleteSessionOptions(session_opts);
TF_DeleteStatus(status);
}
Inference::~Inference()
{
TF_Status* status = TF_NewStatus();
// Clean up all the members
TF_CloseSession(session, status);
TF_DeleteGraph(graph);
//TF_DeleteSession(session); // TODO: delete session?
TF_DeleteStatus(status);
// input_op & output_op are delete by deleting the graph
}
TF_Tensor* Inference::operator()(TF_Tensor* input_tensor) const
{
TF_Status* status = TF_NewStatus();
TF_Tensor* output_tensor;
TF_SessionRun(session, nullptr,
&input, &input_tensor, 1,
&output, &output_tensor, 1,
&output_op, 1,
nullptr, status);
AssertOk(status);
TF_DeleteStatus(status);
return output_tensor;
}
| true |
1182aba9a118c6f62edf14de667b6de7d093b954 | C++ | Waseem-Akram7/PGJQP_Waseem | /greater of two.cpp | UTF-8 | 328 | 3.671875 | 4 | [] | no_license | #include<iostream>
using namespace std;
class greateroftwo
{
int num1,num2;
public:void number()
{
cout<<"Enter the numbers";
cin>>num1>>num2;
if(num1>num2)
{
cout<<"NUM1 is greater";
}
else
{
cout<<"Num2 is greater";
}
}
};
int main()
{
greateroftwo num;
num.number();
}
| true |
943394625a4a2959cee3f00071f45c21930e779e | C++ | sergeyampo/Incoming-Stock | /Good.h | UTF-8 | 182 | 2.71875 | 3 | [] | no_license | #ifndef GOOD_H
#define GOOD_H
#include <string>
//Товар, содержащий наименование и цену.
struct Good{
std::string name;
float price;
};
#endif | true |
632087d2b92173c1bc6eb8a4787bb9f5de64296c | C++ | soumy47/Data-Structures-Algorithms-in-C | /algorithm/5872. Number of Pairs of Strings With Concatenation Equal to Target.cpp | UTF-8 | 942 | 3.5625 | 4 | [
"MIT"
] | permissive | Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.
#include<bits/stdc++.h>
using namespace std;
int numOfPairs(vector<string>& nums, string target) {
int n = nums.size();
int count = 0;
for(int i=0; i< n; i++)
{
for(int j =0; j<n ; j++)
{
if(i!=j)
{
string ans = nums[i] + nums[j];
if(ans == target)
count++;
}
}
}
return count;
}
int main()
{
int n;
cin>>;
string arr[n];
for(int i=0; i< n ; i++)
cin>>a[i];
string target;
cin>>target;
cout<<"The no. of distinct pairs :"<<numOfPairs(a, target);
return 0;
}
| true |
14409d20c3704910c0951fc9d23ed55cbfd85328 | C++ | zxycode007/Sapphire2 | /Core/Mutex.h | GB18030 | 683 | 3.0625 | 3 | [] | no_license | #pragma once
#include "Sapphire.h"
namespace Sapphire
{
///
class SAPPHIRE_API Mutex
{
public:
Mutex();
~Mutex();
// õ壬Ѿõ
void Acquire();
/// ͷŻ
void Release();
private:
///
void* handle_;
};
// ԶúͷŻ
class SAPPHIRE_API MutexLock
{
public:
/// 첢û
MutexLock(Mutex& mutex);
/// ͷŻ
~MutexLock();
private:
/// ֹ캯
MutexLock(const MutexLock& rhs);
/// ֵֹ
MutexLock& operator =(const MutexLock& rhs);
///
Mutex& mutex_;
};
} | true |
302285be6be1c0d36d7a0e2b270222f9e4b74b95 | C++ | ZhongZeng/Leetcode | /lc148sortLst.cpp | UTF-8 | 2,279 | 3.46875 | 3 | [] | no_license |
/*
Leetcode 148. Sort List
Related Topics
Linked List, Sort
Similar Questions
Merge Two Sorted Lists, Sort Colors, Insertion Sort List
Next challenges: Insert Interval,
Convert Sorted List to Binary Search Tree, Reorganize String
Test Cases:
[1,6,2,5,7,3,4]
[]
Runtime: 61 ms
Your runtime beats 18.80 % of cpp submissions.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
// merge sort; note add/deletion/ time complexity of list differs from vector
if(!head) return head;
int len=0;
ListNode * st=head;
while(st){
len++;
st=st->next;
}
st=mergeSort(head, len);
head=st;
for(int i=0; i<len-1; i++) st=st->next;
st->next=NULL;
return head;
}
ListNode* mergeSort(ListNode* ls, int len){
if(len<2) return ls;
ListNode * lt=ls;
int mid=len>>1;
for(int i=0; i<mid; i++) lt=lt->next;
ls=mergeSort(ls, mid);
lt=mergeSort(lt, len-mid);
return mergeList(ls, mid, lt, len-mid);;
}
ListNode* mergeList(ListNode* ls, int len1, ListNode* lt, int len2){
// merge sorted list
ListNode * rt, * st;// node to return, last node
int i=0, j=0;
if(ls->val<lt->val){
rt=ls;
ls=ls->next;
i++;
}else{
rt=lt;
lt=lt->next;
j++;
}
st=rt;
while( i<len1&&j<len2 ){
//cout<<st->val<<" ";
if(ls->val<lt->val){
st->next=ls;
st=ls;
ls=ls->next;
i++;
}else{
st->next=lt;
st=lt;
lt=lt->next;
j++;
}
}
//cout<<endl;
if(j==len2) st->next=ls;
else st->next=lt;
return rt;// what left beyond the end doesn't matter
}
};
| true |
b8db4284299f8be210af62a0a366c8541ceb94e7 | C++ | Mniek/project | /ProjektMapa/randomCityGene.cpp | UTF-8 | 529 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include <random>
#include <string>
using namespace std;
string randomCity( size_t length)
{
static const string alphabet = "abcdefghijklmnopqrstuvwxyz";
static default_random_engine randomCity(time(nullptr));
static uniform_int_distribution<size_t>distribution(0,alphabet.size()-1);
string city;
while(city.size()<length)
{
city += alphabet[distribution(randomCity)];
return city;
}
}
int main()
{
for(size_t i = 10 ; i < 40 ; i += 3 ) cout << randomCity(i);
}
| true |
46f4597609468d1d61d12f665a89b86103960a34 | C++ | opendarkeden/server | /src/Core/CGBuyStoreItem.h | UHC | 2,597 | 2.90625 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////////
// Filename : CGBuyStoreItem.h
// Written By : 輺
// Description :
// ÷̾ NPC â , ϰ
// Ŷ̴. ÷̾ κ丮
// ڸ ִ , ÷̾ ѱ.
////////////////////////////////////////////////////////////////////////////////
#ifndef __CG_BUY_STORE_ITEM_H__
#define __CG_BUY_STORE_ITEM_H__
#include "Packet.h"
#include "PacketFactory.h"
////////////////////////////////////////////////////////////////////////////////
//
// class CGBuyStoreItem;
//
////////////////////////////////////////////////////////////////////////////////
class CGBuyStoreItem : public Packet
{
public:
CGBuyStoreItem() {};
~CGBuyStoreItem() {};
void read(SocketInputStream & iStream) ;
void write(SocketOutputStream & oStream) const ;
void execute(Player* pPlayer) ;
PacketID_t getPacketID() const { return PACKET_CG_BUY_STORE_ITEM; }
PacketSize_t getPacketSize() const { return szObjectID+szObjectID+szBYTE; }
string getPacketName() const { return "CGBuyStoreItem"; }
string toString() const ;
public:
ObjectID_t getOwnerObjectID() { return m_OwnerObjectID; }
void setOwnerObjectID(ObjectID_t ObjectID) { m_OwnerObjectID = ObjectID; }
ObjectID_t getItemObjectID() { return m_ItemObjectID; }
void setItemObjectID(ObjectID_t ObjectID) { m_ItemObjectID = ObjectID; }
BYTE getIndex(void) const { return m_Index; }
void setIndex(BYTE index) { m_Index = index;}
private:
ObjectID_t m_OwnerObjectID;
ObjectID_t m_ItemObjectID;
BYTE m_Index;
};
////////////////////////////////////////////////////////////////////////////////
//
// class CGBuyStoreItemFactory;
//
////////////////////////////////////////////////////////////////////////////////
class CGBuyStoreItemFactory : public PacketFactory
{
public:
Packet* createPacket() { return new CGBuyStoreItem(); }
string getPacketName() const { return "CGBuyStoreItem"; }
PacketID_t getPacketID() const { return Packet::PACKET_CG_BUY_STORE_ITEM; }
PacketSize_t getPacketMaxSize() const { return szObjectID+szObjectID+szBYTE; }
};
////////////////////////////////////////////////////////////////////////////////
//
// class CGBuyStoreItemHandler;
//
////////////////////////////////////////////////////////////////////////////////
class CGBuyStoreItemHandler
{
public:
static void execute(CGBuyStoreItem* pPacket, Player* player) ;
};
#endif
| true |
29ee65ce669f3d4fe0edcd9527f2193c70f47ee1 | C++ | Lacty/2DCollisionToTexture | /src/shape.hpp | UTF-8 | 202 | 2.9375 | 3 | [] | no_license |
#pragma once
template<typename T>
class Rect {
public:
T l, r, t, b;
Rect(T l, T r, T t, T b) : l(l), r(r), t(t), b(b) {}
Rect(const Rect& src) : l(src.l), r(src.r), t(src.t), b(src.b) {}
}; | true |
f4f3bf1985592a43193e4ec5189a81efd20e37d7 | C++ | wailo/orderbook-matching-engine | /test/market_test.cpp | UTF-8 | 8,128 | 2.953125 | 3 | [] | no_license | //Link to Boost
#define BOOST_TEST_DYN_LINK
//Define our Module name (prints at testing)
#define BOOST_TEST_MODULE "BaseClassModule"
#include "matchingEngine.hpp"
#include "trader.hpp"
#include "orderBook.hpp"
#include <boost/test/unit_test.hpp>
// dummy representation of order contracts
enum contract { IBM, APPLE };
BOOST_AUTO_TEST_CASE(adding_valid_orders)
{
using namespace market;
matchingEngine _market;
auto _traderA = _market.addTrader();
auto _traderB = _market.addTrader();
_traderA->sendOrder(IBM, 100, 12.30, orderSide::BUY );
_traderA->sendOrder(IBM, 100, 12.30, orderSide::SELL );
BOOST_CHECK_EQUAL(_market.getOrderManagement().totalVolume(), 200);
}
BOOST_AUTO_TEST_CASE(adding_invalid_orders)
{
using namespace market;
matchingEngine _market;
auto _traderA = _market.addTrader();
_traderA->sendOrder(IBM, -10, 12.30, orderSide::BUY );
_traderA->sendOrder(IBM, -10, 12.30, orderSide::SELL );
BOOST_CHECK_EQUAL(_market.getOrderManagement().totalVolume(), 0);
}
BOOST_AUTO_TEST_CASE(matching_orders_no_cross_price)
{
using namespace market;
matchingEngine _market;
auto _traderA = _market.addTrader();
auto _traderB = _market.addTrader();
_traderA->sendOrder(IBM, 100, 12.29, orderSide::BUY );
_traderB->sendOrder(IBM, 100, 12.30, orderSide::SELL );
_market.close();
BOOST_CHECK_EQUAL(_market.getOrderManagement().totalTradedVolume(), 0);
}
BOOST_AUTO_TEST_CASE(matching_orders_no_cross_contract)
{
using namespace market;
matchingEngine _market;
auto _traderA = _market.addTrader();
auto _traderB = _market.addTrader();
_traderA->sendOrder(IBM, 100, 12.30, orderSide::BUY );
_traderB->sendOrder(APPLE, 100, 12.30, orderSide::SELL );
_market.close();
BOOST_CHECK_EQUAL(_market.getOrderManagement().totalTradedVolume(), 0);
}
BOOST_AUTO_TEST_CASE(matching_orders_cross_contract)
{
for (unsigned int i=0; i < 1; i++)
{
using namespace market;
matchingEngine _market;
auto _traderA = _market.addTrader();
auto _traderB = _market.addTrader();
_traderA->sendOrder(IBM, 100, 12.30, orderSide::BUY );
_traderB->sendOrder(APPLE, 100, 12.30, orderSide::SELL );
_traderA->sendOrder(APPLE, 100, 12.30, orderSide::BUY );
_traderB->sendOrder(IBM, 100, 12.30, orderSide::SELL );
_market.close();
BOOST_CHECK_EQUAL(_market.getOrderManagement().totalTradedVolume(), 200);
}
}
BOOST_AUTO_TEST_CASE(matching_orders_cross)
{
for (int i=0; i<100; i++)
{
using namespace market;
matchingEngine _market;
auto _traderA = _market.addTrader();
auto _traderB = _market.addTrader();
_traderA->sendOrder(IBM, 100, 12.30, orderSide::BUY );
_traderB->sendOrder(IBM, 100, 12.30, orderSide::SELL );
_market.close();
BOOST_CHECK_EQUAL(_market.getOrderManagement().totalTradedVolume(), 100);
}
}
BOOST_AUTO_TEST_CASE(orders_example_from_the_task)
{
/*
Order 1 Buy 100@12.30
Order 2 Buy 25@12:15
Order 3 Buy 10@12.20
Order 4 Sell 115@12.17
*/
using namespace market;
matchingEngine _market;
auto _traderA = _market.addTrader();
auto _traderB = _market.addTrader();
_traderA->sendOrder(IBM, 100, 12.30, orderSide::BUY );
_traderA->sendOrder(IBM, 25, 12.15, orderSide::BUY );
_traderA->sendOrder(IBM, 10, 12.20, orderSide::BUY );
_traderB->sendOrder(IBM, 115, 12.17, orderSide::SELL );
_market.close();
BOOST_CHECK_EQUAL(_market.getOrderManagement().totalTradedVolume(), 110);
}
BOOST_AUTO_TEST_CASE(order_updates_test)
{
/*
Order 1 Buy 100@12.30
Order 2 Buy 25@12:15
Order 3 Buy 10@12.20
Order 4 Sell 115@12.17
*/
using namespace market;
matchingEngine _market;
auto _traderA = _market.addTrader();
auto _traderB = _market.addTrader();
auto _executedOrdersVolume = 0;
_traderA->setOnOrderExecutionCallBack([&](const tradeData& p_tradeData) {
_executedOrdersVolume += p_tradeData.m_tradedVolume;
});
_traderA->sendOrder(IBM, 100, 12.30, orderSide::BUY );
_traderA->sendOrder(IBM, 25, 12.15, orderSide::BUY );
_traderA->sendOrder(IBM, 10, 12.20, orderSide::BUY );
_traderB->sendOrder(IBM, 115, 12.17, orderSide::SELL );
_market.close();
BOOST_CHECK_EQUAL(_executedOrdersVolume, 110);
BOOST_CHECK_EQUAL(_market.getOrderManagement().totalTradedVolume(), 110);
}
BOOST_AUTO_TEST_CASE(public_trades_test)
{
/*
Order 1 Buy 100@12.30
Order 2 Buy 25@12:15
Order 3 Buy 10@12.20
Order 4 Sell 115@12.17
*/
using namespace market;
matchingEngine _market;
auto _traderA = _market.addTrader();
auto _traderB = _market.addTrader();
auto _traderC = _market.addTrader();
auto _executedOrdersVolume = 0;
_traderC->setOnPublicTradeCallBack([&](const tradeData& p_tradeData) {
_executedOrdersVolume += p_tradeData.m_tradedVolume;
});
_traderA->sendOrder(IBM, 100, 12.30, orderSide::BUY );
_traderA->sendOrder(IBM, 25, 12.15, orderSide::BUY );
_traderA->sendOrder(IBM, 10, 12.20, orderSide::BUY );
_traderB->sendOrder(IBM, 115, 12.17, orderSide::SELL );
_market.close();
BOOST_CHECK_EQUAL(_executedOrdersVolume, 110);
BOOST_CHECK_EQUAL(_market.getOrderManagement().totalTradedVolume(), 110);
}
BOOST_AUTO_TEST_CASE(order_book_test)
{
/*
Order 1 Buy 100@12.30
Order 2 Buy 25@12:15
Order 3 Buy 10@12.20
Order 4 Sell 115@12.17
*/
using namespace market;
matchingEngine _market;
auto _traderA = _market.addTrader();
auto _traderB = _market.addTrader();
auto _orderBookTotalBuyPrice = 0;
auto _orderBookTotalSellPrice = 0;
auto _orderBookTotalBuyVolume = 25;
auto _orderBookTotalSellVolume = 5;
_traderA->setOnOrderBookCallBack([&](const orderBook& p_orderBook) {
auto buys = p_orderBook.getBuyOrders();
auto sells = p_orderBook.getSellOrders();
_orderBookTotalBuyVolume = 0;
_orderBookTotalBuyPrice = 0;
_orderBookTotalSellVolume = 0;
_orderBookTotalSellPrice = 0;
for ( const auto& b : buys )
{
// std::cout << b << std::endl;
_orderBookTotalBuyPrice += b.price();
_orderBookTotalBuyVolume += b.volume();
}
for ( const auto& s : sells )
{
// std::cout << s << std::endl;
_orderBookTotalSellPrice += s.price();
_orderBookTotalSellVolume += s.volume();
}
});
_traderA->sendOrder(IBM, 100, 12.30, orderSide::BUY );
_traderA->sendOrder(IBM, 25, 12.15, orderSide::BUY );
_traderA->sendOrder(IBM, 10, 12.20, orderSide::BUY );
_traderB->sendOrder(IBM, 115, 12.17, orderSide::SELL );
_market.close();
BOOST_CHECK_EQUAL(_orderBookTotalBuyVolume, 25);
BOOST_CHECK_EQUAL(_orderBookTotalBuyPrice, 1215);
BOOST_CHECK_EQUAL(_orderBookTotalSellVolume, 5);
BOOST_CHECK_EQUAL(_orderBookTotalSellPrice, 1217);
}
BOOST_AUTO_TEST_CASE(stress_test)
{
using namespace market;
matchingEngine _market;
unsigned int n = 1000;
for (unsigned int i=0; i<n; ++i )
{
auto _traderA = _market.addTrader();
_traderA->sendOrder(IBM, 100, 12.30, orderSide::BUY );
auto _traderB = _market.addTrader();
_traderB->sendOrder(IBM, 100, 12.30, orderSide::SELL );
}
_market.close();
BOOST_CHECK_EQUAL(_market.getOrderManagement().totalVolume(), 2*n*100);
BOOST_CHECK_EQUAL(_market.getOrderManagement().totalTradedVolume(), n*100);
}
BOOST_AUTO_TEST_CASE(multi_thread_test)
{
using namespace market;
matchingEngine _market;
unsigned int n = 1000;
unsigned int i=0; // j=0;
auto _traderA = _market.addTrader();
auto _traderB = _market.addTrader();
std::thread producer([ & ] {
while (i++ < n) {
_traderA->sendOrder(IBM, 100, 12.30, orderSide::SELL );
_traderB->sendOrder(IBM, 100, 12.30, orderSide::BUY );
}
});
producer.join();
// wait for the order Management to finish matching orders
auto w = 5000000;
while (w--) {}
BOOST_CHECK_EQUAL(_market.getOrderManagement().totalVolume(), 2*n*100);
BOOST_CHECK_EQUAL(_market.getOrderManagement().totalTradedVolume(), n*100);
}
| true |
5905bb271cc749dd85eb5e416c2c96e691885510 | C++ | Satzyakiz/CP | /Array/Segmented_Sieve_Prime_Nos.cpp | UTF-8 | 633 | 2.921875 | 3 | [] | no_license | // Generate all prime numbers between two given numbers.
// Input:
// 2
// 1 10
// 3 5
// Output:
// 2 3 5 7
// 3 5
#include<bits/stdc++.h>
using namespace std;
int sieve[100001];
void solve(){
int s,e;
cin>>s>>e;
for(int i=s; i<=e; i++){
if(sieve[i] == 0)
cout<<i<<" ";
}
cout<<endl;
}
void initialize(){
sieve[0] = sieve[1] = 1;
for(int i=2; i*i<100001; i++){
if(sieve[i] == 0)
for(int j=i*i; j<=1e5; j+=i){
sieve[j] = 1;
}
}
}
int main(){
initialize();
int t;
cin>>t;
while(t--)
solve();
return 0;
}
| true |
c7dfe6be8209cf2a1de9416055808de2374c17b6 | C++ | P-compete/Trees | /Sum_tree.cpp | UTF-8 | 476 | 3.046875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct node
{ int data;
node *left,*right;
node(int item)
{
data=item;
left=NULL;
right=NULL;
}
};
int sum(node *t)
{
if(t==NULL){return 0;}
int old=t->data;
t->data=sum(t->left)+sum(t->right);
return t->data+old;
}
int main()
{
node *root=new node(1);
root->left=new node(3);
root->right=new node(2);
root->left->left=new node(5);
root->right->left=new node(4);
sum(root);
return 0;
}
| true |
500d58dc110954d5f5d93d80ec49f49dc3ff60e0 | C++ | xczhang07/leetcode | /cpp/middle/fraction_to_recurring_decimal.cpp | UTF-8 | 900 | 2.875 | 3 | [] | no_license | class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if(numerator == 0) return "0";
if(!denominator) return "";
string ret;
if((numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0))
ret = "-" + ret;
long n = abs((long)numerator);
long d = abs((long)denominator);
long rest = n%d;
ret = ret + to_string(n/d);
if(!rest)
return ret;
ret.push_back('.');
unordered_map<long, int> m;
while(rest)
{
if(m.count(rest))
{
ret.insert(m[rest],"(");
ret.push_back(')');
return ret;
}
m[rest] = ret.size();
rest *= 10;
ret = ret + to_string(rest/d);
rest %= d;
}
return ret;
}
};
| true |
858e87fd513d955020a1e973bfc9df177e43958c | C++ | leoqingliu/StateGrid | /Public/IPC.h | UTF-8 | 334 | 2.625 | 3 | [] | no_license | #pragma once
class IPC
{
public:
IPC(void);
~IPC(void);
public:
BOOL Create(LPCTSTR pszName);
BOOL Open(LPCTSTR pszName);
VOID Close();
BOOL IsOpen(void) const {return (m_hFileMap != NULL);}
BOOL Read(LPBYTE pBuf, DWORD &dwBufSize);
BOOL Write(const LPBYTE pBuf, const DWORD dwBufSize);
protected:
HANDLE m_hFileMap;
};
| true |
981d6fa424eefd6bb331fea23d4dfa36df3bfce8 | C++ | Laz-berry/Sensor_Robot_ROS | /my_publisher_class/src/my_publisher_class.cpp | UTF-8 | 3,017 | 2.953125 | 3 | [] | no_license | #include <my_publisher_class.hpp>
namespace my_publisher_class
{
MyPublisherClass::MyPublisherClass() : private_nh("~")
{
//launch file parameter
if(!private_nh.getParam("param_int", param_int_)) throw std::runtime_error("fail to get param_int");
if(!private_nh.getParam("param_float", param_float_)) throw std::runtime_error("fail to get param_float");
if(!private_nh.getParam("param_string", param_string_)) throw std::runtime_error("fail to get param_string");
if(!nh.getParam("/my_publisher_class/param_int", param_int_nh_)) throw std::runtime_error("fail to get param_int");
if(!nh.getParam("/my_publisher_class/param_float", param_float_nh_)) throw std::runtime_error("fail to get param_float");
if(!nh.getParam("/my_publisher_class/param_string", param_string_nh_)) throw std::runtime_error("fail to get param_string");
std::cout << "===== getParam using private_nh ======" << std::endl;
std::cout << param_int_ << " , " << param_float_ << " , " << param_string_ << std::endl;
std::cout << "===== getParam using nh ======" << std::endl;
std::cout << param_int_nh_ << " , " << param_float_nh_ << " , " << param_string_nh_ << std::endl;
std::cout << "===== finish setting parameter =====" << std::endl;
pub_rand_int_ = nh.advertise<std_msgs::Int32>("/my_first_topic", 100);
pub_class_msg_ = nh.advertise<my_publisher_class::class_msg>("/my_first_msg", 100);
srand((unsigned int)time(NULL));
}
MyPublisherClass::~MyPublisherClass()
{
}
void MyPublisherClass::run()
{
// Int32
// my_data_int_.data = makeRandInt();
my_data_int_.data = param_int_;
// float_data
//class_msg_.float_data.data = makeRandFloat();
class_msg_.float_data.data = param_float_;
// string data
//class_msg_.string_data.data = makeString();
class_msg_.string_data.data = param_string_;
pub_rand_int_.publish(my_data_int_);
pub_class_msg_.publish(class_msg_);
std::cout << "my_publisher node publishes [ " << my_data_int_.data << " ] and [ "
<< class_msg_.float_data.data << " , " << class_msg_.string_data.data << " ] " << std::endl;
}
int MyPublisherClass::makeRandInt()
{
int rand_int;
rand_int = rand() % 100;
return rand_int;
}
float MyPublisherClass::makeRandFloat()
{
float rand_float;
rand_float = (rand() % 100) / 7.0;
return rand_float;
}
std::string MyPublisherClass::makeString()
{
std::string ss;
ss = "sensor motion robot engineer";
return ss;
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "my_publisher");
my_publisher_class::MyPublisherClass MPC;
ros::Rate loop_rate(10);
while(ros::ok())
{
MPC.run();
ros::spinOnce();
loop_rate.sleep();
}
} | true |
450149bcf6a5e0bac80003e19aa9b4b224bbd134 | C++ | vivia1994/SummerTest5 | /VIJOS-P1037/源.cpp | GB18030 | 1,300 | 3.109375 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
/*ڵiˮ 3
1
2Ÿ
3Ű
1.Ը
2.*/
int dp[105][20005]; //dp[i][j]ʾǰi,߶ȲΪj,ĸ߶ȡYYתƷ
int tmp[105];
int main()
{
int n;
cin >> n;
int sum = 0;
for (int i = 1; i <= n; i++)
{
cin>>tmp[i];
sum += tmp[i];
}
memset(dp, -1, sizeof(dp));
dp[0][0] = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 0; j <= sum; j++)
{
if (dp[i - 1][j] > -1) //1.ŵiˮ;
dp[i][j] = dp[i - 1][j];
if (tmp[i] > j && dp[i - 1][tmp[i] - j] > -1) //2.Žȥ䰫iڰˣ;
dp[i][j] = max(dp[i][j], dp[i - 1][tmp[i] - j] + j);
if (j + tmp[i] <= sum&&dp[i - 1][j + tmp[i]] > -1) //3.ŽȥԸߣiڰϣ;
dp[i][j] = max(dp[i][j], dp[i - 1][j + tmp[i]]);
if (j >= tmp[i] && dp[i - 1][j - tmp[i]] > -1) //4.Žȥߣiڸϣ.
dp[i][j] = max(dp[i][j], dp[i - 1][j - tmp[i]] + tmp[i]);
}
}
if (dp[n][0] > 0)
cout << dp[n][0] << endl;
else
cout << "Impossible" << endl;
return 0;
} | true |
0e50ea55549516377ffdf1ffe7ca214e5ef07c72 | C++ | fdoperezi/Thesis | /Code/Thesis/include/thesis/BoltzmannPolicy.h | UTF-8 | 4,837 | 2.546875 | 3 | [
"MIT"
] | permissive | /*
* Copyright (c) 2016 Pierpaolo Necchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef BOLTZMANNEXPLORATIONPOLICY_H
#define BOLTZMANNEXPLORATIONPOLICY_H
#include <thesis/StochasticPolicy.h> /* StochasticPolicy */
#include <armadillo> /* arma::vec */
#include <vector> /* std::vector */
#include <random>
/*!
* BoltzmannPolicy is a class that implements the Boltzmann stochastic policy
* for a finite action space. For further information, cf. Wiering, M. and Van
* Otterlo, M. - "Reinforcement learning." Adaptation, Learning, and
* Optimization 12 (2012).
*/
class BoltzmannPolicy : public StochasticPolicy
{
public:
/*!
* Constructor.
* Initialize a Boltzmann policy given the sizes of the observation
* space and a list of the possible actions that can be selected.
* \param dimObservation_ dimension of the observation space
* \param possibleActions_ vector of possible actions
*/
BoltzmannPolicy(size_t dimObservation_,
std::vector<double> possibleActions_);
//! Default destructor
virtual ~BoltzmannPolicy() = default;
//! Clone method for polymorphic clone
std::unique_ptr<StochasticPolicy> clone() const
{
return checkedClone<StochasticPolicy>();
}
/*!
* Get policy parameters size, i.e. size of the parameter vector
* \return parameters size
*/
virtual size_t getDimParameters() const { return dimParameters; }
/*!
* Get method for the policy parameters.
* \return parameters stored in an arma::vector
*/
virtual arma::vec getParameters() const;
/*!
* Set method for the policy parameters.
* \param parameters_ the new parameters stored in an arma::vector
*/
virtual void setParameters(arma::vec const ¶meters_);
/*!
* Given an observation, select an action accordind to the policy.
* \param observation_ observation
* \return action
*/
virtual arma::vec getAction(arma::vec const &observation_) const;
/*!
* Evaluate the Likelihood score function at a given observation and
* action.
* \param observation_ observation
* \param action_ action
* \return likelihood score evaluated at observation_ and action_
*/
virtual arma::vec likelihoodScore(arma::vec const &observation_,
arma::vec const &action_) const;
/*!
* Reset policy to initial conditions.
*/
virtual void reset();
private:
//! Virtual inner clone method
virtual std::unique_ptr<Policy> cloneImpl() const;
//! Initialize the Boltzmann policy parameters
void initializeParameters();
//! Possible actions
std::vector<double> possibleActions;
//! Number of possible actions
size_t numPossibleActions;
//! Number of parameters per action
size_t dimParametersPerAction;
//! Parameters size
size_t dimParameters;
//! Policy parameters: Theta = [ theta_1 | thetha_2 | ... | theta_D ]
arma::mat parametersMat;
arma::vec parametersVec; // Linearized matrix (shares memory)
/*!
* Boltzmann probability distribution and random number generator
* Need to be mutable because the generator state changes when
* simulating an action.
*/
mutable std::mt19937 generator;
mutable std::vector<double> boltzmannProbabilities;
// TODO: Consider generic features of the input
};
#endif // BOLTZMANNEXPLORATIONPOLICY_H
| true |
1423dd6e8347017f38f6fd002f4bda2233e46e54 | C++ | kpnaranj/Athabascau-c- | /Eckles examples/TMA1/TMA1Question4.cpp | WINDOWS-1258 | 3,811 | 3.828125 | 4 | [] | no_license | //: TMA1Question4.cpp
/*
Title: TMA1Question4.cpp
Description:
Write a program that creates an array of 100 string objects. Fill the array by
having your program open a (text) file and read one line of the file into each
string until you have filled the array. Display the array using the format
line #: <string>, where # is the actual line number (you can use the array
counter for this value) and <string> is the stored string.
Date: February 22, 2019
Author: Kevin P. Naranjo Paredes
Copyright: 2019 Kevin P. Naranjo Paredes
*/
/*
DOCUMENTATION
Program Purpose:
Measure understanding and proper use of arrays and for loops in external
documents
Also, determine the limits of arrays and store arrays in variables
Compile: g++ TMA1Question4.cpp -o TMA1Question4.exe
Execution: ./TMA1Question4.exe
Classes: none
functions:
printLine - void - function that prints out an array of 100 strings after being stored in
the variable
Variables:
printLine() Local variables - void parameters: string arrayLine [100]
arrayLine[100] - string - used to print out the information provided in the main() after
collecting information of text
i - unsigned int - used to run a for loop that will print out the number and the line of the
document
int main()
inputFile - iftream - used to store and open text file to text program
nLine - string - used to go throught the end of the document and count
the number of lines in the text file (next line)
arrayLine[100] - string - array used to store each line of the text
External files:
Text1 - txt - Text example used to test and compile program
Notes: We could add a header file, however; since the code is short, it was decided to maintain normal
convention
*/
/*
TEST PLAN
Normal case:
>(program is executed)
>"Line #1 Lorem Ipsum text"
>"Line #2 (Blank)"
>"Line #3 3 Lorem ipsum dolor sit amet, consectetur adipiscing elit."
>(after line finishes)
>"line #35 Duis sollicitudin gravida nisl, at condimentum risus malesuada cursus"
>"line #36 In mollis nec nisi sit amet interdum."
>"line #37 In mollis nec nisi sit amet interdum."
>(Fill out the array until you complete 100 strings)
>"line #100 In mollis nec nisi sit amet interdum. "
>"The array has been filled"
>"End of compilation"
Notes: There is not bad case since there is not input for the user to store negative values or random text
Discussion:
The program can compile and fill out 100 strings using a for loop to print out stored values of the document
The program could have had an additional option to stop once the program has reached the last line of the
document using a break statement, however; it might not complete the task of fill out the array as requested
in the exercise
The program can also work with .cpp documents
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//Declaration
void printValue (string arrayLine[100]);
//Definition
// Function that displays a number after lines are stored in the document
void printLine(string arrayLine[100]){
for(unsigned int i=0; i<100; i++){
cout<<"line #"<<i+1<<" "<<arrayLine[i]<<endl;
}
}
int main(){
ifstream inputFile("Test.txt");
string nLine;
// Based on program Arrays.cpp by Bruce Eckel, Chapter 03 and adapted to string inputs.
string arrayLine[100];
// For loop that stores a line at a time and fills the array
for(unsigned int i=0; i<100; i++){
getline(inputFile,nLine);
arrayLine[i]=nLine;
}
printLine (arrayLine);
cout<<"The array has been filled"<<endl;
cout<<"End of compilation"<<endl;
return 0;
}///:~ | true |
86a23f7983505519b65ff7f3b9d54dd11c85cdd2 | C++ | 15831944/src-1 | /TestDrive/UpVersion/UpVersion.cpp | UHC | 4,356 | 2.734375 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | #include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include <string>
#include <list>
using namespace std;
typedef list<string> LineList;
class CLineLink{
public:
char m_line[1024];
CLineLink* m_pNext;
CLineLink(void){m_pNext = NULL;}
~CLineLink(void){if(m_pNext) delete m_pNext;}
CLineLink* New(void){
if(m_pNext) return NULL;
m_pNext = new CLineLink;
return m_pNext;
}
};
class CLineMgr{
CLineLink* m_pLinefirst;
CLineLink* m_pLineCur;
public:
CLineMgr(void){
m_pLinefirst = NULL;
m_pLineCur = NULL;
}
~CLineMgr(void){
if(m_pLinefirst) delete m_pLinefirst;
m_pLineCur = NULL;
}
char* GetFirst(void){
m_pLineCur = m_pLinefirst;
if(!m_pLineCur) return NULL;
return m_pLineCur->m_line;
}
char* GetNext(void){
if(!m_pLineCur) return NULL;
m_pLineCur = m_pLineCur->m_pNext;
if(!m_pLineCur) return NULL;
return m_pLineCur->m_line;
}
char* New(void){
if(!m_pLinefirst){
m_pLinefirst = new CLineLink;
m_pLineCur = m_pLinefirst;
}else{
if(!m_pLineCur) return NULL;
m_pLineCur = m_pLineCur->New();
}
return m_pLineCur->m_line;
}
};
const char* g_sNumberTag[4]={"st", "nd", "rd", "th"};
int _tmain(int argc, _TCHAR* argv[])
{
FILE* fp;
char line_buf[4096];
char* pTok;
const char* pNumTag = NULL;
int version[4] = { 1,0,0,0 };
bool bMajorUpdate = false;
LineList LineMap;
if (argc == 3) {
if (!strcmp(argv[2], "major")) bMajorUpdate = true;
else
if (!strcmp(argv[2], "minor")) bMajorUpdate = false;
else {
printf("invalid argument : %s\n", argv[2]);
return 0;
}
} else if (argc != 2) {
printf("Version auto increaser\n\nUsage : UpVersion resource_file [major/minor]\n\nUpdate FILEVERSION/PRODUCTVERSION/VALUE \"FileVersion\"/VALUE \"ProductVersion\"/ID_PROJECT_VERSION");
return 0;
}
{
// read version
if (!(fp = fopen(argv[1], "rt"))) {
printf("Resource file is not existed\n");
return 0;
}
while(fgets(line_buf, 4095, fp) != NULL) {
char token_buf[4096];
strcpy(token_buf, line_buf);
pTok = strtok(token_buf, " \t");
if (pTok) {
if (!strcmp(pTok, "FILEVERSION")) {
for (int i = 0; i < 4; i++) {
version[i] = atoi(strtok(NULL, " ,\t\n\r"));
}
if (bMajorUpdate) {
version[2]++;
version[3] = 1;
}
else {
version[3]++;
}
sprintf(line_buf, " FILEVERSION %d,%d,%d,%d\n", version[0], version[1], version[2], version[3]);
pNumTag = g_sNumberTag[version[3] > 4 ? 3 : (version[3] - 1)];
}
else if (pNumTag) {
if (!strcmp(pTok, "PRODUCTVERSION")) {
sprintf(line_buf, " PRODUCTVERSION %d,%d,%d,%d\n", version[0], version[1], version[2], version[3]);
}
else if (!strcmp(pTok, "VALUE")) {
pTok = strtok(NULL, " ,\"\t");
if (!strcmp(pTok, "FileVersion")) {
sprintf(line_buf, " VALUE \"FileVersion\", \"%d.%d.%d - %d%s release\"\n", version[0], version[1], version[2], version[3], pNumTag);
}
else if (!strcmp(pTok, "ProductVersion")) {
sprintf(line_buf, " VALUE \"ProductVersion\", \"%d.%d.%d - %d%s release\"\n", version[0], version[1], version[2], version[3], pNumTag);
}
}
else if (!strcmp(pTok, "ID_PROJECT_VERSION")) {
sprintf(line_buf, " ID_PROJECT_VERSION \"%d.%d.%d - %d%s release\"\n", version[0], version[1], version[2], version[3], pNumTag);
}
}
}
// put text to buffer
LineMap.push_back(string(line_buf));
}
fclose(fp);
}
// print the new version
printf(" Ʈ : %d.%d.%d - %d%s release\n", version[0], version[1], version[2], version[3], pNumTag);
// write version
{
if (!(fp = fopen((char*)argv[1], "wt"))) {
printf("Can't open the resource file to write.\n");
return 0;
}
for(LineList::iterator i = LineMap.begin();i != LineMap.end(); i++){
fprintf(fp, (*i).c_str());
}
fclose(fp);
}
// save header file
{
FILE* fp = fopen("TestDriveVersion.h", "wb");
if(!fp){
printf("Can't open 'TestDriveVersion.h' file.\n");
return 0;
}
fprintf(fp,
"#ifndef __TESTDRIVE_VERSION_H__\r\n" \
"#define __TESTDRIVE_VERSION_H__\r\n" \
"\r\n" \
"#define TESTDRIVE_VERSION 0x%08X\r\n" \
"\r\n" \
"#endif//__TESTDRIVE_VERSION_H__\r\n",
version[2] + (version[1]<<16) + (version[0]<<24)
);
fclose(fp);
}
return 0;
}
| true |
dd0e4ce5887c5ab821e9d9bc98ea4344e0560acc | C++ | mshipchandler/NeuralNetDev | /src/image_preprocessor.h | UTF-8 | 10,159 | 3.0625 | 3 | [] | no_license | /*
Ma'ad Shipchandler
Neural Net Input Module 2.0 - image_preprocessor.h
21-09-2015
*/
/*
SUGGESTED INPUT IMAGE SIZE: 256 x 256
*/
#include <iostream>
#include <vector>
#include <fstream>
// OpenCV 3 Library List -------------------------------------------------------------------
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp> // CV_LOAD_IMAGE_COLOR, imread(), imshow(), waitKey()
#include <opencv2/calib3d.hpp> // Blob detection functionality
#include <opencv2/imgproc.hpp> // line, corner, edge detection functionality
using namespace cv;
// -----------------------------------------------------------------------------------------
/*
This struct holds pixel characteristics for each pixel in an image.
*/
struct PixelChar
{
Point2f coordinates;
float intensity;
bool blobFlag, lineFlag, cornerFlag;
PixelChar() { coordinates.x = -1, coordinates.y = -1; }
PixelChar(Point2f point, float _intensity) : coordinates(point), intensity(_intensity)
{
blobFlag = false, lineFlag = false, cornerFlag = false;
}
void display() // Debug purposes
{
std::cout << "Coordinates: " << coordinates << std::endl;
std::cout << " Intensity: " << intensity << std::endl;
std::cout << " Blob?: " << blobFlag << std::endl;
std::cout << " Line?: " << lineFlag << std::endl;
std::cout << " Corner?: " << cornerFlag << std::endl;
}
};
/*
Function will extract pixel co-ordinates and their itensity values,
and start adding them into the image_features vector.
*/
void extractIntensity(const Mat& image, std::vector<PixelChar>& image_features)
{
Mat image_gray;
cvtColor(image, image_gray, CV_BGR2GRAY);
for(int row = 0; row < image_gray.rows; row++)
{
for(int column = 0; column < image_gray.cols; column++)
{
Point2f pixelPoint = Point2f(column, row);
Vec3b channels = image_gray.at<uchar> (row, column);
image_features.push_back(PixelChar(pixelPoint, channels[0]));
}
}
}
/*
Function detects blobs in an image and adds the co-ordinates of the
pixels in the blob the the vector blobCoords.
*/
void blobDetection(Mat image, std::vector<Point2f>& blobCoords)
{
SimpleBlobDetector::Params params;
params.blobColor = 255; // Light blobs
Ptr<SimpleBlobDetector> blobDetector_white = SimpleBlobDetector::create(params);
params.blobColor = 0; // Dark blobs
Ptr<SimpleBlobDetector> blobDetector_black = SimpleBlobDetector::create(params);
// Detect blobs.
std::vector<KeyPoint> keypoints_black, keypoints_white, keypoints;
blobDetector_black->detect(image, keypoints_black);
blobDetector_white->detect(image, keypoints_white);
for(size_t i = 0; i < keypoints_black.size(); i++)
keypoints.push_back(keypoints_black[i]);
for(size_t i = 0; i < keypoints_white.size(); i++)
keypoints.push_back(keypoints_white[i]);
Size image_size = image.size();
Mat mask = Mat::zeros(image_size.height, image_size.width, CV_8U);
for(size_t i = 0; i < keypoints.size(); i++)
{
Point2f kp_center = keypoints[i].pt;
float kp_radius = keypoints[i].size / 2;
circle(mask, kp_center, kp_radius, Scalar(255), -1);
}
// Adding pixels located within the blob radius
for(int row = 0; row < image.rows; row++)
{
for(int column = 0; column < image.cols; column++)
{
Vec3b channels = mask.at<uchar> (row, column);
if(channels[0] > 0)
blobCoords.push_back(Point2f(column, row));
}
}
/*imshow("Mask", mask);
imshow("Original", image);
waitKey(0);*/
}
/*
Function detects presence of lines in an image and adds the co-ordinates
of the pixel that fall on the line to the vector pointsOnLine.
*/
void lineDetection(Mat image, std::vector<Point2f>& pointsOnLine)
{
Mat output;
/*
Canny(Mat input, Mat output, double threshold1,
double threshold2, int apertureSize = 3, bool L2gradient = false);
input:Single channel 8-bit input image
output: output edge map (same size and type as image)
threshold1: first threshold for hysteresis procedure
threshold2: second threshold for hysteresis procedure
apertureSize: aperture size for Sobel() operator
L2gradient: a flag, indicating whether a more accurate
L2 norm =\sqrt{(dI/dx)^2 + (dI/dy)^2} should be used to
calculate the image gradient magnitude (L2gradient=true),
or whether the default L1 norm =|dI/dx|+|dI/dy| is enough (L2gradient=false)
*/
Canny(image, output, 300, 400, 3, true);
/*
HoughLines(Mat image, vector of lines, double rho, double theta, int thresh,
double srn = 0, double stn = 0); <-- Returns Polar coordinates
HoughLinesP(Mat image, vector of lines, doubel rho, double theta, int thresh
double minLineLength = 0, double maxLineGap = 0); <-- Returns cartesian coordinates
*/
#if 0
// This calculation is done to convert polar coordinates to the cartesian plane.
std::vector<Vec2f> lines;
HoughLines(output, lines, 1, CV_PI/180, 100);
for(size_t i = 0; i < lines.size(); i++)
{
float rho = lines[i][0];
float theta = lines[i][1];
double a = cos(theta), b = sin(theta);
double x0 = a*rho, y0 = b*rho;
Point pt1(cvRound(x0 + 1000*(-b)),
cvRound(y0 + 1000*(a)));
Point pt2(cvRound(x0 - 1000*(-b)),
cvRound(y0 - 1000*(a)));
line(output, pt1, pt2, Scalar(255, 255, 255), 3, CV_AA);
}
#else
std::vector<Vec4i> lines;
HoughLinesP(output, lines, 1, CV_PI/180, 80, 50, 50);
for(size_t i = 0; i < lines.size(); i++)
{
Vec4i l = lines[i];
//line(image, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 1, CV_AA);
// Getting all the points on the line.
LineIterator lineIter(image, Point(l[0], l[1]), Point(l[2], l[3]), 8);
for(int i = 0; i < lineIter.count; i++, ++lineIter)
{
Point2f pOnL= lineIter.pos();
//image.at<Vec3b>(pOnL) = 255; // To see if LineIterator works properly
pointsOnLine.push_back(pOnL);
}
}
#endif
}
/*
Function detects corners in an image and adds the co-ordinates of the corners
to the vector corners.
*/
void cornerDetection(Mat image, std::vector<Point2f>& corners)
{
Mat image_gray;
cvtColor(image, image_gray, CV_BGR2GRAY);
int thresh = 200, max_thresh = 255;
Mat dst, dst_norm, dst_norm_scaled;
dst = Mat::zeros(image.size(), CV_32FC1);
// Detector parameters.
int blockSize = 2;
int apertureSize = 3;
double k = 0.04;
// Detecting corners.
cornerHarris(image_gray, dst, blockSize, apertureSize, k, BORDER_DEFAULT);
// Normalizing.
normalize(dst, dst_norm, 0, 255, NORM_MINMAX, CV_32FC1, Mat());
convertScaleAbs(dst_norm, dst_norm_scaled);
// Drawing a circle around corners.
for(int i = 0; i < dst_norm.rows; i++)
{
for(int j = 0; j < dst_norm.cols; j++)
{
if((int)dst_norm.at<float>(i,j) > thresh && (int)dst_norm.at<float>(i,j) < max_thresh)
{
//circle(dst_norm_scaled, Point(j, i), 5, Scalar(255, 255, 255), 1, CV_AA, 0);
corners.push_back(Point2f(j, i));
}
}
}
Size image_size = image.size();
Mat mask = Mat::zeros(image_size.height, image_size.width, CV_8U);
for(size_t i = 0; i < corners.size(); i++)
{
Point2f center = corners[i];
circle(mask, center, 1, Scalar(255), -1);
}
corners.clear();
// Adding pixels located within the corner radius
for(int row = 0; row < image.rows; row++)
{
for(int column = 0; column < image.cols; column++)
{
Vec3b channels = mask.at<uchar> (row, column);
if(channels[0] > 0)
corners.push_back(Point2f(column, row));
}
}
/*imshow("Mask", mask);
imshow("Original", image);
waitKey(0);*/
}
/*
Function updates the image_features vector by checking off flags
for blobs, points on a line and corners.
*/
void updateImageFeatures(std::vector<PixelChar>& image_features,
const std::vector<Point2f>& blobCoords,
const std::vector<Point2f>& pointsOnLine,
const std::vector<Point2f>& corners)
{
std::cout << "Updating the vector" << std::endl;
#pragma omp parallel for
for(size_t i = 0; i < image_features.size(); i++)
{
#pragma omp parallel for
for(size_t j = 0; j < blobCoords.size(); j++)
{
if(image_features[i].coordinates == blobCoords[j])
image_features[i].blobFlag = true;
}
#pragma omp parallel for
for(size_t j = 0; j < pointsOnLine.size(); j++)
{
if(image_features[i].coordinates == pointsOnLine[j])
image_features[i].lineFlag = true;
}
#pragma omp parallel for
for(size_t j = 0; j < corners.size(); j++)
{
if(image_features[i].coordinates == corners[j])
image_features[i].cornerFlag = true;
}
}
}
/*
Writing data to file.
*/
void writeToFile(const std::vector<PixelChar>& image_features)
{
std::ofstream fout("../resources/training_data/chessBoardtrainingData.csv");
fout << "x, y, intensity, blob, line, corner" << std::endl;
std::cout << "Writing to file." << std::endl;
for(size_t i = 0; i < image_features.size(); i++)
{
fout << image_features[i].coordinates.x << ", " <<
image_features[i].coordinates.y << ", " <<
image_features[i].intensity << ", " <<
image_features[i].blobFlag << ", " <<
image_features[i].lineFlag << ", " <<
image_features[i].cornerFlag << std::endl;
}
}
/*
Controller function to process the image by calling necessary sub
functions.
*/
void processImage(const Mat& image, std::vector<PixelChar>& image_features)
{
extractIntensity(image, image_features);
std::vector<Point2f> blobCoords;
blobDetection(image, blobCoords);
std::vector<Point2f> pointsOnLine;
lineDetection(image, pointsOnLine);
std::vector<Point2f> corners;
cornerDetection(image, corners);
updateImageFeatures(image_features, blobCoords, pointsOnLine, corners);
writeToFile(image_features);
}
/*
int main(int argc, char* argv[])
{
std::cout << "OpenCV Version: " << CV_VERSION << std::endl;
if(argc != 2)
{
std::cerr << "Error: Please enter ONE image." << std::endl;
std::cerr << " Usage: " << argv[0] << " image.extension" << std::endl;
return 1;
}
Mat image = imread(argv[1], CV_LOAD_IMAGE_COLOR);
if(image.empty())
{
std::cerr << "Error: Could not load image." << std::endl;
return 2;
}
imshow("Image", image);
waitKey(0);
// -----------------------------------------
std::vector<PixelChar> image_features;
processImage(image, image_features);
// -----------------------------------------
return 0;
}*/ | true |
f08bf32509dd46b11fa9690108da646133b8023c | C++ | l3shen/PHY1610 | /Assignment 8/walkring.cc | UTF-8 | 2,038 | 3.234375 | 3 | [] | no_license | //
// walkring.cc
//
// 1d random walk on a ring
//
// Compile with make using provided Makefile
//
#include <fstream>
#include <rarray>
#include "walkring_output.h"
#include "walkring_timestep.h"
#include "walkring_parameters.h"
// the main function drives the simulation
int main(int argc, char *argv[])
{
// Simulation parameters
double L; // ring length
double D; // diffusion constant
double T; // time
double dx; // spatial resolution
double dt; // temporal resolution (time step)
int Z; // number of walkers
std::string datafile; // filename for output
double time_between_output;
// Read parameters from a file given on the command line.
// If no file was given, use "walkring.ini".
std::string paramFilename = argc>1?argv[1]:"walkring.ini";
read_walking_parameters(paramFilename, L, D, T, dx, dt, Z, datafile, time_between_output);
// Compute derived parameters
const int numSteps = int(T/dt + 0.5); // number of steps to take
const int N = int(L/dx + 0.5); // number of grid points
const int outputEvery = int(time_between_output/dt + 0.5); // how many steps between output
const double p = D*dt/pow(dx,2); // probability to hop left or right
const int outputcols = 48; // number of columns for sparkline output
// Allocate walker data
rarray<int,1> w(Z);
// Setup initial conditions for w
w.fill(0);
// Setup initial time
double time = 0.0;
// Open a file for data output
std::ofstream file;
output_init(file, datafile);
// Initial output to screen
output(file, 0, time, N, w, outputcols);
// Time evolution
for (int step = 1; step <= numSteps; step++) {
// Compute next time point
perform_time_step(w, N, p);
// Update time
time += dt;
// Periodically add data to the file
if (step % outputEvery == 0 and step > 0)
output(file, step, time, N, w, outputcols);
}
// Close file
output_finish(file);
// All done
return 0;
}
| true |
5c4458ae10443b36eabf6612c8648a8d7ed367ad | C++ | Maigo/gea | /gea/libs/gea_math/src/gea/mth_vector/point3.inl | UTF-8 | 4,367 | 3.0625 | 3 | [] | no_license | // gea includes
#include <gea/utility/assert.h>
namespace gea {
namespace mth {
// ------------------------------------------------------------------------- //
// point3 //
// ------------------------------------------------------------------------- //
// constructors
inline point3::point3() : x(0.0f), y(0.0f), z(0.0f) {}
inline point3::point3(const float x, const float y, const float z) : x(x), y(y), z(z) {}
inline point3::point3(skip_initialization) {}
inline point3::point3(zero_initialization) : x(0.0f), y(0.0f), z(0.0f) {}
inline point3::point3(const point3 &o) : x(o.x), y(o.y), z(o.z) {}
// arithmetic
inline point3 &point3::operator= (const point3 &o) {
x = o.x; y = o.y; z = o.z; return (*this);
}
inline const point3 point3::operator+ (const vector3 &v) const {
return point3(x + v.x, y + v.y, z + v.z);
}
inline const point3 point3::operator- (const vector3 &v) const {
return point3(x - v.x, y - v.y, z - v.z);
}
// compound assignment
inline point3 &point3::operator+= (const vector3 &v) {
x += v.x; y += v.y; z += v.z; return (*this);
}
inline point3 &point3::operator-= (const vector3 &v) {
x -= v.x; y -= v.y; z -= v.z; return (*this);
}
// comparative
inline bool point3::operator== (const point3 &o) const {
return (x == o.x && y == o.y && z == o.z);
}
inline bool point3::operator!= (const point3 &o) const {
return (x != o.x || y != o.y || z != o.z);
}
inline bool point3::operator< (const point3 &o) const {
return (x != o.x) ? (x < o.x) : ((y != o.y) ? (y < o.y) : (z < o.z));
}
inline bool point3::operator<= (const point3 &o) const {
return ((*this) == o) || ((*this) < o);
}
inline bool point3::operator> (const point3 &o) const {
return (x != o.x) ? (x > o.x) : ((y != o.y) ? (y > o.y) : (z>o.z));
}
inline bool point3::operator>= (const point3 &o) const {
return ((*this) == o) || ((*this) > o);
}
// member access
inline float &point3::operator[] (int32_t i) {
l_assert_msg(mth::range(i, 0, 2), "index out of bounds!");
return (&x)[i];
}
inline const float &point3::operator[] (int32_t i) const {
l_assert_msg(mth::range(i, 0, 2), "index out of bounds!");
return (&x)[i];
}
// linear algebra
inline const vector3 point3::to(const point3 &o) const {
return vector3(o.x - x, o.y - y, o.z - z);
}
// attributes
inline const bool point3::is_zero() const { return (*this) == point3::ORIGIN; }
// ------------------------------------------------------------------------- //
// global functions //
// ------------------------------------------------------------------------- //
// ------------------------------------------------------------------------- //
// helper functions //
// ------------------------------------------------------------------------- //
// approximative comparison
inline const bool approx_eq(const point3 &p0, const point3 &p1, const float e) {
return approx_eq(p0.x, p1.x, e) &&
approx_eq(p0.y, p1.y, e) &&
approx_eq(p0.z, p1.z, e);
}
inline const bool approx_ne(const point3 &p0, const point3 &p1, const float e) {
return approx_ne(p0.x, p1.x, e) ||
approx_ne(p0.y, p1.y, e) ||
approx_ne(p0.z, p1.z, e);
}
// attributes
inline const bool nice(const point3 &p) {
return nice(p.x) && nice(p.y) && nice(p.z);
}
inline const bool finite(const point3 &p) {
return finite(p.x) && finite(p.y) && finite(p.z);
}
// round
inline const point3 round(const point3 &p) {
return point3(roundf(p.x), roundf(p.y), roundf(p.z));
}
inline const point3 ceil(const point3 &p) {
return point3(ceilf(p.x), ceilf(p.y), ceilf(p.z));
}
inline const point3 floor(const point3 &p) {
return point3(floorf(p.x), floorf(p.y), floorf(p.z));
}
// ------------------------------------------------------------------------- //
// debug functions //
// ------------------------------------------------------------------------- //
#if defined(DEBUG) || defined(PRODUCTION)
inline std::ostream &operator<< (std::ostream &os, const point3 &p) {
return os << "p:[" << p.x << "," << p.y << "," << p.z << "]";
}
#endif
} // namespace mth //
} // namespace gea //
| true |
2987e83d65f97193a25d3c37ce7a080849477c67 | C++ | bdliyq/algorithm | /leetcode/palindrome-linked-list.cc | UTF-8 | 2,535 | 3.78125 | 4 | [] | no_license | // Question: https://leetcode.com/problems/palindrome-linked-list/
#include "headers.h"
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) {
return true;
}
ListNode* slow = head;
ListNode* fast = head->next;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* head2 = slow->next;
if (fast->next) {
head2 = head2->next;
}
slow->next = NULL;
ListNode dummy(0);
while (head2) {
ListNode* t = dummy.next;
dummy.next = head2;
ListNode* head2_next = head2->next;
head2->next = t;
head2 = head2_next;
}
ListNode* cur1 = head;
ListNode* cur2 = dummy.next;
while (cur1 && cur2 && cur1->val == cur2->val) {
cur1 = cur1->next;
cur2 = cur2->next;
}
return cur1 == NULL && cur2 == NULL;
}
};
int main(int argc, char** argv) {
Solution s;
{
ListNode* head = new ListNode(1);
cout << s.isPalindrome(head) << endl;
// true
}
{
ListNode* head = new ListNode(1);
head->next = new ListNode(1);
cout << s.isPalindrome(head) << endl;
// true
}
{
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
cout << s.isPalindrome(head) << endl;
// false
}
{
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(1);
cout << s.isPalindrome(head) << endl;
// true
}
{
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
cout << s.isPalindrome(head) << endl;
// false
}
{
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(2);
head->next->next->next = new ListNode(1);
cout << s.isPalindrome(head) << endl;
// true
}
{
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(1);
cout << s.isPalindrome(head) << endl;
// false
}
return 0;
}
| true |
4afa93f84372257db38d08928464f4663bc93306 | C++ | arthurlz/hairy-coding | /Chinese chess.cpp | UTF-8 | 241 | 2.9375 | 3 | [] | no_license | #include <iostream>
using namespace std;
typedef unsigned char byte;
int main(int argc, char *argv[])
{
byte b = 81;
while(b--)
{
if(b/9%3 == b%9%3)
continue;
cout<<"A="<<(b/9+1)<<" B="<<(b%9+1)<<endl;
}
return 0;
}
| true |
aa5ca2f9557970d6e529d24277251d2b413c3dca | C++ | ashwitharao21/silver-train | /BST.CPP | UTF-8 | 1,087 | 3.25 | 3 | [] | no_license | #include<iostream.h>
#include<conio.h>
//using namespace std;
struct bstnode{
int data;
struct bstnode* left;
struct bstnode* right;
};
bstnode* getnewnode(int data){
bstnode* newnode= new bstnode();
newnode->data=data;
newnode->left=newnode->right=NULL;
return newnode;
}
bstnode* Insert(bstnode* root, int data){
if(root==NULL){
root=getnewnode(data);
}
else if(data<=root->data){
root->left=Insert(root->left,data);
}
else{
root->right=Insert(root->right,data);
}
return root;
}
int search(bstnode* root,int data){
if(root==NULL) return 0;
else if(root->data==data) return 1;
else if(data<=root->data) return search(root->left, data);
else return search(root->right, data);
}
void main(){
bstnode* root=NULL;
clrscr();
root=Insert(root,15);root=Insert(root,10);root=Insert(root,20);
root=Insert(root,8);root=Insert(root,12);root=Insert(root,25);
int number;
cout<<"Enter number to be search\n";
cin>>number;
if(search(root,number)==1)
cout<<"Found\n";
else
cout<<"Not Found\n";
getch();
}
| true |
98acea01547cc90f01edae4a8632f96738abdc3a | C++ | HDBaggy/Sboard | /Main/Client/ClsClient.cpp | UTF-8 | 2,582 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <signal.h>
#include "TCPClient.h"
#include <fstream>
#include <unistd.h>
#include <stdio.h>
#include <cstdlib>
#include <pthread.h>
#include <thread>
#include <chrono>
#include "ClsClient.h"
#include "../Common.hpp"
using namespace std;
void *startTmpMsg(void *t);
void sendMessage();
TCPClient tcp;
void sig_exit(int s)
{
tcp.exit();
exit(0);
}
ClsClient::ClsClient(){
}
ClsClient::ClsClient(string strAddress, int port){
pthread_t threads[1];
int i = 0;
while (tcp.setup(strAddress, port) == false){
i++;
cout << "Retrying...";
sleep(5);
if(i>300 && i<600){
sleep(15);
} else if(i>600 && i<900){
sleep(30);
} else if(i>900 && i< 3600){
sleep(45);
} else if (i>3600 && i<7200){
sleep(120);
} else if (i>7200 && i<9600) {
sleep(360);
} else if (i==9600) {
sleep(960);
} else {
sleep(2);
i = 0;
}
}
i = 0;
while(1)
{
srand(time(NULL));
string rec = tcp.receive();
if (rec == "t1" || rec=="t1\n"){
cout << "toggle";
// tcp.Send(to_string("toggled to"));
// sendMessage();
int rc6 = pthread_create(&threads[0], NULL, startTmpMsg, NULL);
if (rc6 ) {
cout << "Error:unable to create Client thread," << rc6 << endl;
exit(-1);
}
if(clientListner != NULL)
clientListner(rec);
} else if ( rec != "" ){
cout << "Server Response:" << rec;
}
}
sleep(1);
}
void *startTmpMsg(void *t){
sendMessage();
pthread_exit(0);
}
void sendMessage(){
ofstream myfile;
myfile.open ("server_log.txt");
myfile << "t1";
myfile.close();
ifstream myReadFile;
myReadFile.open("s1_pid.txt");
char output[10];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
//cout<<output;
}
}
char *value = output;
const char* strPID = value;
std::string str1(strPID);
int intId = atoi(str1.c_str());
if (intId != 0){
cout << "Sending notification to PID: " << intId;
int ret;
ret = kill(intId,SIGUSR1);
}else {
cout << "PID wad nil";
}
}
| true |
b64f88b1b297d499523bc9ad6d881830cb7648bb | C++ | shadowSQ/practice | /模拟赛第四题.cpp | GB18030 | 1,254 | 3.21875 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include <stdio.h>
int total=0;
int flag=0;
struct Cages{
int cages[100];
int size;
};
void push(int t,Cages &cage)
{
int i ;
for(i=0;i<cage.size;i++)
{
if(cage.cages[i]==t)
return;
}
cage.cages[cage.size] = t;
cage.size++;
}
bool initcages(Cages &cage)
{
cage.size = 0;
}
int getsize(Cages &cage)
{
return cage.size;
}
//
void turncage(int *pnum,int *price,int N,int dfsnum,int total,Cages &cage,int temp)
{
int i;
if(dfsnum>=N)
{
push(total,cage);
flag = 1;
// cout<<"total:"<<total<<endl;
return;
}
for(i=0;i<=pnum[dfsnum];i++)
{
if(flag == 1)
{
total -= temp;
flag = 0;
}
total += price[dfsnum]*i;
temp = price[dfsnum]*i;
turncage(pnum,price,N,dfsnum+1,total,cage,temp);
}
}
int main(){
int T;
int M,N,V;
int *pnum,*price;
int i,j;
cin>>T;
Cages cage1;
initcages(cage1);
while(T--)
{
cin>>N;
//ÿֹƱ۸
price = new int[N];
for(i=0;i<N;i++)
cin>>price[i];
//ӡǷгִ
// for(i=0;i<N;i++)
// cout<<*(price+i);
//ÿֹƱĸ
pnum = new int[N];
for(i=0;i<N;i++)
cin>>*(pnum+i);
turncage(pnum,price,N,0,total,cage1,0);
cout<<cage1.size;
}
}
| true |
484f0a99b021c3c98aafb5490a1dc44c685c2808 | C++ | isysoi3/SPOVM | /lab4/linux/main.cpp | UTF-8 | 2,661 | 3.328125 | 3 | [] | no_license | #include <stack>
#include <iostream>
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include "pthread.h"
#define DELAY_TIME_SEC 2
std::stack <pthread_t> childThreads;
pthread_mutex_t consoleMutex;
int getch() {
struct termios oldattr, newattr;
int ch;
tcgetattr( STDIN_FILENO, &oldattr );
newattr = oldattr;
newattr.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
return ch;
}
void printMenu() {
pthread_mutex_lock(&consoleMutex);
std::cout << "Child threads: " << childThreads.size() << std::endl;
std::cout << "[+] - add child thread\n";
std::cout << "[-] - remove child thread\n";
std::cout << "[q] - exit\n";
pthread_mutex_unlock(&consoleMutex);
}
void killChildThread(pthread_t childThread) {
pthread_cancel(childThread);
}
void* childThreadFunc(void * args) {
std::string processString = "Child thread id - " + std::to_string((long) pthread_self());
while (true) {
pthread_mutex_lock(&consoleMutex);
for(std::string::size_type i = 0; i < processString.size(); ++i) {
std::cout << processString[i];
}
std::cout << std::endl;
pthread_mutex_unlock(&consoleMutex);
sleep(DELAY_TIME_SEC);
}
}
void addChildThread() {
pthread_t thread;
int threadCreateResult = pthread_create(&thread, NULL, childThreadFunc, NULL);
if (threadCreateResult == 0) {
childThreads.push(thread);
} else {
std::cout << "Failed to create child thread\n";
}
}
void removeChildThread() {
if (childThreads.empty()) {
std::cout << "Nothing to delete.\n";
} else {
pthread_t childThread = childThreads.top();
childThreads.pop();
killChildThread(childThread);
}
}
void removeAllChildThreads() {
while(!childThreads.empty()) {
pthread_t childThread = childThreads.top();
childThreads.pop();
killChildThread(childThread);
}
}
int main() {
char operation;
bool isFinished = false;
pthread_mutex_init(&consoleMutex, NULL);
while(!isFinished) {
printMenu();
operation = getch();
switch (operation) {
case '+':
addChildThread();
break;
case '-':
removeChildThread();
break;
case 'q':
removeAllChildThreads();
isFinished = true;
break;
default:
break;
}
}
pthread_mutex_destroy(&consoleMutex);
return 0;
}
| true |
59dfad05178c5d0c247d1c342bec4d4754d3e515 | C++ | luchev/uni-object-oriented-programming-2021 | /Week 09/Template inheritance/string_using_vector.hpp | UTF-8 | 381 | 3.28125 | 3 | [] | no_license | #pragma once
#include <vector>
class String : public std::vector<char> {
public:
String() {
push_back('\0');
}
void push_back(char c) {
if (!this->empty()) {
pop_back();
}
std::vector<char>::push_back(c);
std::vector<char>::push_back('\0');
}
const char* c_str() const {
return &at(0);
}
};
| true |
bb715aeddcc896069de0f1420c590b885131a8c2 | C++ | Req1630/TankDefense | /TankDefense/SourceCode/Object/Collider/CollisionManager/CollisionManager.cpp | SHIFT_JIS | 10,531 | 2.546875 | 3 | [] | no_license | #include "CollisionManager.h"
#include "..\Sphere\Sphere.h"
#include "..\Capsule\Capsule.h"
#include "..\Box\Box.h"
#include "..\Ray\Ray.h"
#include "..\Mesh\Mesh.h"
namespace coll
{
//---------------------------------------.
// ̓m̓蔻.
//---------------------------------------.
bool IsSphereToSphere( CSphere* pMySphere, CSphere* pOppSphere )
{
// XtBA nullptr ȂI.
if( pMySphere == nullptr ) return false;
if( pOppSphere == nullptr ) return false;
// a 0 ȉȂI.
if( pMySphere->GetRadius() <= 0.0f ) return false;
if( pOppSphere->GetRadius() <= 0.0f ) return false;
// tO낵Ƃ.
pMySphere->SetHitOff();
pOppSphere->SetHitOff();
// _Ԃ̋擾.
const float length = D3DXVec3Length( &(pMySphere->GetPosition() - pOppSphere->GetPosition()) );
// ݂̔a̍v擾.
const float totalRadius = pMySphere->GetRadius() + pOppSphere->GetRadius();
// 2_Ԃ̋2̔a̍v傫̂.
// Փ˂ĂȂ.
if( length > totalRadius ) return false;
// Փ˂Ă.
// tO𗧂Ă.
pMySphere->SetHitOn();
pOppSphere->SetHitOn();
return true;
}
//---------------------------------------.
// JvZm̓蔻.
//---------------------------------------.
bool IsCapsuleToCapsule( CCapsule* pMyCapsule, CCapsule* pOppCapsule )
{
if( pMyCapsule == nullptr ) return false;
if( pOppCapsule == nullptr ) return false;
// a 0 ȉȂI.
if( pMyCapsule->GetRadius() <= 0.0f ) return false;
if( pOppCapsule->GetRadius()<= 0.0f ) return false;
// tO낵Ƃ.
pMyCapsule->SetHitOff();
pOppCapsule->SetHitOff();
SSegment mySeg = pMyCapsule->GetSegment();
SSegment oppSeg = pOppCapsule->GetSegment();
float d = CalcSegmentSegmentDist( mySeg, oppSeg );
if( d >= pMyCapsule->GetRadius()+pOppCapsule->GetRadius() ) return false;
// Փ˂Ă.
// tO𗧂Ă.
pMyCapsule->SetHitOn();
pOppCapsule->SetHitOn();
return true;
}
//---------------------------------------.
// {bNXm̓蔻.
//---------------------------------------.
bool IsOBBToOBB( CBox* pMyBox, CBox* pOppBox )
{
if( pMyBox == nullptr ) return false;
if( pOppBox == nullptr ) return false;
// tO낵Ƃ.
pMyBox->SetHitOff();
pOppBox->SetHitOff();
// exNg̊m.
// iN***:WxNgj.
D3DXVECTOR3 NAe1 = pMyBox->GetDirection(0), Ae1 = NAe1 * pMyBox->GetScale().x;
D3DXVECTOR3 NAe2 = pMyBox->GetDirection(1), Ae2 = NAe2 * pMyBox->GetScale().y;
D3DXVECTOR3 NAe3 = pMyBox->GetDirection(2), Ae3 = NAe3 * pMyBox->GetScale().z;
D3DXVECTOR3 NBe1 = pOppBox->GetDirection(0), Be1 = NBe1 * pOppBox->GetScale().x;
D3DXVECTOR3 NBe2 = pOppBox->GetDirection(1), Be2 = NBe2 * pOppBox->GetScale().y;
D3DXVECTOR3 NBe3 = pOppBox->GetDirection(2), Be3 = NBe3 * pOppBox->GetScale().z;
D3DXVECTOR3 Interval = pMyBox->GetPosition() - pOppBox->GetPosition();
FLOAT rA, rB, L;
auto LenSegOnSeparateAxis = []( D3DXVECTOR3 *Sep, D3DXVECTOR3 *e1, D3DXVECTOR3 *e2, D3DXVECTOR3 *e3 = 0 )
{
// 3̓ς̐Βl̘aœevZ.
// Sep͕WĂ邱.
FLOAT r1 = fabs(D3DXVec3Dot( Sep, e1 ));
FLOAT r2 = fabs(D3DXVec3Dot( Sep, e2 ));
FLOAT r3 = e3 ? (fabs(D3DXVec3Dot( Sep, e3 ))) : 0;
return r1 + r2 + r3;
};
auto isHitLength = [&](
const D3DXVECTOR3& e,
D3DXVECTOR3 Ne,
D3DXVECTOR3 e1, D3DXVECTOR3 e2, D3DXVECTOR3 e3 )
{
rA = D3DXVec3Length( &e );
rB = LenSegOnSeparateAxis( &Ne, &e1, &e2, &e3 );
L = fabs(D3DXVec3Dot( &Interval, &Ne ));
if( L > rA + rB ) return false; // Փ˂ĂȂ.
return true;
};
auto isHitCross = [&](
const D3DXVECTOR3& NAe, const D3DXVECTOR3& NBe,
D3DXVECTOR3 Ae1, D3DXVECTOR3 Ae2,
D3DXVECTOR3 Be1, D3DXVECTOR3 Be2 )
{
D3DXVECTOR3 Cross;
D3DXVec3Cross( &Cross, &NAe, &NBe );
rA = LenSegOnSeparateAxis( &Cross, &Ae1, &Ae2 );
rB = LenSegOnSeparateAxis( &Cross, &Be1, &Be2 );
L = fabs(D3DXVec3Dot( &Interval, &Cross ));
if( L > rA + rB ) return false; // Փ˂ĂȂ.
return true;
};
// : Ae.
if( isHitLength( Ae1, NAe1, Be1, Be2, Be3 ) == false ) return false;
if( isHitLength( Ae2, NAe2, Be1, Be2, Be3 ) == false ) return false;
if( isHitLength( Ae3, NAe3, Be1, Be2, Be3 ) == false ) return false;
// : Be.
if( isHitLength( Be1, NBe1, Ae1, Ae2, Ae3 ) == false ) return false;
if( isHitLength( Be2, NBe2, Ae1, Ae2, Ae3 ) == false ) return false;
if( isHitLength( Be3, NBe3, Ae1, Ae2, Ae3 ) == false ) return false;
// : C1.
if( isHitCross( NAe1, NBe1, Ae2, Ae3, Be2, Be3 ) == false ) return false;
if( isHitCross( NAe1, NBe2, Ae2, Ae3, Be1, Be3 ) == false ) return false;
if( isHitCross( NAe1, NBe3, Ae2, Ae3, Be1, Be2 ) == false ) return false;
// : C2.
if( isHitCross( NAe2, NBe1, Ae1, Ae3, Be2, Be3 ) == false ) return false;
if( isHitCross( NAe2, NBe2, Ae1, Ae3, Be1, Be3 ) == false ) return false;
if( isHitCross( NAe2, NBe3, Ae1, Ae3, Be1, Be2 ) == false ) return false;
// : C3.
if( isHitCross( NAe3, NBe1, Ae1, Ae2, Be2, Be3 ) == false ) return false;
if( isHitCross( NAe3, NBe2, Ae1, Ae2, Be1, Be3 ) == false ) return false;
if( isHitCross( NAe3, NBe3, Ae1, Ae2, Be1, Be2 ) == false ) return false;
// Փ˂Ă.
pMyBox->SetHitOn();
pOppBox->SetHitOn();
return true;
}
//---------------------------------------.
// CƋ̂̓蔻.
//---------------------------------------.
bool IsRayToSphere( CRay* pRay, CSphere* pSphere, D3DXVECTOR3* pOutStartPos, D3DXVECTOR3* pOutEndPos )
{
if( pRay == nullptr ) return false;
if( pSphere == nullptr ) return false;
// tO낵Ƃ.
pRay->SetHitOff();
pSphere->SetHitOff();
const D3DXVECTOR3 v = pRay->GetVector();
const D3DXVECTOR3 l = pRay->GetStartPos();
const D3DXVECTOR3 p = pSphere->GetPosition() - l;
const float A = v.x * v.x + v.y * v.y + v.z * v.z;
const float B = v.x * p.x + v.y * p.y + v.z * p.z;
const float C = p.x * p.x + p.y * p.y + p.z * p.z - pSphere->GetRadius()*pSphere->GetRadius();
// xNg̒ȂΏI.
if( A == 0.0f ) return false;
const float s = B * B - A * C;
const float sq = sqrtf(s);
const float a1 = ( B - sq ) / A;
const float a2 = ( B + sq ) / A;
// C̊JnʒuƋ̂̋.
// ̂̔a菬ΏՓ˂Ă.
if( D3DXVec3Length( &p ) <= pSphere->GetRadius() ){
if( pOutStartPos != nullptr ){
*pOutStartPos = pRay->GetStartPos();
}
if( pOutStartPos != nullptr ){
pOutEndPos->x = l.x + a2 * v.x;
pOutEndPos->y = l.y + a2 * v.y;
pOutEndPos->z = l.z + a2 * v.z;
}
pRay->SetHitOn();
pSphere->SetHitOn();
return true;
}
if( s < 0.0f ) return false;
if( a1 < 0.0f || a2 < 0.0f ) return false;
pRay->SetHitOn();
pSphere->SetHitOn();
if( pOutStartPos == nullptr ) return true;
pOutStartPos->x = l.x + a1 * v.x;
pOutStartPos->y = l.y + a1 * v.y;
pOutStartPos->z = l.z + a1 * v.z;
if( pOutEndPos == nullptr ) return true;
pOutEndPos->x = l.x + a2 * v.x;
pOutEndPos->y = l.y + a2 * v.y;
pOutEndPos->z = l.z + a2 * v.z;
return true;
}
//---------------------------------------.
// CƃbV̓蔻.
//---------------------------------------.
bool IsRayToMesh( CRay* pRay, CMesh* pMesh, float* pOutDistance, D3DXVECTOR3* pIntersect, D3DXVECTOR3* pOutNormal, const bool& isNormalHit )
{
if( pRay == nullptr ) return false;
if( pMesh == nullptr ) return false;
pRay->SetHitOff(); // qbgtO낵Ƃ.
// ΏۃbV̂̋ts߂.
D3DXMATRIX mInvWorld;
D3DXMatrixInverse( &mInvWorld, nullptr, &pMesh->GetTranceform().GetWorldMatrix() );
// C̊JnʒuƏIʒuݒ.
D3DXVECTOR3 startVec, endVec;
startVec = pRay->GetStartPos();
endVec = pRay->GetStartPos() + (pRay->GetVector()*pRay->GetLength());
// C̎n_,I_ɔf.
D3DXVec3TransformCoord( &startVec, &startVec, &mInvWorld );
D3DXVec3TransformCoord( &endVec, &endVec, &mInvWorld );
// ߂(xNg).
D3DXVECTOR3 vecDirection = endVec - startVec;
BOOL isHit = FALSE; // tO.
DWORD dwIndex = 0; // CfbNXԍ.
D3DXVECTOR3 vertex[3]; // _W.
FLOAT U = 0.0f, V = 0.0f; // dSqbgW.
// ΏۃbVƃCƂĂ邩.
D3DXIntersect(
pMesh->GetMesh(), // ΏۃbV.
&startVec, // C̊Jnʒu.
&vecDirection, // C̕.
&isHit, // (out)茋.
&dwIndex, // (out)ՓˎɃC̎n_ɍł߂ʂ̃CfbNXԍ.
&U, &V, // (out)dSqbgW.
pOutDistance, // (out)bVƂ̋.
nullptr, nullptr );
// ĂȂ̂ŏI.
if( isHit == FALSE ) return false;
// _擾łȂ̂ŏI.
if( FAILED( pMesh->FindVerticesOnPoly( dwIndex, vertex )) ) return false;
// [J_ṕAv0 + U*(v1-v0) + v*(v2-v0) ŋ܂.
D3DXVECTOR3 v0, v1, v2;
v0 = vertex[0];
v1 = vertex[1];
v2 = vertex[2];
*pIntersect = v0 + U * (v1 - v0) + V * (v2 - v0);
// bVƂ̋ '1,0' 傫ΏI.
if( *pOutDistance > 1.0f ) return false;
D3DXVECTOR3 normal;
// {̃xNgɑāAp̃xNg쐬.
D3DXVec3Cross( &normal, &(v1 - v0), &(v2 - v0) );
D3DXVec3Normalize( &normal, &normal );
if( pOutNormal != nullptr ) *pOutNormal = normal;
if( isNormalHit == true ){
// vecDirectionvNormalt̎DOTŽʂ-1A
// ꏏPAt̎̓CƃCΖʂłԂ荇Ă邩瓖ĂA
// ̎͑ΖʂłԂĂȂ瓖ĂȂ.
float vecDirDotNormal = D3DXVec3Dot( &vecDirection, &normal );
if( vecDirDotNormal >= 0.0f ) return false;
// \痈CƏՓ˂Ă.
}
// qbgtO𗧂Ă.
pRay->SetHitOn();
return true;
}
}; | true |
b7495cdc90bb15017edc8e8efdd437ba1f61a58d | C++ | CermakM/CodinGame | /Medium/ShadowsOfTheKnightEpisode1.cpp | UTF-8 | 1,507 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cmath>
using std::cin; using std::cout; using std::endl;
int Difference( const int& bound, const int& current ) {
return round( fabs( (float)bound - (float)current) / 2 );
}
int main() {
int W, H; // width and height of the building.
cin >> W >> H; cin.ignore();
int N; // maximum number of turns before game over.
cin >> N; cin.ignore();
int X0, Y0;
cin >> X0 >> Y0; cin.ignore();
// Set up search limits
int lower_hbound, lower_vbound; lower_hbound = lower_vbound = 0;
int higher_hbound = W - 1, higher_vbound = H - 1;
while ( 1 ) {
std::string bombDir; // the direction of the bombs from batman's current location (U, UR, R, DR, D, DL, L or UL)
cin >> bombDir; cin.ignore();
// Each step set the new lower or higher bound based on current position and compute diff
// Note: We add or subtract one in order not to visit the place agian
for ( char& letter : bombDir ) {
switch ( letter ) {
case 'U':
higher_vbound = Y0 - 1;
Y0 -= Difference( lower_hbound, Y0 );
break;
case 'D':
lower_hbound = Y0 + 1;
Y0 += Difference( higher_vbound, Y0 );
break;
case 'R':
lower_vbound = X0 + 1;
X0 += Difference( higher_hbound, X0 );
break;
case 'L':
higher_hbound = X0 - 1;
X0 -= Difference( lower_vbound, X0 );
break;
}
}
std::string output = std::to_string( X0 ) + " " + std::to_string( Y0 );
cout << output << endl;
}
}
| true |
9e4c3b784e62eea308519432b7b7eaed91ba1cc9 | C++ | bmclaine/Space-Yetis-In-Space | /Code/source/IntroState.h | UTF-8 | 1,469 | 2.921875 | 3 | [] | no_license | //*********************************************************************//
// File: IntroState.h
// Author: Brian McLaine
// Course: SGD
// Purpose: IntroState class handles the intro screen
//*********************************************************************//
#pragma once
#include "IGameState.h"
class IntroState : public IGameState
{
public:
//*****************************************************************//
// Singleton Accessor:
static IntroState* GetInstance(void);
//*****************************************************************//
// IGameState Interface:
virtual void Enter(void) override; // load resources / reset data
virtual void Exit(void) override; // unload resources
virtual bool Update(float elapsedTime) override; // handle input / update entities
virtual void Render(float elapsedTime) override; // draw entities / menu
private:
//*****************************************************************//
// SINGLETON (not-dynamically allocated)
// - Hide the "Quadrilogy-of-Evil" so they cannot be called
// by outside functions
IntroState(void) = default; // default constructor
virtual ~IntroState(void) = default; // destructor
IntroState(const IntroState&) = delete; // copy constructor
IntroState& operator= (const IntroState&) = delete; // assignment operator
//*****************************************************************//
// Members:
float m_fTitlePosX = 0.0f;
float m_fSubTitlePosX = 0.0f;
};
| true |
016e93535927cbca2b1c95869726500847c4f4bc | C++ | iomeone/PudgeNSludge | /Source/Utilities/CollisionLib/CollisionRay.cpp | UTF-8 | 5,303 | 2.96875 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////////////////
// Filename: CollisionRay.cpp
// Author: Josh Fields
// Date: 5/24/12
// Purpose: This class holds on to the information for a Ray
//////////////////////////////////////////////////////////////////////////////////////
#include "CollisionRay.h"
#include "CollisionShapes.h"
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CCollisionRay(): Default Constructor
//
// Returns: Void
//
// Mod. Name:
// Mod. Date:
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CCollisionRay::CCollisionRay ()
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CCollisionRay(): Default Destructor
//
// Returns: Void
//
// Mod. Name:
// Mod. Date:
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CCollisionRay::~CCollisionRay ()
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ClosestPointOnRay(): Takes in a vec3f (vPoint) and an output vec3f (ptA). This will find the closest point on the
// ray using the point passed in and save the point on the ray in the output pramater.
//
// Returns: Void
//
// Mod. Name:
// Mod. Date:
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void CCollisionRay::ClosestPointOnRay( vec3f vPointA, vec3f& pta )
{
// find the direction from the point to start of the ray.
vec3f vvectopoint = vPointA - m_cptStart.Get3DCentorid();
// calculate the dot product of the direction and above direction
float fdistance = dot_product (m_cptDirection.Get3DCentorid(), vvectopoint);
// if the dot product is less then 0 then the closest point is the start point
if ( fdistance < 0.0f)
{
pta = m_cptStart.Get3DCentorid();
return;
}
// calculate the normal with the length of the direction
vec3f vnormalprime = m_cptDirection.Get3DCentorid() * fdistance;
// calculate the new point on the line using the start point
pta = m_cptStart.Get3DCentorid() + vnormalprime;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// RayToPlane(): Takes in a Plane (plA) and an output vec3f (ptA). This will find the closest point on the plane
// using the ray and save the point in the output pramater.
//
// Returns: bool
//
// Mod. Name:
// Mod. Date:
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool CCollisionRay::RayToPlane ( CCollisionPlane pla, vec3f& pta)
{
// early out test to see if the ray is faceing away from the plane or facing perpendicular
if (!dot_product (pla.GetNormal3D(), m_cptDirection.Get3DCentorid()))
{
return false;
}
if (pla.PositiveHalfSpaceTest (m_cptStart.Get3DCentorid()))
{
if (dot_product (pla.GetNormal3D(), m_cptDirection.Get3DCentorid()) > 0)
{
return false;
}
}
else
{
if (dot_product (pla.GetNormal3D(), m_cptDirection.Get3DCentorid()) < 0)
{
return false;
}
}
// find the time of intersection on the ray
float ftime = (pla.GetOffset() - (dot_product (pla.GetNormal3D(), m_cptStart.Get3DCentorid()))) / (dot_product (pla.GetNormal3D(), m_cptDirection.Get3DCentorid()));
// calculate the point at that time of intersection.
pta = m_cptStart.Get3DCentorid() + m_cptDirection.Get3DCentorid() * ftime;
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// RayToSphere(): Takes in a Sphere (spA) and an output vec3f (ptA). This function will find the closest point on the
// sphere and put the point on the sphere in the output pramater.
//
// Returns: bool
//
// Mod. Name:
// Mod. Date:
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool CCollisionRay::RayToSphere ( CCollisionSphere spa, vec3f& pta)
{
// calculate the vector from the start of the ray to the sphere's center
vec3f vdirtosphere = m_cptStart.Get3DCentorid() - spa.GetCenter3D();
// get the distance of the vector in the direction of the ray's normal
float fb = dot_product (vdirtosphere, m_cptDirection.Get3DCentorid());
// calculate the distance of the vector minus the sphere's radius squared
float fc = dot_product (vdirtosphere, vdirtosphere) - spa.GetRadius() * spa.GetRadius();
// if either of these is greater then 0 return false
if (fc > 0.0f && fb > 0.0f)
return false;
// calculate the discriminant
float fdiscr = fb*fb - fc;
// if the discriminant
if (fdiscr < 0.0f)
return false;
// subtract the square root of the discriminant and negative fb
float ft = -fb - sqrt (fdiscr);
// if ft is less then 0 then clamp ft to 0
if (ft < 0.0f)
{
ft = 0.0f;
}
// claculate the point on the ray by adding the ray's start to the ray's normal times ft
pta = m_cptStart.Get3DCentorid() + m_cptDirection.Get3DCentorid() * ft;
return true;
} | true |
6203c3410fdb501b4a4d888979022736db7b2c6f | C++ | moevm/oop | /8383/maximova_anastasia/gameField.h | UTF-8 | 782 | 2.765625 | 3 | [] | no_license | #pragma once
#include "Object.h"
#include "Unit.h"
#include "AbstractFactory.h"
class GameField {
protected:
int width, height;
int step;
int maxUnits;
Object*** field; //двумерный массив указателей
public:
GameField();
GameField(int height, int width);
GameField(const GameField& other); //конструктор копирования
GameField(GameField&& other); //конструктор переноса
void createField();
Unit* createUnit(char view, int type);
int addUnit(Object* unit, int x, int y);
int movingUnit(int x, int y, char course, int steps);
int deleteUnit(int x, int y);
void printCurField();
int getHeight();
int getWidth();
int getStep();
int getMaxUnits();
~GameField();
};
| true |
741a75088568c6a21232dec58f9c40458d810602 | C++ | kangli-bionic/algorithm | /lintcode/1568.dfs.cpp | UTF-8 | 1,782 | 3.28125 | 3 | [
"MIT"
] | permissive | /**
1568. Minimum Number of Days to Disconnect Island
https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/
DFS
**/
class Solution {
private:
vector<int> DELTA_X = {0, 0, -1, 1};
vector<int> DELTA_Y = {-1, 1, 0, 0};
bool isOneIsland(vector<vector<int>> &grid) {
int n = grid.size(), m = grid[0].size();
int islands = 0;
vector<vector<bool>> vis(n, vector<bool>(m, false));
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if (grid[i][j] & !vis[i][j]) {
dfs(grid, i, j, vis);
++islands;
}
return islands == 1;
}
void dfs(vector<vector<int>> &grid, int x, int y, vector<vector<bool>>& v) {
int n = grid.size(), m = grid[0].size();
v[x][y] = true;
for (int i = 0; i < 4; ++i) {
int nx = x + DELTA_X[i], ny = y + DELTA_Y[i];
if (!isValid(nx, ny, grid, v)) continue;
dfs(grid, nx, ny, v);
}
}
bool isValid(int x, int y, vector<vector<int>> &grid, vector<vector<bool>>& v) {
if (x < 0 || x >= grid.size()) return false;
if (y < 0 || y >= grid[0].size()) return false;
if (v[x][y]) return false;
if (grid[x][y] == 0) return false;
return true;
}
public:
int minDays(vector<vector<int>>& grid) {
if (!isOneIsland(grid)) return 0;
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[0].size(); ++j) {
if (grid[i][j] == 1) {
grid[i][j] = 0;
if (!isOneIsland(grid)) return 1;
grid[i][j] = 1;
}
}
}
return 2;
}
}; | true |
67f3340afc67b8152301f2efd14408b24215214c | C++ | YacerRazouani/INF1010 | /TP3_versionRemise/TP3_versionRemise/ProduitAuxEncheres.h | ISO-8859-1 | 1,086 | 2.828125 | 3 | [] | no_license | /********************************************
* Titre: Travail pratique #3 - ProduitAuxEncheres.h
* Date: 25 fvrier 2018
* Modifier par: Amar Ghaly (1905322) & Yacer Razouani (1899606)
*******************************************/
#ifndef PRODUITAUXENCHERES_H
#define PRODUITAUXENCHERES_H
#include <string>
#include <iostream>
#include "Produit.h"
using namespace std;
class ProduitAuxEncheres : public Produit
{
public:
//Constructeur
ProduitAuxEncheres(Fournisseur& fournisseur,const string& nom = "outil", int reference = 0,
double prix = 0.0,TypeProduit type = TypeProduitAuxEncheres);
//Methode d'acces
int obtenirIdentifiantClient() const;
double obtenirPrixBase() const;
//Methode de modification
void modifierIdentifiantClient(int identifiantClient) ;
void modifierPrixBase(double prixBase) ;
//Surcharge des operateur
friend istream& operator>>(istream& is, ProduitAuxEncheres& produit);
friend ostream& operator<<(ostream& os, const ProduitAuxEncheres& produit);
private:
double prixBase_;
int identifiantClient_;
};
#endif
| true |
382c0fe8a42325f9c262bf1dd95903742f694884 | C++ | proweb4all/c-cpp | /urok96-massiv-obj-class.cpp | WINDOWS-1251 | 1,456 | 3.234375 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
//
using namespace std;
class Pixel{
public:
Pixel(){
r = g = b = 0;
}
Pixel(int r, int g, int b){
this->r = r;
this->g = g;
this->b = b;
}
string getPixel(){
return "Pixel(r,g,b): (" + to_string(r) + "," + to_string(g) + ","+ to_string(b) + ")\n";
}
private:
int r, g, b;
};
class Image{
public:
void getImage(){
for (int i = 0; i < len; i++){
cout << "#" << i << "_" << arr[i].getPixel();
}
}
private:
static const int len = 5;
Pixel arr[len] = {
Pixel(10, 10, 10),
Pixel(20, 20, 20),
Pixel(30, 30, 30),
Pixel(40, 40, 40),
Pixel(50, 50, 50)
};
};
int main()
{
setlocale(LC_ALL, "Rus");
Image A;
A.getImage();
Pixel B;
Pixel C(100,100,100);
cout << "#B_" << B.getPixel();
cout << "#C_" << C.getPixel();
cout <<"----- -----\n";
const int len = 5;
Pixel arr[len];
arr[2] = Pixel(200,200,200);
for (int i = 0; i < len; i++){
cout << "#" << i << "_" << arr[i].getPixel();
}
cout <<"----- -----\n";
int lend = 3;
Pixel *arrd = new Pixel[lend];
arrd[2] = Pixel(22,22,22);
for (int i = 0; i < lend; i++){
cout << "#" << i << "_" << arrd[i].getPixel();
}
delete [] arrd;
system("pause");
}
| true |
ef2d9a94e1659463ff50ed5255f9f10b631293d5 | C++ | alaneurich/darksnakes | /helpers.cpp | UTF-8 | 1,012 | 2.640625 | 3 | [] | no_license | //
// Created by alane on 02.01.2018.
//
#include <afxres.h>
#include <sys/time.h>
#include "helpers.h"
Snake* getDynamicSizedSnakeArray(int size) {
auto *snakes = new Snake[size];
int playerCount = gPlayerCount;
for(int a = 0; a < size; a++) {
snakes[a].positions[0][0] = 0;
snakes[a].positions[0][1] = 0;
snakes[a].positions[1][0] = 0;
snakes[a].positions[1][1] = 0;
if(playerCount != 0) {
snakes[a].isPlayer = true;
playerCount--;
}
}
return snakes;
}
void deleteFirstObject(struct Snake *tmpSnake) {
for (int a = 0; a < (*tmpSnake).currSize; a++) {
if (a + 1 != (*tmpSnake).currSize) {
(*tmpSnake).positions[a][0] = (*tmpSnake).positions[a + 1][0];
(*tmpSnake).positions[a][1] = (*tmpSnake).positions[a + 1][1];
}
}
}
long long timeMs() {
struct timeval tv{};
gettimeofday(&tv, nullptr);
return (((long long) tv.tv_sec) * 1000) + (tv.tv_usec / 1000);
} | true |
1841277d7e2db522256d50c754641d8196483d1c | C++ | habib302/leetcode-1 | /166. Fraction to Recurring Decimal.cpp | UTF-8 | 1,113 | 2.75 | 3 | [] | no_license | class Solution {
public:
string fractionToDecimal(int num, int den) {
if( num == 0 ) return "0";
if( den == 1 ) return to_string(num);
if(num==INT_MAX&&den==-1)return to_string(INT_MIN) ;
if(num==INT_MIN&&den==-1)return "2147483648" ;
string sign = "";
if( ( num < 0 && den > 0 ) || ( num > 0 && den < 0 ) ) sign = "-";
num = abs( num );
den = abs( den );
string ans = sign + to_string(num/den);
unordered_map < long long int, int > check;
int idx = 0;
long long int rem = num % den;
if( !rem ) return ans;
ans += ".";
string afterFloat = "";
while( rem > 0 ) {
check[rem] = idx++;
afterFloat += to_string(rem * 10 / den );
rem = ( rem * 10 ) % den;
if( check.find( rem ) != check.end() ) {
afterFloat.insert(check[rem], "(");
ans += afterFloat;
ans += ")";
return ans;
}
}
return ans + afterFloat;
}
};
| true |
a0095a3fe2f534b885929e630d70995b87b5e68e | C++ | navpreetkaurr/OOP345_final | /milestone2/CustomerOrder.cpp | UTF-8 | 3,231 | 2.90625 | 3 | [] | no_license | // Name: Navpreet Kaur
// Seneca Student ID: 148332182
// Seneca email: nk79
// Date of completion: 26 March, 2020
//
// I confirm that I am the only author of this file
// and the content was created entirely by me.
#include "CustomerOrder.h"
#include"Utilities.h"
#include<vector>
#include<iostream>
#include<iomanip>
size_t CustomerOrder::m_widthField = 0u;
size_t temp = 0u;
CustomerOrder::CustomerOrder()
{
m_name = "";
m_product = "";
m_cntItem = 0;
m_lstItem = nullptr;
}
CustomerOrder::CustomerOrder(const std::string str)
{
Utilities utils;
size_t next_pos = 0;
bool check = false;
std::vector<Item*> tmpVec;
m_name = utils.extractToken(str, next_pos, check);
m_product = utils.extractToken(str, next_pos, check);
while (check) {
tmpVec.push_back(new Item(utils.extractToken(str, next_pos, check)));
}
if (temp < utils.getFieldWidth()) {
temp = utils.getFieldWidth();
}
m_cntItem = static_cast<unsigned int>(tmpVec.size());
m_lstItem = new Item * [m_cntItem];
for (size_t i = 0; i < m_cntItem; i++) {
m_lstItem[i] = std::move(tmpVec[i]);
}
}
CustomerOrder::CustomerOrder(CustomerOrder& copy)
{
throw "ERROR: Cannot make copies.";
}
CustomerOrder::CustomerOrder(CustomerOrder&& move) noexcept {
*this = std::move(move);
}
CustomerOrder& CustomerOrder::operator=(CustomerOrder&& mv)
{
if (this != &mv) {
m_name = mv.m_name;
m_product = mv.m_product;
m_cntItem = mv.m_cntItem;
m_lstItem = mv.m_lstItem;
m_widthField = mv.m_widthField;
mv.m_name = "";
mv.m_product = "";
mv.m_cntItem = 0;
mv.m_lstItem = nullptr;
mv.m_widthField = 0;
}
return *this;
// TODO: insert return statement here
}
CustomerOrder::~CustomerOrder() {
delete[] m_lstItem;
m_lstItem = nullptr;
}
bool CustomerOrder::isItemFilled(std::string str) const
{
for (size_t i = 0; i < m_cntItem; i++) {
if (m_lstItem[i]->m_itemName == str) {
if (!m_lstItem[i]->m_isFilled) {
return false;
}
}
}
return true;
}
bool CustomerOrder::isOrderFilled() const
{
for (size_t i = 0; i < m_cntItem; i++) {
if (m_lstItem[i]->m_isFilled == false)
return false;
}
return true;
}
void CustomerOrder::fillItem(Station& station, std::ostream& os)
{
for (size_t i = 0; i < m_cntItem; i++) {
if (m_lstItem[i]->m_itemName == station.getItemName()) {
if (station.getQuantity() != 0) {
station.updateQuantity();
m_lstItem[i]->m_serialNumber = station.getNextSerialNumber() - 1;
m_lstItem[i]->m_isFilled = true;
os << (m_lstItem[i]->m_isFilled ? " Filled" : "Unfilled") << " "
<< m_name << ", " << m_product << " [" << m_lstItem[i]->m_itemName << "]" << std::endl;
}
else if (station.getQuantity() == 0) {
os << " Unable to fill " << m_name << ", " << m_product << " [" << m_lstItem[i]->m_itemName << "]" << std::endl;
}
}
}
}
void CustomerOrder::display(std::ostream& os) const {
m_widthField = temp;
os << m_name << " - " << m_product << std::endl;
for (size_t i = 0; i < m_cntItem; i++) {
os << std::setw(6) << std::setfill('0') << "[" << m_lstItem[i]->m_serialNumber << "] " << std::setfill(' ') << std::setw(m_widthField) << m_lstItem[i]->m_itemName << " - ";
os << (isItemFilled(m_lstItem[i]->m_itemName) ? "Filled" : "MISSING") << std::endl;
}
}
| true |
5f16d42a08496c3b97cfa43ba74ce1c85c75f2ee | C++ | shadab16/SymlinkMerge | /src/invalid_path.h | UTF-8 | 491 | 2.59375 | 3 | [] | no_license | /*
* invalid_path.h
*
* Author: Shadab Ansari
*/
#ifndef INVALID_PATH_H_
#define INVALID_PATH_H_
#include <exception>
#include "boost/filesystem.hpp"
namespace SymlinkMerge {
namespace fs = boost::filesystem;
class invalid_path : public std::exception {
protected:
const fs::path _path;
public:
invalid_path(fs::path) throw();
const fs::path path() const throw();
virtual const char* what() const throw();
virtual ~invalid_path() throw();
};
}
#endif /* INVALID_PATH_H_ */
| true |
9ca3369f555c9d0d63550f6e8b3d575323ca7b83 | C++ | rika77/competitive_programming | /atcoder/event/dwa/b.cpp | UTF-8 | 307 | 2.625 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
using namespace std;
int main(){
string a;
cin >> a;
int cnt2=0;
int cnt5=0;
for (int i=0;i<a.length();i++) {
if (a[i]=='2') cnt2++;
else cnt5++;
}
if (cnt2 != cnt5) {
cout << "-1" <<endl;
return 0;
}
return 0;
}
| true |