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
8c6a44cdb332cfa1694a293ec3ad31fc2f399254
C++
kamyu104/LeetCode-Solutions
/C++/the-skyline-problem.cpp
UTF-8
5,722
3.171875
3
[ "MIT" ]
permissive
// Time: O(nlogn) // Space: O(n) // BST solution. class Solution { public: enum {start, end, height}; struct Endpoint { int height; bool isStart; }; vector<pair<int, int> > getSkyline(vector<vector<int> >& buildings) { map<int, vector<Endpoint>> point_to_height; // Ordered, no duplicates. for (const auto& building : buildings) { point_to_height[building[start]].emplace_back(Endpoint{building[height], true}); point_to_height[building[end]].emplace_back(Endpoint{building[height], false}); } vector<pair<int, int>> res; map<int, int> height_to_count; // BST. int curr_max = 0; // Enumerate each point in increasing order. for (const auto& kvp : point_to_height) { const auto& point = kvp.first; const auto& heights = kvp.second; for (const auto& h : heights) { if (h.isStart) { ++height_to_count[h.height]; } else { --height_to_count[h.height]; if (height_to_count[h.height] == 0) { height_to_count.erase(h.height); } } } if (height_to_count.empty() || curr_max != height_to_count.crbegin()->first) { curr_max = height_to_count.empty() ? 0 : height_to_count.crbegin()->first; res.emplace_back(point, curr_max); } } return res; } }; // Time: O(nlogn) // Space: O(n) // Divide and conquer solution. class Solution2 { public: enum {start, end, height}; vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { const auto intervals = ComputeSkylineInInterval(buildings, 0, buildings.size()); vector<pair<int, int>> res; int last_end = -1; for (const auto& interval : intervals) { if (last_end != -1 && last_end < interval[start]) { res.emplace_back(last_end, 0); } res.emplace_back(interval[start], interval[height]); last_end = interval[end]; } if (last_end != -1) { res.emplace_back(last_end, 0); } return res; } // Divide and Conquer. vector<vector<int>> ComputeSkylineInInterval(const vector<vector<int>>& buildings, int left_endpoint, int right_endpoint) { if (right_endpoint - left_endpoint <= 1) { // 0 or 1 skyline, just copy it. return {buildings.cbegin() + left_endpoint, buildings.cbegin() + right_endpoint}; } int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2); auto left_skyline = ComputeSkylineInInterval(buildings, left_endpoint, mid); auto right_skyline = ComputeSkylineInInterval(buildings, mid, right_endpoint); return MergeSkylines(left_skyline, right_skyline); } // Merge Sort vector<vector<int>> MergeSkylines(vector<vector<int>>& left_skyline, vector<vector<int>>& right_skyline) { int i = 0, j = 0; vector<vector<int>> merged; while (i < left_skyline.size() && j < right_skyline.size()) { if (left_skyline[i][end] < right_skyline[j][start]) { merged.emplace_back(move(left_skyline[i++])); } else if (right_skyline[j][end] < left_skyline[i][start]) { merged.emplace_back(move(right_skyline[j++])); } else if (left_skyline[i][start] <= right_skyline[j][start]) { MergeIntersectSkylines(merged, left_skyline[i], i, right_skyline[j], j); } else { // left_skyline[i][start] > right_skyline[j][start]. MergeIntersectSkylines(merged, right_skyline[j], j, left_skyline[i], i); } } // Insert the remaining skylines. merged.insert(merged.end(), left_skyline.begin() + i, left_skyline.end()); merged.insert(merged.end(), right_skyline.begin() + j, right_skyline.end()); return merged; } // a[start] <= b[start] void MergeIntersectSkylines(vector<vector<int>>& merged, vector<int>& a, int& a_idx, vector<int>& b, int& b_idx) { if (a[end] <= b[end]) { if (a[height] > b[height]) { // |aaa| if (b[end] != a[end]) { // |abb|b b[start] = a[end]; merged.emplace_back(move(a)), ++a_idx; } else { // aaa ++b_idx; // abb } } else if (a[height] == b[height]) { // abb b[start] = a[start], ++a_idx; // abb } else { // a[height] < b[height]. if (a[start] != b[start]) { // bb merged.emplace_back(move(vector<int>{a[start], b[start], a[height]})); // |a|bb } ++a_idx; } } else { // a[end] > b[end]. if (a[height] >= b[height]) { // aaaa ++b_idx; // abba } else { // |bb| // |a||bb|a if (a[start] != b[start]) { merged.emplace_back(move(vector<int>{a[start], b[start], a[height]})); } a[start] = b[end]; merged.emplace_back(move(b)), ++b_idx; } } } };
true
fb473cf5800acc923b00c27c679f4032194fa738
C++
csg-tokyo/caldwell
/SyntheticProgramPair/SensorMonitorOO/src/platform.cpp
UTF-8
527
3.015625
3
[]
no_license
/* * new.cpp * * Created on: Mar 29, 2017 * Author: Joe */ #include <stdint.h> typedef unsigned int size_t; uint8_t* g_heap_memory[8096]; uint32_t position; void* operator new (size_t size) { uint32_t allocatedPosition = position; position += size; return (void*) g_heap_memory[allocatedPosition]; } void* operator new[] (size_t size) { return operator new(size); } void operator delete (void* pointer) { // Do nothing! This platform can only allocate statically. }
true
ea2346dc1e5a1cd7377fb72dbf4d128b60bcfa61
C++
AnjaliG1999/DSA
/cpp/dynamic-programming/countSubset.cpp
UTF-8
736
3.015625
3
[]
no_license
// Online C++ compiler to run C++ program online #include <bits/stdc++.h> using namespace std; int countSubsetSum (int *arr, int sum, int n) { int t[n+1][sum+1]; for(int i=0; i<=n; i++){ for(int j=0; j<=sum; j++){ if(i == 0) t[i][j] = 0; if(j == 0) t[i][j] = 1; else if(arr[i-1] <= j){ t[i][j] = t[i-1][j] + t[i-1][j-arr[i-1]]; } else { t[i][j] = t[i-1][j]; } } } return t[n][sum]; } int main() { int arr[] = {1, 1, 1, 1}; int sum = 1; int n = sizeof(arr) / sizeof(arr[0]); // memset(t, 0, sizeof(t)); int result = countSubsetSum(arr, sum, n); cout << result; }
true
a2008ac1e838f49208c3560c8e3de4610822de37
C++
onehundredfifteen/autotest
/test_process.h
UTF-8
1,210
2.53125
3
[]
no_license
#ifndef TEST_PROCESS_H #define TEST_PROCESS_H #include <windows.h> #include <string> typedef unsigned long int time_int; class TestProcess { public: TestProcess(std::string cmd, std::string input, int max_waitfor = 0 ); //TestProcess() : TestProcess("cmd", "echo no argument passed") {}; short getError() const; std::string getOutputString() const; time_int getTime() const; int getExitCode() const; bool isTimeout() const; private: HANDLE hChildStd_IN_Rd; HANDLE hChildStd_IN_Wr; HANDLE hChildStd_OUT_Rd; HANDLE hChildStd_OUT_Wr; HANDLE Guard; PROCESS_INFORMATION processInformation; STARTUPINFO startupInfo; SECURITY_ATTRIBUTES securityAttributes; short internal_error; std::string result_output; int result_exit_code; time_int result_time; bool timeout; int waitfor; //max miliseconds to wait, else kill std::string test_input; std::string cmd_arg; void RunTest(); void InitPipes(); void ReadOutputFromPipe(); void WriteInputToPipe(); void AddEnterToInput(); static DWORD WINAPI GuardThreadStart( LPVOID lpParam ); DWORD GuardThreadMonitor(); void RunGuardThread(); }; #endif
true
e0fafa0b9b4fcdffe0b3d0a67a0daaf481287e4e
C++
rleonborras/Development
/String_Class/String_Class/String_Class.h
UTF-8
1,452
3.3125
3
[]
no_license
#ifndef STRING_CLASS #define STRING_CLASS #include <string.h> class String { private: char* str = nullptr; unsigned int mem_allocated = 0; public: String(const char* string){ if (string != NULL) { mem_allocated = strlen(string) + 1; str = new char[mem_allocated]; strcpy(str,string); } }; String(const String &string){ if (string.str != NULL) { mem_allocated = string.mem_allocated; str = new char[mem_allocated]; strcpy(str,string.str); } }; String(){}; ~String(){ if (str != NULL) delete[] str; }; public: bool empty() const { if (str != NULL) { return false; } else return true; } unsigned int lenght() const { if (str != NULL) return strlen(str); } void clear() { if (str != NULL) { delete[] str; mem_allocated = 0; } } void print() { if (str!= NULL) std::cout << str << std::endl; } public: String operator=(const String &string) { mem_allocated=(string.mem_allocated); if (mem_allocated != 0) { delete[]str; str = new char[mem_allocated]; return strcpy_s(str,sizeof(str), string.str); } else return *this; } // //void operator+(const String &string) { // if (str != NULL) { // strcat(str, string.str); // mem_allocated += string.mem_allocated; // } // else{ // strcpy(str, string.str); // mem_allocated = string.mem_allocated; // } //} //bool operator == (const String &string) { //} }; #endif // !1
true
e00e93529df5294cbb4166624d67523e5bbb744e
C++
caniro/algo-note
/Baekjoon/Step8/1011/main.cpp
UTF-8
739
3.1875
3
[]
no_license
#include <iostream> void calc(int& count, int i, int len) { if (len <= 0) return ; if (i - 1 <= len && len <= i + 1) count++; else if (len == i + 2 && i != 0) count += 2; else if (i + 2 < len && len < 2 * (i - 1)) count += 2; else if (2 * (i - 1) <= len && len <= 2 * (i + 1)) count += 2; else if (2 * (i + 1) + 1 < len && len < 2 * (i + 1) + i - 1) { count += 3; } else { count += 2; calc(count, i + 1, len - 2 * (i + 1)); } } int main() { using namespace std; int start_point; int end_point; int len; int T; cin >> T; for (int i = 0; i < T; ++i) { cin >> start_point >> end_point; len = end_point - start_point; int count; count = 0; calc(count, 0, len); cout << count << '\n'; } }
true
30b15ddd6f8bacbc07ff90553958a9b897d3a3cd
C++
zsebastian/LD26
/LD26/LD26/Tree.h
UTF-8
708
2.546875
3
[]
no_license
#ifndef TREE_H #define TREE_H #include "Entity.h" #include <SFML\System\Vector2.hpp> class Canvas; class Tree : public Entity { public: Tree(float x, float y); virtual void update(); virtual void render(Canvas& canvas); virtual void handleCollision(std::shared_ptr<Entity>); virtual void setAblaze(); virtual bool isAblaze(); virtual sf::Vector2f getPosition(); virtual sf::FloatRect getBounds(); virtual bool isSolid() {return true;}; virtual bool needsCollision() {return false;}; void chop(float strength); protected: virtual void onDeath(); private: sf::Vector2f mPosition; bool mIsAblaze; float mHealth; int mShake; float mShakePosition; float mShakePositionDirection; }; #endif
true
f57fa489eae4cd288b87ebb54f756df189b97f64
C++
juakofz/SuperPong
/Pong/source/Globals.h
UTF-8
407
2.890625
3
[]
no_license
#pragma once #include <algorithm> // ------------------------------------------------- Global objects and constants //Screen dimension constants const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; // ------------------------------------------------- Useful functions template <typename T> T clip(const T & n, const T & lower, const T & upper) { return std::max(lower, std::min(n, upper)); }
true
bf64f8def0ea670ea3504f5f0a33275e4885e516
C++
whunt1965/EC535_Final_Project
/fighterguy/fighter.cpp
UTF-8
3,174
3.140625
3
[]
no_license
#include "fighter.h" #include<QtMath> //default constructor Fighter::Fighter() : name("default"), health(20), blocking(false){} //parameterized constructor Fighter::Fighter(const QString &fname, const QVector<QPixmap>& pics) : name(fname), pics(pics), health(20), blocking(false){ setPixmap(pics[0].scaled(120,240,Qt::KeepAspectRatio)); } //destructor - clean up dynamically allocated memory Fighter::~Fighter(){ delete timer; delete animationUp; } //sets a fighter's opponent void Fighter::setOpponent(Fighter* opponent){ this->opponent = opponent; } //indicates if a fighter is alive bool Fighter::isAlive(){ return this->health > 0; } //returns a fighter's health int Fighter::getHealth(){ return this->health; } //set blocking state to true void Fighter::block(){ setPixmap(pics[3].scaled(120,240,Qt::KeepAspectRatio)); this->blocking = true; } //set blocking state to false void Fighter::unblock(){ reset(); this->blocking = false; } //move a fighter in -x direction void Fighter::moveLeft(){ reset(); setPos(x()-16, y()); } //move a fighter in +x direction void Fighter::moveRight(){ reset(); setPos(x()+16, y()); } //make fighter jump 1 unit (up) in y direction void Fighter::jump(){ if(timer == nullptr || timer->state() == QTimeLine::NotRunning){ delete timer; delete animationUp; reset(); timer = new QTimeLine(500); timer->setFrameRange(0, 100); animationUp = new QGraphicsItemAnimation; animationUp->setItem(this); animationUp->setTimeLine(timer); animationUp->setPosAt(.2, QPointF(x(), y()-50)); animationUp->setPosAt(1, QPointF(x(), y())); timer->start(); } } //Determines if an opponent is in range for an attack bool Fighter::opponentInRange(){ qreal xdist = qFabs(this->pos().x() - this->opponent->pos().x()); qreal ydist = qFabs(this->pos().y() - this->opponent->pos().y()); if(xdist <= 220 && ydist == 0){ return true; } return false; } //Kick an opponent void Fighter::kick(){ setPixmap(pics[1].scaled(120,240,Qt::KeepAspectRatio)); if (this->opponentInRange()){ this->opponent->takeKick(); } } //Punch an opponent void Fighter::punch(){ setPixmap(pics[2].scaled(120,240,Qt::KeepAspectRatio)); //.scaled(140,280,Qt::KeepAspectRatio)); if (this->opponentInRange()){ this->opponent->takePunch(); } } //indicates if a fighter is blocking bool Fighter::isBlocking(){ return this->blocking; } //take a kick void Fighter::takeKick(){ this->isBlocking()? this->health-=1 : this->health -=2; setPixmap(pics[4].scaled(120,240,Qt::KeepAspectRatio)); } //take a punch void Fighter::takePunch(){ if(!this->isBlocking()){ setPixmap(pics[4].scaled(120,240,Qt::KeepAspectRatio)); this->health-=1; } } //reset to default image void Fighter::reset(){ setPixmap(pics[0].scaled(120,240,Qt::KeepAspectRatio)); } //getter for opponent pointer Fighter *Fighter::getOpponent(){ return this->opponent; } QString Fighter::getName(){ return name; }
true
cff6e7f78a580e71306431bf57dec22354f6ae78
C++
Evalir/Algorithms
/Lectures/Mathematics/Fibo-Fact/DPFactFib.cpp
UTF-8
1,021
2.78125
3
[]
no_license
#include <iostream> #include <vector> #include <set> #include <map> #include <stack> #include <queue> #include <cmath> #include <algorithm> #include <list> #include <bitset> #define INF (int)1e9; using namespace std; typedef long long llong; typedef unsigned long long uint64; typedef vector<int> VI; typedef vector<VI> VII; int N; int memF[10000]; unsigned int fact(int n) { if (n == 0 || n == 1) return 1; if (memF[n] > 1) return memF[n]; memF[n] = n * fact(n - 1); return memF[n]; } int memFib[10000]; unsigned int fib(int n) { if (n == 0) return 0; if (n == 1) return 1; if (memFib[n] > 0) return memFib[n]; memFib[n] = fib(n-1) + fib(n-2); return memFib[n]; } int main() { N = 40; VI facts; VI fibs; for(int i = 0; i < N; i++) { facts.push_back(fact(i)); fibs.push_back(fib(i)); } for(int x : facts) { cout << x << " IN FACT ARRAY " <<endl; } for(int x : fibs) { cout << x << " IN FIB ARRAY " <<endl; } return 0; }
true
a3e3d4259c05799b9350488e45905e9503057a24
C++
jwaterworth/snooker_scoreboard
/rgb_test/rgb_test.ino
UTF-8
375
2.609375
3
[]
no_license
#include <RGBLed.h> #define RED_PIN 9 #define GREEN_PIN 10 #define BLUE_PIN 11 RGBLed led(RED_PIN, GREEN_PIN, BLUE_PIN); void setup() { } void loop() { led.Red(); delay(1000); led.Yellow(); delay(1000); led.Green(); delay(1000); led.Brown(); delay(1000); led.Blue(); delay(1000); led.Pink(); delay(1000); led.Black(); delay(1000); }
true
269ab41a908a95227938c889b201dde7d0024276
C++
dburian/cpp_mfo
/src/operation_result.h
UTF-8
2,708
2.890625
3
[]
no_license
#ifndef MFO_OPERATION_RESULT_HEADER #define MFO_OPERATION_RESULT_HEADER #include <filesystem> #include <future> #include <vector> #include "operation_result.h" namespace mfo { template<class ReturnType, class ArgumentType> class operation_result { public: using argument_t = ArgumentType; using return_t = ReturnType; operation_result(const std::shared_future<std::vector<return_t>>& res, std::size_t index, operation_type oper_t, const argument_t& arg) : m_holds_error_state{false}, m_res_retrieved{false}, m_err{"", std::error_code()}, m_res{res}, m_index{index}, m_arg{arg}, m_oper_t{std::move(oper_t)} {} operation_result(std::filesystem::filesystem_error&& err, operation_type oper_t, const argument_t& arg) : m_holds_error_state{true}, m_res_retrieved{false}, m_err{std::move(err)}, m_arg{arg}, m_oper_t{oper_t} {} const argument_t& peek_operation_arguments() const; const operation_type& peek_operation_type() const; const return_t& get(); private: bool m_holds_error_state; bool m_res_retrieved; std::filesystem::filesystem_error m_err; std::shared_future<std::vector<return_t>> m_res; return_t m_cached_res; std::size_t m_index; argument_t m_arg; operation_type m_oper_t; }; using copy_operation_result = operation_result<bool, copy_arg>; using move_operation_result = operation_result<bool, move_arg>; using remove_operation_result = operation_result<std::uintmax_t, remove_arg>; template<class UnaryPredicate> using find_operation_result = operation_result<std::vector<std::filesystem::directory_entry>, find_arg<UnaryPredicate>>; template<class UnaryPredicate> using find_recursive_operation_result = operation_result<std::vector<std::filesystem::directory_entry>, find_recursive_arg<UnaryPredicate>>; } template<class ReturnType, class ArgumentType> const ArgumentType& mfo::operation_result<ReturnType, ArgumentType>::peek_operation_arguments() const { return m_arg; } template<class ReturnType, class ArgumentType> const mfo::operation_type& mfo::operation_result<ReturnType, ArgumentType>::peek_operation_type() const { return m_oper_t; } template<class ReturnType, class ArgumentType> const ReturnType& mfo::operation_result<ReturnType, ArgumentType>::get() { if(m_holds_error_state) throw m_err; if(!m_res_retrieved) m_cached_res = m_res.get()[m_index]; m_res_retrieved = true; return m_cached_res; } #endif //MFO_OPERATION_RESULT_HEADER
true
cad46b92a29b88b9a928aa0c7587e312908ed378
C++
Salyel/QtGame
/player.h
UTF-8
3,519
2.734375
3
[]
no_license
#ifndef PLAYER_H #define PLAYER_H #include <QPropertyAnimation> #include <QEasingCurve> #include "entities/entity.h" /** * Le joueur (c'est toi!) */ class Player : public Entity { Q_OBJECT Q_PROPERTY(qreal jumpFactor READ getJumpFactor WRITE setJumpFactor NOTIFY jumpFactorChanged) public: Player(); ~Player(); /* SURCHARGES */ QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *options, QWidget *widget); /* GETTERS ET SETTERS */ int getDirection() const; // Pour gérer les déplacements void addDirection(const int direction); // du joueur qreal getJumpFactor() const; // Utilisée uniquement par void setJumpFactor(const qreal &newJumpFactor); // l'animation de saut void setLastPlatform(QGraphicsItem *item); // Utilisée uniquement au lancement du jeu bool isFalling(); int getHealth(); int getCoins(); int getBoxes(); void setBoxes(int boxes); public slots: /* Ces méthodes changent le state et l'animation du joueur, * puis déclanchent les timers correspondant à l'action */ void stand(); void jump(); void walk(); void fall(); private slots: /* Ces méthodes sont appelée par des signaux et gèrent * les mouvements du joueur */ void movePlayer(); void jumpPlayer(); void fallPlayer(); void checkTimer(); signals: void jumpFactorChanged(qreal); // Signal émit par l'animation de saut lorsque jumpFactor change void playerMoved(int); // Signal émit lorsque le joueur bouge void statsChanged(); // Signal émit lorsque les stats du joueur changent private: const int velocity = 7; // Vitesse const int jumpHeight = 140; // Hauteur de saut enum State { // État actuel Standing = 0, Walking, Jumping, Falling }; State state; int direction; // Direction (-1=gauche, 0=immobile, 1=droite) // Stats int health; int coins; int boxes; // Sprites QPixmap walkPixmap; QPixmap standPixmap; QPixmap jumpPixmap; QPixmap hurtPixmap; QPixmap walk1, walk2, walk3, walk4, walk5, walk6, walk7, walk8, walk9, walk10, walk11; int walkFrame; // Numéro de la frame actuel de l'animation de marche bool dead; // Assez explicite... // Gestion de l'animation de saut QPropertyAnimation *jumpAnimation; qreal jumpFactor; // Timers pour le déplacement QTimer *moveTimer; QTimer *fallTimer; QGraphicsItem *lastPlatform; // Dernière plateforme (utilisée pour savoir la hauteur d'un saut) const qreal groundLevel = 672; // Hauteur du sol (vraiment nécessaire ?) /* MÉTHODES PRIVÉES */ RigidBody * collidingPlatforms(); void checkCollisions(); void die(); // "Tue" le joueur void nextFrame(); // Change la frame de marche // Définition des hitboxes du joueur bool isTouchingFoot(QGraphicsItem *item); // Renvoie true si les pieds du joueur touchent 'item' (utile pour tuer les mobs) bool isTouchingHead(QGraphicsItem *item); // Renvoie true si la tête du joueur touche 'item' (utile pour casser les caisses) bool isTouchingPlatform(QGraphicsItem *item); // Renvoie true si les pieds du joueur touchent 'item' (plus flexible, utile pour la chute) }; #endif // PLAYER_H
true
2a38f9d6afddb319611e364fcdd577eebfc71d08
C++
overnew/CodeSaving
/LeetCode/1.Two Sum.cpp
UTF-8
515
3.140625
3
[]
no_license
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<pair<int, int>> arr(nums.size()); for (int i=0; i<nums.size() ; ++i) arr[i] = {nums[i], i}; sort(arr.begin(), arr.end()); int left = 0, right = arr.size() - 1; int add_num; while (1) { add_num = arr[left].first + arr[right].first; if (add_num > target) --right; else if (add_num < target) ++left; else break; } return vector<int> {arr[left].second, arr[right].second}; } };
true
8c41c864e57b2bd4c71ac11b0128891238ba51c0
C++
mls-m5/xml-loader
/src/xmldocument.cpp
UTF-8
7,861
2.953125
3
[]
no_license
/* * xmldocument.cpp * * Created on: 6 okt 2014 * Author: Mattias Larsson Sköld */ #include "xmldocument.h" #include <sstream> #include <fstream> #include <stack> #include <ctype.h> using std::istream; using std::ostream; using std::stringstream; using std::string; #define DEBUG if(0) class Token: public string{ public: enum TokenType { Space, Word, StartTag, StartEndTag, StartHeaderTag, EndStartTag, EndTag, EndHeaderTag, Digit, Literal, CharacterData, None }; Token (string str, TokenType type): type(type){ this->string::operator=(str); } TokenType type; }; XmlDocument::XmlDocument() { } XmlDocument::~XmlDocument() { } Token getNextToken(std::istream &stream){ char c; stringstream ss; Token::TokenType mode = Token::Space; auto isAlphaOrSimilar = [](char c) { return isalpha(c) || c == '-' || c == '_' || c == ':'; }; while (!stream.eof()){ c = stream.get(); switch (mode){ case Token::Space: if (isspace(c)){ continue; } else if(isAlphaOrSimilar(c)){ ss.put(c); mode = Token::Word; break; } else if (isdigit(c)){ ss.put(c); mode = Token::Digit; break; } else if (c == '"'){ ss.put(c); mode = Token::Literal; break; } else if (c == -1){ //Something went wrong, probably end of input return Token(ss.str(), mode); } else{ ss.put(c); switch(c){ case '<': if (stream.peek() == '/'){ ss.put(stream.get()); return Token(ss.str(), Token::StartEndTag); } if (stream.peek() == '?') { ss.put(stream.get()); return Token(ss.str(), Token::StartHeaderTag); } else{ mode = Token::StartTag; } break; case '/': if (stream.peek() == '>'){ ss.put(stream.get()); return Token(ss.str(), Token::EndStartTag); } break; case '>': mode = Token::EndTag; break; case '?': if (stream.peek() == '>') { ss.put(stream.get()); return Token(ss.str(), Token::EndHeaderTag); } } return Token(ss.str(), mode); } break; case Token::Digit: if (isdigit(c) || c == '.'){ ss.put(c); } else{ stream.unget(); return Token(ss.str(), mode); } break; case Token::Word: if (isdigit(c) || isAlphaOrSimilar(c)){ ss.put(c); } else{ stream.unget(); return Token(ss.str(), mode); } break; case Token::Literal: ss.put(c); if (c == '"'){ auto str = ss.str(); str.erase(0, 1); str.erase(str.length()-1); return Token(str, mode); } break; } } return Token(ss.str(), mode); } std::string cite(std::string str) { return "\"" + str + "\""; } Token parseData(istream &stream){ stringstream ss; while (isspace(stream.peek())){ stream.get(); } while (stream.peek() != '<' && !stream.eof()){ auto c = stream.get(); if (isspace(c)){ while (isspace(stream.peek())){ stream.get(); } c = ' '; } ss.put(c); } return Token(ss.str(), Token::CharacterData); } void XmlDocument::load(std::istream &stream) { using std::cout; using std::endl; using std::cerr; #define EXPECT_ERROR(x, y) { cout << __FILE__ << ": expected token " << x << " not " << y << ". abort..." << endl; return; } #define EXPECT_TOKEN(x) if (token.type != x) EXPECT_ERROR(x, token.type); XmlDom *currentStructure = 0; std::stack<XmlDom*> stack; while (!stream.eof()){ auto token = getNextToken(stream); DEBUG cout << token << endl; switch (token.type) { case Token::StartTag: { token = getNextToken(stream); EXPECT_TOKEN(Token::Word); DEBUG cout << "new tag " << token << endl; if (currentStructure == 0){ name = token; currentStructure = this; } else{ stack.push(currentStructure); currentStructure->push_back(XmlDom(token)); currentStructure = &currentStructure->back(); } token = getNextToken(stream); bool inputData = true; while (inputData){ if (token.type == Token::EndStartTag){ if (!stack.empty()) { currentStructure = stack.top(); stack.pop(); } inputData = false; } else if (token.type == Token::EndTag){ inputData = false; } else if (token.type == Token::Word){ //Read arguments string argumentName = token; token = getNextToken(stream); if (token.compare("=")){ EXPECT_ERROR("=", token); } token = getNextToken(stream); currentStructure->setAttribute(argumentName, token); token = getNextToken(stream); } else { EXPECT_ERROR("argument", token); } } break; } case Token::StartEndTag: { token = getNextToken(stream); EXPECT_TOKEN(Token::Word); if (token.compare(currentStructure->name)){ EXPECT_ERROR(currentStructure->name, token); } token = getNextToken(stream); EXPECT_TOKEN(Token::EndTag); DEBUG cout << "end tag " << currentStructure->name << endl; if (stack.empty()){ return; //Finished } else { currentStructure = stack.top(); stack.pop(); } } break; case Token::StartHeaderTag: { token = getNextToken(stream); if (token != "xml") { cerr << "in xml header, expected xml, got " << token << endl; } token = getNextToken(stream); while(!stream.eof() && token.type != Token::EndHeaderTag) { EXPECT_TOKEN(Token::Word); string variableName = token; token = getNextToken(stream); if (token != "=") { cerr << "Expected '=' got " << token << endl; } token = getNextToken(stream); EXPECT_TOKEN(Token::Literal); if (variableName == "version") { version = token; } else if (variableName == "encoding") { encoding = token; } else if (variableName == "standalone") { standalone = token; } token = getNextToken(stream); } if (token.type != Token::EndHeaderTag) { std::cerr << "reached end of xml file without end of header" << endl; } break; } default: //Read data token += parseData(stream); if (currentStructure){ currentStructure->data = token; } } } } void XmlDocument::save(std::ostream &stream) { stream << "<?xml"; if (!version.empty()) { stream << " version=" << cite(version); } if (!encoding.empty()) { stream << " encoding=" << cite(encoding); } if (!standalone.empty()) { stream << " standalone=" << cite(standalone); } stream << " ?>" << std::endl; print(0, &stream); } void indent(int level, std::ostream *target){ for (int i = 0; i < level; ++i){ *target << " "; } } void XmlDom::print(int level, std::ostream *printTarget) { using std::endl; auto target = printTarget; if (!target){ target = &std::cout; } indent(level, target); *target << "<" << name; for (const auto &it: attributes) { *target << " " << it.first << "=" << cite(it.second); } bool doIndent = size(); if (size() || !data.empty()){ *target << ">"; if (doIndent){ *target << endl; } if (!data.empty()){ if (doIndent){ indent(level + 1, target); } *target << data; if (doIndent){ *target << endl; } } for (auto &it: *this){ it.print(level + 1, target); } if (doIndent){ indent(level, target); } *target << "</" << name << ">" << endl; } else{ *target << "/>" << endl; } } XmlDom* XmlDom::find(std::string name) { for (auto &it: *this){ if (it.name.compare(name) == 0){ return &it; } } return 0; } std::vector<XmlDom*> XmlDom::findAll(std::string name) { std::vector<XmlDom*> retList; for (auto &it: *this){ if (it.name.compare(name) == 0){ retList.push_back(&it); } } return retList; } bool XmlDocument::loadFile(std::string fname) { std::ifstream file(fname); if (!file.is_open()){ return false; } load(file); return true; } void XmlDocument::saveFile(std::string fname) { std::ofstream file(fname); save(file); }
true
f9ed820beb4d599af81a1befd2bd958d62ffce3e
C++
kenii28/CS-1124
/Object-Oriented Programming/rec09/rec09.cpp
UTF-8
3,047
2.6875
3
[]
no_license
#include "Registar.h" #include <iostream> #include <fstream> #include <vector> #include <string> using namespace BrooklynPoly; using namespace std; //int main() { // // Registar registrar; // // cout << "No courses or students added yet\n"; // registrar.printReport(); // // cout << "AddCourse CS101.001\n"; // registrar.addCourse("CS101.001"); // registrar.printReport(); // // cout << "AddStudent FritzTheCat\n"; // registrar.addStudent("FritzTheCat"); // registrar.printReport(); // // cout << "AddCourse CS102.001\n"; // registrar.addCourse("CS102.001"); // registrar.printReport(); // // cout << "EnrollStudentInCourse FritzTheCat CS102.001\n"; // registrar.enrollStudentInCourse("FritzTheCat", "CS102.001"); // cout << "EnrollStudentInCourse FritzTheCat CS101.001\n"; // registrar.enrollStudentInCourse("FritzTheCat", "CS101.001"); // registrar.printReport(); // // cout << "EnrollStudentInCourse Bullwinkle CS101.001\n"; // cout << "Should fail, i.e. do nothing, since Bullwinkle is not a student.\n"; // registrar.enrollStudentInCourse("Bullwinkle", "CS101.001"); // registrar.printReport(); // // cout << "CancelCourse CS102.001\n"; // registrar.cancelCourse("CS102.001"); // registrar.printReport(); // // /* // // [OPTIONAL - do later if time] // cout << "ChangeStudentName FritzTheCat MightyMouse\n"; // registrar.changeStudentName("FritzTheCat", "MightyMouse"); // cout << registrar << endl; // or registrar.printReport() // // cout << "DropStudentFromCourse MightyMouse CS101.001\n"; // registrar.dropStudentFromCourse("MightyMouse", "CS101.001"); // cout << registrar << endl; // or registrar.printReport() // // cout << "RemoveStudent FritzTheCat\n"; // registrar.removeStudent("FritzTheCat"); // cout << registrar << endl; // or registrar.printReport() // */ // // cout << "Purge for start of next semester\n"; // registrar.purge(); // registrar.printReport(); // system("pause"); //} void openFile(ifstream& ifs, string& fileName) { ifs.open(fileName); if (!ifs) { cout << "The file doesn't exist."; exit(1); } } void processFile(ifstream& ifs, Registar registrar) { string firstWord; string secondWord; string thirdWord; while (ifs >> firstWord) { if (firstWord == "PrintReport") { registrar.printReport(); } else if (firstWord == "AddCourse") { ifs >> secondWord; registrar.addCourse(secondWord); } else if (firstWord == "AddStudent") { ifs >> secondWord; registrar.addStudent(secondWord); } else if (firstWord == "EnrollStudentInCourse") { ifs >> secondWord; ifs >> thirdWord; registrar.enrollStudentInCourse(secondWord, thirdWord); } else if (firstWord == "CancelCourse") { ifs >> secondWord; registrar.cancelCourse(secondWord); } else { // purge registrar.purge(); } } } int main() { string fileName = "registar.txt"; ifstream ifs; openFile(ifs, fileName); Registar registrar; processFile(ifs, registrar); system("pause"); }
true
1b83151a587da3dda71d8d0124286818af47e7e9
C++
satyampandey9811/competitive-programming
/2. Leetcode/hard level/045. unique paths III.cpp
UTF-8
1,372
2.890625
3
[]
no_license
// link to question - https://leetcode.com/problems/unique-paths-iii/ class Solution { public: int m, n; vector<vector<int>> a; vector<vector<bool>> vis; int ans; void go(int i, int j, int& ex, int& ey) { if(i < 0 or j < 0 or i == m or j == n or a[i][j] == -1 or vis[i][j]) return; if(i == ex and j == ey) { for(int r = 0; r < m; r++) { for(int c = 0; c < n; c++) { if(a[r][c] == 0 and !vis[r][c]) { return; } } } ans++; return; } vis[i][j] = true; go(i - 1, j, ex, ey); go(i + 1, j, ex, ey); go(i, j - 1, ex, ey); go(i, j + 1, ex, ey); vis[i][j] = false; } int uniquePathsIII(vector<vector<int>>& grid) { m = grid.size(), n = grid[0].size(); a = grid; ans = 0; vis.resize(m, vector<bool>(n, false)); int sx, sy, ex, ey; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(a[i][j] == 1) sx = i, sy = j; else if(a[i][j] == 2) ex = i, ey = j; } } go(sx, sy, ex, ey); return ans; } };
true
ad81b1d26731d92e3be390c08ddcd1c79a0f4750
C++
sarah2627/IMACWorld
/Imac_World/libs/glimac/src/Grid.cpp
UTF-8
4,330
2.9375
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include "glimac/Grid.hpp" #include "glimac/RadialBasisFunction.hpp" namespace glimac{ Grid::Grid() { for(int i=0; i < 10; i++) { for(int j=0; j<10; j++) { for(int k=0; k<3; k++) { m_Grid.push_back(ShapeGrid(i,-k,j, glm::vec3(0.16f, 0.46f, 0.74f))); } } } m_sizeGrid = m_Grid.size(); } void Grid::generateWorld(int iterator) { resetCube(); RadialBasisFunction test; for(int i=0; i<iterator; i++) { for(int j=0; j<iterator; j++) { for(int k=0; k<iterator;k++) { glm::vec3 v = {i,j,k}; // if the result is under 0, we don't create the cube if(test.calculBasisFunction(v) >= 0.0) { m_Grid.push_back(ShapeGrid(i,j,k, glm::vec3(i, j, k))); m_sizeGrid = m_Grid.size(); } } } } } int Grid::findCube(const int &x, const int &y, const int &z) // return index of the cube { for(int i=0; i< m_sizeGrid; i++) { if(x == m_Grid[i].get_CoordX()) { if(y == m_Grid[i].get_CoordY()) { if(z == m_Grid[i].get_CoordZ()) { return i; } } } } return -1; } void Grid::createCube(const int &x, const int &y, const int &z) { if(findCube(x,y,z) == -1 ) { m_Grid.push_back(ShapeGrid(x,y,z, glm::vec3(x, y, z))); m_sizeGrid = m_Grid.size(); } else std::cerr << "cube already exist" << std::endl; } void Grid::createCubeColor(const int &x, const int &y, const int &z, const int type, const int &r, const int &g, const int &b) { if(findCube(x,y,z) == -1 ) { m_Grid.push_back(ShapeGrid(x,y,z, glm::vec3(r, g, b))); m_sizeGrid = m_Grid.size(); if(type != 0 ) { changeType(x,y,z,type); } } else std::cerr << "cube already exist" << std::endl; } void Grid::changeColor(const int x, const int y, const int z, const glm::vec3 color) { if(findCube(x,y,z) != -1) { m_Grid[findCube(x,y,z)].set_Color(color); } } void Grid::changeType(const int x, const int y, const int z, const int type) { if(findCube(x,y,z) != -1) { m_Grid[findCube(x,y,z)].set_Type(type); } } void Grid::deleteCube(const int x, const int y, const int z) { int index = findCube(x,y,z); if(index != -1) { m_Grid.erase(m_Grid.begin() + index); m_sizeGrid = m_Grid.size(); } else std::cerr << "cube doesn't exist" << std::endl; } int Grid::UpColumn(const int x, const int y, const int z) { int indexCol = y; while(findCube(x,indexCol,z) != -1) { indexCol++; } return indexCol; } void Grid::extrudeCube(const int x, const int y, const int z) { int positionCursor = findCube(x,y,z); if(positionCursor != -1) { createCube(x,UpColumn(x,y,z),z); } else { std::cerr << "can't extrud " << std::endl; } } void Grid::digCube(const int x, const int y, const int z) { int indexCol = UpColumn(x,y,z) - 1; int positionCursor = findCube(x,y,z); if(positionCursor != -1) { deleteCube(x,indexCol,z); } else { std::cerr << "can't dig " << std::endl; } } void Grid::resetCube() { m_Grid.clear(); } void Grid::writeFile(std::string name) { std::string const nomFichier("../Imac_World/save/" + name); std::ofstream monFlux(nomFichier.c_str()); if(monFlux) { for(int i=0; i< getGridSize(); i++) { glm::vec3 color = getColor_Grid(i); monFlux << getX_Grid(i)<<" " << getY_Grid(i) <<" " <<getZ_Grid(i) << " " << getType_Grid(i) << " " << color[0] << " " << color[1] << " " << color[2] << std::endl; } } else { std::cerr << "ERREUR : Impossible d'ouvrir le fichier" << std::endl; } } void Grid::readFile(std::string name) { std::ifstream myFile("../Imac_World/save/" + name); if(myFile) { std::string ligne; int ValueX; int ValueY; int ValueZ; int ValueType; int ValueR, ValueG, ValueB; resetCube(); while(getline(myFile, ligne) ) { myFile >> ValueX; myFile >> ValueY; myFile >> ValueZ; myFile >> ValueType; myFile >> ValueR; myFile >> ValueG; myFile >> ValueB; createCubeColor(ValueX,ValueY,ValueZ,ValueType,ValueR,ValueG,ValueB); } myFile.close(); } else { std::cerr << "ERREUR : Impossible d'ouvrir le fichier" << std::endl; } } }
true
3e9374243f42b620d6d1d2fff4498cce915c353d
C++
SamVargas14/LabosFunda
/Laboratorio4/Lab4ej1.cpp
UTF-8
332
3.453125
3
[]
no_license
#include <iostream> using namespace std; int main(void){ int n1,n2,r; cout<<"Ingrese valores a dividir\nValor 1: ";cin>>n1;cout<<"\nValor 2: ";cin>>n2; r = n1/n2; if (r % 2 == 0){ cout<<n1<<" es divisible entre "<<n2; } else { cout<<n1<<" no es divisible entre "<<n2; } return 0;}
true
b1968935254d376c6aeaf942c82d2e38c627f379
C++
tudoroancea/cube-timer
/test/durationUnitTest.cpp
UTF-8
1,202
2.765625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // Created by Tudor Oancea on 13/04/2021. // Copyright (c) 2021 Tudor Oancea.. All rights reserved. // Licensed under the MIT licence (see details at https://github.com/tudoroancea/cube-timer/blob/develop/LICENSE) // #include <gtest/gtest.h> #include "MainWindow.hpp" #include "Duration.hpp" #include <random> TEST(DurationTest, Construction) { std::random_device rd; //Will be used to obtain a seed for the random number engine std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd() std::uniform_int_distribution<long> distrib(0); for (size_t i(0); i < 10000; ++i) { long x(distrib(gen)); Duration<long> duration(x); ASSERT_EQ(x,duration.getMilliseconds()+duration.getSeconds()*1000+duration.getMinutes()*60000+duration.getHours()*3600000); } } TEST(DurationTest, StringConversion) { std::random_device rd; //Will be used to obtain a seed for the random number engine std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd() std::uniform_int_distribution<long> distrib(0); for (size_t i(0); i < 10000; ++i) { Duration<long> duration(distrib(gen)); ASSERT_NO_THROW((void) duration.toQString()); ASSERT_NO_THROW((void) duration.toString()); } }
true
3aa08cc682426438f4b736a723e41b06f4832577
C++
mridul-mc/all_c_part2
/sum_of_number_return.cpp
UTF-8
403
3.59375
4
[]
no_license
#include<stdio.h> #include<conio.h> int sum(int,int); //create function int main() { int num1,num2; printf("Enter first number:"); scanf("%d",&num1); printf("Enter second number:"); scanf("%d",&num2); printf("Sum of two number:%d",sum(num1,num2)); //call function } int sum(int num1,int num2) { int sum_of_number=(num1+num2); return sum_of_number; //return the total value }
true
0ace8a32944e28560a2464d75a7e4f065b4b85db
C++
sanjusss/leetcode-cpp
/0/800/820/825.cpp
UTF-8
2,063
2.78125
3
[]
no_license
/* * @Author: sanjusss * @Date: 2021-12-27 08:46:24 * @LastEditors: sanjusss * @LastEditTime: 2021-12-27 09:30:43 * @FilePath: \0\800\820\825.cpp */ #include "leetcode.h" // class Solution { // public: // int numFriendRequests(vector<int>& ages) { // int n = ages.size(); // int ans = 0; // for (int i = 0; i < n; ++i) { // for (int j = 0; j < n; ++j) { // if (i != j && ages[j] > 0.5 * ages[i] + 7 && ages[j] <= ages[i] && !(ages[j] > 100 && ages[i] < 100)) // { // ++ans; // } // } // } // return ans; // } // }; // class Solution { // public: // int numFriendRequests(vector<int>& ages) { // map<int, int> cnt; // for (int i : ages) { // ++cnt[i]; // } // int ans = 0; // auto fast = cnt.begin(); // auto slow = cnt.begin(); // int sum = 0; // while (fast != cnt.end()) { // int c = fast->second; // double minAge = fast->first * 0.5 + 7; // if (fast->first > minAge) { // ans += c * (c - 1); // } // while (slow != fast && slow->first <= minAge) { // sum -= slow->second; // ++slow; // } // ans += sum * c; // sum += c; // ++fast; // } // return ans; // } // }; class Solution { public: int numFriendRequests(vector<int>& ages) { sort(ages.begin(), ages.end()); int ans = 0; int n = ages.size(); int left = 0; int right = 0; for (int i : ages) { double minAge = i * 0.5 + 7; while (left < n && ages[left] <= minAge) { ++left; } while (right + 1 < n && ages[right + 1] <= i) { ++right; } ans += max(right - left, 0); } return ans; } }; TEST(&Solution::numFriendRequests)
true
be30589409f867be36d94c78845ec4f80a45e96f
C++
SomeTake/HF21MisotenH206
/project/Framework/Resource/PolygonResource.cpp
SHIFT_JIS
2,210
2.5625
3
[ "MIT" ]
permissive
//===================================== // //PolygonResource.cpp //@\:|S\[X //Author:GP12B332 21 ԗY // //===================================== #include "PolygonResource.h" #include "../Renderer3D/BoardPolygon.h" /************************************** RXgN^ ***************************************/ PolygonResource::PolygonResource(const D3DXVECTOR2 & size, const D3DXVECTOR2 & uv, const char* path) : vtxBuff(nullptr), texture(nullptr), cntRef(0) { LPDIRECT3DDEVICE9 pDevice = GetDevice(); //_obt@쐬 pDevice->CreateVertexBuffer(sizeof(VERTEX_MATERIAL) * NUM_VERTEX, D3DUSAGE_WRITEONLY, FVF_VERTEX_MATERIAL, D3DPOOL_MANAGED, &vtxBuff, 0); //_obt@ VERTEX_MATERIAL *pVtx; vtxBuff->Lock(0, 0, (void**)&pVtx, 0); pVtx[0].vtx = D3DXVECTOR3(-size.x, size.y, 0.0f); pVtx[1].vtx = D3DXVECTOR3(size.x, size.y, 0.0f); pVtx[2].vtx = D3DXVECTOR3(-size.x, -size.y, 0.0f); pVtx[3].vtx = D3DXVECTOR3(size.x, -size.y, 0.0f); pVtx[0].tex = D3DXVECTOR2(0.0f, 0.0f); pVtx[1].tex = D3DXVECTOR2(1.0f / uv.x, 0.0f); pVtx[2].tex = D3DXVECTOR2(0.0f, 1.0f / uv.y); pVtx[3].tex = D3DXVECTOR2(1.0f / uv.x, 1.0f / uv.y); pVtx[0].nor = pVtx[1].nor = pVtx[2].nor = pVtx[3].nor = D3DXVECTOR3(0.0f, 0.0f, -1.0f); vtxBuff->Unlock(); //eNX`ǂݍ if (path != nullptr) { D3DXCreateTextureFromFile(pDevice, path, &texture); } } /************************************** fXgN^ ***************************************/ PolygonResource::~PolygonResource() { SAFE_RELEASE(vtxBuff); SAFE_RELEASE(texture); //N[BoardPolygonɊJĂ邩mF assert(cntRef == 0); } /************************************** N[ ***************************************/ void PolygonResource::Clone(BoardPolygon * entity) { if (entity == nullptr) return; entity->vtxBuff = vtxBuff; vtxBuff->AddRef(); entity->texture = texture; texture->AddRef(); entity->resource = this; cntRef++; } /************************************** [X̏ ***************************************/ void PolygonResource::OnRelease() { cntRef--; }
true
fbbedaad39a3e83d5e4720e00cf9015f9ff3aafc
C++
LeeeeoLiu/DBMS
/DBMS.cpp
UTF-8
2,842
2.96875
3
[]
no_license
/* * DBMS.cpp * * Created by Leeeeo on 2017.3.30 * * Input 学生(学号:是,姓名:否,性别:否,年龄:否) * 课程(课程号:是,课程名:否,学分:否) * 选课(学生:学号,课程:课程号,成绩) * * Output 学生.txt * #学生,学号:主键,姓名,性别,年龄 * 课程.txt * #选课,学生:主键,课程:主键,成绩 * * Description just a easy case for simple m:n convert from ER Model to Data Model */ #include <iostream> #include <fstream> #define MAX_LENTH 10000 using namespace std; int main() { string entityA, entityB, assoAB, tmpStr; int flag = 0; cin >> entityA; cin >> entityB; cin >> assoAB; tmpStr = entityA; while (tmpStr != "") { string tmpStrName = tmpStr.substr(0, tmpStr.find("(")); ofstream outFile; outFile.open(tmpStrName + ".txt"); outFile << "#" << tmpStrName << ","; if (tmpStr.substr(tmpStr.find(":") + 1, tmpStr.find(",") - tmpStr.find(":") - 1) == "是") { outFile << tmpStr.substr(tmpStr.find("(") + 1, tmpStr.find(":") - tmpStr.find("(") - 1) << ":主键"; } else outFile << tmpStr.substr(tmpStr.find("(") + 1, tmpStr.find(":") - tmpStr.find("(") - 1); while (tmpStr.find(",") < MAX_LENTH) { tmpStr = tmpStr.substr(tmpStr.find(",") + 1, tmpStr.size() - tmpStr.find(",") + 1); if (tmpStr.substr(tmpStr.find(":") + 1, tmpStr.find(",") - tmpStr.find(":") - 1) == "是") { outFile << "," << tmpStr.substr(0, tmpStr.find(":")) << ":主键"; } else { outFile << "," << tmpStr.substr(0, tmpStr.find(":")); } } if (tmpStr.substr(tmpStr.find(":") + 1, tmpStr.find(")") - tmpStr.find(":") - 1) == "是") { outFile << ":主键"; } outFile.close(); tmpStr = entityB; if (flag) break; flag = 1; } tmpStr = assoAB; string tmpStrName = tmpStr.substr(0, tmpStr.find("(")); ofstream outFile; outFile.open(tmpStrName + ".txt"); outFile << "#" << tmpStrName << ","; outFile << tmpStr.substr(tmpStr.find("(") + 1, tmpStr.find(":") - tmpStr.find("(") - 1) << ":主键"; tmpStr = tmpStr.substr(tmpStr.find(",") + 1, tmpStr.size() - tmpStr.find(",") + 1); outFile << "," << tmpStr.substr(tmpStr.find("(") + 1, tmpStr.find(":") - tmpStr.find("(") - 1) << ":主键"; tmpStr = tmpStr.substr(tmpStr.find(",") + 1, tmpStr.size() - tmpStr.find(",") + 1); while (tmpStr.find(",") < MAX_LENTH) { outFile << "," << tmpStr.substr(0, tmpStr.find(",")); tmpStr = tmpStr.substr(tmpStr.find(",") + 1, tmpStr.size() - tmpStr.find(",") + 1); } outFile << "," << tmpStr.substr(0, tmpStr.find(")")); outFile.close(); return 0; }
true
819a743ca3e3cd9bc1579df6c1037b5ec28f8bee
C++
Rodrigo61/GUAXINIM
/CodeBook/Graphs/EulerTour.cpp
UTF-8
3,591
3.25
3
[]
no_license
/* [DEFINITION] a) Eulerian Path: visits every edge only once, but can repeat vertices. b) Eulerian Cycle: is a eulerian path that is a cycle (start vertice == end vertice) OBS: We disconsider vertices that have indegree==outdegree==0 (we call them as useless vertices) [CONDITIONS] [Undirected graph] [Path/Cycle] a) The number of vertices with odd degrees is 2(Eulerian Path) or 0(Eulerian cycle) b) The graph of useful vertices (see OBS above) should be connected If either of the above condition fails Euler Path/Cycle can't exist. [Directed graph] [Cycle] a) All vertices should have (indegree==outdegree) b) The UNDIRECTED version of the graph of useful vertices (see OBS above) should be connected [Path] a) Equal to Cycle's conditions, but: b) There should be a vertex in the graph which has (indegree+1==outdegree) d) There should be a vertex in the graph which has (indegree==outdegree+1) If either of the above condition fails Euler Path/Cycle can't exist. OBS: The "connected" condition it's not explicit tested by the algorithm because it's enough checking the size of the found path. [COMPLEXITY] O(V + E) [USAGE] After selecting between Directed and Undirected (uncommenting functions), one should call the init function and then the euler_tour function: [Global: vector<V>& vertices] * 0-indexed * It's fine to include useless vertices * In Undirected problems be sure the idx(u,v) == idx(v,u) [Function: euler_tour(src)] * If one wants a Euler Cycle that starts/ends at the given src vertice. Of course, this will only work if a Euler Cycle really exists * src = -1 (Default). The function will find the correct start of the Path/Cycle. [Return] An integer vector that represents the vertices' indexes of the found cycle (when exists) or the found path (when exists). If none was found, an empty vector is returned. OBS: One can check if the returned value is a path by checking if ret.front() != ret.back() */ namespace euler { struct edge { int u, v, id; }; struct vertice { vi outs; // edges indexes int in_degree = 0; // not used with undirected graphs }; int n, m; edge edges[MAXM]; vertice vertices[MAXN]; vi::iterator its[MAXN]; bool used_edge[MAXM]; void init() { for (int i = 0; i < n; i++) { its[i] = vertices[i].outs.begin(); } } vi euler_tour(int n_edges, int src = -1) { vi ret_vertices; //vi ret_edges; vii s = {{src, -1}}; while(!s.empty()) { int x = s.back().fi; int e = s.back().se; auto &it = its[x], end = vertices[x].outs.end(); while(it != end && used_edge[*it]) ++it; if(it == end) { ret_vertices.push_back(x); //ret_edges.push_back(e); s.pop_back(); } else { auto edge = edges[*it]; int v = edge.u == x ? edge.v:edge.u; s.push_back({v, *it}); used_edge[*it] = true; } } if (sz(ret_vertices) != n_edges+1) ret_vertices.clear(); // No Eulerian cycles/paths. /* if (sz(ret_edges) != n_edges) ret_edges.clear(); // No Eulerian cycles/paths. */ // Check if is cycle ret_vertices.front() == ret_vertices.back() reverse(all(ret_vertices)); return ret_vertices; /* reverse(all(ret_edges)); return ret_edges; */ } }
true
8dfa55faaede591fafee7fa720b4e93a19e2edc9
C++
HK-Dilip-kumar/H-CKeR_3-RTH_SOLUTIONS
/prime2nd.cpp
UTF-8
201
2.78125
3
[]
no_license
#include<iostream> int main() { int j=1; int n; std::cin>>n; for(int i=2;i<=n;i++) { int c=0; while(j<=i) { if(i%j==0) { c++; }j++; if(c==2){std::cout<<i<<" ";} } } }
true
d939f2020c6c369653d07bb8b6e3a2873e7cb7be
C++
cyrillev/qgameoflife
/generic/model/golquadtreenode.h
UTF-8
1,363
2.75
3
[]
no_license
#ifndef GOLQUADTREENODE_H #define GOLQUADTREENODE_H #include "golquadtreenodebase.h" namespace gol { /** * Each GolQuadtreeNode has exactly 4 children, * one for each cardinal direction. * */ class GolQuadtreeNode : public GolQuadtreeNodeBase { public: enum Quadrant { NorthWest, NorthEast, SouthEast, SouthWest, NumberOfQuadrants }; GolQuadtreeNode(coord_t x, coord_t y, coord_t width, coord_t height, golquadtreenode_weakptr parent); virtual ~GolQuadtreeNode(); /** Implement GolModelInterface */ void set(coord_t x, coord_t y); bool unset(coord_t x, coord_t y); bool get(coord_t x, coord_t y) const; bool isLeaf() const; void dump() const; // FIXME: find a better alternative than passing references to vector. void nextGeneration(boost::unordered_set<point_t>& new_cells, boost::unordered_set<point_t>& dead_cells); void getOverlappedNodesAt(coord_t x, coord_t y, std::vector<golquadtreenode_ptr>& nodes); private: coord_t getQuadrantX(Quadrant q) const; coord_t getQuadrantY(Quadrant q) const; coord_t getQuadrantWidth(Quadrant q) const; coord_t getQuadrantHeight(Quadrant q) const; Quadrant getQuadrant(coord_t x, coord_t y) const; golquadtreenode_ptr _quadrants[NumberOfQuadrants]; }; } #endif // GOLQUADTREENODE_H
true
1d8784172eea417b5f1595fb87bc8c2d9f7de73e
C++
chadlayton/sparky
/sparky/source/handle.h
UTF-8
1,800
3.1875
3
[]
no_license
#pragma once #include <cstdlib> #include <cstdint> #include <cassert> #include <intsafe.h> struct sp_handle { short index = SHORT_MAX; operator bool() const { return index != SHORT_MAX; }; }; struct sp_handle_pool { short _count = 0; short _capacity = 0; sp_handle* _dense = nullptr; sp_handle* _sparse = nullptr; }; void sp_handle_pool_create(sp_handle_pool* handle_pool, int capacity) { assert(capacity < SHORT_MAX && "capacity too large"); handle_pool->_dense = new sp_handle[capacity]; handle_pool->_sparse = new sp_handle[capacity]; handle_pool->_capacity = capacity; handle_pool->_count = 0; sp_handle* dense = handle_pool->_dense; for (int i = 0; i < capacity; i++) { dense[i].index = i; } } void sp_handle_pool_destroy(sp_handle_pool* pool) { if (pool) { delete[] pool->_dense; pool->_dense = nullptr; delete[] pool->_sparse; pool->_sparse = nullptr; pool->_count = 0; pool->_capacity = 0; } } sp_handle sp_handle_alloc(sp_handle_pool* pool) { sp_handle handle; if (pool->_count < pool->_capacity) { handle = pool->_dense[pool->_count]; pool->_sparse[handle.index] = { pool->_count }; ++pool->_count; } else { assert(0 && "handle pool is full"); } return handle; } void sp_handle_free(sp_handle_pool* pool, sp_handle handle) { assert(pool->_count > 0 && "handle pool is empty"); --pool->_count; sp_handle dense_handle = pool->_dense[pool->_count]; sp_handle sparse_handle = pool->_sparse[handle.index]; pool->_dense[pool->_count] = handle; pool->_sparse[dense_handle.index] = sparse_handle; pool->_dense[sparse_handle.index] = dense_handle; } void sp_handle_pool_reset(sp_handle_pool* pool) { sp_handle* dense = pool->_dense; for (int i = 0; i < pool->_capacity; i++) { dense[i].index = i; } pool->_count = 0; }
true
7f40e573a470dbb6090296e8d705885d6c4a4528
C++
samueldong-us/ARHideAndGoSeek
/AR Hide And Go Seek/C++ Source/BasicMesh.hpp
UTF-8
1,461
2.6875
3
[]
no_license
// // BasicMesh.hpp // Model Based Tracking // // Created by Samuel Dong on 11/11/15. // Copyright © 2015 Samuel Dong. All rights reserved. // #pragma once #import "OpenGLES/ES3/gl.h" #import "glm/glm.hpp" #import "ShaderProgram.hpp" #import "TextureManager.hpp" #import <string> #import <vector> #import <map> class BasicMesh { public: BasicMesh(std::string filename, TextureManager* manager); ~BasicMesh(); void Draw(ShaderProgram* program); void SetPosition(glm::vec3 newPosition) {position = newPosition;} void SetRotation(glm::vec3 newRotation) {rotation = newRotation;} void SetScale(glm::vec3 newScale) {scale = newScale;} private: GLuint positionBufferID; GLuint uvBufferID; GLuint indexBufferID; std::vector<GLuint> textureIDs; std::vector<int> textureCount; TextureManager* textureManager; glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; glm::mat4 GetModelMatrix(); void ParseOBJ(std::string objContents, TextureManager* manager, std::vector<float>& positionArray, std::vector<float>& uvArray, std::vector<unsigned int>& indexArray); void AddFace(std::map<std::string, int>& vertexMap, std::vector<glm::vec3>& positions, std::vector<glm::vec2>& uvs, std::vector<float>& positionArray, std::vector<float>& uvArray, std::vector<unsigned int>& indexArray, int vertexInfo[2]); void VertexHash(int vertexInfo[2], std::string& output); };
true
24f2b1dab8486d643d75346b778379a1500984ae
C++
jacarvalho/SimuRLacra
/RcsPySim/src/cpp/core/util/BoxSpaceProvider.h
UTF-8
1,405
2.9375
3
[ "BSD-3-Clause" ]
permissive
#ifndef RCSPYSIM_BOXSPACEPROVIDER_H #define RCSPYSIM_BOXSPACEPROVIDER_H #include "BoxSpace.h" #include "nocopy.h" namespace Rcs { /** * A class that lazily provides an 1D box space. */ class BoxSpaceProvider { private: mutable BoxSpace* space; public: BoxSpaceProvider(); virtual ~BoxSpaceProvider(); // not copy- or movable RCSPYSIM_NOCOPY_NOMOVE(BoxSpaceProvider) /** * Compute and return the space. */ const BoxSpace* getSpace() const; /** * Provides the number of elements in the space. * Since the BoxSpace object will be cached, this must not change. * * @return number of elements for the space. */ virtual unsigned int getDim() const = 0; /** * Provides minimum and maximum values for the space. * * The passed arrays will be large enough to hold getDim() values. * * @param[out] min minimum value storage * @param[out] max maximum value storage */ virtual void getMinMax(double* min, double* max) const = 0; /** * Provides names for each entry of the space. * * These are intended for use in python, i.e., for pandas dataframe column names. * * @return a vector of name strings. Must be of length getDim() or empty. */ virtual std::vector<std::string> getNames() const; }; } // namespace Rcs #endif //RCSPYSIM_BOXSPACEPROVIDER_H
true
2d2b3333d4cac616941d8fb4bffc7c4143648dda
C++
MOON-CLJ/learning_cpp
/algorithm/queue.h
UTF-8
787
3.65625
4
[]
no_license
#include <iostream> template<typename T> class queue { public: queue(): first(NULL), last(NULL), N(0) {} bool isEmpty() { return (first == NULL); } int size() {return N;} void enqueue(T item) { Node* oldLast = last; last = new Node; last->val = item; last->next = NULL; if (isEmpty()) first = last; else oldLast->next = last; N++; } T dequeue() { Node* oldFirst = first; T item = first->val; first = first->next; if (isEmpty()) last = NULL; delete oldFirst; N--; return item; } private: struct Node { T val; Node * next; }; Node * first; Node * last; int N; };
true
bd3b6ca155a182606b169077550976e0a0f4e8be
C++
spd-user/GeneralSPD
/src/spd/output/ConsoleOutput.hpp
UTF-8
1,554
3.03125
3
[]
no_license
/** * ConsoleOutput.hpp * * @date 2012/12/18 * @author katsumata */ #ifndef CONSOLEOUTPUT_H_ #define CONSOLEOUTPUT_H_ #include <memory> #include "OutputVisitor.hpp" namespace spd { namespace core { class Player; } namespace output { /** * 空間状態を標準出力へ表示するクラス */ class ConsoleOutput: public OutputVisitor { public: /** * 二次元格子に即した出力 * @param[in] topology 空間構造 * @param[in] space 空間状態 */ void output(const spd::topology::Lattice& topology, spd::core::Space& space); /** * 立体格子に即した出力 * @param[in] topology 空間構造 * @param[in] space 空間状態 */ void output(const spd::topology::Cube& topology, spd::core::Space& space); /** * ネットワーク構造に即した出力 * @note * 標準エラー出力へのエラー出力のみ * * @param[in] topology 空間構造 * @param[in] space 空間状態 */ void output(const spd::topology::Network& topology, spd::core::Space& space); /** * 初期化 * @param[in, out] space 空間 * @param[in, out] param パラメタ */ void init(spd::core::Space& space, spd::param::Parameter& param); /** * 出力方法名の出力 * @return 出力方法名 */ std::string toString() const { return "Console"; } private: /** * 1プレイヤを出力する * * @param[in] player プレイヤ */ void printPlayer(const std::shared_ptr<spd::core::Player> player); }; } /* namespace output */ } /* namespace spd */ #endif /* CONSOLEOUTPUT_H_ */
true
aa6aabf76beb21bd7821d7369da5f3d4bcb7ba45
C++
SegwayRase2019/SegwayRace
/data/src/client/ui/Canvas.h
UTF-8
1,238
2.625
3
[]
no_license
#pragma once #include "../../common/math/Math.h" #include "./Button.h" #include <SDL2/SDL.h> #include <cstdint> #include <string> #include <functional> #include <vector> class Canvas { public: Canvas(class Game *game); virtual ~Canvas(); virtual void Update(float deltaTima); virtual void Draw(SDL_Renderer *renderer); virtual void ProcessInput(const uint8_t *keys); virtual void HandleKeyPress(int key); enum UIState { EActive, EClosing }; void Close(); UIState GetState() const { return mState; } void SetTitle(const std::string &title, const Vector3 &Color = Color::White, int pointSize = 40); void SetTitlePos(const Vector2 pos) { mTitlePos = pos; } void AddButton(const std::string &name, std::function<void()> onClick); protected: void DrawTexture(SDL_Renderer *renderer, SDL_Texture *texture, const Vector2 &offset = Vector2::Zero, float scale = 1.0f); class Game *mGame; class Font *mFont; SDL_Texture *mTitle; SDL_Texture *mBackGround; SDL_Texture *mButtonOn; SDL_Texture *mButtonOff; Vector2 mTitlePos; Vector2 mNextButtonPos; Vector2 mBGPos; UIState mState; int mWindowWidth; int mWindowHeight; int mClientNum; std::vector<Button *> mButtons; };
true
8eae364dd7c31f1e3b008f1286d279eb379c2590
C++
ak9999/structures-and-algorithms
/cpp/DataStructures/LinkedQueue/test.cpp
UTF-8
886
3.734375
4
[]
no_license
/* * @Author: Abdullah Khan * @File: main.cpp * @Description: Test LinkedQueue. */ #include <iostream> #include <cassert> #include "LinkedQueue.hpp" using namespace std; int main() { // We create the blank LinkedQueue a here. LinkedQueue<int> a; assert( a.size() == 0 ); // If the size isn't 0, the program stops here. a.push(23); // Add 23 to a. assert( a.size() == 1 ); cout << "Front: " << a.front() << endl; for(size_t i = 0; i < 10; i++) { assert( a.size() == i + 1); a.push(i); } // LinkedQueue a should now be of size 11. cout << "Printing out as we pop." << endl; while (a.size() > 0) { cout << "Front: " << a.front() << endl; a.pop(); } cout << "Creating Stack `b` of size 5 from {}-list." << endl; LinkedQueue<double> b{1.57, 3.14, 6.12, 6.67, 10.24}; assert( b.size() == 5 ); cout << "Size of stack b: " << b.size() << endl; return 0; }
true
62089bbc8ea12cb4949bf88a57b227dd3becfa35
C++
collinskoech11/DSA-Practice-Problems
/Arrays/Transition_point.cpp
UTF-8
1,369
3.625
4
[]
no_license
/*Find Transition Point You are given a sorted array containing only numbers 0 and 1. Find the transition point efficiently. Transition point is a point where "0" ends and "1" begins. Note that, if there is no "1" exists, print -1. Input: You have to complete the method which takes 2 argument: the array arr[] and size of array N. You should not read any input from stdin/console. There are multiple test cases. For each test cases, this method will be called individually. Output: Your function should return transition point. Constraints: 1 ≤ T ≤ 100 1 ≤ N ≤ 500000 0 ≤ C[i] ≤ 1 Example: Input 1 5 0 0 0 1 1 Output 3 */ #include <bits/stdc++.h> using namespace std; int transitionPoint(int arr[], int n); int main() { int t; cin >> t; while (t--) { int n; cin >> n; int a[n], i; for (i = 0; i < n; i++) { cin >> a[i]; } cout << transitionPoint(a, n) << endl; } return 0; } // Function to find the transition point int transitionPoint(int arr[], int n) { // code here int l=0; int high=n-1; int mid=0; while(l<=high) { mid=((l+high)/2); if(arr[mid]==1 && arr[mid-1]!=1) return mid; else { if(arr[mid-1]==1) high=mid-1; else l=mid+1; } } return -1; }
true
864c60d659e9afb1b418532b3f34006c52787afe
C++
georgeganea/cgymnachos
/nachos/userprog/timerdriver.cc
UTF-8
1,221
3.34375
3
[]
no_license
#include "timerdriver.h" ntimer_t TimerDriver::timers[MaxTimerCount]; TimerDriver::TimerDriver() { int i; for (i = 0; i < MaxTimerCount; i++) initTimer(i); } TimerDriver::~TimerDriver() { } /* Adds a new timer for a thread. The timer will activate * after the number of ticks given. */ int TimerDriver::addTimer(Thread *thread, int ticks) { int rc = -1, i; for (i = 0; i < MaxTimerCount; i++) if (timers[i].t == NULL) break; if (i == MaxTimerCount) { // nu mai este loc DEBUG('u', "No more timers available."); } else { timers[i].t = thread; timers[i].ticksRemaining = ticks; rc = 0; } return rc; } /* Called by the kernel, will decrement the number * of remaining ticks on all timers and wake up any * threads whose remainingTicks value has reached 0. */ void TimerDriver::checkTimer(void) { int i; for (i = 0; i < MaxTimerCount; i++) { if (timers[i].t != NULL) { if (--timers[i].ticksRemaining == 0) { scheduler->ReadyToRun(timers[i].t); initTimer(i); DEBUG('u', "waking up thread\n"); } } } } /* Initialize the timer data structure to a void timer */ void TimerDriver::initTimer(int i) { timers[i].t = NULL; timers[i].ticksRemaining = -1; }
true
84f60bb356a408a13e859dbc704a8bb82ffbed82
C++
kiwonyun/LeetCode
/C++/addTwoNumbers.cpp
UTF-8
1,232
3.234375
3
[ "MIT" ]
permissive
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int n1, n2, sum, c = 0; ListNode* prev = NULL; ListNode* res = NULL; while(l1 != NULL || l2 != NULL){ if(l1 != NULL){ n1 = l1->val; l1 = l1->next; } else n1 = 0; if(l2 != NULL){ n2 = l2->val; l2 = l2->next; } else n2 = 0; sum = n1 + n2 + c; if( sum >= 10 ){ sum -= 10; c = 1; } else c = 0; ListNode* cur = new ListNode(sum); if( prev != NULL ) prev->next = cur; else res = cur; prev = cur; } if( c != 0 ){ ListNode* cur = new ListNode(1); prev->next = cur; } return res; } };
true
bbee34c7c43d92e81ccd7577a0c6b7681ffeff8f
C++
san-kir-k/oop_exercise_04
/tuple_handler.hpp
UTF-8
3,222
3.34375
3
[]
no_license
// Киреев А.К. 206 #include <iostream> #include <tuple> #include <utility> #include <cmath> #include <string> #include <typeinfo> #define _USE_MATH_DEFINES #include "octagon.hpp" #include "square.hpp" #include "triangle.hpp" template <class T> double getArea(T& figure) { using Type = typename T::type; double res = 0.0; if (!figure.valid) { return 0.0; } double r = sqrt((figure.v.first - figure.center.first) * (figure.v.first - figure.center.first) + (figure.v.second - figure.center.second) * (figure.v.second - figure.center.second)); if constexpr (std::is_same<decltype(figure), Triangle<Type>&>::value) { res += 3.0 * sqrt(3.0) * r * r / 4.0; } else if constexpr (std::is_same<decltype(figure), Square<Type>&>::value) { res += 2.0 * r * r; } else if constexpr (std::is_same<decltype(figure), Octagon<Type>&>::value) { res += 2.0 * sqrt(2.0) * r * r; } else { return 0.0; } return res; } template <class T, int index> double getTotalArea(T& tuple) { auto figure = std::get<index>(tuple); double res = getArea(figure); if constexpr ((index+1) < std::tuple_size<T>::value) { return res + getTotalArea<T, index + 1>(tuple); } return res; } template <class T> void print(T& figure) { using Type = typename T::type; // проверка фигуры на валидность (она может не существовать в каких-то координатах) if (!figure.valid) { if constexpr (std::is_same<decltype(figure), Triangle<Type>&>::value) { std::cout << "Invalid figure: Triangle<" << typeid(Type).name() << ">" << std::endl; } else if constexpr (std::is_same<decltype(figure), Square<Type>&>::value) { std::cout << "Invalid figure: Square<" << typeid(Type).name() << ">" << std::endl; } else if constexpr (std::is_same<decltype(figure), Octagon<Type>&>::value) { std::cout << "Invalid figure: Octagon<" << typeid(Type).name() << ">" << std::endl; } else { std::cout << "Invalid undefined figure." << std::endl; } return; } // конец проверки // вывод координат вершин фигуры std::cout.precision(3); std::cout << "[ "; if constexpr ((std::is_same<decltype(figure), Triangle<Type>&>::value) || (std::is_same<decltype(figure), Square<Type>&>::value) || (std::is_same<decltype(figure), Octagon<Type>&>::value)) { for (int i = 0; i < figure.path.size(); ++i) { std::cout << "(" << std::fixed << figure.path[i].first << ", " << std::fixed << figure.path[i].second << ") "; } } std::cout << "]" << std::endl; // конец вывода координат вершин фигуры } template <class T,size_t index> typename std::enable_if<index >= std::tuple_size<T>::value, void>::type printTuple(T& tuple){ std::cout << std::endl; } template <class T,size_t index> typename std::enable_if<index < std::tuple_size<T>::value, void>::type printTuple(T& tuple){ auto figure = std::get<index>(tuple); print(figure); printTuple<T, index + 1>(tuple); }
true
263086cc5076a572d667a92af8cbf6c50e912b88
C++
isliulin/PythonDemoRepository
/项目/格子机2.0/wine_grid2018_11_10/temp/dialog.h
UTF-8
1,636
2.671875
3
[]
no_license
#ifndef DIALOG_H #define DIALOG_H #include <QObject> #include <QWidget> #include <QLabel> #include <QPushButton> #include <QStyleOption> #include <QPainter> #include <QTimer> #include "app.h" class Dialog : public QWidget { Q_OBJECT public: Dialog(QString str,int _ms=11000, QWidget *parent=0); Dialog(QWidget *parent=0); ~Dialog(){ delete timer; delete label; delete button; } void show(){ this->setVisible(true); this->raise(); timer->start(ms); } void close(){ timer->stop(); this->hide(); } void setText(QString str){ if(str.isEmpty()){ label->setText("<font color=red size=3>请输入正确的商品编号</font>"); } else{ label->setText(str); } } void setText(QString str,int _ms){ ms=_ms; label->setText(str); this->show(); } void move_to_centre(){ this->move((App::DeskWidth-400)/2,(App::DeskHeight-240)/2); } bool shake_flag; protected: //如果要子类化一个QWidget,为了能够使用样式表,则需要提供paintEvent事件。 //这是因为QWidget的paintEvent()是空的,而样式表要通过paint被绘制到窗口中。 void paintEvent(QPaintEvent *){ QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); } void closeEvent(QCloseEvent *){ shake_flag=false; } private: QLabel *label; QPushButton *button; QTimer *timer; int ms; }; #endif // DIALOG_H
true
1cfa7751e919a83501c4232343f7f9831497e8aa
C++
Peydon/LeetCode
/LeetCode/Q4.cpp
UTF-8
1,343
3.21875
3
[]
no_license
//#include<Vector> //#include<iostream> //#include <algorithm> //using namespace std; //class Solution { //public: // // double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { // int m = nums1.size(); // int n = nums2.size(); // if (m > n) { return findMedianSortedArrays(nums2, nums1); } // int left = 0, right = m; // int halfLength = (m + n + 1) / 2; // int leftMax = 0; // int rightMin = 0; // while (left <= right) // { // int i = (left + right) / 2; // int j = halfLength - i; // if (i < m&&nums1[i] < nums2[j - 1]) // { // left = i + 1; // } // else // if (i > 0&&nums1[i-1] > nums2[j]) // { // right = i - 1; // } // else // { // if (i == 0)leftMax = nums2[j - 1]; // else // { // if (j == 0)leftMax = nums1[i - 1]; // else leftMax = max(nums1[i - 1], nums2[j - 1]); // } // if ((m + n) % 2 == 1) // return leftMax; // // if (i == m)rightMin = nums2[j]; // else // { // if (j == n)rightMin = nums1[i]; // else rightMin = min(nums1[i], nums2[j]); // } // // // return (leftMax + rightMin) / 2.0; // } // } // } //}; //int main() //{ // int a[8] = {1,3,2,3,4,5,6,7}; // int b[2] = {2,9}; // vector<int>a1(a, a + 2); // vector<int>a2(b, b + 1); // Solution s = Solution(); // cout<<s.findMedianSortedArrays(a1, a2); //}
true
a8e84bb2842517133fe04c175bb19ff72e182076
C++
ehonda/dominion_online_log_prettifier
/dominion_online_log_prettifier_2_app/inc/string_utils.h
UTF-8
607
2.671875
3
[ "Unlicense" ]
permissive
#pragma once #include <string> namespace dominion_online { namespace string_utils { std::string removeAll(std::string s, const char& target); std::string replaceAll(std::string s, const char& target, const char& replacement); //Removes blank (' ' '\t') characters in front of the following special characters: '.' ',' ')' ':' std::string removeBlanksInFrontOfSpecialCharacters(const std::string& s); std::string trim(const std::string& s); std::string appendToFileName(const std::string& fileName, const std::string& appendix); bool endsWith(const std::string& s, const std::string& endSubstring); } }
true
4cc07785ccb96363806ab5d7657c437defd1cbd9
C++
chffy/ACM-ICPC
/topcoder/srm610-619/srm611/550.cpp
UTF-8
1,906
2.796875
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <cmath> using namespace std; double sqr(double x) { return x * x; } double dis(double x, double y) { return sqrt(sqr(x) + sqr(y)); } double len[500], event[500000]; int ll[500], rr[500]; const double esp = 1e-11; int n, m; int parent[30]; int find(int x) { if (parent[x] != x) parent[x] = find(parent[x]); return parent[x]; } pair<double, int> edge[500]; double calc(double A, double B, double C, double X) { return A * sqr(X) + B * X + C; } double mst(double l, double r) { for (int i = 0; i < m; ++i) edge[i] = make_pair(sqr((r + l) / 2 - len[i]), i); sort(edge, edge + m); double A = n - 1, B = 0, C = 0; for (int i = 0; i < n; ++i) parent[i] = i; for (int i = 0; i < m; ++i) { int id = edge[i].second; int x = ll[id], y = rr[id]; if (find(x) == find(y)) continue; parent[find(x)] = find(y); B -= 2.0 * len[id]; C += len[id] * len[id]; } double t = - B / (A * 2.0); if (t >= l && t <= r) return calc(A, B, C, t); else return min(calc(A, B, C, l), calc(A, B, C, r)); } class Egalitarianism2 { public: double minStdev(vector <int> x, vector <int> y) { n = x.size(); m = 0; double bmin = 1e60, bmax = 0; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) { ll[m] = i; rr[m] = j; len[m++] = dis(x[i] - x[j], y[i] - y[j]); bmin = min(bmin, len[m - 1]); bmax = max(bmax, len[m - 1]); } int num = 0; for (int i = 0; i < m; ++i) for (int j = i + 1; j < m; ++j) event[num++] = (len[i] + len[j]) / 2.0; sort(event, event + num); double cur = bmin - esp, ans = 1e60; for (int i = 0; i < num; ++i) { if (fabs(event[i] - cur) < esp) continue; ans = min(ans, mst(cur, event[i])); cur = event[i]; } ans = min(ans, mst(cur, bmax + esp)); return sqrt(ans / (n - 1)); } };
true
fcc19e0fb6c51d557d505d32480e41c18b175b9b
C++
mandaltj/Parallel_Computing
/matrix_multiply/matrix_multiply.cpp
UTF-8
5,020
3.203125
3
[]
no_license
#include <iostream> #include <vector> #include <chrono> #include <math.h> using Matrix = std::vector<std::vector<int>>; void print_matrix(Matrix & A) { int dimension = A.size(); for (int i=0; i<dimension; i++){ std::cout << "["; for (int j=0; j<dimension; j++){ std::cout << A[i][j]; if (j!=dimension-1){ std::cout <<","; } } std::cout << "]\n"; } std::cout<<'\n'; } std::vector<std::vector<int>> create_matrix(int dimension){ //Create a Matrix with random integers std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension, 0)); unsigned int seed = 1; for(int i=0; i<dimension;i++){ for(int j=0; j<dimension;j++){ int x = int(rand_r(&seed)%10); //Just to avoid Zeroes; Some random number if (x==0){ A[i][j] = int(rand_r(&seed)%2)+1; } else{ A[i][j] = x; } seed *= (j+1); } } return A; } Matrix multiply_matrix_serial(const Matrix &A, const Matrix &B){ int A_row_dimension = A.size(); int A_col_dimension = A[0].size(); int B_row_dimension = B.size(); int B_col_dimension = B[0].size(); //if (A_col_dimension!=B_row_dimension){ // std::cout<<"A_col_dimension: "<<A_col_dimension<<'\n'; // std::cout<<"B_row_dimension: "<<B_row_dimension<<'\n'; // throw std::runtime_error(std::string("Multiply Error: Dimension not same\n")); //} //std::cout<<"A row_dimension:"<<A.size()<<" A col_dimension: "<<A[0].size()<<'\n'; //std::cout<<"B row_dimension:"<<B.size()<<" B col_dimension: "<<B[0].size()<<'\n'; Matrix C(A_row_dimension, std::vector<int>(B_col_dimension, 0)); for(int i=0; i<A_row_dimension; i++){ for(int j=0; j<B_col_dimension; j++){ for(int k=0; k<A_col_dimension; k++){ C[i][j] += A[i][k]*B[k][j]; //std::cout<<"A["<<i<<"]["<<k<<"]: "<< A[i][k]<<" "; //std::cout<<"B["<<k<<"]["<<j<<"]: "<< B[k][j]<<" "; //std::cout<<"C["<<i<<"]["<<j<<"]: "<< C[i][j]<<'\n'; } } } //} //std::cout<<'\n'; return C; } Matrix multiply_matrix_parallel(const Matrix &A, const Matrix &B){ int A_row_dimension = A.size(); int A_col_dimension = A[0].size(); int B_row_dimension = B.size(); int B_col_dimension = B[0].size(); //if (A_col_dimension!=B_row_dimension){ // std::cout<<"A_col_dimension: "<<A_col_dimension<<'\n'; // std::cout<<"B_row_dimension: "<<B_row_dimension<<'\n'; // throw std::runtime_error(std::string("Multiply Error: Dimension not same\n")); //} //std::cout<<"A row_dimension:"<<A.size()<<" A col_dimension: "<<A[0].size()<<'\n'; //std::cout<<"B row_dimension:"<<B.size()<<" B col_dimension: "<<B[0].size()<<'\n'; Matrix C(A_row_dimension, std::vector<int>(B_col_dimension, 0)); #pragma omp parallel for collapse(2) for(int i=0; i<A_row_dimension; i++){ for(int j=0; j<B_col_dimension; j++){ for(int k=0; k<A_col_dimension; k++){ C[i][j] += A[i][k]*B[k][j]; //std::cout<<"A["<<i<<"]["<<k<<"]: "<< A[i][k]<<" "; //std::cout<<"B["<<k<<"]["<<j<<"]: "<< B[k][j]<<" "; //std::cout<<"C["<<i<<"]["<<j<<"]: "<< C[i][j]<<'\n'; } } } //} //std::cout<<'\n'; return C; } bool equal_check(const Matrix & A, const Matrix & B){ int dimension = A.size(); for(int i=0; i<dimension; i++){ for(int j=0; j<dimension; j++){ if (A[i][j] != B[i][j]){ return false; } } } return true; } int main(int argc, char *argv[]){ //Check input arguments if (argc < 2){ std::cout << "Error: Please enter 1) Matrix Dimension; \n"; exit(1); } int dimension = std::atoi(argv[1]); std::vector<std::vector<int>> A = create_matrix(dimension); //print_matrix(A); std::vector<std::vector<int>> B = create_matrix(dimension); //print_matrix(B); auto start_time = std::chrono::high_resolution_clock::now(); Matrix C_serial = multiply_matrix_serial(A, B); auto stop_time = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::milli> dur_ms = stop_time - start_time; std::cout << "Time elapsed Serial: " << dur_ms.count() << "ms" << std::endl; std::cout<<"C_serial\n"; print_matrix(C_serial); start_time = std::chrono::high_resolution_clock::now(); Matrix C_parallel = multiply_matrix_parallel(A, B); stop_time = std::chrono::high_resolution_clock::now(); dur_ms = stop_time - start_time; std::cout << "Time elapsed Parallel: " << dur_ms.count() << "ms" << std::endl; std::cout<<"C_parallel\n"; print_matrix(C_parallel); std::cout<<"Equality Check: "<<equal_check(C_serial, C_parallel)<<'\n'; return 0; }
true
bec0930ea33153e3de4e08e8f1205d95f18e444d
C++
akshpreetsingh988/Introduction-To-C-
/Character Arrays/ReverseWordwise.cpp
UTF-8
1,543
4.0625
4
[]
no_license
/* Reverse Word Wise Send Feedback Reverse the given string word wise. That is, the last word in given string should come at 1st place, last second word at 2nd place and so on. Individual words should remain as it is. Input format : String in a single line Output format : Word wise reversed string in a single line Constraints : 0 <= |S| <= 10^7 where |S| represents the length of string, S. Sample Input 1: */ // CPP program to reverse a string #include <stdio.h> // Function to reverse any sequence // starting with pointer begin and // ending with pointer end void reverse(char* begin, char* end) { char temp; while (begin < end) { temp = *begin; *begin++ = *end; *end-- = temp; } } // Function to reverse words*/ void reverseStringWordWise(char* s) { char* word_begin = s; // Word boundary char* temp = s; // Reversing individual words as // explained in the first step while (*temp) { temp++; if (*temp == '\0') { reverse(word_begin, temp - 1); } else if (*temp == ' ') { reverse(word_begin, temp - 1); word_begin = temp + 1; } } // Reverse the entire string reverse(s, temp - 1); } #include <iostream> #include "solution.h" using namespace std; int main() { char input[1000]; cin.getline(input, 1000); reverseStringWordWise(input); cout << input << endl; }
true
110d8122d2e41774a1fcd369cd11d1db4960df44
C++
ahdemitalug/Algorithms-Programs
/Algorithms/insertion_sort.cpp
UTF-8
1,145
2.984375
3
[]
no_license
// // insertion_sort.cpp // // // Created by Medha gulati on 9/3/19. // #include<iostream> #include<fstream> using namespace std; int main(int argc,char **argv) { ifstream inputfile(argv[1]); ofstream outfile(argv[2]); int arr[10000],n,m,x; x=0; while(inputfile) { string str; inputfile>>str; int nsize=str.size(); str=str+" "; for(int i=0;i<nsize;i++) { int num=str[i]-48; i++; while(str[i]!=32) { num=(num*10)+str[i]-48; i++; } arr[x]=num; x++; } } n=x; for(int i=0;i<n;i++) { outfile<<arr[i]<<" "; } outfile<<endl; for(int i=1;i<n;i++) {int val=arr[i]; int x=i-1; while(arr[x]>arr[i]&&x>-1) { x--; } x++; m=i-1; for(m=i-1;m>=x;m--) { arr[m+1]=arr[m]; } arr[m+1]=val; for(int i=0;i<n;i++) { outfile<<arr[i]<<" "; } outfile<<endl; } }
true
be0ed927c86685d4e547707fcfaa61ff1d5f11f6
C++
mbaldwin2015/CSE340-Project-2
/parser.cc
UTF-8
7,759
2.796875
3
[]
no_license
/* Michael Baldwin 1208386656 7/29/2016 */ #include <iostream> #include <istream> #include <fstream> #include <vector> #include <string> #include <cctype> #include <stdio.h> #include <cstring> #include <cstdlib> #include <cstdio> #include "lexer.h" #include "inputbuf.h" #include "parser.h" using namespace std; /*struct sTableItem { string name; string scope; int permission; }; struct sTable { sTableItem* item; sTable* next; sTable* prev; }; struct printOutput { string line; printOutput* next; };*/ LexicalAnalyzer lexer; Parser parser; Token token; sTable* entry1; // for searching, refer to parse_stmt() sTable* entry2; // for searching, refer to parse_stmt() sTable* head; sTable* temp; sTable* n; sTable* ptr; printOutput* stringHead; printOutput* stringTemp; printOutput* stringNew; string currentScope = "ERROR", line = "ERROR"; int currentPermission = -1; bool syntaxError = false; void Parser::parse_program() { bool scopeParsed = false; token = lexer.GetToken(); if (token.token_type == ID) { Token token2 = lexer.GetToken(); if (token2.token_type == COMMA || token2.token_type == SEMICOLON) { lexer.UngetToken(token2); lexer.UngetToken(token); parser.parse_global_vars(); parser.parse_scope(); scopeParsed = true; } else if (token2.token_type == LBRACE) { lexer.UngetToken(token2); lexer.UngetToken(token); parser.parse_scope(); scopeParsed = true; } else { syntaxError = true; return; } } token = lexer.GetToken(); if (token.token_type == LBRACE || scopeParsed) { //cout << "program parsed\n"; } else { syntaxError = true; return; } } void Parser::parse_global_vars() { token = lexer.GetToken(); if (token.token_type == ID) { currentScope = "::"; // save scope before creating vars currentPermission = 0; // 0 = GLOBAL permission, save before creating vars lexer.UngetToken(token); parser.parse_var_list(); } else { syntaxError = true; return; } token = lexer.GetToken(); if (token.token_type == SEMICOLON) { //cout << "global_vars parsed\n"; } else { syntaxError = true; return; } } void Parser::parse_scope() { token = lexer.GetToken(); if (token.token_type == ID) { currentScope = token.lexeme; // save current scope before creating vars token = lexer.GetToken(); if (token.token_type == LBRACE) { parse_public_vars(); parse_private_vars(); parse_stmt_list(); token = lexer.GetToken(); if (token.token_type == RBRACE) { //cout << "scope parsed\n"; } else { syntaxError = true; return; } } else { syntaxError = true; return; } } else { syntaxError = true; return; } } void Parser::parse_public_vars() { token = lexer.GetToken(); if (token.token_type == PUBLIC) { currentPermission = 1; // 1 = PUBLIC permission, save before creating vars token = lexer.GetToken(); if (token.token_type == COLON) { token = lexer.GetToken(); if (token.token_type == ID) { lexer.UngetToken(token); parser.parse_var_list(); } else { syntaxError = true; return; } } else { syntaxError = true; return; } } else { lexer.UngetToken(token); return; } token = lexer.GetToken(); if (token.token_type == SEMICOLON) { //cout << "public_vars parsed\n"; } else { syntaxError = true; return; } return; } void Parser::parse_private_vars() { token = lexer.GetToken(); if (token.token_type == PRIVATE) { currentPermission = 2; // 2 = PRIVATE permission, save before creating vars token = lexer.GetToken(); if (token.token_type == COLON) { token = lexer.GetToken(); if (token.token_type == ID) { lexer.UngetToken(token); parser.parse_var_list(); } else { syntaxError = true; return; } } else { syntaxError = true; return; } } else { lexer.UngetToken(token); return; } token = lexer.GetToken(); if (token.token_type == SEMICOLON) { //cout << "private_vars parsed\n"; } else { syntaxError = true; return; } return; } void Parser::parse_var_list() { token = lexer.GetToken(); if (token.token_type == ID) { // add a new var to the table if (head->item->permission == -2) { n->item->name = token.lexeme; n->item->scope = currentScope; n->item->permission = currentPermission; } else { n = new sTable; n->item = new sTableItem; n->item->name = token.lexeme; n->item->scope = currentScope; n->item->permission = currentPermission; addList(n); } token = lexer.GetToken(); if (token.token_type == COMMA) { parser.parse_var_list(); } else if (token.token_type == SEMICOLON) { lexer.UngetToken(token); } } else { syntaxError = true; return; } } void Parser::parse_stmt_list() { token = lexer.GetToken(); if (token.token_type == ID) { Token token2 = lexer.GetToken(); if (token2.token_type == EQUAL || token2.token_type == LBRACE) { lexer.UngetToken(token2); lexer.UngetToken(token); parser.parse_stmt(); } else { lexer.UngetToken(token2); lexer.UngetToken(token); return; } token = lexer.GetToken(); if (token.token_type == ID) { lexer.UngetToken(token); parser.parse_stmt_list(); } else { lexer.UngetToken(token); //cout << "stmt_list parsed\n"; } return; } } void Parser::parse_stmt() { token = lexer.GetToken(); if (token.token_type == ID) { Token token2 = lexer.GetToken(); if (token2.token_type == EQUAL) { Token token3 = lexer.GetToken(); Token token4 = lexer.GetToken(); if (token3.token_type != ID && token4.token_type != SEMICOLON) { syntaxError = true; return; } else { // Resolve the names line = ""; searchList(token.lexeme); line += " = "; searchList(token3.lexeme); line += "\n"; addString(line); } } else if (token2.token_type == LBRACE) { lexer.UngetToken(token2); lexer.UngetToken(token); parser.parse_scope(); } else { syntaxError = true; return; } } else { lexer.UngetToken(token); } //cout << "stmt parsed\n"; return; } void Parser::addList(sTable* table) { temp->next = table; table->prev = temp; table->next = NULL; temp = temp->next; } void Parser::addString(string s) { if (stringHead->line == "BRAND NEW LIST") { stringNew->line = s; } else { stringNew = new printOutput; stringNew->line = s; stringTemp->next = stringNew; stringNew->next = NULL; stringTemp = stringTemp->next; } } void Parser::searchList(string Id) { bool found = false; ptr = temp; if (ptr->prev == NULL) { if (ptr->item->name == Id) { if (ptr->item->scope != currentScope && ptr->item->scope != "::") line += "?."; else { line += ptr->item->scope; if (ptr->item->scope != "::") line += "."; } line += Id; } else { line += "?."; line += Id; } } else { while (ptr != NULL && !found) { if (ptr->item->name == Id) { if ((ptr->item->scope != currentScope && (ptr->item->permission == 0 || ptr->item->permission == 1)) || ptr->item->scope == currentScope || ptr->item->scope == "::") { line += ptr->item->scope; if (ptr->item->scope != "::") line += "."; found = true; } } ptr = ptr->prev; } if (!found) line += "?."; line += Id; } } int main() { n = new sTable; n->next = NULL; n->prev = NULL; n->item = new sTableItem; n->item->permission = -2; head = n; temp = n; stringNew = new printOutput; stringNew->next = NULL; stringNew->line = "BRAND NEW LIST"; stringHead = stringNew; stringTemp = stringNew; parser.parse_program(); // Print final name resolution result if (syntaxError == true) { cout << "Syntax Error\n"; } else { stringTemp = stringHead; while (stringTemp != NULL) { cout << stringTemp->line; stringTemp = stringTemp->next; } } }
true
bfd650e76847162d05c6cb914d4e8fcd995d6eb9
C++
bsu2019gr9/Graneva
/5-1.cpp
UTF-8
2,197
3.75
4
[]
no_license
//Класс французские деньги(1 франк = 20су) #include <iostream> using namespace std; class FrenchMoney { private: int frank; int soo; public: FrenchMoney(); FrenchMoney(int a, int b=0); ~FrenchMoney(); void operator=(const FrenchMoney& m); FrenchMoney operator+(const FrenchMoney& m); FrenchMoney operator-(const FrenchMoney& m); FrenchMoney operator*(const int k); friend void operator<<(ostream& out, const FrenchMoney& m); friend void operator>>(istream& in, FrenchMoney& m); }; FrenchMoney::FrenchMoney() : frank(0), soo(0) { cout << "no params constructor working \n"; } FrenchMoney::FrenchMoney(int a, int b) : frank(a + b / 20), soo(b % 20) { cout << "constructor working for " << this->frank << ' ' << this->soo << "\n"; } FrenchMoney::~FrenchMoney() { cout << "destructor working\n"; } void FrenchMoney::operator=(const FrenchMoney& m) { frank = m.frank; soo = m.soo; } FrenchMoney FrenchMoney::operator+(const FrenchMoney& m) { return FrenchMoney(frank + m.frank + (soo + m.soo) / 20, (soo + m.soo) % 20); } FrenchMoney FrenchMoney::operator-(const FrenchMoney& m) { return FrenchMoney(frank - m.frank - (soo - m.soo) / 20, (soo - m.soo) % 20); } FrenchMoney FrenchMoney::operator*(const int k) { return FrenchMoney(frank * k + (soo * k) / 20, (soo * k) % 20); } void operator<<(ostream& out, const FrenchMoney& m) { out << m.frank << " frank " << m.soo << " soo " << "\n"; } void operator>>(istream& in, FrenchMoney& m) { in >> m.frank; in >> m.soo; m.frank += m.soo / 20; m.soo = m.soo % 20; } FrenchMoney ffgg(FrenchMoney m) { return m; } FrenchMoney fff(FrenchMoney& m) { return m; } FrenchMoney* ggg(FrenchMoney* m) { return m; } int main() { FrenchMoney m1(4, 7); cout << m1; FrenchMoney m2; cin >> m2; cout << m2; FrenchMoney m3[4] = { {6, 17}, {9, 3}, 3, {4, 12} }; for (int i = 0; i < 4; ++i) cout << m3[i]; FrenchMoney* m4 = new (nothrow) FrenchMoney[3]; *m4 = m2; cout<<"m4=" << *ggg(m4); cout<<"m1 * 2=" << m1 * 2 ; cout << "m1 +m2=" << m1 +m2; cout << "m1 -m3[3]=" << m1-m3[2]; cout << "ffgg: " << fff(m3[0]); cout << "fff: " << fff(m1); cout << "ggg: " << *ggg(m4); delete[] m4; return 0; }
true
0efb395ade29f86e32e65afc029bcf607f976971
C++
Auram20/CPP_IMAC2
/TP3/ImagesRGBU8.cpp
UTF-8
738
3.09375
3
[]
no_license
// ================================ // POO C++ - IMAC 2 // TP 4 - Exercice 1 // ================================ #include "ImageRGBU8.hpp" #include <vector> // Créer une image // Constructeur ImagesRGBU8::ImagesRGBU8(const unsigned int width, const unsigned int height):m_width(width), m_height(height), m_data(width*height*3) // Pour les types primitifs pas besoin de construire, en écrivait m_wifth(width) le compilo comprend automatiquement { std::fill(m_data.begin(),m_data.end(),255); // On remplit le tableau de blanc pour avoir une image blanche par défaut }; // Constructeur par défaut ImagesRGBU8::ImagesRGBU8():m_width(0), m_height(0), m_data() { }; // Détruire une image ImagesRGBU8::~ImagesRGBU8() { }
true
1bb3b53ee41241b5653a72fe0634d22a71b8639e
C++
lvan100/PrettyFramework
/PrettyFramework/Typedef.h
GB18030
2,793
2.875
3
[ "Apache-2.0" ]
permissive
#pragma once #include <array> #include <functional> using namespace std; #include "Coordinate.h" namespace PrettyFramework { /** * ȡöٵԪ */ template<typename T> struct enum_size { const static int size = 0; }; /** * 뷽ʽ */ enum Gravity { Top = 0x0000, Left = 0x0000, CenterH = 0x0001, Right = 0x0002, CenterV = 0x0004, Bottom = 0x0008, }; template<> struct enum_size<Gravity> { const static int size = 6; }; /** * ؼ״̬ */ enum State { Normal = 0x00, // ͨ Hovered = 0x01, // ȵ Pressed = 0x02, // Focused = 0x04, // Disable = 0x08, // }; template<> struct enum_size<State> { const static int size = 5; }; class UserControl; /** * ¼IJ */ struct EventParam { /** * 굱ǰ */ Point point; /** * ǷԵ¼ */ BOOL will_eat_it; /** * ¼Դؼ */ UserControl* control; }; /** * ¼Ӧԭ */ using MouseEvent = function<void(EventParam&)>; /** * ¼IJ */ struct ClickParam { /** * ¼Դؼ */ UserControl* control; }; /** * ¼Ӧԭ */ using ClickEvent = function<void(ClickParam&)>; /** * СΧ */ inline void DeflateRect(Gdiplus::RectF& rect, const Margin& margin) { rect.Height -= margin.Top + margin.Bottom; rect.Width -= margin.Left + margin.Right; rect.X += margin.Left; rect.Y += margin.Top; } /** * СΧ */ inline void DeflateRect(Gdiplus::RectF& rect, float margin) { rect.Height -= margin + margin; // margin * 2 rect.Width -= margin + margin; // margin * 2 rect.X += margin; rect.Y += margin; } /** * תΪ Gdiplus ϵ */ inline Gdiplus::PointF toGdiplusPoint(Point point) { return Gdiplus::PointF(point.X, point.Y); } /** * תΪ GDI ϵ */ inline CPoint toGDIPoint(Point point) { return CPoint(int(point.X), int(point.Y)); } /** * תΪ Gdiplus ϵ */ inline Gdiplus::RectF toGdiplusRect(Rect rect) { return Gdiplus::RectF(rect.Left, rect.Top, rect.Width, rect.Height); } /** * תΪ GDI ϵ */ inline CRect toGdiRect(Rect rect) { return CRect(int(rect.GetLeft()), int(rect.GetTop()), int(rect.GetRight()), int(rect.GetBottom())); } /** * תΪ Pretty ϵ */ inline Point fromGdiPoint(CPoint point) { return Point(float(point.x), float(point.y)); } /** * תΪ Pretty ϵ */ inline Rect fromGdiRect(CRect rect) { return Rect(float(rect.left), float(rect.top), float(rect.Width()), float(rect.Height())); } }
true
c4790e08415f96f9e7a8f26474d41eb8cd0c4d05
C++
balooop/cplusplus_projects
/maze_solver/maze.h
UTF-8
1,547
3.21875
3
[]
no_license
/* Your code here! */ #pragma once #include <stdint.h> #include <vector> #include <utility> #include "cs225/PNG.h" #include "cs225/HSLAPixel.h" #include "dsets.h" using namespace cs225; using namespace std; class SquareMaze { private: int maze_width_; int maze_height_; int maze_size_; DisjointSets maze_set_; //2D array of pairs for walls //pair.first = right //pair.second = down vector<vector<pair<bool, bool>>> walls_; //helper functions //helper for createmazes void addAllWalls(); //helper for solve maze travelling pair<int,int> travelHelper(pair<int,int> current, int dir); //helper for solve maze solution directios int checkDirection(pair<int,int> current, pair<int,int> parent); public: //default constructor SquareMaze(); //creates a maze with width and height parameter void makeMaze(int width, int height); //checks if we can travel in the direction (dir) from {x,y} bool canTravel(int x, int y, int dir) const; //sets whether or not the specified wall exists from {x,y} in the specified direction (dir) void setWall(int x, int y, int dir, bool exists); //solves the square maze vector<int> solveMaze(); //draws the maze without the solution PNG * drawMaze() const; //draws the maze with the solution PNG * drawMazeWithSolution(); //part 3 PNG* drawMazeCreative(); };
true
d3688db217818a73da79e3d8e40b3b8b1c9b121f
C++
minuby963/other-projects
/Języki programowania/C++/JIMP 2/zajecia 3/operator3/functions.cpp
UTF-8
547
3.046875
3
[]
no_license
/*#include <iostream> using namespace std; class complex2 { public: int real; int imaginary; complex2 & operator+(complex2 & com) { int i=0,j=0; static complex2 com3(i,j); com3.real=this->real+com.real; com3.imaginary=this->imaginary+com.imaginary; return com3; } complex2(int alfa, int beta) { real=alfa; imaginary=beta; } }; ostream &operator<<(ostream &out, complex2 & com) { out<<com.real<<"+i*"<<com.imaginary<<endl; return out; }*/
true
b34342d7ca3a6432b8b4334b732730d9c20fb9c6
C++
wovert/CTutorials
/C++/oop/data.cpp
UTF-8
728
3.109375
3
[]
no_license
#include "data.h" void Data::setNum(int n) { num = n; } int Data::getNum(void) { return num; } void Data::setAge(int n) { age = n; } int Data::getAge(void) { return age; } void Data::setName(char *name) { this->name = name; } char * Data::getName(void) { return this->name; } // const 修饰成员变量,函数不能修改普通成员变量,除了mutable 声明的成员变量 void Data::getInfo() const { mnum = 123; cout << "const function"<< endl; cout << "mnum=" << mnum << endl; } void Data::envNum() const { cout << "const function" << endl; } int Data::shareData = 100; // 静态成员变量类外定义+初始化 const int Data::onlyData = 10000; // 类外定义+初始化
true
caab478450bc10a4475614bc31b32698dd346b01
C++
quentinplessis/projet3D_rendu
/RayTracer.cpp
UTF-8
8,917
2.640625
3
[]
no_license
// ********************************************************* // Ray Tracer Class // Author : Tamy Boubekeur (boubek@gmail.com). // Copyright (C) 2012 Tamy Boubekeur. // All rights reserved. // ********************************************************* #include "RayTracer.h" #include "Ray.h" #include "Scene.h" #include "KDTree.h" #include <QProgressDialog> static RayTracer * instance = NULL; RayTracer * RayTracer::getInstance () { if (instance == NULL) instance = new RayTracer (); return instance; } void RayTracer::destroyInstance () { if (instance != NULL) { delete instance; instance = NULL; } } inline int clamp (float f, int inf, int sup) { int v = static_cast<int> (f); return (v < inf ? inf : (v > sup ? sup : v)); } QImage RayTracer::render (const Vec3Df & camPos, const Vec3Df & direction, const Vec3Df & upVector, const Vec3Df & rightVector, float fieldOfView, float aspectRatio, unsigned int screenWidth, unsigned int screenHeight) { QImage image (QSize (screenWidth, screenHeight), QImage::Format_RGB888); Scene * scene = Scene::getInstance (); QProgressDialog progressDialog ("Raytracing...", "Cancel", 0, 100); progressDialog.show (); for (unsigned int i = 0; i < screenWidth; i++) { progressDialog.setValue ((100*i)/screenWidth); for (unsigned int j = 0; j < screenHeight; j++) { //Paramètres variables bool softShadows=true; bool hardShadows=false; unsigned nbRaysPerPixel=2; // 2 => distribution 2*2, 3 => distribution 3*3, etc unsigned nbPointsDisc = 20; // nombre de point répartis aléatoirement sur la source étendue float tanX = tan (fieldOfView)*aspectRatio; float tanY = tan (fieldOfView); float pixelWidth =tanX/screenWidth; float pixelHeight = tanY/screenHeight; Vec3Df stepX = (float (i) - screenWidth/2.f) * pixelWidth * rightVector; Vec3Df stepY = (float (j) - screenHeight/2.f) * pixelHeight * upVector; Vec3Df step = stepX + stepY; Vec3Df dir = direction + step; dir.normalize (); Vertex intersectionPoint; unsigned objectIntersectedIndex; // retient l'objet de la scene qui a été intersecté float smallestIntersectionDistance = 1000000.f; Vec3Df c (backgroundColor); bool hasIntersection=false; vector<Vec3Df> miniSteps; // Pour créer des points espacés régulirement à l'intérieur du pixel miniSteps.resize(nbRaysPerPixel*nbRaysPerPixel); vector<Vec3Df> colors; // c sera la moyenne des couleurs obtenu pour chaque rayon du pixel colors.resize(nbRaysPerPixel*nbRaysPerPixel); for(unsigned i1=0; i1<colors.size(); i1++) colors[i1]=Vec3Df(backgroundColor); // On crée des points espacés régulièrement à l'intérieur du pixel for(unsigned rx=0; rx<nbRaysPerPixel; rx++) { for(unsigned ry=0; ry<nbRaysPerPixel; ry++) { miniSteps[ry*nbRaysPerPixel+rx] = Vec3Df(((float)(rx+1)/(float)(nbRaysPerPixel+1)-0.5f)*pixelWidth, ((float)(ry+1)/(float)(nbRaysPerPixel+1)-0.5f)*pixelHeight,0); } } //On cherche l'intersection de chacun des rayons passant par un point du pixel avec la scene for(unsigned r=0; r<nbRaysPerPixel*nbRaysPerPixel; r++) { //On test tous les objets de la scene et on ne garde que l'intersection de l'objet le plus proche for (unsigned int k = 0; k < scene->getObjects().size (); k++) { Vertex intersectionPointTemp; const Object & o = scene->getObjects()[k]; Ray ray(camPos-o.getTrans (), dir+miniSteps[r]); if (ray.intersectObject (o, intersectionPointTemp)) { float intersectionDistance = Vec3Df::squaredDistance (intersectionPointTemp.getPos() + o.getTrans (), camPos); if (intersectionDistance < smallestIntersectionDistance) { hasIntersection=true; objectIntersectedIndex=k; intersectionPoint=intersectionPointTemp; smallestIntersectionDistance = intersectionDistance; } } } //Si le rayon a intersecté un triangle if(hasIntersection) { //L'objet sera noir s'il n'est visible par aucune source lumineuse colors[r] = Vec3Df(0.0f,0.0f,0.0f); const Object & o = scene->getObjects()[objectIntersectedIndex]; Material material = o.getMaterial(); std::vector<AreaLight> sceneAreaLights = scene->getAreaLights(); //On traite chaque source de lumière for(unsigned l=0; l < sceneAreaLights.size(); l++) { // Position du point en World Space Vec3Df pointWS = intersectionPoint.getPos()+o.getTrans(); // Position de la source lumineuse, elle est fixe dans l'espace caméra Vec3Df lightPos=sceneAreaLights[l].getPos(); lightPos[0]=Vec3Df::dotProduct(rightVector,lightPos); lightPos[1]=Vec3Df::dotProduct(upVector,lightPos); lightPos[2]=Vec3Df::dotProduct(-direction,lightPos); lightPos+=camPos; //Direction du point vers la source lumineuse Vec3Df directionToLight = lightPos - pointWS; directionToLight.normalize(); float visibility = (float)nbPointsDisc; //Si l'on veut représenter des ombres douces if(softShadows) { // On répartit aléatoirement des point sur la surface de la source sceneAreaLights[l].discretize(nbPointsDisc); const vector<Vec3Df>& discretization = sceneAreaLights[l].getDiscretization(); // Pour chacun des points discrétisés On va lancé un rayon vers chacun des points discrétisé for(unsigned n=0; n<nbPointsDisc; n++) { // Le point discrétisé de la source étendue reste fixe par rapport à la caméra Vec3Df lightPosDisc=discretization[n]; lightPosDisc[0]=Vec3Df::dotProduct(rightVector,lightPosDisc); lightPosDisc[1]=Vec3Df::dotProduct(upVector,lightPosDisc); lightPosDisc[2]=Vec3Df::dotProduct(-direction,lightPosDisc); lightPosDisc+=camPos; Vec3Df directionToLightDisc = lightPosDisc - pointWS; directionToLightDisc.normalize(); //On test si le point d'intersection est visible du point // discretisé de la source lumineuse for (unsigned int k = 0; k < scene->getObjects().size (); k++) { Vertex intersectionPointTemp; const Object & oTemp = scene->getObjects()[k]; Ray rayPointToLightDisc(pointWS-oTemp.getTrans(), directionToLightDisc); // if (rayPointToLightDisc.intersectObject (oTemp, intersectionPointTemp)) { //Un objet cache le point discretisé de la source étendue //Ce point de la source étendu n'éclaire donc pas le point d'intersection visibility--; // Pas la peine de chercher d'autres intersections avec d'autres objets break; } } } }// On a fini de traiter les ombres douces //Si l'on veut représenter des ombres dures //On ne considére que des sources ponctuelles //On n'envoie par conséquent qu'un rayon vers la source lumineuse else if(hardShadows) { for (unsigned int k = 0; k < scene->getObjects().size (); k++) { Vertex intersectionPointTemp; const Object & oTemp = scene->getObjects()[k]; Ray rayPointToLight(pointWS-oTemp.getTrans(), directionToLight); if (rayPointToLight.intersectObject (oTemp, intersectionPointTemp)) { visibility=0.0f; // L'objet n'est pas éclairé break; } } } visibility/=(float)nbPointsDisc; //Si l'objet est au moins partiellement éclairé if(visibility>0.0f) { //Phong Shading //la normal de l'objet en ce point //Seule des translations ont été appliquées à l'objet, la normale n'est dont pas modifiée Vec3Df normal=intersectionPoint.getNormal()/intersectionPoint.getNormal().getLength(); float diff = Vec3Df::dotProduct(normal, directionToLight); Vec3Df reflected = 2*diff*normal-directionToLight; if(diff<=0.0f) diff=0.0f; reflected.normalize(); float spec = Vec3Df::dotProduct(reflected, -dir); if(spec <= 0.0f) spec=0.0f; colors[r] += sceneAreaLights[l].getIntensity()*(material.getDiffuse()*diff + material.getSpecular()*spec)*sceneAreaLights[l].getColor()*material.getColor(); //l'intensité est plus ou moins forte selon que le point est plus ou moins eclairé colors[r]*=visibility; } }// On a fini de traiter chacune des lumières de la scène }// On a fini de calculer la couleur du pixel lorsqu'un rayon intersecte la scène c+=colors[r]; }// On a traité tous les rayons envoyés à l'intérieur d'un même pixel c=255.0f*c/colors.size(); // On fait la moyenne de la couleur obtenue pour chaque rayon; image.setPixel (i, j, qRgb (clamp (c[0], 0, 255), clamp (c[1], 0, 255), clamp (c[2], 0, 255))); } } progressDialog.setValue (100); return image; }
true
5c14c9f0beba68f69855183d74122680e288d95b
C++
Satori32/GlobalObject
/NGグローバル??/Source.cpp
UTF-8
207
2.828125
3
[]
no_license
#include <iostream> template<class T,class... A> T& Global(const A&... Arg) { static T V(Arg...); return V; } int main() { Global<int,int>(25)++; int N = Global<int,int>(0);//return 26; return 0; }
true
65dabe714b3e79c5097b37ccf299158fc23fc5e9
C++
jordantonni/Design_Patterns
/9 Strategy/DynamicStrategy.cpp
UTF-8
2,706
3.765625
4
[]
no_license
#include <iostream> #include <string> #include <sstream> #include <vector> #include <memory> using namespace std; /* * ABSTRACT: * TextProcessor class is the high level algorithim section. It drives the overall algorihim by defining what to do. * * Both Markdown and Html strategies derive from the ListStrategy, which is what the TextProcessor invokes for the implmentation of the low level strategies. * * NOTE: TextProcessor is able to change strategy dynamically at run time by passing it a different strategy. */ enum class OutputFormat { Markdown, Html }; class ListStrategy { public: virtual ~ListStrategy() = default; virtual void Start(ostringstream& oss) = 0; virtual void End(ostringstream& oss) = 0; virtual void Append(ostringstream& oss, const string& s) = 0; }; class MarkdownStrategy : public ListStrategy { public: void Start(ostringstream& oss) override {} void End(ostringstream& oss) override {} void Append(ostringstream& oss, const string& s) override { oss << "*** " << s << "\n"; } }; class HtmlStrategy : public ListStrategy { public: void Start(ostringstream& oss) override { oss << "<html> \n\t<body>\n\t\t<ul>\n"; } void End(ostringstream& oss) override { oss << "\t\t</ul>\n\t</body>\n</html>\n"; } void Append(ostringstream& oss, const string& s) override { oss << "\t\t\t<li> " << s << " </li>\n"; } }; class TextProcessor { ostringstream oss; unique_ptr<ListStrategy> strategy_used; public: void append_list_items(const vector<string> items) { strategy_used->Start(oss); for (const auto& i : items) strategy_used->Append(oss, i); strategy_used->End(oss); } void set_strategy(OutputFormat strategy) { switch (strategy) { case OutputFormat::Html: strategy_used = make_unique<HtmlStrategy>(); break; case OutputFormat::Markdown: strategy_used = make_unique<MarkdownStrategy>(); break; } } void clear_strategy() { oss.str(""); oss.clear(); } friend ostream& operator<<(ostream& oss, const TextProcessor& tp) { return oss << tp.oss.str(); } }; void test_dynamic_strategy() { TextProcessor tp; tp.set_strategy(OutputFormat::Markdown); tp.append_list_items({ "Kitten Food", "Cat Litter", "Treats", "Play Toy" }); cout << tp << endl << endl; tp.clear_strategy(); tp.set_strategy(OutputFormat::Html); tp.append_list_items({ "Kitten Food", "Cat Litter", "Treats", "Play Toy" }); cout << tp << endl; }
true
ff5dd9f8f4f524cbbbdb3c1cf46463f71c7178f4
C++
H-Shen/Collection_of_my_coding_practice
/Kattis/cantinaofbabel.cpp
UTF-8
5,414
2.515625
3
[]
no_license
// https://open.kattis.com/problems/cantinaofbabel // #include <bits/extc++.h> using namespace std; using namespace __gnu_pbds; using ll = long long; constexpr int MAX_NODES = 105; struct custom_hash { static uint64_t splitmix64(uint64_t x) { // http://xorshift.di.unimi.it/splitmix64.c x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = std::chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } }; unordered_map<int, unordered_set<int, custom_hash>, custom_hash> G; // A collection of containers and procedures that implements Tarjan's strongly // connected components algorithm. Assume that the node id starts from 1 and the // index of a strongly connected component (SCC) also starts from 1 Reference: // https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm#The_algorithm_in_pseudocode namespace SCC { int number_of_nodes; // number of nodes in the graph int number_of_scc; // number of strongly connected components int current_timestamp; // current timestamp std::stack<int> s; // A stack is used to store all nodes that may form a // strongly connected component std::vector<bool> visited; // visited.at(id) flags if the node id is in the stack std::vector<int> dfs_rank; // dfs_rank.at(id) numbers the nodes consecutively in // the order in which they are discovered by DFS std::vector<int> low_link; // low_link.at(id) represents the smallest node id of // any node known to be reachable from id through // id's DFS subtree, including id itself std::vector<int> scc; // scc.at(id) is the index of the strongly connected // component that the node id belongs to std::vector<int> size_of_scc; // size_of_scc.at(id) is the size of the strongly // connected component whose index is id // Initialize all global variables in the namespace inline void init(int n) { number_of_nodes = n; number_of_scc = 0; current_timestamp = 1; // Give some flexibility of size of our containers since // the node id/SCC id may not strictly start from 1 int offset = 5; visited.resize(number_of_nodes + offset, false); dfs_rank.resize(number_of_nodes + offset, 0); low_link.resize(number_of_nodes + offset, 0); scc.resize(number_of_nodes + offset, 0); size_of_scc.resize(number_of_nodes + offset, 0); } inline void Tarjan(int u) { // u: the node id being processed dfs_rank.at(u) = current_timestamp; low_link.at(u) = current_timestamp; ++current_timestamp; s.push(u); visited.at(u) = true; for (const auto &v : G[u]) { if (!dfs_rank[v]) { Tarjan(v); low_link.at(u) = std::min(low_link.at(u), low_link.at(v)); } else if (visited.at(v)) { low_link.at(u) = std::min(low_link.at(u), dfs_rank.at(v)); } } if (low_link.at(u) == dfs_rank.at(u)) { ++number_of_scc; while (s.top() != u) { int top_id = s.top(); // Paint top_id s.pop(); scc.at(top_id) = number_of_scc; ++size_of_scc.at(number_of_scc); visited.at(top_id) = false; } // Paint u s.pop(); scc.at(u) = number_of_scc; ++size_of_scc.at(number_of_scc); visited.at(u) = false; } } } inline static vector<string> splitByChar(string s, const char &delim) { vector<string> res; istringstream f(s); string temp; while (getline(f, s, delim)) { res.emplace_back(s); } return res; } struct Node { string can_speak; unordered_set<string> can_understand; }; vector<Node> nodes(MAX_NODES); int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; string s; cin >> n; cin.get(); for (int i = 1; i <= n; ++i) { getline(cin, s); auto p = splitByChar(s, ' '); nodes.at(i).can_speak = p.at(1); if (p.size() > 2) { for (size_t j = 2; j != p.size(); ++j) { nodes.at(i).can_understand.insert(p.at(j)); } } // All characters understand the language they speak nodes.at(i).can_understand.insert(nodes.at(i).can_speak); } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { if (i != j) { if (nodes.at(j).can_understand.find(nodes.at(i).can_speak) != nodes.at(j).can_understand.end()) { G[i].insert(j); } } } } SCC::init(n); for (int i = 1; i <= n; ++i) { if (!SCC::dfs_rank.at(i)) { SCC::Tarjan(i); } } int max_nodes_in_a_scc = -1; for (int i = 1; i <= SCC::number_of_scc; ++i) { max_nodes_in_a_scc = max(max_nodes_in_a_scc, SCC::size_of_scc.at(i)); } cout << n - max_nodes_in_a_scc << '\n'; return 0; }
true
8c05a12cb01154c6e4f0e14fab532b24a96af30e
C++
amumu/nokuno
/cc/topcoder/Chessboard.cpp
UTF-8
2,510
2.859375
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <functional> #include <sstream> #include <complex> #include <stack> #include <queue> #include <sstream> using namespace std; static const double EPS = 1e-5; typedef long long ll; class Chessboard { public: string changeNotation(string cell) { string result; if (cell[0] > '9') { int num = (int)(cell[0]-'a') + (int)(cell[1]-'1') * 8 + 1; stringstream ss; ss << num; result = ss.str(); } else { int num = strtol(cell.c_str(), NULL, 0); result += ('a' + (char)(num-1)%8); result += ('1' + (char)((num-1)/8)); } return result; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "1"; string Arg1 = "a1"; verify_case(0, Arg1, changeNotation(Arg0)); } void test_case_1() { string Arg0 = "2"; string Arg1 = "b1"; verify_case(1, Arg1, changeNotation(Arg0)); } void test_case_2() { string Arg0 = "26"; string Arg1 = "b4"; verify_case(2, Arg1, changeNotation(Arg0)); } void test_case_3() { string Arg0 = "c1"; string Arg1 = "3"; verify_case(3, Arg1, changeNotation(Arg0)); } void test_case_4() { string Arg0 = "e4"; string Arg1 = "29"; verify_case(4, Arg1, changeNotation(Arg0)); } void test_case_5() { string Arg0 = "h8"; string Arg1 = "64"; verify_case(5, Arg1, changeNotation(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { Chessboard ___test; ___test.run_test(-1); } // END CUT HERE
true
9ada422f4ab017e2f5d38f2a8ae0340cd5169bd1
C++
iamjatin08/competitive
/DP/LCS.cpp
UTF-8
1,147
2.96875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int lcs(char* s1, char* s2){ if(s1[0]=='\0' || s2[0]=='\0'){ return 0; } if(s1[0]==s2[0]){ return 1+lcs(s1 + 1,s2 + 1); } else{ int opt1 = lcs(s1,s2+1); int opt2 = lcs(s1+1,s2); return max(opt1,opt2); } } int lcsHelper(char* s1, char* s2, int m , int n, int**dp){ if(m==0 or n==0) return 0; if(dp[m][n]>-1) return dp[m][n]; int ans; if(s1[0]==s2[0]){ ans = lcsHelper(s1+1,s2+1,m-1,n-1,dp)+1; } else{ int opt1 = lcsHelper(s1+1,s2,m-1,n,dp); int opt2 = lcsHelper(s1,s2+1,m,n-1,dp); ans = max(opt1,opt2); } dp[m][n] = ans; return ans; } int lcsDP(char* s1,char*s2){ int m = strlen(s1); int n = strlen(s2); int** dp = new int*[m+1]; for(int i = 0 ; i<=m ;i++){ dp[i] = new int[n+1]; for(int j = 0 ; j<=n ; j++) dp[i][j] = -1; } int ans = lcsHelper(s1,s2,m,n,dp); for(int i = 0 ; i<= m ; i++) delete [] dp[i]; delete [] dp; return ans; } int main(int argc, char const *argv[]) { char a[100]; char b[100]; cin>>a>>b; cout<<lcsDP(a,b)<<endl; cout<<lcs(a,b)<<endl; return 0; }
true
087b8ffc06b8a06f963cbecf9043c14437193363
C++
tprice108/School-Projects
/COP 3330 - Object Oriented Programming/Assignments/proj-5/matrix.cpp
UTF-8
7,086
3.875
4
[]
no_license
/* Name: Caijun Qin Course and Section: COP3330-0009 Project: 5 Summary: Creates representations of matrices using a single array of unsigned integers. Allows basic matrix operations including summation and matrix product. */ #include <iostream> #include "matrix.h" //CONSTRUCTORS Matrix::Matrix(unsigned int row, unsigned int column, unsigned int value) { //storage type is row major by default numRows = row; numCols = column; storageType = 'r'; unsigned int size = row * column; array = new unsigned int[size]; for(unsigned int i = 0; i < size; i++) array[i] = value; } Matrix::Matrix(const Matrix & b) { //copies all member data of Matrix b to the calling Matrix object numRows = b.numRows; numCols = b.numCols; storageType = b.storageType; unsigned int size = b.numRows * b.numCols; array = new unsigned int[size]; for(unsigned int i = 0; i < size; i++) array[i] = b.array[i]; } //DESTRUCTORS Matrix::~Matrix() { delete [] array; } //ACCESSORS / NON-MUTATORS int Matrix::numofrows() const { return numRows; } int Matrix::numofcols() const { return numCols; } int Matrix::get(unsigned int r, unsigned int c) const { //index of array containing the entry (*this)_ij unsigned int index; unsigned int size = numRows * numCols; if(storageType == 'r') { index = (r - 1) * numCols + (c - 1); if(index >= 0 && index <= size - 1) return array[index]; } else if(storageType == 'c') { index = (c - 1) * numRows + (r - 1); if(index >= 0 && index <= size - 1) return array[index]; } return -1; } void Matrix::printinternal() const { //prints out the entries from array in one line unsigned int size = numRows * numCols; for(unsigned int i = 0; i < size; i++) cout << array[i] << "\t"; cout << endl; return; } Matrix Matrix::transpose() const { //converts row i into column i //the same thing as converting column i into row i //each entry (*this)_ij turns into (*this)_ji Matrix b(numCols, numRows); //creates a copy of array by making a copy of the object Matrix copy(*this); //assigning values to array in b for(unsigned int i = 1; i <= b.numRows; i++) for(unsigned int j = 1; j <= b.numCols; j++) b.set(i, j, copy.get(j, i)); return b; } Matrix Matrix::submatrix(unsigned int startrow, unsigned int endrow, unsigned int startcol, unsigned int endcol) const { //crop and return a copy of the matrix with dimensions no larger than the original dimensions if(endrow < startrow || endcol < startcol ||startrow > numRows || startcol > numCols || startrow < 0 || endrow < 0 || startcol < 0 || endcol < 0) { Matrix b(numRows, numCols); return b; } else { unsigned int b_numRows = endrow - startrow + 1; unsigned int b_numCols = endcol - startcol + 1; Matrix b(b_numRows, b_numCols); unsigned int index = 0; for(int i = startrow; i <= endrow; i++) for(int j = startcol; j <= endcol; j++) { b.array[index] = get(i, j); ++index; } return b; } } //MUTATORS bool Matrix::set(unsigned int r, unsigned int c, unsigned int value) { //sets a value to the entry at the ith row and jth column unsigned int index; unsigned int size = numRows * numCols; if(storageType == 'r') { index = (r - 1) * numCols + (c - 1); if(index >= 0 && index <= size - 1) { array[index] = value; return true; } } else if(storageType == 'c') { index = (c - 1) * numRows + (r - 1); if(index >= 0 && index <= size - 1) { array[index] = value; return true; } } return false; } void Matrix::torowmajor() { //if storage is by column, converts to by row if(storageType == 'r') return; else { //creates a copy of array by making a copy of the object Matrix copy(*this); //reconfigures original array with a different storage format unsigned int index = 0; for(unsigned int i = 1; i <= numRows; i++) for(unsigned int j = 1; j <= numCols; j++) { array[index] = copy.get(i, j); ++index; } storageType = 'r'; return; } } void Matrix::tocolumnmajor() { //if storage is by row, converts to by column if(storageType == 'c') return; else { //creates a copy of array by making a copy of the object Matrix copy(*this); //reconfigures original array with a different storage format unsigned int index = 0; for(unsigned int j = 1; j <= numCols; j++) for(unsigned int i = 1; i <= numRows; i++) { array[index] = copy.get(i, j); ++index; } storageType = 'c'; return; } } //OPERATOR OVERLOADING Matrix & Matrix::operator = (const Matrix & b) { if(this != &b) { delete [] array; numRows = b.numRows; numCols = b.numCols; unsigned int size = b.numRows * b.numCols; array = new unsigned int[size]; for(unsigned int i = 0; i < size; i++) array[i] = b.array[i]; } return *this; } Matrix Matrix::operator + (const Matrix & b) const { //returns the summation of two Matrix objects //both matrices must have same dimensions Matrix c(numRows, numCols); if(numRows == b.numRows && numCols == b.numCols) { for(unsigned int i = 1; i <= numRows; i++) for(unsigned int j = 1; j <= numCols; j++) c.set(i, j, get(i, j) + b.get(i, j)); } return c; } Matrix Matrix::operator * (const Matrix & b) const { //returns the matrix product of two Matrix objects Matrix c(numRows, b.numCols); //matrices must have dimensions m x n and n x p if(numCols == b.numRows) { unsigned int size = c.numRows * c.numCols; delete [] c.array; c.array = new unsigned int[size]; for(unsigned int i = 1; i <= c.numRows; i++) for(unsigned int j = 1; j <= c.numCols; j++) { //entry of C at the ith row and jth column unsigned int entry = 0; for(unsigned int k = 1; k <= numCols; k++) entry += get(i, k) * b.get(k, j); c.set(i, j, entry); } } return c; } ostream & operator << (ostream & out, const Matrix & b) { //prints out the Matrix object for(unsigned int i = 1; i <= b.numRows; i++) for(unsigned int j = 1; j <= b.numCols; j++) { if(j < b.numCols) out << b.get(i, j) << "\t"; else out << b.get(i, j) << endl; } return out; }
true
5f53ee9f65b08e9aa7282c9348ad1bc603e9c9ad
C++
timrobot/Tachikoma-Project
/interface/ovr/ovr.cpp
UTF-8
2,194
2.890625
3
[ "MIT" ]
permissive
#include "highgui.h" #include "imgproc.h" #include <cmath> using namespace arma; /* Rift dimensions are generally 2 screens, each 800x640 pixels * so in total 800x1280 * the recommended parameters are 1.0, 0.22, 0.24, 0.0 */ const double u_distortion[4] = { 1.0, 0.22, 0.24, 0 }; // distortion parameters double distortionScale(const vec &offset) { assert(offset.n_elem == 2); vec offsetSquared = offset % offset; double radiusSquared = offsetSquared(0) + offsetSquared(1); double distortion = u_distortion[0] + u_distortion[1] * radiusSquared + u_distortion[2] * radiusSquared * radiusSquared + u_distortion[3] * radiusSquared * radiusSquared * radiusSquared; return distortion; } mat barrel_distort(const mat &F, double offset_x) { mat G(F.n_rows, F.n_cols, fill::zeros); // find the radius of the barrel distortion double r_y = F.n_rows / 2; double r_x = F.n_cols / 2; double r_max = sqrt((r_x * (1 + abs(offset_x))) * (r_x * (1 + abs(offset_x))) + r_y * r_y); // grab the distortionScale for (uword i = 0; i < F.n_rows; i++) { for (uword j = 0; j < F.n_cols; j++) { double x = (double)(j-r_x) / r_max + offset_x; double y = (double)(i-r_y) / r_max; double distortion = distortionScale(vec({ y, x })); int _i = (int)round(distortion*y*r_max+r_y); int _j = (int)round((distortion*x-offset_x)*r_max+r_x); if (_i >= 0 && _i < F.n_rows && _j >= 0 && _j < F.n_cols) { G(i, j) = F(_i, _j); } } } return G; } cube barrel_distort_rgb(const cube &F, double offset_x) { cube G(F.n_rows, F.n_cols, F.n_slices); G.slice(0) = barrel_distort(F.slice(0), offset_x); G.slice(1) = barrel_distort(F.slice(1), offset_x); G.slice(2) = barrel_distort(F.slice(2), offset_x); return G; } cube ovr_image(const cube &left, const cube &right, double offset_x) { cube l = barrel_distort_rgb(left, -offset_x); cube r = barrel_distort_rgb(right, offset_x); cube combined(l.n_rows, l.n_cols + r.n_cols, l.n_slices); combined(span::all, span(0, l.n_cols-1), span::all) = l; combined(span::all, span(l.n_cols, l.n_cols+r.n_cols-1), span::all) = r; return imresize2(combined, 800, 1200); }
true
7b9a2e135627ef0d45c6d7295c280c3443f06a59
C++
jnawrocki33/mit_coursework
/calculate_pi.cpp
UTF-8
720
3.34375
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> using namespace std; int const SIZE = 100000000; // int distance(double x, double y) { // return (x*x + y*y) // } int main() { int count = 0; for(int i = 0; i < SIZE; i++) { double x = rand() / (double)RAND_MAX; double y = rand() / (double)RAND_MAX; //cout << "(" << x << ", " << y << ") - distance: " << sqrt(x*x + y*y) << endl; if (sqrt(x*x + y*y) < 1) { count += 1; } } int area_square = 2 * 2; double area_circle = count / (double) SIZE * area_square; int radius = 1; double pi = area_circle / (radius * radius); cout << "pi = " << pi; return 0; }
true
13207c4cb035e68c638379fb8446d6d42e173ae7
C++
dsw5775/bspline
/OpenMP_template/testbspline.cpp
UTF-8
5,968
3.125
3
[]
no_license
#include <iostream> #include "bspline.h" #include "common.h" using std::cout; int main(int argc, char *argv[]) /* testing bspline_1d to bspline_5d with order 6 you can change order with command line parameter, e.g. ./bspline 4 */ { double start, end; int order = 6; if(argc > 1 && isdigit(argv[1][0])) order = atol(argv[1]); int num_x1 = 100+1; double min_x1 = 0.0, max_x1 = 1.0; double width_x1 = (max_x1-min_x1) / (num_x1-1); double x1 = 0.5; double value, d1, d2; // test bspline_1d for data generated from function x^2 double *data1 = new double[num_x1]; for(int i = 0; i < num_x1; i++) data1[i] = (width_x1*i) * (width_x1*i); start = seconds(); bspline_1d(data1, min_x1, max_x1, num_x1, x1, order, value, d1, true, d2, true); end = seconds(); cout << std::fixed; cout << "bspline_1d test:\n"; cout << "Calculated:\n"; cout << value << '\t' << d1 << '\t' << d2 << '\n'; cout << "Expected:\n"; cout << x1*x1 << '\t' << 2*x1 << '\t' << 2.0 << '\n'; cout << "Time: " << end - start << " sec" << '\n'; cout << "\n\n"; delete[] data1; /* test bspline_2d for data generated from function x1^2*x2 */ num_x1 = 100; min_x1 = 0.005; max_x1 = 0.995; width_x1 = (max_x1-min_x1) / (num_x1-1); x1 = 0.3; int num_x2 = 24+1; double min_x2 = -10000.0, max_x2 = 10000.0; double width_x2 = (max_x2-min_x2) / (num_x2-1); double *data2 = new double[num_x1*num_x2]; double x2 = 4000.0; for(int i = 0; i < num_x1; i++) for(int j = 0; j < num_x2; j++) data2[i*num_x2+j] = (min_x1+width_x1*i) * (min_x1+width_x1*i) * (min_x2+width_x2*j); start = seconds(); bspline_2d(data2, min_x1, max_x1, num_x1, x1, min_x2, max_x2, num_x2, x2, order, value, d1, d2, true); end = seconds(); cout << std::fixed; cout << "bspline_2d test:\n"; cout << "Calculated:\n"; cout << value << '\t' << d1 << '\t' << d2 << '\n'; cout << "Expected:\n"; cout << x1*x1*x2 << '\t' << 2*x1*x2 << '\t' << x1*x1 << '\n'; cout << "Time: " << end - start << " sec" << '\n'; cout << "\n\n"; delete[] data2; /* test bspline_3d for data generated from function x1^2*x2*x3 */ int num_x3 = 24+1; double min_x3 = -0.01, max_x3 = 0.01; double width_x3 = (max_x3-min_x3) / (num_x3-1); double x3 = 0.005; double d3 = 0.0; double *data3 = new double[num_x1*num_x2*num_x3]; for(int i = 0; i < num_x1; i++) for(int j = 0; j < num_x2; j++) for(int k = 0; k < num_x3; k++) data3[i*num_x2*num_x3+j*num_x3+k] = (min_x1+width_x1*i) * (min_x1+width_x1*i) * (min_x2+width_x2*j) * (min_x3+width_x3*k); start = seconds(); bspline_3d(data3, min_x1, max_x1, num_x1, x1, min_x2, max_x2, num_x2, x2, min_x3, max_x3, num_x3, x3, order, value, d1, d2, d3, true); end = seconds(); cout << std::fixed; cout << "bspline_3d test:\n"; cout << "Calculated:\n"; cout << value << '\t' << d1 << '\t' << d2 << '\t' << d3 << '\n'; cout << "Expected:\n"; cout << x1*x1*x2*x3 << '\t' << 2*x1*x2*x3 << '\t' << x1*x1*x3 << '\t' << x1*x1*x2 << '\n'; cout << "Time: " << end - start << " sec" << '\n'; cout << "\n\n"; delete[] data3; /* test bspline_4d for data generated from function x1^2*x2*x3*x4 */ int num_x4 = 24+1; double min_x4 = -10000.0, max_x4 = 10000.0; double width_x4 = (max_x4-min_x4) / (num_x4-1); double x4 = 6000.0; double d4 = 0.0; double *data4 = new double[num_x1*num_x2*num_x3*num_x4]; for(int i = 0; i < num_x1; i++) for(int j = 0; j < num_x2; j++) for(int k = 0; k < num_x3; k++) for(int m = 0; m < num_x4; m++) data4[i*num_x2*num_x3*num_x4+j*num_x3*num_x4+k*num_x4+m] = (min_x1+width_x1*i) * (min_x1+width_x1*i) * (min_x2+width_x2*j) * (min_x3+width_x3*k) * (min_x4+width_x4*m); start = seconds(); bspline_4d(data4, min_x1, max_x1, num_x1, x1, min_x2, max_x2, num_x2, x2, min_x3, max_x3, num_x3, x3, min_x4, max_x4, num_x4, x4, order, value, d1, d2, d3, d4, true); end = seconds(); cout << std::fixed; cout << "bspline_4d test:\n"; cout << "Calculated:\n"; cout << value << '\t' << d1 << '\t' << d2 << '\t' << d3 << '\t' << d4 << '\n'; cout << "Expected:\n"; cout << x1*x1*x2*x3*x4 << '\t' << 2*x1*x2*x3*x4 << '\t' << x1*x1*x3*x4 << '\t' << x1*x1*x2*x4 << '\t' << x1*x1*x2*x3 << '\n'; cout << "Time: " << end - start << " sec" << '\n'; cout << "\n\n"; delete[] data4; /* test bspline_5d for data generated from function x1^2*x2*x3*x4*x5 */ int num_x5 = 24+1; double min_x5 = -0.01, max_x5 = 0.01; double width_x5 = (max_x5-min_x5) / (num_x5-1); double x5 = 0.007; double d5 = 0.0; double *data5 = new double[num_x1*num_x2*num_x3*num_x4*num_x5]; for(int i = 0; i < num_x1; i++) for(int j = 0; j < num_x2; j++) for(int k = 0; k < num_x3; k++) for(int m = 0; m < num_x4; m++) for(int n = 0; n < num_x5; n++) data5[i*num_x2*num_x3*num_x4*num_x5+j*num_x3*num_x4*num_x5+k*num_x4*num_x5+m*num_x5+n] = (min_x1+width_x1*i) * (min_x1+width_x1*i) * (min_x2+width_x2*j) * (min_x3+width_x3*k) * (min_x4+width_x4*m) * (min_x5+width_x5*n); start = seconds(); bspline_5d(data5, min_x1, max_x1, num_x1, x1, min_x2, max_x2, num_x2, x2, min_x3, max_x3, num_x3, x3, min_x4, max_x4, num_x4, x4, min_x5, max_x5, num_x5, x5, order, value, d1, d2, d3, d4, d5, true); end = seconds(); cout << std::fixed; cout << "bspline_5d test:\n"; cout << "Calculated:\n"; cout << value << '\t' << d1 << '\t' << d2 << '\t' << d3 << '\t' << d4 << '\t' << d5 << '\n'; cout << "Expected:\n"; cout << x1*x1*x2*x3*x4*x5 << '\t' << 2*x1*x2*x3*x4*x5 << '\t' << x1*x1*x3*x4*x5 << '\t' << x1*x1*x2*x4*x5 << '\t' << x1*x1*x2*x3*x5 << '\t' << x1*x1*x2*x3*x4 << '\n'; cout << "Time: " << end - start << " sec" << '\n'; cout << "\n\n"; delete[] data5; return 0; }
true
11628b947a6412950cc581239f5e6281c74efcea
C++
N-eeraj/code_website
/Code/cpp/circle.cpp
UTF-8
234
3.3125
3
[]
no_license
#include<iostream> using namespace std; int main() { float radius; cout << "Enter radius: "; cin >> radius; cout << "Area: " << 3.14 * radius * radius; cout << "\nCircumference: "<< 6.28 * radius; return 0; }
true
e4210cc670569638b6034f3b3892880f164e1a3d
C++
vukovic/so1
/src/HEAP.H
UTF-8
465
2.53125
3
[]
no_license
//File: Heap.h #ifndef _HEAP_H_ #define _HEAP_H_ class PCB; class Heap{ public: void insert(PCB* pcb, int key); void remove(Elem* e) private: void siftUp(Elem* e); void siftDown(Elem* e); class Elem{ int prio; PCB* pcb; Elem* childL, *childR, *parent; }; Elem* head; *tail; }; #endif /*-------------------------------- / 0\ <---HEAD / \ 0<----->0 / \ / 0<-->0<->0<-TAIL *///------------------------------
true
88d168931b4d6c0faf1d8a93e5d5a1950618f6db
C++
Kumarasamy/CloudPushServerDBUSAPI
/Cloud_Push_Curl.cpp
UTF-8
2,145
2.90625
3
[]
no_license
#pragma once #include<cstring> #include<curl/curl.h> #include<cstdlib> #include<iostream> #include<string> #define EMPTY "" using namespace std; class Cloud_Push_Curl { private: typedef struct s_curl { CURL *curl; CURLcode res; struct curl_slist *headers; string cloudURL; }s_curl; typedef struct userdetails { string username; string password; }userdetails; s_curl st_curl ; public: Cloud_Push_Curl() { } void setCurlURL(string url) { st_curl.cloudURL = url; } void Curl_Init(string url) { curl_global_init(CURL_GLOBAL_ALL); st_curl.curl = curl_easy_init(); st_curl.cloudURL = url; st_curl.headers = NULL; if(st_curl.curl && st_curl.cloudURL != EMPTY) { curl_easy_setopt(st_curl.curl, CURLOPT_URL,st_curl.cloudURL.c_str()); } } void SetHeader() { st_curl.headers = curl_slist_append(st_curl.headers, "Expect:"); st_curl.headers = curl_slist_append(st_curl.headers, "Content-Type: application/json"); curl_easy_setopt(st_curl.curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_easy_setopt(st_curl.curl, CURLOPT_HTTPHEADER, st_curl.headers); curl_easy_setopt(st_curl.curl, CURLOPT_POSTFIELDSIZE, -1L); } void SetUserUserName(string username,string password) { curl_easy_setopt(st_curl.curl, CURLOPT_USERNAME,username.c_str()); curl_easy_setopt(st_curl.curl, CURLOPT_PASSWORD,password.c_str()); } void SetCurlData(string jsonvalue ) { curl_easy_setopt(st_curl.curl, CURLOPT_POSTFIELDS, jsonvalue); st_curl.res = curl_easy_perform(st_curl.curl); if(st_curl.res != CURLE_OK) { std::cout<<"curl_easy_perform() failed: \n", std::cout<<curl_easy_strerror(st_curl.res); /* always cleanup */ curl_easy_cleanup(st_curl.curl); curl_slist_free_all(st_curl.headers); } curl_global_cleanup(); } }; int main() { Cloud_Push_Curl obj; obj.Curl_Init("http://localhost:5555"); obj.SetHeader(); string jsonvalue = "{ username : kumarasamy}"; obj.SetCurlData(jsonvalue); }
true
2cbb604a2aa677327966e9475f2a1aee334af465
C++
M4573R/UVa-Online-Judge-1
/11747/11747.cpp
UTF-8
2,022
2.703125
3
[]
no_license
//============================================================== // Coded by: Huynh Nhat Minh // Problem Number: 11747 - Heavy Cycle Edges //============================================================== #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <string> #include <cctype> #include <deque> #include <stack> #include <queue> #include <list> #include <vector> #include <map> #include <sstream> #include <cmath> #include <bitset> #include <utility> #include <set> #define INF 99999999 using namespace std; typedef struct { int u,v; long long c; }edge; edge data[25005]; long long check[1005][1005]; long long res[1005]; int lab[1005]; int n,m; int getRoot(int u) { if(lab[u]==u) return u; return lab[u]=getRoot(lab[u]); } int unionset(int a,int b) { return lab[a]=b; } bool cmp(edge a,edge b) { return a.c<b.c; } int main() { //freopen("11747.INP","r",stdin); //freopen("11747.OUT","w",stdout); while(scanf(" %d %d ",&n,&m) && n) { for(int i=0;i<m;i++) scanf(" %d %d %d ",&data[i].u,&data[i].v,&data[i].c); sort(data,data+m,cmp); for(int i=0;i<n;i++) { lab[i]=i; for(int j=0;j<n;j++) check[i][j]=INF; } int cnt=0; for(int i=0;i<m;i++) { int u=data[i].u; int v=data[i].v; long long c=data[i].c; int r1=getRoot(lab[u]); int r2=getRoot(lab[v]); //check[u][v]=check[v][u]=c; if(r1!=r2) { check[u][v]=check[v][u]=INF; unionset(r1,r2); } else res[cnt++]=c; } sort(res,res+cnt); bool lock=false; for(int i=0;i<cnt;i++) { if(lock) printf(" "); printf("%d",res[i]); lock=true; } if(!lock) printf("forest"); printf("\n"); } return 0; }
true
12d3073e7f0f1301de7a640951707de44e1a5c8e
C++
gonglixue/Mandala-Painting-System
/hybridimage.cpp
UTF-8
5,875
2.796875
3
[]
no_license
#include "hybridimage.h" HybridImage::HybridImage() { } QImage HybridImage::Mat2QImage(const Mat &mat) { // 8-bits unsigned, NO. OF CHANNELS = 1 if(mat.type() == CV_8UC1) { QImage image(mat.cols, mat.rows, QImage::Format_Indexed8); // Set the color table (used to translate colour indexes to qRgb values) image.setColorCount(256); for(int i = 0; i < 256; i++) { image.setColor(i, qRgb(i, i, i)); } // Copy input Mat uchar *pSrc = mat.data; for(int row = 0; row < mat.rows; row ++) { uchar *pDest = image.scanLine(row); memcpy(pDest, pSrc, mat.cols); pSrc += mat.step; } return image; } // 8-bits unsigned, NO. OF CHANNELS = 3 else if(mat.type() == CV_8UC3) { // Copy input Mat const uchar *pSrc = (const uchar*)mat.data; // Create QImage with same dimensions as input Mat QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_RGB888); return image.rgbSwapped(); } else if(mat.type() == CV_8UC4) { qDebug() << "CV_8UC4"; // Copy input Mat const uchar *pSrc = (const uchar*)mat.data; // Create QImage with same dimensions as input Mat QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_ARGB32); return image.copy(); } else { qDebug() << "ERROR: Mat could not be converted to QImage."; return QImage(); } } Mat HybridImage::QImage2Mat(QImage image) { cv::Mat mat; qDebug() << image.format(); switch(image.format()) { case QImage::Format_ARGB32: case QImage::Format_RGB32: case QImage::Format_ARGB32_Premultiplied: mat = cv::Mat(image.height(), image.width(), CV_8UC4, (void*)image.constBits(), image.bytesPerLine()); break; case QImage::Format_RGB888: mat = cv::Mat(image.height(), image.width(), CV_8UC3, (void*)image.constBits(), image.bytesPerLine()); cv::cvtColor(mat, mat, CV_BGR2RGB); break; case QImage::Format_Indexed8: mat = cv::Mat(image.height(), image.width(), CV_8UC1, (void*)image.constBits(), image.bytesPerLine()); break; } return mat; } HybridImage::HybridImage(QImage src1, QImage src2) { high_pass_source = QImage2Mat(src1); low_pass_source = QImage2Mat(src2); high_pass_kSize = 15; low_pass_kSize = 7; high_pass_sigma = 1.0f; low_pass_sigma = 30.0f; } HybridImage::HybridImage(Mat src1, Mat src2) { resize(1300,700); high_pass_source = src1; low_pass_source = src2; high_pass_kSize = low_pass_kSize = 7; high_pass_sigma = low_pass_sigma = 0.8f; high_pass_kSize_slider = new QSlider(Qt::Horizontal); high_pass_kSize_slider->setMinimum(0); high_pass_kSize_slider->setMaximum(100); QObject::connect(high_pass_kSize_slider,&QSlider::valueChanged, this, &HybridImage::setHighPassKsize); low_pass_kSize_slider = new QSlider(Qt::Horizontal); low_pass_kSize_slider->setMinimum(0); low_pass_kSize_slider->setMaximum(100); QObject::connect(low_pass_kSize_slider, &QSlider::valueChanged, this, &HybridImage::setLowPassKsize); high_pass_sigma_slider = new QSlider(Qt::Horizontal); high_pass_sigma_slider->setMinimum(0); high_pass_sigma_slider->setMaximum(1000); QObject::connect(high_pass_kSize_slider, &QSlider::valueChanged, this, &HybridImage::setHighPassSigma); low_pass_sigma_slider = new QSlider(Qt::Horizontal); low_pass_sigma_slider->setMinimum(0); low_pass_sigma_slider->setMaximum(1000); QObject::connect(low_pass_sigma_slider, &QSlider::valueChanged, this, &HybridImage::setLowPassSigma); QVBoxLayout* ctrLayout = new QVBoxLayout(); ctrLayout->addWidget(high_pass_kSize_slider); ctrLayout->addWidget(low_pass_kSize_slider); ctrLayout->addWidget(high_pass_sigma_slider); ctrLayout->addWidget(low_pass_sigma_slider); QVBoxLayout* empty = new QVBoxLayout(); QHBoxLayout* mainLayout = new QHBoxLayout(); mainLayout->addLayout(empty); mainLayout->addLayout(ctrLayout); mainLayout->setStretchFactor(empty, 10); mainLayout->setStretchFactor(ctrLayout,3); this->setLayout(mainLayout); } QImage HybridImage::hybrid(Mat high_pass, Mat low_pass) { qDebug() << "hybrid()"; // low pass cv::GaussianBlur(low_pass, low_pass, cv::Size(low_pass_kSize, low_pass_kSize), low_pass_sigma); // high pass Mat subtractImg; Mat low2; cv::GaussianBlur(high_pass,low2,cv::Size(high_pass_kSize, high_pass_kSize), high_pass_sigma); cv::subtract(high_pass,low2, subtractImg); Mat addImg(subtractImg.rows, subtractImg.cols, subtractImg.type(), cv::Scalar(128,128,128)); subtractImg = subtractImg + addImg; imshow("subtract", subtractImg); addWeighted(low_pass, 0.5, subtractImg, 0.5, 0.0, blend); imshow("blend", blend); QImage result = Mat2QImage(blend); result.save("hybridimage.jpg"); return result; } void HybridImage::paintEvent(QPaintEvent *) { qDebug() << "hybridImage::paintEvent" ; QPainter painter(this); QImage BlendQimg = hybrid(high_pass_source, low_pass_source); painter.drawImage(0,0,BlendQimg); } void HybridImage::setHighPassKsize(int size) { high_pass_kSize = 2*size + 1; update(); } void HybridImage::setLowPassKsize(int size) { low_pass_kSize = 2*size + 1; update(); } void HybridImage::setHighPassSigma(int sigma) { high_pass_sigma = sigma / 100.0; update(); } void HybridImage::setLowPassSigma(int sigma) { low_pass_sigma = sigma / 100.0; update(); }
true
8adf610ee990e82108734dfaf76a6c4330ab05d3
C++
KnewHow/studyCPlusPlus
/chapter08IO/8.1.cc
UTF-8
297
2.671875
3
[]
no_license
#include<iostream> using std :: cout; using std :: cin; using std :: endl; using std :: istream; istream& same(istream& in) { char c; auto oldState = in.rdstate(); while(in >> c) { cout << c << endl; } in.setstate(oldState); return in; } int main (){ same(cin); return 0; }
true
a8d86ece55797f1aed8995f8a1005cdca7a30fbf
C++
windystrife/UnrealEngine_NVIDIAGameWorks
/Engine/Source/Editor/Persona/Private/EditorObjectsTracker.h
UTF-8
1,065
2.515625
3
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "UObject/GCObject.h" ////////////////////////////////////////////////////////////////////////// // FEditorObjectTracker class FEditorObjectTracker : public FGCObject { public: FEditorObjectTracker(bool bInAllowOnePerClass = true) : bAllowOnePerClass(bInAllowOnePerClass) {} // FGCObject interface void AddReferencedObjects( FReferenceCollector& Collector ) override; // End of FGCObject interface /** Returns an existing editor object for the specified class or creates one if none exist */ UObject* GetEditorObjectForClass( UClass* EdClass ); void SetAllowOnePerClass(bool bInAllowOnePerClass) { bAllowOnePerClass = bInAllowOnePerClass; } private: /** If true, it uses TMap, otherwise, it just uses TArray */ bool bAllowOnePerClass; /** Tracks editor objects created for details panel */ TMap< UClass*, UObject* > EditorObjMap; /** Tracks editor objects created for detail panel */ TArray<UObject*> EditorObjectArray; };
true
29e68df56664e88784b515b8fe3b759c6eda998f
C++
kmichaelfox/phase_01
/src/DynamicEvent.cpp
UTF-8
2,238
2.765625
3
[]
no_license
// // DynamicEvent.cpp // phase_01 // // Created by Kelly Fox on 5/7/16. // // #include "DynamicEvent.hpp" #include "ofMain.h" #include "ofxAnimatableFloat.h" using namespace std; DynamicEvent::DynamicEvent(Dynamic d, float offset) : type(STATIC) , dynamic(d) , offset(offset) { } DynamicEvent::DynamicEvent(float durSeconds, float offset) : type(DYNAMIC) , offset(offset) , duration(durSeconds) { } void DynamicEvent::tick(float timeElapsed) { if (offset > drawShiftX) { offset -= timeElapsed; if (offset < drawShiftX && type == DYNAMIC) { duration += offset; offset = drawShiftX; active = true; } } else { if (!active) { active = true; } duration -= timeElapsed; } } void DynamicEvent::toggleDynamicOff() { } float DynamicEvent::getOffset() { return offset; } Dynamic DynamicEvent::getDynamic() { return dynamic; } string DynamicEvent::getDynamicAsString() { switch (dynamic) { case niente: return "niente"; case ppp: return "ppp"; case pp: return "pp"; case p: return "p"; case mp: return "mp"; case mf: return "mf"; case f: return "f"; case ff: return "ff"; case fff: return "fff"; } } //DynamicCurve & DynamicEvent::getCurve() { // return & curve; //} bool DynamicEvent::isCompleted() { return (type == DYNAMIC) && (duration <= 0); } Dynamic DynamicEvent::getRandomDynamic() { switch ((int)ofRandom(7.9)+1) { case 0: return niente; case 1: return ppp; case 2: return pp; case 3: return p; case 4: return mp; case 5: return mf; case 6: return f; case 7: return ff; case 8: return fff; } }
true
bd5d7a7a3acec996f7d2eb9d8920e5b3d1c8e382
C++
BekzhanKassenov/olymp
/acm.kbtu.kz/Programming langs/93/93.cpp
UTF-8
316
2.53125
3
[]
no_license
#include <iostream> using namespace std; int main() { int n; cin >> n; int tmp1, tmp2, ans = -1,nmb = -1; for (int i = 0; i < n; i++) { cin >> tmp1 >> tmp2; if (tmp2 == 1 && tmp1 > ans) { ans = tmp1; nmb = i + 1; } } if (ans != -1) cout << nmb; else cout << -1; return 0; }
true
977f4edde2a5b2d3d0798ecff5031dc03a3067a9
C++
jacson-junior/openpnp-capture
/win/tests/main.cpp
UTF-8
14,035
2.578125
3
[ "MIT" ]
permissive
/* openpnp test application Niels Moseley */ #include <stdio.h> #include <conio.h> #include <windows.h> // for Sleep #include <chrono> #include "openpnp-capture.h" #include "../common/context.h" void myCustomLogFunction(uint32_t level, const char *string) { printf("== %s", string); } std::string FourCCToString(uint32_t fourcc) { std::string v; for(uint32_t i=0; i<4; i++) { v += static_cast<char>(fourcc & 0xFF); fourcc >>= 8; } return v; } bool writeBufferAsPPM(uint32_t frameNum, uint32_t width, uint32_t height, const uint8_t *bufferPtr, size_t bytes) { char fname[100]; sprintf(fname, "frame_%d.ppm",frameNum); FILE *fout = fopen(fname, "wb"); if (fout == 0) { fprintf(stderr, "Cannot open %s for writing\n", fname); return false; } fprintf(fout, "P6 %d %d 255\n", width, height); // PGM header fwrite(bufferPtr, 1, bytes, fout); fclose(fout); return true; } void showAutoProperty(CapContext ctx, int32_t streamID, uint32_t propertyID) { uint32_t bValue; if (Cap_getAutoProperty(ctx, streamID, propertyID, &bValue)==CAPRESULT_OK) { if (bValue) { printf("Auto\n"); } else { printf("Manual\n"); } } else { printf("Unsupported\n"); } } void showAutoProperties(CapContext ctx, int32_t streamID) { printf("White balance: "); showAutoProperty(ctx, streamID, CAPPROPID_WHITEBALANCE); printf("Exposure : "); showAutoProperty(ctx, streamID, CAPPROPID_EXPOSURE); printf("Focus : "); showAutoProperty(ctx, streamID, CAPPROPID_FOCUS); printf("Zoom : "); showAutoProperty(ctx, streamID, CAPPROPID_ZOOM); printf("Gain : "); showAutoProperty(ctx, streamID, CAPPROPID_GAIN); } void showProperty(CapContext ctx, int32_t streamID, uint32_t propertyID) { int32_t value; if (Cap_getProperty(ctx, streamID, propertyID, &value)==CAPRESULT_OK) { printf("%d\n", value); } else { printf("Unsupported\n"); } } void showProperties(CapContext ctx, int32_t streamID) { printf("White balance: "); showProperty(ctx, streamID, CAPPROPID_WHITEBALANCE); printf("Exposure : "); showProperty(ctx, streamID, CAPPROPID_EXPOSURE); printf("Focus : "); showProperty(ctx, streamID, CAPPROPID_FOCUS); printf("Zoom : "); showProperty(ctx, streamID, CAPPROPID_ZOOM); printf("Gain : "); showProperty(ctx, streamID, CAPPROPID_GAIN); printf("Brightness : "); showProperty(ctx, streamID, CAPPROPID_BRIGHTNESS); printf("Contrast : "); showProperty(ctx, streamID, CAPPROPID_CONTRAST); printf("Saturation : "); showProperty(ctx, streamID, CAPPROPID_SATURATION); printf("Gamma : "); showProperty(ctx, streamID, CAPPROPID_GAMMA); } void estimateFrameRate(CapContext ctx, int32_t streamID) { std::chrono::time_point<std::chrono::system_clock> tstart, tend; tstart = std::chrono::system_clock::now(); uint32_t fstart = Cap_getStreamFrameCount(ctx, streamID); Sleep(2000); // 2-second wait uint32_t fend = Cap_getStreamFrameCount(ctx, streamID); tend = std::chrono::system_clock::now(); std::chrono::duration<double> fsec = tend-tstart; uint32_t frames = fend - fstart; printf("Frames = %d\n", frames); std::chrono::milliseconds d = std::chrono::duration_cast<std::chrono::milliseconds>(fsec); printf("Measured fps=%5.2f\n", 1000.0f*frames/static_cast<float>(d.count())); } int main(int argc, char*argv[]) { uint32_t deviceFormatID = 0; uint32_t deviceID = 0; Cap_installCustomLogFunction(myCustomLogFunction); printf("==============================\n"); printf(" OpenPNP Capture Test Program\n"); printf(" %s\n", Cap_getLibraryVersion()); printf("==============================\n"); Cap_setLogLevel(8); if (argc == 1) { printf("Usage: openpnp-capture-test <camera ID> <frame format ID>\n"); printf("\n..continuing with default camera parameters.\n\n"); } if (argc >= 2) { deviceID = atoi(argv[1]); } if (argc >= 3) { deviceFormatID = atoi(argv[2]); } CapContext ctx = Cap_createContext(); uint32_t deviceCount = Cap_getDeviceCount(ctx); printf("Number of devices: %d\n", deviceCount); for(uint32_t i=0; i<deviceCount; i++) { printf("ID %d -> %s\n", i, Cap_getDeviceName(ctx,i)); printf("Unique: %s\n", Cap_getDeviceUniqueID(ctx,i)); // show all supported frame buffer formats int32_t nFormats = Cap_getNumFormats(ctx, i); printf(" Number of formats: %d\n", nFormats); std::string fourccString; for(int32_t j=0; j<nFormats; j++) { CapFormatInfo finfo; Cap_getFormatInfo(ctx, i, j, &finfo); fourccString = FourCCToString(finfo.fourcc); printf(" Format ID %d: %d x %d pixels FOURCC=%s\n", j, finfo.width, finfo.height, fourccString.c_str()); } } int32_t streamID = Cap_openStream(ctx, deviceID, deviceFormatID); printf("Stream ID = %d\n", streamID); if (Cap_isOpenStream(ctx, streamID) == 1) { printf("Stream is open\n"); } else { printf("Stream is closed (?)\n"); Cap_releaseContext(ctx); return 1; } printf("Camera set to:\n"); showProperties(ctx, streamID); showAutoProperties(ctx, streamID); printf("=== KEY MAPPINGS ===\n"); printf("Press q to exit.\n"); printf("Press + or - to change the exposure.\n"); printf("Press 1 or 2 to change to auto/manual exposure.\n"); printf("Press f or g to change the focus.\n"); printf("Press z or x to change the zoom.\n"); printf("Press a or s to change the gain.\n"); printf("Press [ or ] to change the white balance.\n"); printf("Press d to display the camera configuration.\n"); printf("Press p to estimate the actual frame rate.\n"); printf("Press w to write the current frame to a PPM file.\n"); // get current stream parameters CapFormatInfo finfo; Cap_getFormatInfo(ctx, deviceID, deviceFormatID, &finfo); //disable auto exposure, focus and white balance if (Cap_setAutoProperty(ctx, streamID, CAPPROPID_EXPOSURE, 0) != CAPRESULT_OK) { printf("Could not disable auto-exposure\n"); } if (Cap_setAutoProperty(ctx, streamID, CAPPROPID_FOCUS, 0) != CAPRESULT_OK) { printf("Could not disable auto-focus\n"); } if (Cap_setAutoProperty(ctx, streamID, CAPPROPID_WHITEBALANCE, 0) != CAPRESULT_OK) { printf("Could not disabe auto-whitebalance\n"); } if (Cap_setAutoProperty(ctx, streamID, CAPPROPID_GAIN, 0) != CAPRESULT_OK) { printf("Could not disable auto-gain\n"); } // set exposure in the middle of the range int32_t exposure = 0; int32_t exmax, exmin, edefault; if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_EXPOSURE, &exmin, &exmax, &edefault) == CAPRESULT_OK) { //exposure = (exmax + exmin) / 2; exposure = edefault; Cap_setProperty(ctx, streamID, CAPPROPID_EXPOSURE, exposure); printf("Set exposure to %d\n", exposure); printf("Default exposure is : %d\n", edefault); } else { printf("Could not get exposure limits.\n"); } // set focus in the middle of the range int32_t focus = 0; int32_t fomax, fomin, fodefault; if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_FOCUS, &fomin, &fomax, &fodefault) == CAPRESULT_OK) { focus = (fomax + fomin) / 2; Cap_setProperty(ctx, streamID, CAPPROPID_FOCUS, focus); printf("Set focus to %d\n", focus); printf("Default focus is : %d\n", fodefault); } else { printf("Could not get focus limits.\n"); } // set zoom in the middle of the range int32_t zoom = 0; int32_t zomax, zomin, zodefault; if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_ZOOM, &zomin, &zomax, &zodefault) == CAPRESULT_OK) { zoom = zomin; Cap_setProperty(ctx, streamID, CAPPROPID_ZOOM, zoom); printf("Set zoom to %d\n", zoom); printf("Default zoom is : %d\n", zodefault); } else { printf("Could not get zoom limits.\n"); } // set white balance in the middle of the range int32_t wbalance = 0; int32_t wbmax, wbmin, wbdefault; int32_t wbstep = 0; if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_WHITEBALANCE, &wbmin, &wbmax, &wbdefault) == CAPRESULT_OK) { wbalance = (wbmax+wbmin)/2; wbstep = (wbmax-wbmin) / 20; Cap_setProperty(ctx, streamID, CAPPROPID_WHITEBALANCE, wbalance); printf("Set white balance to %d\n", wbalance); printf("Default white balance is : %d\n", wbdefault); } else { printf("Could not get white balance limits.\n"); } // set gain in the middle of the range int32_t gain = 0; int32_t gmax, gmin, gdefault; int32_t gstep = 0; if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_GAIN, &gmin, &gmax, &gdefault) == CAPRESULT_OK) { gstep = (gmax-gmin) / 20; Cap_setProperty(ctx, streamID, CAPPROPID_GAIN, gain); printf("Set gain to %d (min=%d max=%d)\n", gain, gmin, gmax); printf("Default gain is : %d\n", gdefault); } else { printf("Could not get gain limits.\n"); } printf("Camera reconfigured to:\n"); showProperties(ctx, streamID); showAutoProperties(ctx, streamID); // try to create a message loop so the preview // window doesn't crash.. MSG msg; BOOL bRet; std::vector<uint8_t> m_buffer; m_buffer.resize(finfo.width*finfo.height*3); char c = 0; uint32_t frameWriteCounter=0; while((c != 'q') && (c != 'Q')) { if (PeekMessage(&msg, NULL, 0, 0, 0) != 0) { bRet = GetMessage(&msg, NULL, 0, 0); if (bRet > 0) // (bRet > 0 indicates a message that must be processed.) { TranslateMessage(&msg); DispatchMessage(&msg); } } if (_kbhit()) { c = _getch(); switch(c) { case '+': Cap_setProperty(ctx, streamID, CAPPROPID_EXPOSURE, ++exposure); printf("exposure = %d \r", exposure); break; case '-': Cap_setProperty(ctx, streamID, CAPPROPID_EXPOSURE, --exposure); printf("exposure = %d \r", exposure); break; case '0': exposure = (exmax + exmin) / 2; Cap_setProperty(ctx, streamID, CAPPROPID_EXPOSURE, exposure); printf("exposure = %d \r", exposure); break; case '1': Cap_setAutoProperty(ctx, streamID, CAPPROPID_EXPOSURE, 1); printf("exposure = auto \r"); break; case '2': Cap_setAutoProperty(ctx, streamID, CAPPROPID_EXPOSURE, 0); printf("exposure = manual \r"); break; case 'f': Cap_setProperty(ctx, streamID, CAPPROPID_FOCUS, ++focus); printf("focus = %d \r", focus); break; case 'g': Cap_setProperty(ctx, streamID, CAPPROPID_FOCUS, --focus); printf("focus = %d \r", focus); break; case 'z': Cap_setProperty(ctx, streamID, CAPPROPID_ZOOM, ++zoom); printf("zoom = %d \r", zoom); break; case 'x': Cap_setProperty(ctx, streamID, CAPPROPID_ZOOM, --zoom); printf("zoom = %d \r", zoom); break; case '[': wbalance -= wbstep; Cap_setProperty(ctx, streamID, CAPPROPID_WHITEBALANCE, wbalance); printf("wbal = %d \r", wbalance); break; case ']': wbalance += wbstep; Cap_setProperty(ctx, streamID, CAPPROPID_WHITEBALANCE, wbalance); printf("wbal = %d \r", wbalance); break; case 'a': gain -= gstep; Cap_setProperty(ctx, streamID, CAPPROPID_GAIN, gain); printf("gain = %d \r", gain); break; case 's': gain += gstep; Cap_setProperty(ctx, streamID, CAPPROPID_GAIN, gain); printf("gain = %d \r", gain); break; case 'p': printf("Estimating frame rate..\n"); estimateFrameRate(ctx, streamID); break; case 'd': printf("\nCamera configuration:\n"); showProperties(ctx, streamID); showAutoProperties(ctx, streamID); printf("\n"); break; case 'w': if (Cap_captureFrame(ctx, streamID, &m_buffer[0], m_buffer.size()) == CAPRESULT_OK) { if (writeBufferAsPPM(frameWriteCounter, finfo.width, finfo.height, &m_buffer[0], m_buffer.size())) { printf("Written frame to frame_%d.ppm\n", frameWriteCounter++); } } break; } } Sleep(10); } Cap_closeStream(ctx, streamID); CapResult result = Cap_releaseContext(ctx); return 0; }
true
ebe2629b7ff0849c13dedeaaa805775e57f80e29
C++
Rampo99/Gravitar
/src/Bunker.cpp
UTF-8
3,041
2.828125
3
[]
no_license
#include "Bunker.h" #include <cstdlib> #include <ctime> #include <iostream> #include <math.h> #define PI 3.141592653589793 double fRand(double fMin, double fMax) // restituisce un reale compreso tra fMin e fMax { double f = (double)rand() / RAND_MAX; return fMin + f * (fMax - fMin); } Bunker::Bunker() { health = 0; isdraw = false; ratio = 1.0 / fRand(0.8, 2.1); for_shooting = seconds(fRand(0, ratio)); rot = 0; type = 0; directions = new double[3]; bullets_speed = new double[3]; } void Bunker::settype(int a) { type = a; health = type; for (int i = 0; i < type; i++) { directions[i] = fRand(-(6.0 / 7 * PI), -(1.0 / 7 * PI)); bullets_speed[i] = fRand(500, 950); } } void Bunker::rotate(double x) { bunker.rotate(x); rot = x; } void Bunker::drawing() { if (type == 3) { bunker.setFillColor(sf::Color::Red); bunker.setOutlineColor(Color(100, 0, 0)); } else { bunker.setFillColor(sf::Color(200, 0, 200)); bunker.setOutlineColor(Color(100, 0, 100)); } bunker.setOutlineThickness(2.5); bunker.setPointCount(20); bunker.setOrigin(117.5, 156); bunker.setPoint(0, sf::Vector2f(100, 100)); bunker.setPoint(1, sf::Vector2f(100, 125)); bunker.setPoint(2, sf::Vector2f(105, 125)); bunker.setPoint(3, sf::Vector2f(105, 154)); bunker.setPoint(4, sf::Vector2f(130, 154)); bunker.setPoint(5, sf::Vector2f(130, 125)); bunker.setPoint(6, sf::Vector2f(135, 125)); bunker.setPoint(7, sf::Vector2f(135, 100)); bunker.setPoint(8, sf::Vector2f(130, 100)); bunker.setPoint(9, sf::Vector2f(130, 105)); bunker.setPoint(10, sf::Vector2f(125, 105)); bunker.setPoint(11, sf::Vector2f(125, 100)); bunker.setPoint(12, sf::Vector2f(120, 100)); bunker.setPoint(13, sf::Vector2f(120, 105)); bunker.setPoint(14, sf::Vector2f(115, 105)); bunker.setPoint(15, sf::Vector2f(115, 100)); bunker.setPoint(16, sf::Vector2f(110, 100)); bunker.setPoint(17, sf::Vector2f(110, 105)); bunker.setPoint(18, sf::Vector2f(105, 105)); bunker.setPoint(19, sf::Vector2f(105, 100)); isdraw = true; double x = bunker.getPosition().x, y = bunker.getPosition().y - 50; if (rot > 300) { x -= 22; y += 5; } else if (rot > 20) { x += 22; y += 5; } } void Bunker::position(int x, int y) { bunker.setPosition(x,y); } void Bunker::draw(sf::RenderWindow& window) { double x = bunker.getPosition().x, y = bunker.getPosition().y - 50; for_shooting += clock_canshoot.restart(); if (for_shooting.asSeconds() >= ratio) { for (int i = 0; i < type; i++) { Bullet *tmp = new Bullet(x, y, directions[i], bullets_speed[i], type); bullets.push_front(*tmp); for_shooting = clock_canshoot.restart(); } } list<Bullet>::iterator it; for(it = bullets.begin(); it != bullets.end(); ) { it->move(); if (it->isAlive(window)) { it->draw(window); it++; } else it = bullets.erase(it); } if (isAlive()) window.draw(bunker); else ratio = 999999999999; } bool Bunker::isAlive() { return health > 0; } sf::ConvexShape Bunker::getShape() { return bunker; } void Bunker::hit() { health--; }
true
107479aeae33dd229c1b46e96c2103b94e5dbed1
C++
mbartling/uTensor-image-tools
/main.cpp
UTF-8
3,766
3.15625
3
[]
no_license
/** * Super hacky host side example program showcasing how to slice up an image in a buffer * and resize the results using uTensor. * */ #include <iostream> #include <stdexcept> #include <string> #include "Interpolation.hpp" #include "SlicedImage.hpp" #include "bitmap_image.hpp" #include "uTensor.h" using std::cout; using std::endl; using namespace uTensor; int str2int(const char* str); const int target_image_resize = 32; /* * uTensor module instantiation */ localCircularArenaAllocator<2048> meta_allocator; // 4MB should be plenty localCircularArenaAllocator<4000000, uint32_t> ram_allocator; SimpleErrorHandler mErrHandler(10); BilinearInterpolator<uint8_t> bilinear; int main(int argc, char* argv[]) { if (argc != 4) { cout << "Unexpected number of command line args" << endl << "Please provide image_path num_row_slices num_col_slices, in that " "order" << endl; } bitmap_image image(argv[1]); image.save_image("dummy.bmp"); if (!image) { printf("Error - Failed to open: %s\n", argv[1]); return 1; } unsigned int total_number_of_pixels = 0; const uint16_t height = image.height(); const uint16_t width = image.width(); const unsigned int num_row_slices = str2int(argv[2]); const unsigned int num_col_slices = str2int(argv[3]); cout << "Image Height: " << height << endl; cout << "Image Width: " << width << endl; cout << "Num Rows: " << num_row_slices << endl; cout << "Num Cols: " << num_col_slices << endl; uint8_t* image_buffer = image.data(); // Stored internally as a vector // From here on, things will look closer to what it's like on an embedded // system Context::get_default_context()->set_metadata_allocator(&meta_allocator); Context::get_default_context()->set_ram_data_allocator(&ram_allocator); Context::get_default_context()->set_ErrorHandler(&mErrHandler); // Keep the buffer around as we may want tu use it for something Tensor image_t = new BufferTensor({1, height, width, 3}, u8, image_buffer); SlicedImage<uint8_t> slicedImage(image_t, num_row_slices, num_col_slices); // Output the sliced image bitmap_image oimage(slicedImage.sliced_width, slicedImage.sliced_height); slicedImage.set_current_slice(0, 3); for (int y = 0; y < slicedImage.sliced_height; y++) { for (int x = 0; x < slicedImage.sliced_width; x++) { // uint8_t r,g,b; const uint8_t r = slicedImage(y, x, 2); const uint8_t g = slicedImage(y, x, 1); const uint8_t b = slicedImage(y, x, 0); oimage.set_pixel(x, y, r, g, b); } } cout << "Saving image" << endl; oimage.save_image("output.bmp"); // Bilinear interpolation slicedImage.set_current_slice(0, 3); Tensor scaledImage = bilinear.interpolate(slicedImage, target_image_resize, true); bitmap_image simage(target_image_resize, target_image_resize); for (int y = 0; y < scaledImage->get_shape()[1]; y++) { for (int x = 0; x < scaledImage->get_shape()[2]; x++) { // uint8_t r,g,b; const uint8_t r = scaledImage(0, y, x, 2); const uint8_t g = scaledImage(0, y, x, 1); const uint8_t b = scaledImage(0, y, x, 0); simage.set_pixel(x, y, r, g, b); } } cout << "Saving image" << endl; simage.save_image("scaled_output.bmp"); return 0; } // Extra stuff int str2int(const char* str) { std::string arg = str; int x; try { std::size_t pos; x = std::stoi(arg, &pos); if (pos < arg.size()) { std::cerr << "Trailing characters after number: " << arg << '\n'; } } catch (std::invalid_argument const& ex) { std::cerr << "Invalid number: " << arg << '\n'; } catch (std::out_of_range const& ex) { std::cerr << "Number out of range: " << arg << '\n'; } return x; }
true
49b8bb59b133e650ad16127fe90a5a3d5214e0b9
C++
cleonro/ThreadBenchmark
/Cpp/resource.cpp
UTF-8
578
3.140625
3
[]
no_license
#include "resource.h" #include <cmath> //#include <random> #include <algorithm> Resource::Resource(size_t size) : m_size(size) { m_v.resize(m_size); } void Resource::generate() { // std::random_device rnd; // std::default_random_engine rne(rnd()); // std::uniform_real_distribution und(0.0, 1.0); std::for_each(m_v.begin(), m_v.end(), [/*&rne, &und*/](double &x){ x = 0.01;//und(rne); }); } size_t Resource::size() const { return m_size; } double Resource::value(size_t index) const { return (index < m_size ? m_v[index] : 0.0); }
true
1243789b846c207b7758558c1a31b7ac68f20ef8
C++
smallHW89/comm_util
/lock_free_list/1p1c_ring_buffer/fifo.h
UTF-8
1,488
3.1875
3
[]
no_license
/******************************************************** * Copyright (C) 2016 All rights reserved. * * Filename:fifo.h * Author :huangwei 497225735@qq.com * Date :2016-12-10 * Describe: 环形队列,定长元素 * * |----------------------------| * in out * out in * in out * out in ********************************************************/ #ifndef _FIFO_H #define _FIFO_H #include<stdint.h> template <typename Ele> class ring_queue { private: uint32_t _size; uint32_t _in; uint32_t _out; Ele *_buffer; public: ring_queue(uint32_t size) { _buffer = new Ele[size]; _size = size; _in = 0; _out = 0; } ~ring_queue() { if(_buffer != NULL ) delete []_buffer; } bool pop(Ele * e) { if(_in == _out ) { //queue is Empty return false; } *e = _buffer[_out]; if(_out+1 == _size) _out = 0; else _out++; return true; } bool push(const Ele &e) { if(_in < _out && _in+1 == _out) //full return false; if( _in > _out && _in -_out == _size-1) //full return false; _buffer[_in] = e; if( _in +1 == _size) _in = 0; else _in ++; return true; } }; #endif //FIFO_H
true
246cafe53abf3493dc9f90017ce9c6e4bbf2b336
C++
reedboat/applib
/tmp/src/Timer.cpp
UTF-8
271
2.625
3
[]
no_license
/* * */ #include"../include/Timer.h" Timer::Timer() { } Timer::~Timer() { } clock_t Timer::GetCurrentTime() { return clock(); } float Timer::TimeDuration(clock_t & begin,clock_t & end) { return (float)((float)(end-begin)/(float)CLOCKS_PER_SEC); }
true
16aeb355520f45eebf8a3e715c8e404093a21485
C++
JJungwoo/algorithm
/baekjoon/code_plus/basic1/2004.cc
UTF-8
699
3.34375
3
[]
no_license
/* [BOJ] 2004. 조합 0의 개수 nCm = n! / m!*(n-m)! 왜 2와 5의 배수 개수를 구한다음 최소 값을 해줘야 할까?.. 당연히 5의 배수 값이 훨씬 적지 않을까? 이에 대한 반론 예시가 필요하다.. ref: https://jaimemin.tistory.com/908 */ #include <cstdio> #include <algorithm> using namespace std; long long zero_cal(long long num, long long div) { long long sum = 0; while(num) { num /= div; sum += num; } return sum; } int main() { long long n,m; scanf("%lld %lld", &n, &m); printf("%lld\n", min(zero_cal(n,2) - zero_cal(m,2) - zero_cal(n-m,2), zero_cal(n,5) - zero_cal(m,5) - zero_cal(n-m,5))); return 0; }
true
909599256688b6ee4bb20cc9ae109810a7aafb6a
C++
timothybaker/mites_and_stars_simulation
/src/mite.cpp
UTF-8
6,045
3.28125
3
[]
no_license
// // Author: Timothy Baker // cs361: Assignment 2 //"A story of Mites and Stars" // //mite.cpp //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// #include "mite.h" #include <iostream> /////////////////////////////////////////////////////////////////// // create random statistics factors for a new mite /////////////////////////////////////////////////////////////////// normal_distribution<double> mite_speed_factor(8,2); normal_distribution<double> mite_tough_factor(1.0,0.2); normal_distribution<double> mite_evasive_factor(1.0, 0.2); /////////////////////////////////////////////////////////////////// // initializing contructor, used in main for initial build of mites /////////////////////////////////////////////////////////////////// // mite::mite(default_random_engine* random_engine) { at_node=false; companion=false; hatched=true; x=y=z=0; last_node_id=current_node_id=-2; clock=0; speed=mite_speed_factor(*random_engine); while(speed<=0) { speed=mite_speed_factor(*random_engine); } evasive=mite_evasive_factor(*random_engine); tough=mite_tough_factor(*random_engine); } /////////////////////////////////////////////////////////////////// // egg-hatched mite constructor, used by a hatching egg (aw so cute) /////////////////////////////////////////////////////////////////// // egg::egg(double i, double j, double k, int id, double s, double e, double t) { companion=false; hatched=false; turns_to_hatch=0; last_node_id=0; clock=0; at_node=true; current_node_id=id; x=i; y=j; z=k; speed=s; evasive=e; tough=t; } /////////////////////////////////////////////////////////////////// // equality operator for a mite /////////////////////////////////////////////////////////////////// // bool mite::operator==(const mite& other)const { if(this->speed==other.speed) { if(this->current_node_id==other.current_node_id) { if(this->x==other.x) { if(this->y==other.y) { if(this->z==other.z) { return true; } } } } } return false; } /////////////////////////////////////////////////////////////////// // inequality operator for a mite /////////////////////////////////////////////////////////////////// // bool mite::operator!=(const mite& other)const { return !(*this==other); } /////////////////////////////////////////////////////////////////// // less than operator for mite /////////////////////////////////////////////////////////////////// // bool mite::operator<(const mite& other)const { if(((this->speed)*(this->evasive)*(this->tough))<((other.speed)*(other.evasive)*(other.tough))) { return true; } return false; } /////////////////////////////////////////////////////////////////// // mite procreation definition /////////////////////////////////////////////////////////////////// // void mite::mite_procreation(list<mite>& mites, list<mite*> planet_mites, mite* mite_mate, list<mite*> planet_eggs) { int t=(this->tough + mite_mate->get_tough())/2; int s=(this->speed + mite_mate->get_speed())/2; int e=(this->evasive + mite_mate->get_evasive())/2; mite* mite_egg_ptr = new egg(x, y, z, current_node_id,s, e, t); mites.push_back(*mite_egg_ptr); planet_eggs.push_back(&(mites.back())); delete mite_egg_ptr; } /////////////////////////////////////////////////////////////////// // move definition /////////////////////////////////////////////////////////////////// // void mite::move() { x=a + x; y=b + y; z=c + z; } /////////////////////////////////////////////////////////////////// // time incrementation for mites /////////////////////////////////////////////////////////////////// // void mite::slipping_time(double i, double j, double k, int id, bool& new_node, int& link_node_id, int& new_node_id) { if(((x>=nx-10 && x <=nx+10) && (y>=ny-10 && y <=ny+10) && (z>=nz-10 && z <=nz+10)) || (clock==0)) { if(clock!=0) { link_node_id=last_node_id; new_node_id=current_node_id; x=nx;y=ny;z=nz; //gravity got them, like falling in a well } if(1) { set_next_node_xyz(i, j, k); distance=sqrt(pow((x-nx),2.0)+pow((y-ny),2.0)+ pow((z-nz),2.0)); pace=distance/speed; a=(nx-x)/pace; b=(ny-y)/pace; c=(nz-z)/pace; last_node_id=current_node_id; if(clock!=0) { current_node_id=next_node_id; } next_node_id=id; new_node=true; } } else { move(); } clock++; } void egg::slipping_time(double i, double j, double k, int id, bool& new_node, int& link_node_id, int& new_node_id) { if(hatched==false) { minus_turns_to_hatch(); } if(hatched==true) { if(((x>=nx-10 && x <=nx+10) && (y>=ny-10 && y <=ny+10) && (z>=nz-10 && z <=nz+10)) || (clock==0)) { if(clock!=0) { link_node_id=last_node_id; new_node_id=current_node_id; x=nx;y=ny;z=nz; //gravity got them, like falling in a well } if(1) { set_next_node_xyz(i, j, k); distance=sqrt(pow((x-nx),2.0)+pow((y-ny),2.0)+ pow((z-nz),2.0)); pace=distance/speed; a=(nx-x)/pace; b=(ny-y)/pace; c=(nz-z)/pace; last_node_id=current_node_id; if(clock!=0) { current_node_id=next_node_id; } next_node_id=id; new_node=true; } } else { move(); } clock++; } }
true
ef29af195cf0f0a85c94745a934af7f0e716ec4c
C++
singhdotabhinav/Arrays
/05_Maximum_Sum_Increasing_Subsequence.cpp
UTF-8
379
2.578125
3
[]
no_license
int msis(int arr[], int n){ int msi[n]; for(int i=0;i<n;i++) msi[i]=arr[i]; for(int i=1;i<n;i++){ for(int j=0;j<i;j++){ if(arr[i]>arr[j]&&msi[i]<arr[i]+msi[j]) msi[i]=arr[i]+ msi[j]; } } int best=0; for(int i=0;i<n;i++){ if(best<msi[i]) best=msi[i]; } return best; }
true
f2fa19cd64443658665c50f949cef8e9f9abc10b
C++
a12fghoen/pcl_cuda
/pcl/cuda/cuda_common.h
UTF-8
1,367
2.53125
3
[]
no_license
#pragma once #include "../pcl/pcl_base.h" #include <thrust/host_vector.h> #include <thrust/device_vector.h> #include <vector_functions.hpp> namespace pclcuda { template<typename T> using PointCloudHost = thrust::host_vector<T>; template<typename T> using PlaneParamHost = thrust::host_vector<T>; template<typename T> using PointCloudDevice = thrust::device_vector<T>; template<typename T> using PlaneParamDevice = thrust::device_vector<T>; } namespace pclcuda { /* Copies the content of the point cloud into the host memory thrust vector. [in] inCloud - Pointer to the cloud [out] outCloudHost - Pointer to the cloud in the thrust host vector [return] boolean - true is process succeeded/ else false */ template <typename T1, typename T2> bool copyPtCldToHostMem(pcl::PointCloud<T1>& inCloud, pclcuda::PointCloudHost<T2>& outCloudHost); /* Copies the content of the mesh into the host memory thrust vector. [in] inCloud - Pointer to the cloud [out] outCloudHost - Pointer to the cloud in the thrust host vector [return] boolean - true is process succeeded/ else false */ template <typename T1, typename T2> bool copyMeshToHostMem(pcl::PolygonMesh<T1>& inMesh, pclcuda::PointCloudHost<T2>& vertices_1, pclcuda::PointCloudHost<T2>& vertices_2, pclcuda::PointCloudHost<T2>& vertices_3, pclcuda::PlaneParamHost<T2>& planeParam); }
true
a7485724d7442886d6cdb2f0069d84ecbcf48044
C++
CSIT-GUIDE/THIRD_SEMESTER
/OOP/C++ Lab Works/C++ 5/AMBUIGUITY_MULTIPLE.cpp
UTF-8
1,207
3.203125
3
[]
no_license
/* THIS C++ PROGRAM ILLUSTRATES THE CONCEPT OF AMBUIGITY * ASSOCIATED WITH THE MULTIPLE INHERITANCE */ /* NAME : SAGAR GIRI, ROLL : 205, SECTION : A */ #include <iostream> using namespace std; class Employee //define base class Employee { protected: char name[20]; public: void getName() { cout<<endl<<"Enter Name: "; cin>>name; } void showData() { cout<<endl<<"Name: "<<name; } }; class Training //define base class Training { protected: char type[20]; public: void getData() { cout<<"Enter Training type: "; cin>>type; } void showData() { cout<<endl<<"Training Completed: "<<type; } }; //derived class Manager from base class Employee and Training class Manager: public Employee, public Training { public: void getData() { Employee::getName(); Training::getData(); } }; int main() { Manager m1; //define object m1 of Manager class cout<<"Enter Data for Manager: "; m1.getData(); cout<<endl<<"Detials of Manager: "; /* m1.showData(); */ //compiler generates error due to ambiguity m1.Employee::showData(); //call showData() methof from Employee m1.Training::showData(); //call showData() methof from Training return 0; }
true
7ffac24fbf25e67f3dab2a5e5aff68ad22aaa56d
C++
zhanglei/arch
/src/concurrent/thread_rwlock.cpp
UTF-8
2,175
2.78125
3
[]
no_license
/* * thread_rwlock.cpp * * Created on: 2011-4-4 * Author: wqy */ #include "concurrent/thread_rwlock.hpp" #include "exception/api_exception.hpp" #include "util/time_helper.hpp" using namespace arch::concurrent; using namespace arch::exception; using namespace arch::util; ThreadReadWriteLock::ThreadReadWriteLock() { if (pthread_rwlock_init(&m_rwlock, NULL) < 0) { throw APIException("Failed to init thread read_write lock."); } } bool ThreadReadWriteLock::Lock(LockMode mode, uint64 timeout) { switch (mode) { case READ_LOCK: { if (0 == timeout) { return 0 == pthread_rwlock_rdlock(&m_rwlock); } else { struct timespec next; get_current_epoch_time(next); uint64 inc = nanostime(timeout, MILLIS); add_nanos(next, inc); return 0 == pthread_rwlock_timedrdlock(&m_rwlock, &next); } } case WRITE_LOCK: { if (0 == timeout) { return 0 == pthread_rwlock_wrlock(&m_rwlock); } else { struct timespec next; get_current_epoch_time(next); uint64 inc = nanostime(timeout, MILLIS); add_nanos(next, inc); return 0 == pthread_rwlock_timedwrlock(&m_rwlock, &next); } } default: { return false; } } } bool ThreadReadWriteLock::Unlock() { return 0 == pthread_rwlock_unlock(&m_rwlock); } bool ThreadReadWriteLock::TryLock(LockMode mode) { switch (mode) { case READ_LOCK: { return 0 == pthread_rwlock_tryrdlock(&m_rwlock); } case WRITE_LOCK: { return 0 == pthread_rwlock_trywrlock(&m_rwlock); } default: { return false; } } } ThreadReadWriteLock::~ThreadReadWriteLock() { pthread_rwlock_destroy(&m_rwlock); }
true
397cb4f0747010b7b7467e4147c58a7469f1f937
C++
joaopfg/Simple-editor-and-viewer-for-3D-shapes-
/TD1.3/main.cpp
UTF-8
4,298
2.765625
3
[]
no_license
#include <igl/opengl/glfw/Viewer.h> #include <igl/readOFF.h> #include <iostream> #include <ostream> using namespace Eigen; MatrixXd V1; // vertex coordinates of the input mesh MatrixXi F1; // incidence relations between faces and edges RowVector3d rotation_axis(1., 0., 0.); // rotation axis /** * Print the components of a quaternion */ void print_quaternion(Quaterniond q) { std::cout << "(" << q.w() << ", " << q.x() << ", "<< q.y() << ", "<< q.z() << "\n"; } /** * Apply to the input points (stored in a matrix V) a rotation of angle 'theta' around a given direction defined by vector 'u' * * @param V a matrix storing the input points ('n' rows, '3' columns) * @param u a vector corresponding to the rotation axis * @param theta rotation angle */ void transform(MatrixXd &V, RowVector3d u, double theta) { // To be COMPLETED Quaterniond rot = Quaterniond(cos(theta/2.0), u(0,0)*sin(theta/2.0), u(0,1)*sin(theta/2.0), u(0,2)*sin(theta/2.0)); Quaterniond rot_conj = Quaterniond(cos(theta/2.0), -u(0,0)*sin(theta/2.0), -u(0,1)*sin(theta/2.0), -u(0,2)*sin(theta/2.0)); int n = V.rows(); for(int i=0;i<n;i++){ Quaterniond q = Quaterniond(0.0, V(i,0), V(i,1), V(i,2)); Quaterniond rotated = rot*q; rotated = rotated*rot_conj; V(i,0) = rotated.x(); V(i,1) = rotated.y(); V(i,2) = rotated.z(); } } // This function is called every time a keyboard button is pressed bool key_down(igl::opengl::glfw::Viewer &viewer, unsigned char key, int modifier) { std::cout << "Key: " << key << " " << (unsigned int)key << std::endl; if (key == 'Q') { std::cout << "rotating with quaternions" << std::endl; MatrixXd &V = V1; MatrixXi &F = F1; RowVector3d u(1., 0., 0.); // rotation axis double angle=0.1; transform(V, u, angle); // apply the rotation around vector 'u' to all points in V viewer.data(0).clear(); viewer.data(0).set_mesh(V, F); //viewer.core(mesh_selection).align_camera_center(V, F); } if (key == 'R') // generate a random direction { rotation_axis(0)=random(); // x component of the rotation axis rotation_axis(1)=random(); // y component rotation_axis(2)=random(); // z component } return false; } // This function is called every time a keyboard button is pressed bool pre_draw(igl::opengl::glfw::Viewer &viewer) { //std::cout << "rotating with quaternions" << std::endl; MatrixXd &V = V1; MatrixXi &F = F1; transform(V, rotation_axis, 0.05); // rotate the object viewer.data(0).clear(); viewer.data(0).set_mesh(V, F); return false; } void draw_bounding_box(igl::opengl::glfw::Viewer &viewer, const MatrixXd &V) { // compute the corners of the bounding box Vector3d m = V.colwise().minCoeff(); Vector3d M = V.colwise().maxCoeff(); MatrixXd V_box(8,3); // Corners of the bounding box MatrixXi E_box(12,2); // edges of the bounding box V_box << m(0), m(1), m(2), M(0), m(1), m(2), M(0), M(1), m(2), m(0), M(1), m(2), m(0), m(1), M(2), M(0), m(1), M(2), M(0), M(1), M(2), m(0), M(1), M(2); E_box << 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 7 ,3; viewer.append_mesh(); viewer.data(1).add_points(V_box,Eigen::RowVector3d(1,0,0)); for (unsigned i=0;i<E_box.rows(); ++i) // Plot the edges of the bounding box viewer.data().add_edges ( V_box.row(E_box(i,0)), V_box.row(E_box(i,1)), Eigen::RowVector3d(1,0,0) ); } // ------------ main program ---------------- int main(int argc, char *argv[]) { igl::readOFF("../data/star.off", V1, F1); // Load an input mesh in OFF format // input mesh std::cout << "Vertices: " << V1.rows() << std::endl; std::cout << "Faces: " << F1.rows() << std::endl; igl::opengl::glfw::Viewer viewer; viewer.callback_key_down = &key_down; viewer.callback_pre_draw = &pre_draw; viewer.data().set_mesh(V1, F1); viewer.core().is_animating = true; // animation is active draw_bounding_box(viewer, V1); viewer.launch(); }
true
02528e78a9dd7c89b80b6e3fbd85818ed9dfceea
C++
rawatamit/lox
/cpplox/include/ASTPrinter.h
UTF-8
3,997
3.125
3
[]
no_license
#include "Expr.h" #include "Stmt.h" #include "Token.h" #include <any> #include <iostream> #include <memory> #include <string> #include <vector> namespace lox { class ASTPrinter : public ExprVisitor, StmtVisitor { public: std::any print(Expr *expr) { return expr->accept(this); } std::any print(Stmt *stmt) { return stmt->accept(this); } std::any print(std::vector<Expr *> exprs) { for (auto expr : exprs) { expr->accept(this); std::cout << ' '; } return nullptr; } std::any print(std::vector<Stmt *> stmts) { for (auto stmt : stmts) { stmt->accept(this); std::cout << '\n'; } return nullptr; } std::any visitBlock(Block *stmt) override { std::cout << "(block\n"; print(stmt->stmts); std::cout << ")"; return nullptr; // return parenthesizeS("block", stmt->stmts); } std::any visitExpression(Expression *stmt) override { return parenthesizeE("", {stmt->expr}); } std::any visitFunction(Function *stmt) override { std::string fn; fn.append("fn "); fn.append(stmt->name.lexeme); fn.append("("); for (auto p : stmt->params) { fn.append(p.lexeme); fn.append(" "); } fn.append(")"); return parenthesizeS(fn, {stmt->body}); } std::any visitIf(If *stmt) override { std::cout << "(if "; print(stmt->condition); return parenthesizeS("", {stmt->thenBranch, stmt->elseBranch}); } std::any visitPrint(Print *stmt) override { return parenthesizeE("print", {stmt->expr}); } std::any visitReturn(Return *Stmt) override { return parenthesizeE("return", {Stmt->value}); } std::any visitWhile(While *Stmt) override { std::cout << "(while "; print(Stmt->condition); std::cout << '\n'; print(Stmt->body); std::cout << ")"; return nullptr; } std::any visitVar(Var *Stmt) override { return parenthesizeE("var " + Stmt->name.lexeme, {Stmt->init}); } std::any visitAssign(Assign *expr) override { return parenthesizeE("= " + expr->name.lexeme, {expr->value}); } std::any visitBinaryExpr(BinaryExpr *expr) override { return parenthesizeE(expr->Operator.lexeme, {expr->left, expr->right}); } std::any visitLogical(Logical *expr) override { return parenthesizeE(expr->Operator.lexeme, {expr->left, expr->right}); } std::any visitGroupingExpr(GroupingExpr *expr) override { return parenthesizeE("group", {expr->expression}); } std::any visitCall(Call *Expr) override { // wrong std::cout << "(call "; print(Expr->callee); print(Expr->args); std::cout << ')'; return nullptr; } std::any visitLiteralExpr(LiteralExpr *expr) override { std::cout << " " << expr->value; return nullptr; } std::any visitUnaryExpr(UnaryExpr *expr) override { return parenthesizeE(expr->Operator.lexeme, {expr->right}); } std::any visitVariable(Variable *expr) override { std::cout << " " << expr->name.lexeme; return nullptr; } std::any parenthesizeS(std::string name, std::vector<Stmt *> v) { std::string pp = "(" + name; // print std::cout << pp; for (auto e : v) { if (e != nullptr) e->accept(this); } std::cout << ")"; return nullptr; } std::any parenthesizeE(std::string name, std::vector<Expr *> v) { std::string pp = "(" + name; // print std::cout << pp; for (auto e : v) { if (e != nullptr) e->accept(this); } std::cout << ")"; return nullptr; } }; } // namespace lox /// EXAMPLE USE: // int main() { // std::unique_ptr<Expr> rootExpr( // new BinaryExpr(new UnaryExpr(*new Token(TokenType::MINUS, "-", "", // 1), // new LiteralExpr("123")), // *new Token(TokenType::STAR, "*", "", 1), // new GroupingExpr(new LiteralExpr("45.67")))); // ASTPrinter pp; // pp.print(rootExpr.get()); // std::cout << std::endl; // return 0; // }
true
3112732844d0fedf3331bdcfc0ed95ec7179bc7e
C++
Faaux/DingoEngine
/src/graphics/Framebuffer.h
UTF-8
947
2.640625
3
[ "MIT" ]
permissive
/** * @file Framebuffer.h * @author Faaux (github.com/Faaux) * @date 11 February 2018 */ #pragma once #include "Texture.h" #include "engine/Types.h" #include "math/GLMInclude.h" namespace DG { class Framebuffer { public: Framebuffer() = default; ~Framebuffer() = default; void Initialize(s32 width, s32 height, bool withColor, bool withDepth, bool isDepthLinear); void Shutdown(); void Resize(s32 width, s32 height); vec2 GetSize() const; void Bind(); void UnBind(); graphics::Texture ColorTexture; graphics::Texture DepthTexture; private: void ReInitialize(); void AddDepthTextureInternal(); void AddColorTextureInternal(); void Cleanup(); s32 _width; s32 _height; u32 fbo = 0; bool _isInitialized = false; bool _isDirty = false; bool _hasColor = false; bool _hasDepth = false; bool _hasLinearDepth = false; }; } // namespace DG
true
7c8e1da2ad5e6828a37d145d83a81bab07d27bfa
C++
gitahn59/Algorithm
/backjoon/boj_01473_미로 탈출-bfs.cpp
UHC
2,942
2.703125
3
[ "MIT" ]
permissive
/* boj_01473_̷ Ż(̵ : 1) bfs ̵ Ǵܰ bitmask ̿ 湮 θ Ȯϴ ٷο */ #include <iostream> #include <queue> #include <vector> #include <map> #include <algorithm> #include <string> #include <cstring> #include <stack> #include <cmath> #include <set> #include <bitset> #include <climits> #include <tuple> #define PRIME 1000000007 using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef pair<ll, ll> LL; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<ll> vll; typedef vector<vi> vvi; typedef deque<int> di; typedef pair<int, ii> iii; typedef set<int> si; int N, M; vii room[4] = { {{-1,0},{1,0},{0,-1},{0,1}}, {}, {{-1,0},{1,0}}, {{0,-1},{0,1}}, }; int arr[8][8]; int visited[8][8][1 << 7][1 << 7]; void rotate(int h, int w, int& rc, int& cc) { if (rc & 1 << h) { rc -= 1 << h; } else { rc += 1 << h; } if (cc & 1 << w) { cc -= 1 << w; } else cc += 1 << w; } bool canMove(int h, int w, int from, int to) { if (from == 0) {//A if (to == 0) return true; else if (to == 2 && h != 0) return true; else if (to == 3 && w != 0) return true; } else if (from == 2) { if (to == 0) return true; else if (to == 2 && h != 0) return true; } else if (from == 3) { if (to == 0) return true; else if (to == 3 && w != 0) return true; } return false; } int getType(int h, int w, int rc, int cc) { int temp = arr[h][w]; if (temp <= 1) return temp; if (rc & 1 << h) { if (arr[h][w] == 2) temp = 3; else temp = 2; } if (cc & 1 << w) { if (temp == 2) temp = 3; else temp = 2; } return temp; } int bfs() { queue<tuple<int, int, int, int>> q; q.push({ 1,1,0,0 }); for (int t = 0; !q.empty(); t++) { int qsize = q.size(); for (int i = 1; i <= qsize; i++) { auto now = q.front(); q.pop(); int h = get<0>(now); int w = get<1>(now); int rc = get<2>(now); int cc = get<3>(now); if (h == N && w == M) { return t; } if (visited[h][w][rc][cc] == 1) continue; else visited[h][w][rc][cc] = 1; int type = getType(h, w, rc, cc); for (ii n : room[type]) { int i = h + n.first; int j = w + n.second; if (i<1 || i>N || j<1 || j>M) continue; if (canMove(n.first, n.second, type, getType(i, j, rc, cc))) { q.push({ i,j,rc,cc }); } } int nrc = rc; int ncc = cc; rotate(h, w, nrc, ncc); q.push({ h,w,nrc,ncc }); } } return -1; } int main() { //freopen("input.txt", "r", stdin); ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> N >> M; char str[15]; for (int n = 1; n <= N; n++) { cin >> str + 1; for (int m = 1; m <= M; m++) { arr[n][m] = str[m] - 'A'; } } cout << bfs() << "\n"; return 0; }
true
bb5f27c936e7f7608fdcd8fe800bc0f7e015ccca
C++
Joseph-Castrejon/Harmonic-Series
/harmonics.cpp
UTF-8
1,020
3.5625
4
[]
no_license
#include<math.h> #include<iostream> #include<cstring> #include<stdlib.h> using namespace std; double HarmonicSeries(long int n); int main(int argc, char *argv[]) { long int n; if(argc == 2) { cout << "Harmonic Series Calculator by JC" << endl; cout << "Calculating for " << atoi(argv[1]) << " terms" << endl; HarmonicSeries(atol(argv[1])); return 0; } cout << "--------------------------------" << endl; cout << "| Harmonic Series Calculator |" << endl; cout << "--------------------------------" << endl; cout << "Enter N: "; cin >> n; HarmonicSeries(n); return 0; } double HarmonicSeries(long int n) { long int i; double sum = 0; for(i = 1; i <= n; i++) { if(i == (n / 4) ){ cout << "25\% Finished" << endl; } else if(i == (n/2)) { cout << "50\% Finished" << endl; } else if(i == (n * 3/4)){ cout << "75\% Finished" << endl; } sum = sum + (1.0 / i); } cout << "Harmonic Series for N = " << n << endl; cout << "Result: " << sum << endl; };
true
35130e578ffce65537b78e133b197d88f3b11627
C++
ljjhome/CPrimerPractice
/chp15/Basket.hpp
UTF-8
897
3.203125
3
[]
no_license
#ifndef BASKET_HPP #define BASKET_HPP #include "Sales_data.hpp" #include <set> #include <memory> #include "Quote.hpp" class Basket { public: void add_item(const Quote & sale){ items.insert(std::shared_ptr<Quote>(sale.clone())); } void add_item(Quote && sale){ items.insert(std::shared_ptr<Quote>(std::move(sale).clone())); } double total_receipt(std::ostream&) const; private: static bool compareIsbn(const std::shared_ptr<Quote>& q1, const std::shared_ptr<Quote>& q2){ return q1->isbn()<q2->isbn(); } std::multiset<std::shared_ptr<Quote>,decltype(compareIsbn)*> items{compareIsbn}; }; double Basket::total_receipt(std::ostream& os) const { double sum = 0.0; for(auto iter = items.begin();iter!=items.end();iter = items.upper_bound(*iter)){ sum += print_total(os, **iter, items.count(*iter)); } os<< "Total sale: " <<sum<<std::endl; return sum; } #endif //BASKET_HPP
true
f5a1ced91ad9bb024fd57b832635639626a30b98
C++
fredfeng/compass
/compass/summary/SummaryClosure.h
UTF-8
11,386
2.671875
3
[]
no_license
/* * SummaryClosure.h * * Created on: Mar 9, 2009 * Author: isil */ #ifndef SUMMARYCLOSURE_H_ #define SUMMARYCLOSURE_H_ #include <vector> #include <string> #include <set> #include <map> #include "Constraint.h" #include "Edge.h" using namespace std; class SummaryGraph; class AccessPath; class MemoryLocation; class Variable; class Edge; class IterationCounter; namespace sail{ class Block; }; enum gen_kind_t {PARAMETRIC, LAST}; /* * Generalization of an access path within a recursive summary unit. * The parametric field is parameterized over a variable k which * represents any iteration number. * The last field refers to iteration N, which is the iteration at which * the loop terminates. * constraint is the constraint under which this generalization holds (e.g. * i may have generalization i+k under flag and i+2k under !flag). */ struct generalization { AccessPath* base; AccessPath* parametric; AccessPath* last; Constraint constraint; // Increment has to be an integer, otherwise we get non-linear things long int increment; static int counter; generalization(AccessPath* rec_base, AccessPath* to_generalize, Constraint c, int cur_counter); generalization(); AccessPath* get_generalization(gen_kind_t kind, int counter_id); long int get_increment(); string to_string(); }; struct generalization_set { set<generalization*> generalizations; generalization_set(); ~generalization_set(); bool add_generalization(AccessPath* rec_base, AccessPath* to_generalize, Constraint c, int cur_counter); void add_generalization(generalization* g); string to_string(); int size(); void clear(); }; /* * SummaryClosure computes the transitive closure of the * summary graph for loops and tail-recursive functions. * This is an alternative way of doing a fixed-point * computation that makes it easier to recover invariants. */ class SummaryClosure { private: SummaryGraph& sg; vector<string>* visuals; /* * The constraint under which the loop/recursion terminates. */ Constraint termination_cond; /* * The set of all locations used in the summary graph. */ set<MemoryLocation*> locs; set<AccessPath*> all_sources; /* * A mapping from memory access paths to the set of edges in * which this access path appears in the target. * This is used in the fixpoint computation for graph closure * to re-enqueue the relevant edges. */ map<AccessPath*, set<Edge*> > target_aps_to_edges; /* * A mapping from access paths pairs to their closed value set * (i.e. values they can take in any possible iteration.) */ map<AccessPath*, generalization_set> generalization_map; /* * The key set of the above map. */ set<AccessPath*> generalized_aps; /* * All the iteration counters used in the summary. */ set<IterationCounter*> counters; /* * This is just used to avoid making the constraint * k1= k2 = ... kn multiple times (used for checking * whether source/target can be overwritten.) */ Constraint counter_ids_eq_constraint; /* * Access paths that are not a linear function of the iteration counter * but that are modified in the loop. */ set<AccessPath*> non_generalizable_aps; /* * Edges that need to be updated. * For instance, if i is incremented by, then summary graph * contains edge from i to *(i+1) but this edge * will need to be replaced with i->*(i+k) etc. */ map<Edge*, set<generalization*> > edges_to_update; /* * Counter for variables used for preprocessing pointer * arithmetic */ int pointer_index_counter; /* * Fake l variables introduced by the analysis to * treat pointer arithmetic as index-based access. */ set<AccessPath*> pointer_indices; /* * If a is an array that has pointer arithmetic applied to it * in the loop, this map will map a to the fake l variable * that expresses pointer arithmetic as index-based access. */ map<AccessPath*, AccessPath*> base_to_index; /* * i-> i+l */ map<Term*, Term*> pointer_arithmetic_subs; public: SummaryClosure(SummaryGraph& sg, vector<string>* visuals = NULL); ~SummaryClosure(); static void get_iteration_counters(Constraint c, set<IterationCounter*>& counters); static void get_termination_vars(Constraint c, set<IterationCounter*>& counters); private: /* * We classify scalars modified by the loop into 3 categories: * 1) Scalars that are linear functions of the iteration counter; * these can be generalized meaningfully as i -> i+c*N +c' * 2) Scalars that are non-linear or unknown function of the iteration * counter, these lead to imprecise generalizations of the form * i->imprecise(N) or i->imprecise(k) * 3) Scalars written to in the loop, but are not even recursively defined; * these are not in the generalization_map. * * Scalars that belong to (2) and (3) are also added to * non_generalizable_aps so that they can be treated as non-deterministic * environment choices when deciding whether two constraints are disjoint. */ void compute_generalizations(); /* * Prepares graph for closure by determining the incoming edges of * each target, i.e., initializes target_aps_to_edges. */ void prepare_graph(); /* * Eliminates access paths in the non_generalizable_aps set * from the constraints. */ void eliminate_non_linear_aps(); /* * Where possible, determines the number of times the loop * executes. */ void compute_termination_constraint(); /* * Computes the last iteration condition for an exit point out of the loop. */ Constraint get_last_iteration_constraint(Constraint break_cond, sail::Block* exit_pred_block); /* * Replaces values used in the constraint with their * generalizations. */ void generalize_constraints(); /* * Recomputes the termination (resp. last iteration) condition of the * loop using the appropriate N's for each block. */ Constraint compute_generalized_termination_cond(); /* * Returns the generalization of a constraint * c is the constraint to be generalized, and parametric indicates whether * k or N should be used in the generalization, and counter_id * indicates which counter id should be used in the generalization. */ Constraint generalize_constraint(Constraint c, gen_kind_t parametric, int counter_id); Constraint generalize_ap_in_constraint(Constraint c, AccessPath* old_ap, gen_kind_t kind, int counter_id); bool target_overwritten_in_prev_it(AccessPath* target, Constraint target_c, Constraint overwrite_c); /* * Can the target of this edge be overwritten in a previous iteration? * We only need to check this for self recursive edges because * for other edges, closing the graph makes sure sufficient conditions * are weakened appropriately. */ bool target_overwritten_in_prev_it(Edge* e); bool source_overwritten_in_future_it(Edge* e); Constraint increment_iteration_counters(Constraint c); Constraint decrement_iteration_counters(Constraint c); Constraint increment_iteration_counters(Constraint c, AccessPath* inc_amount); /* * Eliminates the iteration counters used in the constraints * where appropriate. */ void eliminate_iteration_counters(); Constraint get_counters_eq_constraint(); /* * Checks whether the ap is in terms of the iteration counter, * e.g., i+k is parametric. */ bool is_parametric_ap(AccessPath* ap); /* * Closing the summary graph G means the following: * If there is an edge from X to *Y in G as * well as an edge from Y to *Z, then add the edge * X to *Z. The NC for the edge constraint is the * conjunction of the necessary condition for the individual * edge constraints, but the sufficient condition is false. */ void close_graph(); void enqueue_dependencies(AccessPath* source_ap, AccessPath* new_target, set<Edge*,CompareTimestamp>& edges, Edge* new_edge); /* * Populates locs, i.e., the set of locations * used in the summary. */ void collect_summary_locs(); /* * Makes pointer arithmetic explicit by introducing integer variables * so that we can treat pointer arithmetic and explicit index based * side effects more uniformly. For instance, if there is a side * effect a++, this is turned into a points to (*a)[i] under the constraint * i=l_a and l_a points to *(l_a + 1). */ void preprocess_pointer_arithmetic(); void preprocess_pointer_arithmetic_in_constraints(); void preprocess_pointer_arithmetic(Constraint & c); /* * Removes the fake l_i variables introduces during preprocessing. */ void postprocess_pointer_arithmetic(); /* * Given an access path such as *(a+b) where a's value set is <c/flag, * d/!flag> and where b's value set is <e/flag2, f/!flag2> gives back * the set {*(c+e)/flag&flag2, *(c+f)/flag&!flag2, *(d+e)/!flag&flag2, * *(d+f)/ !flag&!flag2} and so on. * * If the return value is false, it means that there may be infinitely many * possible targets (and cannot be generalized), and the target should * become imprecise. */ bool get_closed_targets(AccessPath* ap, Constraint c, set<pair<AccessPath*, Constraint> >& closed_targets); bool get_closed_targets_rec(AccessPath* ap, Constraint c, set<pair<AccessPath*, Constraint> >& closed_targets); /* * Get the iteration counter for this edge. * INVALID_COUNTER if it does not have consistent * block ids. */ int get_iteration_counter(Edge* e); /* * Generalizes the graph by updating the targets of * summary edges with their correct generalizations. */ void generalize_targets(); /* * Is ap1 contained in ap2? */ bool occurs_check(AccessPath* ap1, AccessPath* ap2); /* * If we were able to generalize an access path like "i", * we need to update any other access paths involving i, such * as i+1 etc. */ void update_generalization_dependencies(); void cross_product_generalizations( map<AccessPath*, generalization_set>& map_set, set<map<AccessPath*, generalization*> > & set_map); void cross_product_generalizations_rec( map<AccessPath*, generalization_set>& map_set, set<map<AccessPath*, generalization*> > & set_map, map<AccessPath*, generalization*>& cur_map); /* * Determines if the given ap contains any N. */ bool contains_termination_var(AccessPath* ap); void generalize_error_traces(); inline Variable* get_pointer_index(); /* * Is the source of this edge guaranteed to represent * a single concrete location? */ bool has_concrete_source(Edge* e); /* * Yields the constraint for the edge that gave rise to this generalization. * For example, if one of the generalizations for i is i+N, then this * function looks up the constraint on the edge i->*(i+1). */ Constraint get_original_constraint(generalization* g); /* * Collects the set of counter ids used in the summary. */ void collect_used_counters(); /* * Minimizes the number of N's used in the summary. */ void minimize_iteration_counters(); /* * Uniquifies error traces by disregarding the block in which * they were generated. */ void uniquify_error_traces(); /* --------------------------- * Debugging functions * --------------------------- */ void print_target_ap_to_edges(); void print_non_generalizable_aps(); void print_base_to_index(); void print_linear_scalars(); void print_used_counters(); }; #endif /* SUMMARYCLOSURE_H_ */
true
8fb7fce44f9a9baabac87b5b8faabb3fba9de556
C++
ekaan/CS406-Parallel-Computing
/HW2/seq_v2.cpp
UTF-8
17,711
2.703125
3
[]
no_license
#include <stdio.h> #include <iostream> #include <fstream> #include <sstream> #include <omp.h> #include <string> #include <cmath> #include <cstring> #include <vector> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <boost/functional/hash.hpp> using namespace std; struct CRS { int* col; int* rowptr; int rowsize; int nonzerosize; CRS(int numRows, int numNZ){ col = new int[numNZ]; rowptr = new int[numRows+1]; rowsize = numRows; nonzerosize = numNZ; } }; bool compareData(pair<int, int> A, pair<int, int> B) { return (A.second < B.second) || ( (A.second == B.second) && (A.first<B.first ) ); } void printCRS(CRS & storage) { cout<<"col values are "<<endl; for(int i = 0; i <storage.nonzerosize; i++) cout<<storage.col[i]<<" "; cout<<endl; cout<<"rowptr values are "<<endl; for(int i = 0; i <= storage.rowsize; i++) cout<<storage.rowptr[i]<<" "; cout<<endl; } void usage() { cout << "USAGE: ./exec <filename>" << endl; exit(0); } int findMaxColor (int* & graphColor, int numRows) { int max = -1; for (int i = 0 ; i < numRows ; i++) { //cout << graphColor[i] << endl; if (graphColor[i] > max) max = graphColor[i]; } return max+1; } bool checkValidity(CRS & storage, int* & graphColor) { int start,end; for (int i = 0 ; i < storage.rowsize ; i++) { start = storage.rowptr[i]; end = storage.rowptr[i+1]; for (start ; start < end ; start++) { if(graphColor[storage.col[start]] == graphColor[i]) { cout << "Collision Spotted !" << endl; cout << "Collision between: " << i << " " << storage.col[start] << endl; cout << "Colors are " << graphColor[i] << " " << graphColor[storage.col[start]] << endl; // return false; } } } cout << "No Collisions !" << endl; return true; } void seqColor_v2(CRS & storage, int* & graphColor, int* available) { int i,end; //cout << storage.rowsize << " " << storage.nonzerosize << endl; //printCRS(storage); for(int v = 0; v < storage.rowsize; v++) { i = storage.rowptr[v]; end = storage.rowptr[v+1]; //cout << v << " " << i << " " << end << endl; for(i ; i < end ; i++) { if (graphColor[storage.col[i]] != -1) available[graphColor[storage.col[i]]] = v; } for(int c = 0; c < storage.rowsize; c++) { if(available[c] != v) { //cout << v << " " << c << endl; graphColor[v] = c; break; } } } } void parColor (CRS & storage, int* & graphColor,int* & available, int* & reColor) { for(int t = 1; t <=16; t*=2) { int ct = storage.rowsize; int a = 0; double s1 = omp_get_wtime(); while(ct > 0) { cout << ct << endl; #pragma omp parallel proc_bind(spread) num_threads(t) shared(ct) { int* ava = new int [storage.rowsize]; for (int j = 0 ; j < storage.rowsize ; j++) ava[j] = available[j]; #pragma omp for schedule(guided) for (int v = 0 ; v < ct ; v++) { int curr_vertex = reColor[v]; int start = storage.rowptr[curr_vertex]; int end = storage.rowptr[curr_vertex + 1]; for (start ; start < end ; start++) { ava[graphColor[storage.col[start]]] = curr_vertex; } for (int c = 0 ; c < storage.rowsize ; c++) { if (ava[c] != curr_vertex) { graphColor[curr_vertex] = c; break; } } } } a = 0; #pragma omp parallel proc_bind(spread) num_threads(t) shared(ct,a) { #pragma omp for schedule(guided) //reduction(+:a) for (int i = 0 ; i < ct ; i++) { int curr_vertex = reColor[i]; int start = storage.rowptr[curr_vertex]; int end = storage.rowptr[curr_vertex+1]; for (start ; start < end ; start++) { int nbr_vertex = storage.col[start]; if ((graphColor[nbr_vertex] == graphColor[curr_vertex]) && (curr_vertex < nbr_vertex)) { #pragma omp critical { //cout << a << endl; reColor[a] = curr_vertex; //cout << reColor[a] << endl; a += 1; } //cout << graphColor[storage.col[start]] << " " << graphColor[i] << " " << a << endl; } } } } cout << "Number of vertices that needs to be re-colored: " << a << endl; ct = a; } double s2 = omp_get_wtime(); cout << "Total time for " << t << " thread(s) are: " << s2 - s1 << endl; cout << "Max color is " << findMaxColor(graphColor, storage.rowsize) << endl; checkValidity(storage, graphColor); //for (int i = 0 ; i < storage.rowsize ; i++) cout << graphColor[i] << " "; //cout << endl; for (int j = 0 ; j < storage.rowsize ; j++) graphColor[j] = -1; //for (int j = 0 ; j < storage.rowsize ; j++) available[j] = -10; for (int j = 0 ; j < storage.rowsize ; j++) reColor[j] = j; } } void seqColor(CRS & storage, int* graphColor, int* available) { graphColor[0] = 0; for (int i = 0 ; i < storage.rowsize ; i++) { for (int k = storage.rowptr[i] ; k != storage.rowptr[i+1] ; k++) { if (graphColor[storage.col[k]] != -1) { available[graphColor[storage.col[k]]] = 1; } } int ct; for (ct = 0; ct < storage.rowsize ; ct++) { if (available[ct] == 0) { break; } } graphColor[i] = ct; for (int k = storage.rowptr[i] ; k != storage.rowptr[i+1] ; k++) { if (graphColor[storage.col[k]] != -1) { available[graphColor[storage.col[k]]] = 0; } } } } int main(int argc, const char** argv) { if(argc != 2) usage(); double start = omp_get_wtime(); unsigned int numRows, numCols, numNZ, edgeStart, edgeEnd, count; string line; string patternType = ""; const char* filename = argv[1]; unsigned int realNumNZ; ifstream input (filename); if(input.fail()) return 0; getline(input, line); stringstream ss(line); string temp; while(ss>>temp); patternType = temp; while(getline(input, line)) { stringstream ss(line); ss>>temp; if(temp.substr(0,1) != "%") { numRows = stoul(temp); ss>>numCols>>numNZ; break; } } cout<<numRows<<" "<<numCols<<" "<<numNZ<<endl; int counter = 0; typedef pair<int, int> nodePair; vector<nodePair> edges(2*numNZ,{0, 0}); while(getline(input, line)){ int row, col; stringstream ss(line); ss>>col>>row; edges[counter] = make_pair(col, row); edges[numNZ+counter] = make_pair(row, col); counter++; } sort(edges.begin(), edges.end(), compareData); auto last = unique(edges.begin(), edges.end()); edges.erase(last, edges.end()); edges.erase(remove_if( edges.begin(),edges.end(), [](const nodePair& p) { return p.first == p.second; // put your condition here }), edges.end()); if(edges[0].second != 0) for(int i = 0; i<edges.size(); i++) { edges[i].first--; edges[i].second--; } /* for(int i = 0; i<edges.size(); i++) { if(edges[i].first == edges[i].second) cout<<"edge"<<edges[i].first<<" "<<edges[i].second<<endl; } */ realNumNZ = edges.size(); CRS storage(numRows, realNumNZ); //storage.col[0] = edges[0].first; //storage.rowptr[0] = edges[0].second; unsigned int prevRow = edges[0].second; for(int i = 0; i<realNumNZ; i++) { storage.col[i] = edges[i].first; if(edges[i].second != prevRow) { prevRow = edges[i].second; storage.rowptr[edges[i].second] = i; } } storage.rowptr[numRows] = realNumNZ; cout<<"Reading file lasted "<<omp_get_wtime() - start<<" seconds"<<endl; cout<<"realnumnz is "<<edges.size()<<endl; //printCRS(storage); int* graphColor = new int [numRows]; for (int j = 0 ; j < numRows ; j++) graphColor[j] = -1; // -1 int* available = new int [numRows]; for (int j = 0 ; j < numRows ; j++) available[j] = -10; // -1 int* reColor = new int [numRows]; for (int j = 0 ; j < numRows ; j++) reColor[j] = j; double s1 = omp_get_wtime(); //seqColor(storage, graphColor, available); //seqColor_v2(storage, graphColor, available); parColor(storage, graphColor, available, reColor); double s2 = omp_get_wtime(); /* cout << "Total Time: " << s2 - s1 << endl; cout << "Max Color: " << findMaxColor(graphColor, numRows) << endl; checkValidity(storage, graphColor); */ delete [] graphColor; delete [] available; delete [] reColor; return 0; } /* void parColor (CRS & storage, int* & graphColor, int* & available, bool* & reColor) { cout << 0 << endl; for(int t = 1; t <=16; t*=2) { bool willContinue = true; double s1 = omp_get_wtime(); cout << 1 << endl; while (willContinue) { int ct; #pragma omp parallel num_threads(t) proc_bind(spread) { cout << 2 << endl; //int tid = omp_get_thread_num(); //int rSize = storage.rowsize; //int startId = (tid * rSize)/t; #pragma omp for schedule(static) for (int v = 0 ; v < storage.rowsize ; v++) { if (reColor[v] == true) { int start = storage.rowptr[v]; int end = storage.rowptr[v+1]; for (start ; start < end ; start++) if (graphColor[storage.col[start]] != -1) available[graphColor[storage.col[start]]] = v; for (int c = 0 ; c < storage.rowsize ; c++) if (available[c] != v) { graphColor[v] = c; reColor[v] = false; break; } } } cout << 3 << endl; ct = 0; #pragma omp for schedule(static) for (int i = 0 ; i < storage.rowsize ; i++) { for (int k = storage.rowptr[i] ; k < storage.rowptr[i+1] ; k++) { if(graphColor[storage.col[k]] == graphColor[i] && i > storage.col[k]) { reColor[i] = true; ct += 1; } } } } cout << 4 << endl; if (ct > 0) willContinue = false; } double s2 = omp_get_wtime(); cout << 5 << endl; cout << "Total time is: " << s2 - s1 << endl; cout << "Max color is: " << findMaxColor(graphColor, storage.rowsize) << endl; //PREPROCESSING PART AGAIN for (int j = 0 ; j < storage.rowsize ; j++) graphColor[j] = -1; for (int j = 0 ; j < storage.rowsize ; j++) available[j] = -10; for (int j = 0 ; j < storage.rowsize ; j++) reColor[j] = true; cout << 6 << endl; } } */ /* void parColor (CRS & storage, int* & graphColor, int* & available, bool* & reColor) { for(int t = 1; t <=16; t*=2) { bool willContinue = true; double s1 = omp_get_wtime(); while (willContinue) { int ct; #pragma omp parallel num_threads(t) proc_bind(spread) { int tid = omp_get_thread_num(); int rSize = storage.rowsize; int startId = (tid * rSize)/t; int endId = ((tid+1) * rSize)/t; #pragma omp for schedule(static) for (int v = startId ; v < endId ; v++) { if (reColor[v] == true) { int start = storage.rowptr[v]; int end = storage.rowptr[v+1]; for (start ; start < end ; start++) if (graphColor[storage.col[start]] != -1) available[graphColor[storage.col[start]]] = v; for (int c = 0 ; c < storage.rowsize ; c++) if (available[c] != v) { graphColor[v] = c; reColor[v] = false; break; } } } ct = 0; #pragma omp for schedule(static) for (int i = startId ; i < endId ; i++) { for (int k = storage.rowptr[i] ; k < storage.rowptr[i+1] ; k++) { if(graphColor[storage.col[k]] == graphColor[i] && i > storage.col[k]) { reColor[i] = true; ct += 1; } } } if (ct == 0) willContinue = false; } double s2 = omp_get_wtime(); cout << "Total time is: " << s2 - s1 << endl; cout << "Max color is: " << findMaxColor(graphColor, storage.rowsize) << endl; } checkValidity(storage, graphColor); //PREPROCESSING PART AGAIN for (int j = 0 ; j < storage.rowsize ; j++) graphColor[j] = -1; for (int j = 0 ; j < storage.rowsize ; j++) available[j] = -10; for (int j = 0 ; j < storage.rowsize ; j++) reColor[j] = true; } } */ /* void parColor (CRS & storage, int* & graphColor,int* & available, int* & reColor) { for(int t = 1; t <=16; t*=2) { int ct = storage.rowsize; int a = 0; double s1 = omp_get_wtime(); while(ct != 0) { cout << ct << endl; #pragma omp parallel proc_bind(spread) num_threads(t) shared(ct) { int* ava = new int [storage.rowsize]; for (int j = 0 ; j < storage.rowsize ; j++) ava[j] = available[j]; #pragma omp for schedule(guided) for (int v = 0 ; v < ct ; v++) { int start = storage.rowptr[reColor[v]]; int end = storage.rowptr[reColor[v]+1]; for (start ; start < end ; start++) ava[graphColor[storage.col[start]]] = v; //if (graphColor[storage.col[start]] != -1)// -- PROBLEM HERE for (int c = 0 ; c < storage.rowsize ; c++) if (ava[c] != v) { graphColor[v] = c; break; } } } #pragma omp parallel proc_bind(spread) num_threads(t) shared(ct,a) { #pragma omp for schedule(guided) //reduction(+:a) for (int i = 0 ; i < ct ; i++) { int start = storage.rowptr[reColor[i]]; int end = storage.rowptr[reColor[i]+1]; for (start ; start < end ; start++) { if ((graphColor[storage.col[start]] == graphColor[i]) && (i > storage.col[start])) { #pragma omp critical { //cout << a << endl; reColor[a] = i; //cout << reColor[a] << endl; a += 1; } //cout << graphColor[storage.col[start]] << " " << graphColor[i] << " " << a << endl; } } } } cout << "Number of vertices that needs to be re-colored: " << a << endl; ct = a; a = 0; } double s2 = omp_get_wtime(); cout << "Total time for " << t << " thread(s) are: " << s2 - s1 << endl; cout << "Max color is " << findMaxColor(graphColor, storage.rowsize) << endl; //checkValidity(storage, graphColor); //for (int i = 0 ; i < storage.rowsize ; i++) cout << graphColor[i] << " "; //cout << endl; for (int j = 0 ; j < storage.rowsize ; j++) graphColor[j] = -1; //for (int j = 0 ; j < storage.rowsize ; j++) available[j] = -10; for (int j = 0 ; j < storage.rowsize ; j++) reColor[j] = j; } } */ /* void parColor_v2 (CRS & storage, int* & graphColor,int* & available, int* & reColor, int t) { int ct = storage.rowsize; int a = 0; while(ct != 0) { #pragma omp parallel proc_bind(spread) num_threads(t) shared(ct) { int* ava = new int [storage.rowsize]; for (int j = 0 ; j < storage.rowsize ; j++) ava[j] = available[j]; #pragma omp for schedule(guided) for (int v = 0 ; v < ct ; v++) { int start = storage.rowptr[reColor[v]]; int end = storage.rowptr[reColor[v]+1]; for (start ; start < end ; start++) ava[graphColor[storage.col[start]]] = v; //if (graphColor[storage.col[start]] != -1)// -- PROBLEM HERE for (int c = 0 ; c < storage.rowsize ; c++) if (ava[c] != v) { graphColor[v] = c; break; } } } #pragma omp parallel proc_bind(spread) num_threads(t) shared(ct,a) { #pragma omp for schedule(guided) //reduction(+:a) for (int i = 0 ; i < ct ; i++) { int start = storage.rowptr[reColor[i]]; int end = storage.rowptr[reColor[i]+1]; for (start ; start < end ; start++) { if ((graphColor[storage.col[start]] == graphColor[i]) && (i > storage.col[start])) { #pragma omp critical { //cout << a << endl; reColor[a] = i; //cout << reColor[a] << endl; a += 1; } //cout << graphColor[storage.col[start]] << " " << graphColor[i] << " " << a << endl; } } } } cout << "Number of vertices that needs to be re-colored: " << a << endl; ct = a; a = 0; } } void seqColor_v2(CRS & storage, int* & graphColor, int* available) { int i,end; //cout << storage.rowsize << " " << storage.nonzerosize << endl; //printCRS(storage); for(int v = 0; v < storage.rowsize; v++) { i = storage.rowptr[v]; end = storage.rowptr[v+1]; //cout << v << " " << i << " " << end << endl; for(i ; i < end ; i++) { if (graphColor[storage.col[i]] != -1) available[graphColor[storage.col[i]]] = v; } for(int c = 0; c < storage.rowsize; c++) { if(available[c] != v) { //cout << v << " " << c << endl; graphColor[v] = c; break; } } } } */
true
16c10f0a0575571465ce435e8a7fa38e20aab628
C++
Madhuraaaaa/cpp-stl_assignments
/speed_average.cpp
UTF-8
625
3.1875
3
[ "BSD-2-Clause" ]
permissive
#include <string> #include <list> #include <iterator> #include <iostream> #include <utility> #include <bits/stdc++.h> using namespace std; double average(vector<int> vec, int length_l) { double sum=0; for (auto i = vec.begin(); i != vec.end(); ++i) { sum=sum+*i; } return sum/length_l; } int main() { vector<int> vec; double data_member, length_l; cin >> length_l; for (int i = 0; i < length_l; i++) { cin >> data_member; vec.push_back(data_member); } double avg=average(vec, length_l); cout<<"Average speeds: "<<avg; }
true
1651573b8f2d0c0e57c419bf2476211f6e391747
C++
lvyong1943/EvHttp
/Utilis/Logger.h
UTF-8
2,705
2.59375
3
[ "MIT" ]
permissive
/** * Copyright (c) 2019, ATP * All rights reserved. * MIT License */ #ifndef __UTILIS_LOGGER_H__ #define __UTILIS_LOGGER_H__ #include <string> #include <list> #include <thread> #include <mutex> #include <condition_variable> #include "NonCopyable.h" namespace Utilis { const int kLogMsgLen = 4096; /// FATAL must be the last level, otherwise first line of AppendLog should be modified /// This is compatible with libevent log level definition typedef enum eLogLevel{ LL_DEBUG = 0, LL_INFO, LL_WARN, LL_ERROR, LL_FATAL }LogLevel; const char kLogLevelStr[][6] = { "DEBUG", "INFO", "WARN", "ERROR", "FATAL" }; /// use __PRETTY_FUNCTION__(gcc) or __FUNCSIG__ (vs) instead will be more powerful #define LogAppend(level, ...) Logger::GetInstance()->AppendLog(Utilis::level, \ __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__) #define LogDebug(...) LogAppend(LL_DEBUG, __VA_ARGS__) #define LogInfo(...) LogAppend(LL_INFO, __VA_ARGS__) #define LogWarn(...) LogAppend(LL_WARN, __VA_ARGS__) #define LogError(...) LogAppend(LL_ERROR, __VA_ARGS__) #define LogFatal(...) LogAppend(LL_FATAL, __VA_ARGS__) #ifdef DEBUG #define DEBUGPrintf(...) printf(__VA__ARGS__) #else #define DEBUGPrintf(...) #endif /// #TODO: Add file rotate /// Improve time get / msg buffer/ efficient class Logger : Utilis::NonCopyable { public: static Logger* GetInstance() { return logger_; } void SetFilePrefix(std::string const & prefix); void SetLogLevel(LogLevel level); ///#TODO: none-thread-safe, should only run once bool StartLogging(); ///not thread-safe, should only run once /// When call this, it will force worker to exit, which lead to log missing void StopLogging(); /// It's better not to call this directly, call LogXXX() MACRO instead /// It will auto log the file name, func name, line number, time happened and line break void AppendLog(LogLevel level, const char* file, const char* func, int line, const char* fmt, ...); void SimpleAppendLog(LogLevel level, const char* fmt, ...); private: void logWriter(); private: static Logger* logger_; std::string filePrefix_{"log"}; std::string filePath_{ "" }; FILE* fp_{nullptr}; LogLevel level_{LL_DEBUG}; bool bStop_{true}; //this variable is not thread-safe std::shared_ptr<std::thread> spLogThread_; std::mutex muxLog_; std::condition_variable cvLog_; // flag to indicate new coming message std::list<std::string> logQueue_; }; } // namespace Utilis #endif // __UTILIS_LOGGER_H__
true
bd79f8d0c895a7c7d1eb0013545e2cdc62d576d9
C++
kbu1564/SimpleAlgorithm
/acmicpc.net/1173.cpp
UTF-8
421
2.75
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; int BEAT[201]; int main() { int N, m, M, T, R; cin >> N >> m >> M >> T >> R; int turn = 0; int count = 0; int beat = m; while (count < N) { if (beat + T <= M) { beat += T; count++; } else { beat -= R; if (BEAT[beat] == count) { turn = -1; break; } BEAT[beat] = count; } if (beat < m) beat = m; turn++; } cout << turn << endl; return 0; }
true
422a0ad824d488aa6b7960cd15fe115dc988a075
C++
Trietptm-on-Security/SoNew
/SoNewCmd/sonewargumentparser.cpp
UTF-8
616
2.765625
3
[]
no_license
#include "sonewargumentparser.h" namespace SoNew { void SoNewArgumentParser::showHelp(const std::string& programName, const int spacing) const { cout << programName << endl; cout << "Options:" << endl; for (vector<Argument>::const_iterator i = vargs.begin(); i != vargs.end(); ++i) { string options = ""; if (i->isShortArg()) { options += i->getShortArg(); if (i->isLongArg()) { options += ", "; } } if (i->isLongArg()) { options += i->getLongArg(); } cout << string(4, ' ') << options << string(spacing-options.size(), ' ') << i->getDescription() << endl; } } }
true
4332397c118a78b3945115123fd3e4e37c39113c
C++
huangwei1024/my_lib
/CompressMap.h
GB18030
6,075
2.859375
3
[]
no_license
/* @file CompressMap.h @author huangwei @param Email: huang-wei@corp.netease.com @param Copyright (c) 2004-2013 ׵繤 @date 2013/4/28 @brief */ #pragma once #ifndef __COMPRESSMAP_H__ #define __COMPRESSMAP_H__ #include <map> #include <vector> #include <algorithm> /** * CompressStorage * * ѹ洢 * ڻֻ֧ջ * ̰߳ȫ */ class CompressStorage { public: struct Pointer { int key; int idx; int off; int len; }; protected: struct _Block { int idx; // blocksλ int w_off; // bufдƫ int old_len; // δѹ int compress_len; // ѹ int cbuf_len; // cbuf char* cbuf; // (ѹ) int buf_len; // buf char* buf; // (ѹ) }; typedef std::vector <_Block> _BlockVec; typedef std::map <int, Pointer> _PointMap; public: CompressStorage(int size = 0); ~CompressStorage(); int Insert(char* src, int src_len); void Remove(int key); void Clear(); Pointer Query(int key); void Compress(); char* GetData(int key); char* GetData(Pointer pos); int QueryBytes(); int QueryCBytes(); protected: void _BlockInit(_Block* block); void _BlockNew(_Block* block, int size); void _BlockNewBuf(_Block* block, int size); void _BlockNewCBuf(_Block* block, int size); void _BlockClear(_Block* block); void _BlockClearBuf(_Block* block); void _BlockClearCBuf(_Block* block); bool _BlockIsSufficient(_Block* block, int len); bool _BlockCopy(_Block* block, char* dst, int off, int len); bool _BlockMove(_Block* block, _Block* block_src, Pointer* ptr); bool _BlockWrite(_Block* block, Pointer* ptr, char* src, int src_len, int w_off = -1); bool _BlockCompress(_Block* block); bool _BlockUnCompress(_Block* block); protected: int default_bufsize; _BlockVec blocks; _PointMap keymap; }; /** * CompressLazyMap * * ѹmap * ֧insert󣬽sortȻfind */ template <typename K, typename T> class CompressLazyMap { public: template <typename K, typename T> struct pair_struct { K first; // key int storage_key; pair_struct(const K& k) : first(k), storage_key(0) {} bool operator< (const pair_struct& right) const { if (first == right.first) return storage_key < right.storage_key; return first < right.first; } }; typedef size_t size_type; typedef K key_type; typedef T mapped_type; typedef pair_struct <K, T> value_type; typedef std::vector <value_type> container_type; typedef typename container_type::iterator iterator; public: CompressLazyMap(int size = 0) : storage(size) { ordered = true; fakeptr = (mapped_type*)malloc(sizeof(mapped_type)); } ~CompressLazyMap() { clear(); free(fakeptr); fakeptr = NULL; } void sort() { // lazy sort all if (ordered || nodes.empty()) return; container_type new_nodes; std::sort(nodes.begin(), nodes.end()); // ordered container_type::iterator it_pre = nodes.begin(); for (container_type::iterator it = it_pre + 1; it != nodes.end(); ++ it) { if ((*it_pre).first != (*it).first) new_nodes.push_back(*it_pre); else { destroy(get(it_pre)); // important!!! storage.Remove((*it_pre).storage_key); } it_pre = it; } new_nodes.push_back(*it_pre); std::swap(new_nodes, nodes); storage.Compress(); ordered = true; } size_type size() const { // return length of sequence return nodes.size(); } bool empty() const { // return true only if sequence is empty return (size() == 0); } iterator begin() { // return iterator for beginning of mutable sequence return nodes.begin(); } iterator end() { // return iterator for end of mutable sequence return nodes.end(); } void clear() { // destroy object and clear for (container_type::iterator it = nodes.begin(); it != nodes.end(); ++ it) destroy(get(it)); // important!!! nodes.clear(); storage.Clear(); } void del(const key_type& _Keyval) { // delete key and value if (ordered) erase(find(_Keyval)); else { } } void set(const key_type& _Keyval, const mapped_type& _Mapval) { // find element matching _Keyval or insert with default mapped if (!ordered) { insert(_Keyval, _Mapval); return; } iterator _Where = std::lower_bound(nodes.begin(), nodes.end(), value_type(_Keyval)); if (_Where == end() || !(_Keyval == (*_Where).first)) { _Where = insert(_Keyval, _Mapval); // unordered ordered = false; } else { *get(_Where) = _Mapval; } } mapped_type* get(iterator _Where) { // convert storage key to object if (_Where == end()) return NULL; value_type& val = *_Where; char* ptr = storage.GetData(val.storage_key); return (mapped_type*)ptr; } iterator find(const key_type& _Keyval) { // find an element in mutable sequence that matches _Keyval if (!ordered) return end(); iterator _Where = std::lower_bound(nodes.begin(), nodes.end(), value_type(_Keyval)); return ((_Where == end() || !(_Keyval == (*_Where).first)) ? end() : _Where); } protected: iterator insert(const key_type& _Keyval, const mapped_type& _Mapval) { // insert a {key, mapped} value, with hint value_type _Val(_Keyval); construct(fakeptr, _Mapval); // important!!! construct object with share-memory _Val.storage_key = storage.Insert((char*)fakeptr, sizeof(mapped_type)); return nodes.insert(end(), _Val); } void erase(iterator _Where) { // erase element at _Where if (_Where == end()) return; value_type& _Val = *_Where; destroy(get(_Where)); // important!!! destroy object storage.Remove(_Val.storage_key); nodes.erase(_Where); } void construct(mapped_type* p, const mapped_type &t) { // construct object at _Ptr with value _Val ::new ((void *)p) mapped_type(t); } void destroy(mapped_type* p) { // destroy object at _Ptr (void)(p); p->~T(); } protected: container_type nodes; bool ordered; CompressStorage storage; mapped_type* fakeptr; }; #endif // __COMPRESSMAP_H__
true
358a647595c83bdf6312ac6bfeb837362605c9fd
C++
bertbuchholz/Particular
/src/Fps.h
UTF-8
1,073
3.125
3
[]
no_license
#ifndef FPS_H #define FPS_H #include <chrono> class Fps_meter { public: Fps_meter() : _fps(0.0f), _frame_counter(0) { start(); } void start() { _last_check = std::chrono::steady_clock::now(); } float get_fps() { _has_new_value = false; return _fps; } bool has_new_value() { return _has_new_value; } void update() { ++_frame_counter; std::chrono::steady_clock::time_point t = std::chrono::steady_clock::now(); int const elapsed_milliseconds = std::chrono::duration_cast<std::chrono::milliseconds> (t-_last_check).count(); if (elapsed_milliseconds > 1000) { _fps = _frame_counter / float(elapsed_milliseconds) * 1000.0f; _frame_counter = 0; _last_check = t; _has_new_value = true; } } private: float _fps; int _frame_counter; std::chrono::steady_clock::time_point _last_check; bool _has_new_value; }; #endif // FPS_H
true
6864c4e83c693632e8650eefe0d194ab6eece848
C++
zxcvbnmmz/GraDeath
/GraDeath/Source/Pool/ObjectPool.cpp
SHIFT_JIS
2,130
3.09375
3
[]
no_license
#include "Pool/ObjectPool.h" #include "Pool/Ref.h" #include <algorithm> ObjectPoolManager* ObjectPoolManager::manager = nullptr; ObjectPool::ObjectPool(){ managedObject.reserve(200); ObjectPoolManager::GetInstance()->Push(this); } ObjectPool::~ObjectPool(){ Clear(); ObjectPoolManager::GetInstance()->Pop(); } void ObjectPool::Add(Ref* ref){ managedObject.push_back(ref); } void ObjectPool::Clear(){ std::for_each(managedObject.begin(), managedObject.end(), [=](Ref* ref){ delete ref; ref = nullptr; }); // ̗vf̏̓G[N // R͕ȂAdeleteuԂmanagedObject̗vfĂ邱Ƃ // eraseIȑ삪sÔ\ // for (auto* ref : managedObject){ // if (ref != nullptr){ // delete ref; // } //} managedObject.clear(); } void ObjectPool::Erase(Ref* object){ auto it = std::find(managedObject.begin(), managedObject.end(), object); if (it != managedObject.end()){ delete (*it); managedObject.erase(it); } } bool ObjectPool::IsContains(Ref* object)const{ auto it = std::find(managedObject.begin(), managedObject.end(), object); if (it != managedObject.end()){ return true; } return false; } unsigned int ObjectPool::GetContainCount(){ return managedObject.size(); } ObjectPoolManager::ObjectPoolManager(){ pools.reserve(20); } ObjectPoolManager::~ObjectPoolManager(){ while (!pools.empty()){ ObjectPool* _pool = pools.back(); delete _pool; } } ObjectPoolManager* ObjectPoolManager::GetInstance(){ if (manager == nullptr){ manager = new ObjectPoolManager; new ObjectPool; } return manager; } void ObjectPoolManager::Destroy(){ if (manager != nullptr){ delete manager; manager = nullptr; } } ObjectPool* ObjectPoolManager::GetCurrentPool(){ return pools.back(); } bool ObjectPoolManager::IsObjectInPool(Ref* object){ for (auto pool : pools){ if (pool->IsContains(object)){ return true; } } return false; } void ObjectPoolManager::Push(ObjectPool* _pool){ pools.push_back(_pool); } void ObjectPoolManager::Pop(){ pools.pop_back(); }
true
23163b6b1d665865045c33e64d738f8894719a1d
C++
EmadRajeh/Beginning-C-Programming-From-Beginner-to-Beyond-Problem-solutions
/STLSets.cpp
UTF-8
2,431
3.4375
3
[]
no_license
// // main.cpp // Standard Template Library // // Created by Emad Rajeh on 27/06/2020. // Copyright © 2020 Emad Rajeh. All rights reserved. // #include <iostream> #include <algorithm> #include <vector> #include <bits/stdc++.h> #define nline "\n" using namespace std; class Person{ friend ostream &operator<<(ostream &os, const Person &p); string name; int age; public: Person():name{"Unknown"}, age(0){} Person(string name, int age) :name(name),age(age){ } bool operator<(const Person &p)const{ return (this->age < p.age); } bool operator==(const Person &p)const{ return this->name == p.name && this->age == p.age; } }; ostream &operator<<(ostream &os, const Person &p){ os << p.name << ":" << p.age; return os; } template <typename T> void print(const set<T> &s){ cout << "[ "; for(auto i : s){ cout << i << " "; } cout << "]\n"; } void test1(){ set<int> s {1, 4, 3,2,5}; print(s); s = {1,2,3,1,1,1,3,3,4,5}; print(s); s.insert(0); s.insert(10); print(s); if (s.count(10)) { cout << "10 is in the set\n"; }else{ cout << "10 is not in the set\n"; } auto it = s.find(20); if(it != s.end()){ cout << "Found: " << *it << nline; } s.clear(); print(s); } void test2(){ set<Person> stooges{ {"Terry", 1}, {"Justin", 2}, {"Andreas", 3} }; print(stooges); stooges.emplace("James", 5); print(stooges); stooges.emplace("Jyrki", 5); print(stooges); auto it = stooges.find(Person{"Justin", 2}); if (it != stooges.end()) { stooges.erase(it); } print(stooges); it = stooges.find(Person{"XXXX", 5}); if (it != stooges.end()) { stooges.erase(it); } print(stooges); } void test3(){ set<string> s {"A", "B", "C"}; print(s); auto result = s.insert("D"); print(s); cout << boolalpha; cout << "First: " << *(result).first << nline; cout << "Second: " << result.second << nline; result = s.insert("A"); print(s); cout<< boolalpha; cout << "First: " << *(result).first << nline; cout << "Second: " << result.second << nline; } int main(int argc, const char * argv[]) { // insert code here... test1(); test2(); test3(); return 0; }
true
52f2d74e4388dfe8e43331d55fd2b00fbd52b19a
C++
ChangguHan/studyAlgorithm
/ETC/BJ-11328.cpp
UTF-8
807
3.21875
3
[]
no_license
// 개수만 비교하면 될듯 #include <iostream> #include <string> using namespace std; int alpha1[26]; int alpha2[26]; int main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; while(n--) { fill(alpha1, alpha1+26, 0); fill(alpha2, alpha2+26, 0); string a, b; cin >> a >> b; for (int i=0; i<a.size(); i++) { alpha1[a[i]-'a']++; } for (int i=0; i<b.size(); i++) { alpha2[b[i]-'a']++; } bool sw = false; for (int i=0; i<26; i++) { if(alpha1[i] != alpha2[i]) { sw = true; break; } } if(sw) cout << "Impossible" << '\n'; else cout << "Possible" << '\n'; } return 0; }
true