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
702c0d74f3320db3fe58031088c14635c2abd9c2
C++
kbergerstock/myProjects
/projects.c/WSRC32/WBASE32/cDIALOG32.CPP
UTF-8
2,089
2.640625
3
[]
no_license
//******************************************************************* // // FILE: cDIALOG.CPP // // AUTHOR: Keith R. Bergerstock // // PROJECT: wbase32 // // COMPONENT: DIALOGBOX // // DATE: 29.07.2004 // // COMMENTS: - modal dialog box base class // // //******************************************************************* #pragma warning (disable:4786) // Includes #include "cDIALOG32.h" // storage to a dialog box pointer that will be used to call the active dialog box handler static pDIALOGBOX pDialogBox = 0; // routine passed to the dialog box creation function to handle the dialog messages BOOL FAR PASCAL MainDlgProc(HWND hDlg, UINT msg, WPARAM wparam, LPARAM lparam) { // if a WM_INITDIALOG - make sure that the doalog object knows it's handle if(msg == WM_INITDIALOG ) { pDialogBox->set_handle(hDlg); } return pDialogBox->DlgProc(hDlg,msg,wparam,lparam); } // constructor = sores hinst cDIALOGBOX::cDIALOGBOX(HINSTANCE hinst) { hInstance = hinst; } // destructor cDIALOGBOX::~cDIALOGBOX() { } // store the handle to the dialog box void cDIALOGBOX::set_handle(HWND hdlg) { hDlgWin = hdlg; } // ok this is the guts of a modal dialog base class void cDIALOGBOX::Display(HWND hwnd, LPCWSTR lpszTemplate) { // store the handle to the parent window hParent = hwnd; // save the contents of the dialog box pointer parent = pDialogBox; // set the diaplog box point to this object pDialogBox = this; // create a modal dialog box int isOk = DialogBox(hInstance,lpszTemplate,hwnd, MainDlgProc ); // error trap return value if( isOk == -1) { MessageBox(hwnd,_T("Unable to show box"),_T("ITS WRONG"),MB_OK); } // reset the dialog box pointer to previous setting pDialogBox = parent; // if it was an active box - ie parent != 0 then reset the focus to that box if(parent) { SetFocus(parent->hDlgWin); } }
true
ffefadbc961eed312a2bed9fecd5c56b26bc59cd
C++
WhiZTiM/coliru
/Archive2/19/9fc3048002f9eb/main.cpp
UTF-8
429
3.5
4
[]
no_license
#include <iostream> class foo { public: foo() { std::cout << "default" << std::endl; } foo(const foo &) { std::cout << "copy" << std::endl; } foo(foo &&) { std::cout << "move" << std::endl; } }; foo f1() { foo f; return f; } foo f2() { foo f; return std::move(f); } int main() { foo foo1 = f1(); std::cout << "---" << std::endl; foo foo2 = f2(); std::cout << "===" << std::endl; }
true
a3ee7a369adff8997c7c0709e537516c0d01535d
C++
wy0705/untitled4
/main.cpp
UTF-8
410
2.78125
3
[]
no_license
#include <iostream> #include<stdio.h> #include<stdlib.h> #include "string.h" void move(char *str,int n){ char temp; int i; temp=str[n-1]; for ( i = n-1; i >0 ; i--) { str[i]=str[i-1]; } str[0]=temp; } int main() { char s[50]; int n,i,z; scanf("%d,%s",&n,s); z=strlen(s); for (i = 0; i <=n ; ++i) { move(s,z); } printf("%s\n",s); return 0; }
true
bec15cc3ddcc2f3995174dce076a1b2e1ff2e132
C++
Chan124a/leetcode-problems
/69. x 的平方根.cpp
UTF-8
958
2.984375
3
[]
no_license
#include <stack> #include <string> #include <iostream> #include <assert.h> #include <vector> #include <sstream> #include <cctype> #include <algorithm> #include <climits> #include <queue> #include <unordered_set> #include <unordered_map> using namespace std; class Solution { public: int mySqrt(int x) { if (x == 0)return 0; if (x < 4)return 1; int left = 0, right = x/2; while (left<right) { int mid = (left + right) / 2; if ((long long)mid * mid < x)left = mid+1; else right = mid; } if ((long long)left * left > x)return left - 1; else return left; } }; int stringToInteger(string input) { return stoi(input); } int main() { string line; while (getline(cin, line)) { int x = stringToInteger(line); int ret = Solution().mySqrt(x); string out = to_string(ret); cout << out << endl; } return 0; }
true
12e1973e72b76ae2fe363ce0d60b1a2f4039ebc9
C++
AlexAndDad/gateway
/libs/minecraft/nbt.hpp
UTF-8
1,754
2.703125
3
[]
no_license
#pragma once #include "minecraft/nbt/nbt_end.hpp" #include "minecraft/nbt/tags.hpp" #include "minecraft/net.hpp" #include <stack> #include <variant> namespace minecraft::nbt { using value_variant = std::variant< nbt::nbt_end >; struct value { explicit value(nbt::nbt_end val = {}) : value_(val) { } bool operator==(value const &other) const; value_variant & as_variant() { return value_; } value_variant const &as_variant() const { return value_; } template < class T > value &assign(T &&x) { value_ = std::forward< T >(x); return *this; } auto operator=(nbt_end arg) -> value & { return assign(std::move(arg)); } value_variant value_; }; std::ostream &operator<<(std::ostream &os, value const &arg); template < class Iter > Iter encode(value const &arg, Iter iter); template < class Iter > Iter parse(Iter first, Iter last, value &arg, error_code &ec); WISE_ENUM_CLASS((endian, std::uint8_t), (big, 0), (little, 1)); struct endian_stack { void push(endian e) { stack_.push(e); } void pop() { stack_.pop(); } endian query() const { if (stack_.empty()) return endian::big; else return stack_.top(); } static thread_local std::stack< endian > stack_; }; struct set_endian : private endian_stack { set_endian(endian e) { push(e); } set_endian(endian const&) = delete; set_endian& operator=(endian const&) = delete; ~set_endian() { pop(); } }; } // namespace minecraft::nbt #include "minecraft/nbt.ipp"
true
a9c5b151e1fbcd57f15403740d30fb30c6975efe
C++
sim2908/ES-SS19
/Task2/dimmLED/dimmLED.ino
UTF-8
1,015
2.578125
3
[]
no_license
#include <DueTimer.h> const uint8_t led_pin = 7; const uint8_t b1_pin = 3; const uint8_t b2_pin = 5; const int dimm_step = 50; volatile int led_state = LOW; volatile int debounced_button1_state = HIGH; volatile int debounced_button2_state = HIGH; int led_intensity = 255; int last_button1_state = HIGH; int last_button2_state = HIGH; DueTimer timer; void setup() { pinMode(b1_pin, INPUT_PULLUP); pinMode(b2_pin, INPUT_PULLUP); // ANALOG pinMode(led_pin, OUTPUT); if (timer.configure(100, debounceButtons)) { timer.start(); } } void loop() { updateIntesity(); analogWrite(led_pin, led_intensity); } void updateIntesity() { if (debounced_button1_state == LOW && last_button1_state == HIGH) { led_intensity = min(led_intensity + dimm_step, 255); } last_button1_state = debounced_button1_state; if (debounced_button2_state == LOW && last_button2_state == HIGH) { led_intensity = max(led_intensity - dimm_step, 0); } last_button2_state = debounced_button2_state; }
true
de5df0c866c6f683ea6d2534d100db00a2c86507
C++
endymioncheung/CarND-Path-Planning-Project
/src/classifier.h
UTF-8
812
2.671875
3
[ "MIT" ]
permissive
#ifndef CLASSIFIER_H #define CLASSIFIER_H #include <string> #include <vector> #include "Eigen-3.3/Eigen/Dense" using Eigen::ArrayXd; using std::string; using std::vector; class GNB { public: /** * Constructor */ GNB(); /** * Destructor */ virtual ~GNB(); /** * Train classifier */ void train(const vector<vector<double>> &data, const vector<string> &labels); /** * Predict with trained classifier */ string predict(const vector<double> &sample); vector<string> possible_labels = {"left","keep","right"}; ArrayXd left_means; ArrayXd left_std_dev; double left_prior; ArrayXd keep_means; ArrayXd keep_std_dev; double keep_prior; ArrayXd right_means; ArrayXd right_std_dev; double right_prior; }; #endif // CLASSIFIER_H
true
4a9c2be3d954e2bb588521facf96450a508f10b2
C++
choi-william/digital-pathology-old
/src/library/MSLeoGrady/x64_mex/qpbo_mex.cpp
UTF-8
3,937
2.875
3
[]
no_license
#include "mex.h" #include "qpboint.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* Vlad's example code QPBO* q; q = new QPBO(2, 1); // max number of nodes & edges q->AddNode(2); // add two nodes q->AddUnaryTerm(0, 0, 2); // add term 2*x q->AddUnaryTerm(1, 3, 6); // add term 3*(y+1) q->AddPairwiseTerm(0, 1, 2, 3, 4, 6); // add term (x+1)*(y+2) q->Solve(); q->ComputeWeakPersistencies(); int x = q->GetLabel(0); int y = q->GetLabel(1); mexPrintf("Solution: x=%d, y=%d\n", x, y); return; */ // first read in input arguments if(nrhs != 2 && nrhs != 3) mexErrMsgTxt("Requires either two or three input parameters: see 'help qpbo' for usage!!!\n"); if(nlhs != 1) mexErrMsgTxt("Only allows one output parameter: see 'help qpbo' for usage!!!\n"); int numEdges = mxGetM(prhs[0]); int weightsPerEdge = mxGetN(prhs[1]); bool unaryTerm; if(numEdges < 1) mexErrMsgTxt("Must have at least one edge: see 'help qpbo' for usage!!!\n"); if(mxGetN(prhs[0])!=2) mexErrMsgTxt("Edge list must connect exactly two nodes: see 'help qpbo' for usage!!!\n"); if(mxGetM(prhs[1]) != numEdges) mexErrMsgTxt("Each edge must have a weight: see 'help qpbo' for usage!!!\n"); if(weightsPerEdge != 1 && weightsPerEdge != 4) mexErrMsgTxt("Weight matrix can only have either 1 or 4 columns: see 'help qpbo' for usage!!!\n"); //// prepare input and output variables double *pEdgeList; double *pWeights; double *pNodeLabels; double *pUnaryTerms; // inputs pEdgeList = mxGetPr(prhs[0]); pWeights = mxGetPr(prhs[1]); // first determine the number of nodes int numNodes = 0; int temp; for(int i=0;i<2*numEdges;i++) { temp = int(pEdgeList[i]); if(temp > numNodes) numNodes = temp; } if(nrhs == 3) { unaryTerm = true; if(mxGetM(prhs[2]) != numNodes && mxGetN(prhs[2]) != 2) mexErrMsgTxt("Unary term matrix must be of size numNodes x 2: see 'help qpbo' for usage!!!\n"); } else unaryTerm = false; if(unaryTerm) pUnaryTerms = mxGetPr(prhs[2]); if(numNodes <= 1) mexErrMsgTxt("Edge list must imply at least 2 nodes: see 'help qpbo' for usage!!!\n"); // outputs plhs[0] = mxCreateDoubleMatrix(numNodes,1,mxREAL); pNodeLabels = mxGetPr(plhs[0]); //// perform computation QPBO* q; q = new QPBO(numNodes,numEdges); // max number of nodes & edges q->AddNode(numNodes); //// prepare pairwise terms //(in case with weight matrix (per edge) is a multiple of identity matrix) if(weightsPerEdge == 1) { if(unaryTerm) for(int i=0;i<numNodes;i++) { q->AddUnaryTerm(i,int(pUnaryTerms[i]),int(pUnaryTerms[i+numNodes])); } for(int i=0;i<numEdges;i++) { q->AddPairwiseTerm(pEdgeList[i]-1,pEdgeList[i+numEdges]-1, 0, pWeights[i], pWeights[i] , 0); } } //(in case with weight matrix is arbitrary) if(weightsPerEdge == 4) { if(unaryTerm) for(int i=0;i<numNodes;i++) { q->AddUnaryTerm(i,int(pUnaryTerms[i]),int(pUnaryTerms[i+numNodes])); } for(int i=0;i<numEdges;i++) { q->AddPairwiseTerm(pEdgeList[i]-1,pEdgeList[i+numEdges]-1, pWeights[i], pWeights[i+numEdges*1], pWeights[i+numEdges*2] , pWeights[i+numEdges*3]); } } q->Solve(); q->ComputeWeakPersistencies(); for(int j=0;j<numNodes;j++) { pNodeLabels[j] = q->GetLabel(j); } delete q; }
true
d765a7bdab0fa977964a81d1174bee96743dbfc9
C++
SergioRAgostinho/PoseCNN
/lib/kinect_fusion/src/util/args.cpp
UTF-8
4,300
2.78125
3
[ "MIT" ]
permissive
#include <df/util/args.h> #include <getopt.h> #include <cstring> #include <limits> #include <set> #include <stdexcept> #include <iostream> namespace df { void OptParse::registerOptionGeneric(const std::string flag, void * valuePtr, const unsigned char shorthand, const bool required, const ArgType type) { flags_.push_back(flag); valuePtrs_.push_back(valuePtr); shorthands_.push_back(shorthand); requireds_.push_back(required); types_.push_back(type); } void OptParse::registerOption(const std::string flag, std::string & value, const unsigned char shorthand, const bool required) { registerOptionGeneric(flag,&value,shorthand,required,String); } void OptParse::registerOption(const std::string flag, int & value, const unsigned char shorthand, const bool required) { registerOptionGeneric(flag,&value,shorthand,required,Integral); } void OptParse::registerOption(const std::string flag, float & value, const unsigned char shorthand, const bool required) { registerOptionGeneric(flag,&value,shorthand,required,FloatingPoint); } void OptParse::registerOption(const std::string flag, bool & value, const unsigned char shorthand, const bool required) { registerOptionGeneric(flag,&value,shorthand,required,Boolean); } int OptParse::parseOptions(int & argc, char * * & argv) { const std::size_t nArgs = flags_.size(); if (nArgs >= std::numeric_limits<unsigned char>::max()) { throw std::runtime_error("too many arguments"); } std::vector<struct option> options(nArgs+1); std::string shorthandString = ""; std::set<unsigned char> usedShorthands; for (std::size_t i = 0; i < nArgs; ++i) { const unsigned char shorthand = shorthands_[i]; if (shorthands_[i] < std::numeric_limits<unsigned char>::max()) { // check to make sure shorthand has not been taken if (usedShorthands.find(shorthands_[i]) != usedShorthands.end()) { throw std::runtime_error("the shorthand " + std::to_string(shorthand) + " was used more than once"); } shorthandString.append( { shorthand } ); if (types_[i] != Boolean) { shorthandString.append({':'}); } } options[i].name = flags_[i].c_str(); options[i].has_arg = types_[i] == Boolean ? no_argument : required_argument; options[i].flag = nullptr; options[i].val = shorthand; } std::memset(&options.back(),0,sizeof(struct option)); // assign unused values to flags with no shorthand int nextShorthand = 0; for (std::size_t i = 0; i < nArgs; ++i) { if (shorthands_[i] == std::numeric_limits<unsigned char>::max()) { while (usedShorthands.find(nextShorthand) != usedShorthands.end()) { nextShorthand++; } shorthands_[i] = nextShorthand; options[i].val = shorthands_[i]; ++nextShorthand; } } int c; while (true) { int optionIndex = 0; c = getopt_long(argc,argv,shorthandString.c_str(),options.data(),&optionIndex); if (c == -1) { break; } std::size_t i; for (i = 0; i < nArgs; ++i) { if (shorthands_[i] == c) { switch (types_[i]) { case Integral: *reinterpret_cast<int *>(valuePtrs_[i]) = atoi(optarg); break; case FloatingPoint: *reinterpret_cast<float *>(valuePtrs_[i]) = atof(optarg); break; case Boolean: *reinterpret_cast<bool *>(valuePtrs_[i]) = true; break; case String: *reinterpret_cast<std::string *>(valuePtrs_[i]) = std::string(optarg); break; } requireds_[i] = false; break; } } if (i == nArgs) { throw std::runtime_error("unrecognized argument"); } } for (std::size_t i = 0; i < nArgs; ++i) { if (requireds_[i]) { throw std::runtime_error("did not find required argument '" + flags_[i] + "'"); } } return optind; } } // namespace df
true
876dab912faf3c9ee3b4c200f046e098045602b3
C++
ivanovskii/UniversityTasks
/AllTasks/SubstringSearching/Brute Force algorithm.cpp
UTF-8
756
3.359375
3
[]
no_license
#include <iostream> #include <vector> std::vector<size_t> naiveStringMatcher(const std::string& haystack, const std::string& needle) { std::vector<size_t> res; for (size_t i = 0; i <= haystack.size() - needle.size(); ++i) { bool success = true; for (size_t j = 0; j < needle.size(); ++j) { if (needle[j] != haystack[i + j]) { success = false; break; } if (success) { res.push_back(i); break; } } } return res; } int main() { auto matches = naiveStringMatcher("abracadabr", "r"); for (const auto& elem : matches) std::cout << elem << " "; system("pause"); }
true
cdfef471c3ee12bd6be78b1d3893b17b5bd3df61
C++
yogeesh/AdvCpp_Project02
/src/reporter.h
UTF-8
857
3
3
[]
no_license
#ifndef PROJECT1_REPORTER_H #define PROJECT1_REPORTER_H #include "hero.h" /** * All Reporters are basically Hero's */ class Reporter : public Hero{ public: /** * create new reporter * @param id : reporter actor id */ Reporter(unsigned int id); /** * Destructor for Reporter */ ~Reporter(); /** * message for reporter victory over other actor * @param other : opponent actor * @return : message for victory */ virtual std::string victory(const Actor &other) const; /** * message for reporter defeat over other actor * @param other : opponent actor * @return : message for defeat */ virtual std::string defeat(const Actor &other) const; // base name for all reporters static const std::string NAME; private: }; #endif //PROJECT1_REPORTER_H
true
cd6bd331a9c1d65376da85768593147a45b0329d
C++
Tonghua-Li/ChineseChess
/AppLib/ChessBoard.h
UTF-8
1,196
2.53125
3
[ "MIT" ]
permissive
#ifndef CHESSBOARD_H #define CHESSBOARD_H #include "ChessPiece.h" #include "IBoard.h" #include "Shuai.h" #include <QObject> class ChessBoard : public QObject, public IBoard { Q_OBJECT public: explicit ChessBoard(QObject *parent = nullptr); ~ChessBoard(); void reset(); QList<ChessPiece *> chessPieces() const; void nextPlayer(); bool canSelect(ChessPiece *piece) const; void select(ChessPiece *piece); bool isAttack(ChessPiece *piece) const; void attack(ChessPiece *a, ChessPiece *b); Player getWinner() const; Player getActivePlayer() const; Player getPlayer(int x, int y) const; bool isShuai(int x, int y) const; bool isCrossRiver(Player player, int y) const; void moveSelectedTo(const QPoint &pos); ChessPiece *getSelected() const; void onPieceClicked(ChessPiece *piece); int getPieceId(int x, int y) const; bool isInsidePalace(Player player,int x, int y) const; signals: void chessPiecesChanged(); public slots: private: ChessPiece *getPiece(int x, int y) const; QList<ChessPiece *> _chessPieces; Player _activePlayer; Shuai *_blackShuai; Shuai *_redShuai; }; #endif // CHESSBOARD_H
true
bd44a9218700426bc0755ae592c5785e03154115
C++
dangdang1250/LearnCPP
/DesignPattern/DesignPattern/DesignPattern/Pizza.cpp
UTF-8
393
2.796875
3
[]
no_license
#include "Pizza.h" #include <iostream> #include <string> void Pizza::prepare() { std::cout << topping + " Preparing Pizza!" << std::endl; } void Pizza::bake() { std::cout << topping + " Baking!" << std::endl; } void Pizza::cut() { std::cout << topping + " Cutting!" << std::endl; } void Pizza::box() { std::cout << topping + " Boxing, it's ready." << std::endl; } Pizza::~Pizza() { }
true
ff63985ec7206f8b0cc701457f7e85b22e6dace1
C++
btcup/sb-admin
/exams/2558/02204111/1/final/3_2_839_5420501333.cpp
UTF-8
336
2.59375
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; int main () { int i,j,m,n ; cout<<"Enter matrix size:" ; cin >>n; int B[n][n] ; cout<<"Enter matrix values:" ; for (i=0;i<n;i++) { for (j=0;j<n;j++) cin>>B[i][j]; } for (i=0;i<m;i++) { cout <<B[i][j]; cout<<endl; } system ("pause") ; return 0; }
true
c6585befe05c12eccb2c9597a65410b2147ebc03
C++
psenzee/senzee5
/blog/optimization/primes_senzee_multicore.cpp
UTF-8
7,449
2.8125
3
[]
no_license
/** * Primes_Senzee_MultiCore is an optimized brute force (Sieve of Eratosthenes) implementation of the prime counting problem. It uses no dynamically allocated memory and approximately 90k * # threads of stack. A release build of this implementation enumerates and counts the primes from 2 to 2**32-1 (4294967295) in ~7.15s on my dual core development machine. (c) 2006-2007 Paul D. Senzee Senzee 5 http://senzee.blogspot.com */ unsigned long Primes_Senzee_MultiCore(unsigned long lo, unsigned long hi); //// Implementation //// #include <string.h> #define _WIN32_WINNT 0x0500 #include <windows.h> namespace { __forceinline void _setnthbits(unsigned long start, unsigned long sz, unsigned long n, unsigned char *array); unsigned long _simpleeratosthenes(unsigned long *primes, unsigned long limit, unsigned char *array); void _populatebitcounts(unsigned char *bitcounts); unsigned long _countzerobits(const unsigned char *array, unsigned long size, const unsigned char *bitcounts); unsigned long _countprimes(unsigned long lo, unsigned long hi, const unsigned long *primes, unsigned char *array, const unsigned char *bitcounts); DWORD __stdcall _primethread(void *arg); unsigned long _isqrt(unsigned long x); struct arguments_t { unsigned long lo, hi, result; const unsigned char *counts; unsigned char *array; const unsigned long *primes; arguments_t(unsigned long lo = 0, unsigned long hi = 0, const unsigned char *counts = 0, unsigned char *array = 0, const unsigned long *primes = 0) : lo(lo), hi(hi), counts(counts), array(array), primes(primes), result(0) {} }; } /** * Primes_Senzee_MultiCore is an optimized brute force (Sieve of Eratosthenes) implementation of the prime counting problem. It uses no dynamically allocated memory and approximately 90k * thread count of stack. A release build of this implementation enumerates and counts the primes from 2 to 2**32-1 (4294967295) in ~7.15s on my dual core development machine. */ unsigned long Primes_Senzee_MultiCore(unsigned long lo, unsigned long hi) { enum { THREAD_COUNT = 2, NO_THREAD_THRESHOLD = 1 << 22 }; // used a binary search timing algorithm to find the optimal-ish NO_THREAD_THRESHOLD const unsigned long RANGE = 1024 * 1024, PRIME_COUNT = 6541; // RANGE = 1m numbers at a time; PRIME_COUNT = number of primes less than 65536 unsigned char counts[256], array[THREAD_COUNT][RANGE / 16 + 1]; unsigned long primes[PRIME_COUNT + 1], count = 0, mid = 0, r = 0; _simpleeratosthenes(primes, _isqrt(hi) + 1, array[0]); _populatebitcounts(counts); if (hi - lo <= NO_THREAD_THRESHOLD) { arguments_t arg(lo, hi, counts, array[0], primes); _primethread(&arg); r = arg.result; } else { for (int i = 1; i < THREAD_COUNT; i++) memcpy(array[i], array[0], sizeof(array[0])); arguments_t arg[THREAD_COUNT]; unsigned long delta = (hi - lo) / THREAD_COUNT; for (int i = 0; i < THREAD_COUNT; i++) arg[i] = arguments_t(lo + delta * i, i == THREAD_COUNT - 1 ? hi : lo + delta * (i + 1) - 1, counts, array[i], primes); HANDLE threads[THREAD_COUNT]; for (int i = 0; i < THREAD_COUNT; i++) { threads[i] = ::CreateThread(NULL, 0, _primethread, &arg[i], CREATE_SUSPENDED, NULL); ::SetThreadIdealProcessor(threads[i], i); ::SetPriorityClass(threads[i], REALTIME_PRIORITY_CLASS); ::SetThreadPriority(threads[i], THREAD_PRIORITY_TIME_CRITICAL); ::ResumeThread(threads[i]); } ::WaitForMultipleObjects(THREAD_COUNT, threads, true, INFINITE); for (int i = 0; i < THREAD_COUNT; i++) r += arg[i].result; } return r; } namespace { DWORD __stdcall _primethread(void *p) { arguments_t *arg = (arguments_t *)p; enum { RANGE = 1024 * 1024 }; unsigned count = 0, mid = 0, lo = arg->lo, hi = arg->hi; if (lo < 3) { lo = 3; count = 1; } mid = lo + RANGE; // calculate the primes in a given window, RANGE numbers at a time while (true) { if (mid > hi || mid < RANGE /** rolled over.. */) mid = hi; count += _countprimes(lo, mid, arg->primes, arg->array, arg->counts); if (mid == hi) break; lo = mid + 1; mid += RANGE; } arg->result = count; return 0; } __forceinline void _setnthbits(unsigned long start, unsigned long sz, unsigned long n, unsigned char *array) { //for (unsigned long i = start; i < sz; i += n) // array[i >> 3] |= 1 << (i & 7); __asm { mov esi, start mov edi, sz cmp esi, edi jae done mov eax, n mov ebx, array repeat: mov ecx, esi mov edx, 1 and ecx, 7 shl edx, cl mov ecx, esi shr ecx, 3 add ecx, ebx add esi, eax or [ecx], dl cmp esi, edi jb repeat done: } } unsigned long _isqrt(unsigned long x) { unsigned long a = 1, b = (x >> 5) + 8, m = 0; if (b > 65535) b = 65535; do { m = (a + b) >> 1; if (m * m > x) b = m - 1; else a = m + 1; } while (b >= a); return a - 1; } unsigned long _simpleeratosthenes(unsigned long *primes, unsigned long limit, unsigned char *array) { memset(array, 0, limit); unsigned long szq = _isqrt(limit); for (unsigned long i = 3; i <= szq; i += 2) for (unsigned long j = i + i; j < limit; j += i) array[j] = 1; unsigned long c = 0; for (unsigned long i = 3; i < limit; i += 2) if (!array[i]) primes[c++] = i; primes[c] = 0; return c; } void _populatebitcounts(unsigned char *bitcounts) { const unsigned char bits[4] = { 0, 1, 1, 2 }; for (unsigned int i = 0; i < 256; i++) bitcounts[i] = bits[i >> 6] + bits[(i >> 4) & 3] + bits[(i >> 2) & 3] + bits[i & 3]; } unsigned long _countzerobits(const unsigned char *array, unsigned long size, const unsigned char *bitcounts) { unsigned long count = 0; for (unsigned long i = 0; i < size; i++) count += bitcounts[(unsigned char)~array[i]]; return count; } unsigned long _countprimes(unsigned long lo, unsigned long hi, const unsigned long *primes, unsigned char *array, const unsigned char *bitcounts) { if (!(lo & 1)) lo++; if (!(hi & 1)) hi--; const unsigned long sz = hi - lo + 1, asz = (sz + 15) >> 4, innersz = (sz + 1) >> 1; unsigned long szq = _isqrt(hi) + 1; memset(array, 0, asz); unsigned char fbits = (unsigned char)((asz << 4) - sz) >> 1; // mark the end bits (representing numbers > hi) in the byte as non-prime array[asz - 1] |= ((1 << (fbits + 1)) - 1) << (8 - fbits); unsigned long i = 0, of = 0, j = 0; // populate while ((i = *primes) && *primes <= szq) { if (i >= lo) j = i + i + i; else { j = (lo + (i - 1)) / i * i; if (!(j & 1)) j += i; } j = (j - lo) >> 1; _setnthbits(j, innersz, i, array); primes++; } return _countzerobits(array, asz, bitcounts); // count } }
true
d5ebacf09015281289013f6aa52b194642cf2c9f
C++
ToLoveToFeel/LeetCode
/Cplusplus/_0000_study/_leetcode/_swordoffer/_005_replaceSpace/_swordoffer_05_main.cpp
UTF-8
403
3.296875
3
[]
no_license
// Created by WXX on 2021/7/18 14:28 #include <iostream> using namespace std; class Solution { public: string replaceSpace(string s) { string res = ""; for (auto c : s) if (c == ' ') res += "%20"; else res += c; return res; } }; int main() { cout << Solution().replaceSpace("We are happy.") << endl; // We%20are%20happy. return 0; }
true
3938a56fc7685c3801a9c2aa3746d5468adca650
C++
alex4814/algo-solution
/usaco/ch2/2.3/cow-pedigrees.cc
UTF-8
1,168
2.5625
3
[]
no_license
/* ID: alex4814 LANG: C++ TASK: nocows */ #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; #define EPS 1e-8 #define MAXN 205 #define MAXK 105 #define MOD 9901 typedef pair<int, int> pii; typedef long long ll; #define FILEIO int f[MAXN][MAXK]; bool gt(int n, int k) { int r = 1; for (int i = 0; i < k; ++i) { r <<= 1; if (r > n) return false; } return true; } int cal(int n, int k) { if (f[n][k] != -1) return f[n][k]; if (n == 1) return f[n][k] = (k == 1 ? 1 : 0); int ret = 0; for (int l = 1; l < n; l += 2) { int r = n - 1 - l; for (int h = 0; h < k - 1; ++h) { ret = (ret + cal(l, k - 1) * cal(r, h)) % MOD; ret = (ret + cal(r, k - 1) * cal(l, h)) % MOD; } ret = (ret + cal(l, k - 1) * cal(r, k - 1)) % MOD; } return f[n][k] = ret; } int main() { #ifdef FILEIO freopen("nocows.in", "r", stdin); freopen("nocows.out", "w", stdout); #endif int n, k; scanf("%d %d", &n, &k); if (!(n & 1) || gt(n, k)) { printf("0\n"); } else { memset(f, -1, sizeof(f)); printf("%d\n", cal(n, k)); } return 0; }
true
19435fe6b4dc5245e93040facbf70f86c990552c
C++
z-Endeavor/PAT
/Advanced Level/1012 The Best Rank(部分正确).cpp
UTF-8
1,939
2.75
3
[]
no_license
#include <bits/stdc++.h> using namespace std; struct student{ int id; int cGrade; int mGrade; int eGrade; int aGrade; int cRank; int mRank; int eRank; int aRank; }stus[2005]; int main(){ int N, M, stuID[2005], flag = 0; cin>>N>>M; for (int i=0; i<N; i++) { cin>>stus[i].id>>stus[i].cGrade>>stus[i].mGrade>>stus[i].eGrade; stus[i].aGrade = (stus[i].cGrade + stus[i].mGrade + stus[i].eGrade) / 3; } for (int i=0; i<N-1; i++) { for (int j=0; j<N-1-i; j++) { if (stus[j].aGrade < stus[j+1].aGrade) swap(stus[j], stus[j+1]); if (j+1 == N-1-i) stus[j+1].aRank = N-i; } if (i == N-2) stus[0].aRank = 1; } for (int i=0; i<N; i++) { for (int j=i+1; j<N; j++) { if (stus[i].cGrade < stus[j].cGrade) swap(stus[i], stus[j]); } stus[i].cRank = i+1; } for (int i=0; i<N-1; i++) { for(int j=0; j<N-1-i; j++) { if (stus[j].mGrade < stus[j+1].mGrade) swap(stus[j], stus[j+1]); if (j+1 == N-1-i) stus[j+1].mRank = N-i; } if (i == N-2) stus[0].mRank = 1; } for (int i=0; i<N; i++) { for (int j=i+1; j<N; j++) { if (stus[i].eGrade < stus[j].eGrade) swap(stus[i], stus[j]); } stus[i].eRank = i+1; } for (int i=0; i<M; i++) { cin>>stuID[i]; } for (int i=0; i<M; i++) { flag = 0; for(int j=0; j<N; j++) { if (stus[j].id == stuID[i]) { if (stus[j].aRank <= stus[j].cRank && stus[j].aRank <= stus[j].mRank && stus[j].aRank <= stus[j].eRank) cout<<stus[j].aRank<<" A"<<endl; else if (stus[j].cRank < stus[j].aRank && stus[j].cRank <= stus[j].mRank && stus[j].cRank <= stus[j].eRank) cout<<stus[j].cRank<<" C"<<endl; else if (stus[j].mRank < stus[j].aRank && stus[j].mRank < stus[j].cRank && stus[j].mRank <= stus[j].eRank) cout<<stus[j].mRank<<" M"<<endl; else if (stus[j].eRank < stus[j].aRank && stus[j].eRank < stus[j].cRank && stus[j].eRank < stus[j].mRank) cout<<stus[j].eRank<<" E"<<endl; flag = 1; } } if (!flag) cout<<"N/A"<<endl; } return 0; }
true
f9bd81429eed7a93705152280da6e5377461d7d8
C++
Pendulun/SistemaDeProvas
/src/persistence/DAO/UsuarioDAOJSON.cpp
UTF-8
5,244
2.953125
3
[]
no_license
#include <business/Modelo/professor.hpp> #include <business/Modelo/aluno.hpp> #include "persistence/DAO/UsuarioDAOJSON.hpp" namespace Persistence{ UsuarioDAOJSON::~UsuarioDAOJSON(){ delete jsonObject; } std::string UsuarioDAOJSON::ARQUIVO_USUARIOS = "usuarios.json"; UsuarioDAOJSON::UsuarioDAOJSON() { jsonObject = new JSONObject(ARQUIVO_USUARIOS); checkMaxId(); } int UsuarioDAOJSON::cadastrar(Modelo::Usuario usuario) { int maxId = getMaxId()+ 1; usuario.setId(maxId); if (loginExiste(usuario.getLogin()) ) throw std::invalid_argument( "Login já existe" ); atualizarRegistro(usuario); setMaxId(usuario.getId()); jsonObject->salvarNoArquivo(ARQUIVO_USUARIOS); return usuario.getId(); } bool UsuarioDAOJSON::loginExiste(std::string login) { std::vector<std::string> Path = { login }; auto user = jsonObject->getObjectPropertyByPath(Path); bool existe = user == nullptr; return !(existe); } Modelo::Usuario* UsuarioDAOJSON::login(std::string login, std::string senha) { std::vector<std::string> path = { login, "senha"}; auto senhaBanco = jsonObject->getStringPropertyByPath(path); if (senha == senhaBanco) return buscarUsuarioPeloLogin(login); return nullptr; } Modelo::Usuario* UsuarioDAOJSON::pesquisar(int id) { std::string key = jsonObject->pesquisar("id",id); if(key != "") { return buscarUsuarioPeloLogin(key); } else { return nullptr; } } std::list<Modelo::Usuario> UsuarioDAOJSON::pesquisar(const std::list<int> ids) { std::list<Modelo::Usuario> lista; for (int id : ids) { auto aux = pesquisar(id); if(aux != nullptr) { lista.push_back(*aux); } } return lista; } bool UsuarioDAOJSON::remover(Modelo::Usuario usuario) { if(loginExiste(usuario.getLogin())) { jsonObject->remover(usuario.getLogin()); jsonObject->salvarNoArquivo(ARQUIVO_USUARIOS); return true; } return false; } int UsuarioDAOJSON::getMaxId() { return jsonObject->getNumberPropertyByPath({"maxId"}); } void UsuarioDAOJSON::setMaxId(int maxId) { jsonObject->setIntPropertyByPath({"maxId"},maxId); } void UsuarioDAOJSON::checkMaxId() { try { jsonObject->getNumberPropertyByPath({"maxId"}); } catch (...) { jsonObject->setIntPropertyByPath({"maxId"},0); } } bool UsuarioDAOJSON::atualizar(Modelo::Usuario usuario) { if (!loginExiste(usuario.getLogin()) ) throw std::invalid_argument( "Usuário não existe" ); atualizarRegistro(usuario); jsonObject->salvarNoArquivo(ARQUIVO_USUARIOS); return true; } void UsuarioDAOJSON::atualizarRegistro(Modelo::Usuario usuario) { jsonObject->setStringPropertyByPath({usuario.getLogin(), "nome"},usuario.getNome()); jsonObject->setStringPropertyByPath({usuario.getLogin(), "login"},usuario.getLogin()); jsonObject->setStringPropertyByPath({usuario.getLogin(), "senha"},usuario.getSenha()); jsonObject->setIntPropertyByPath({usuario.getLogin(), "id"},usuario.getId()); jsonObject->setIntPropertyByPath({usuario.getLogin(), "tipoUsuario"},(int)usuario.getTipoUsuario()); std::list<int> turmas = usuario.getTurmas(); std::vector<int> turmasCadastrar(turmas.begin(),turmas.end()); jsonObject->setIntArrayPropertyByPath({usuario.getLogin(), "turmas"},turmasCadastrar); } bool UsuarioDAOJSON::cadastrarEmTurma(Modelo::Usuario usuario, int idTurma) { if(!loginExiste(usuario.getLogin())) { return false; } auto turmasUsuario = jsonObject->getIntArrayPropertyByPath({usuario.getLogin(),"turmas"}); turmasUsuario.push_back(idTurma); jsonObject->setIntArrayPropertyByPath({usuario.getLogin(),"turmas"},turmasUsuario); jsonObject->salvarNoArquivo(ARQUIVO_USUARIOS); return true; } Modelo::Usuario *UsuarioDAOJSON::buscarUsuarioPeloLogin(std::string key) { if(!loginExiste(key)) return nullptr; Modelo::Usuario* usuario; Modelo::TipoUsuario tipo = (Modelo::TipoUsuario)jsonObject->getNumberPropertyByPath({key, "tipoUsuario"}); if(tipo == Modelo::TipoUsuario::ALUNO) usuario = new Modelo::Professor; else usuario = new Modelo::Aluno; usuario->setNome(jsonObject->getStringPropertyByPath({key, "nome"})); usuario->setSenha(jsonObject->getStringPropertyByPath({key, "senha"})); usuario->setLogin(jsonObject->getStringPropertyByPath({key, "login"})); usuario->setId(jsonObject->getNumberPropertyByPath({key, "id"})); auto turmas = jsonObject->getIntArrayPropertyByPath({key, "turmas"}); std::list<int> turmasUsuario(turmas.begin(),turmas.end()); usuario->setTurmas(turmasUsuario); usuario->setTipoUsuario(tipo); return usuario; } }
true
32b209644cc051afcec1b05da4644cb538cb2f98
C++
art-lux/C17_stl_features
/C17_chapter3/C17_chapter3/using_validated_iter.cpp
UTF-8
293
2.578125
3
[]
no_license
#define _ITERATOR_DEBUG_LEVEL 2 // sanitizer feature #include <iostream> #include <vector> void using_validated_iter() { std::vector<int> v{ 1,2,3 }; v.shrink_to_fit(); const auto it(std::begin(v)); std::cout << *it << std::endl; v.push_back(123); //std::cout << *it << std::endl; }
true
2a0eb573012ec6f2a12fa307374304b476936d3b
C++
YuHao000/sign_objects_detection
/SignObjectsDetection/SignObjectsDetection/sources/thread_pool.cpp
UTF-8
771
2.9375
3
[]
no_license
#include "thread_pool.h" void Worker::AppendFunc(func_type fn) { std::unique_lock<std::mutex> locker(mMutex); mFqueue.push(fn); mCv.notify_one(); } size_t Worker::GetTaskCount() { std::unique_lock<std::mutex> locker(mMutex); return mFqueue.size(); } bool Worker::IsEmpty() { std::unique_lock<std::mutex> locker(mMutex); return mFqueue.empty(); } void Worker::ThreadFunc() { while (mEnabled) { std::unique_lock<std::mutex> locker(mMutex); mCv.wait(locker, [&]() { return !mFqueue.empty() || !mEnabled; }); while (!mFqueue.empty()) { func_type func = mFqueue.front(); locker.unlock(); func(); locker.lock(); mFqueue.pop(); } } }
true
399fdfc6e70e041caad9cbc6052da39367336e94
C++
Xumengqi0201/OJ
/Leetcode/001-100/005.cpp
UTF-8
2,714
3.796875
4
[]
no_license
/* Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb" */ /* 求字符串的最长回文子串 1.DP: if p[i][j] = 1, then s[i...j] is palindrome if p[i+1][j-1] = 1 && s[i] == s[j], then p[i][j] = 1 base: p[i][i] = 1; p[i][i+1] = 1 if s[i] = s[i+1]; */ class Solution { public: string longestPalindrome(string s) { if (s == "") return ""; bool **dp = new bool*[s.size()]; for (int i = 0; i < s.size(); i++){ dp[i] = new bool[s.size()]; memset(dp[i], 0, s.size()*sizeof(bool)); } for (int i = 0; i < s.size(); i++){ dp[i][i] = 1; } for (int i = 0; i < s.size()-1; i++){ dp[i][i+1] = (s[i] == s[i+1]); } //前面考虑了长度为1和2的回文串,下面从长度为3的开始考虑 for (int len = 3; len <= s.size(); len++){ for (int i = 0; i < s.size()-len+1; i++){ int j = i+len-1; if (dp[i+1][j-1] == 1 && s[i] == s[j]){ dp[i][j] = 1; } } } int maxlen = 0, start; for (int i = 0; i < s.size(); i++){ for(int j = i; j < s.size(); j++){ if (dp[i][j] == 1){ if (j-i+1 > maxlen){ maxlen = j-i+1; start = i; } } } } return s.substr(start, maxlen); } }; /* 2.中心扩散 O(N2) class Solution { public: string longestPalindrome(string s) { if (s == "") return ""; int maxlen = 0, start = 0; for (int i = 0; i < s.size(); i++) { //每次扩散有两种方法,以i为中心或者以i,i+1为中心 int l1 = center(s, i, i); int l2 = center(s, i ,i+1); int len1 = 2*(i-l1)+1; int len2 = 2*(i-l2)+2; if (maxlen < len1){ maxlen = len1; start = l1; } if (maxlen < len2){ maxlen = len2; start = l2; } } return s.substr(start, maxlen); } int center(const string &s, int left, int right){ while(left >= 0 && right < s.size() && s[left] == s[right]) { left--; right++; } return left+1; } }; */
true
fa1aa3dfac5860a351306dff1509606565507207
C++
koneu/Stereokamera
/Menue.h
UTF-8
1,649
2.640625
3
[]
no_license
#pragma once #include <iostream> #include <sstream> class Menue { public: Menue(void); ~Menue(void); static void Menue::printMenueEntry(int userEntry, const char* description, int value, const char* end=""); static void Menue::printMenueEntry(int userEntry, const char* description, float value, const char* end=""); static void Menue::printMenueEntry(int userEntry, const char* description, const char* value, const char* end=""); static void Menue::printMenueEntry(int userEntry, const char* description); static void Menue::printMenueEntryMid(int userEntry, const char* description, int value, const char* end=""); static void Menue::printMenueEntryMid(int userEntry, const char* description, float value, const char* end=""); static void Menue::printMenueEntryMid(int userEntry, const char* description, const char* value, const char* end=""); static void Menue::printMenueEntryMid(int userEntry, const char* description); static void Menue::printMenueEntrySmall(int userEntry, const char* description, int value, const char* end=""); static void Menue::printMenueEntrySmall(int userEntry, const char* description, const char* value, const char* end=""); static void Menue::printMenueEntrySmall(int userEntry, const char* description); static void Menue::printOutput(const char* description, int value, const char* end=""); static void Menue::printOutput(const char* description, const char* value, const char* end=""); static void Menue::readValue(float* changedVar); static void Menue::readValue(double* changedVar); static void Menue::readValue(bool* changedVar); static void Menue::readValue(int* changedVar); };
true
adf5378dd390f9724da16631eda8ea442316383a
C++
maknoll/cg
/raytracer/Ray.hpp
UTF-8
2,918
3.28125
3
[]
no_license
#ifndef RAY_HPP_INCLUDE_ONCE #define RAY_HPP_INCLUDE_ONCE #include <memory> #include "Math.hpp" namespace rt { class Renderable; /// Ray consists of point and direction class Ray { public: Ray() : mOrigin(0.0,0.0,0.0), mDirection(0.0,0.0,0.0) {} Ray(const Vec3 &origin, const Vec3 &direction) : mOrigin(origin), mDirection(direction.normalized()) {} Vec3 pointOnRay(real lambda) const { return mOrigin + mDirection*lambda; } const Vec3& origin() const { return mOrigin; } const Vec3& direction() const { return mDirection; } void setOrigin(const Vec3& origin) { mOrigin=origin; } void setDirection(const Vec3& direction) { mDirection=direction.normalized(); } void transform(const Mat4 &transform) { mOrigin = transform.transformPoint(mOrigin); mDirection = transform.transformVector(mDirection).normalized(); } Ray transformed(const Mat4 &transform) const { return Ray(transform.transformPoint(mOrigin), transform.transformVector(mDirection)); } private: Vec3 mOrigin; Vec3 mDirection; }; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /// Container class for intersection between a renderable and a ray class RayIntersection { public: /// All necessary information for intersection must be passed to /// constructor. No mutator methods are available. RayIntersection(const Ray &ray, std::shared_ptr<const Renderable> renderable, const real lambda, const Vec3 &normal, const Vec3 &uvw) : mRay(ray), mRenderable(renderable), mLambda(lambda), mNormal(normal), mUVW(uvw) { mPosition=ray.pointOnRay(mLambda); } virtual ~RayIntersection() {} const Ray& ray() const { return mRay; } std::shared_ptr<const Renderable> renderable() const { return mRenderable; } real lambda() const { return mLambda; } const Vec3& position() const { return mPosition; } const Vec3& normal() const { return mNormal; } const Vec3& uvw() const { return mUVW; } virtual void transform(const Mat4 &transform, const Mat4 &transformInvTransp) { //transform local intersection information to global system mPosition = transform.transformPoint(mPosition); mNormal = transformInvTransp.transformVector(mNormal).normalize(); mRay.transform(transform); mLambda = (mPosition - mRay.origin()).norm(); } protected: Ray mRay; std::shared_ptr<const Renderable> mRenderable; real mLambda; Vec3 mPosition; Vec3 mNormal; Vec3 mUVW; }; } //namespace rt #endif //RAY_HPP_INCLUDE_ONCE
true
424f060f818639835ee4556e75aeb54e131730cd
C++
HenriChataing/cppnes
/src/exception.h
UTF-8
846
3.078125
3
[]
no_license
#ifndef _EXCEPTION_H_INCLUDED_ #define _EXCEPTION_H_INCLUDED_ #include <exception> class InvalidRom : public std::exception { public: InvalidRom() {} ~InvalidRom() {} const char *what() const noexcept { return "Invalid ROM File"; } }; class UnsupportedInstruction : public std::exception { public: UnsupportedInstruction(u16 pc, u8 opcode) : address(pc), opcode(opcode) {} ~UnsupportedInstruction() {} const char *what() const noexcept { return "Unsupported Instruction"; } u16 address; u8 opcode; }; class JammingInstruction : public std::exception { public: JammingInstruction(u16 pc, u8 opcode) : address(pc), opcode(opcode) {} ~JammingInstruction() {} const char *what() const noexcept { return "Jamming Instruction"; } u16 address; u8 opcode; }; #endif /* _EXCEPTION_H_INCLUDED_ */
true
1b6d70ade09940185ad02af9534db3a467b9ac17
C++
southor/planet
/Prototype/src/Rectangle.h
UTF-8
1,589
3.171875
3
[]
no_license
#ifndef __rectangle_h__ #define __rectangle_h__ #include "basic.h" #include "OrthogonalLine.h" namespace Prototype { class Rectangle { public: Pos pos; Vec size; inline Rectangle() {} inline Rectangle(Pos pos, Vec size) : pos(pos), size(size) {} inline Rectangle(float x, float y, float w, float h) : pos(x, y), size(w, h) {} Rectangle(Pos centerPos, float size); inline float getX() const { return pos.x; } inline float getY() const { return pos.y; } inline float getWidth() const { return size.x; } inline float getHeight() const { return size.y; } inline float getLeft() const { return pos.x; } inline float getRight() const { return pos.x + size.x; } inline float getBottom() const { return pos.y; } inline float getTop() const { return pos.y + size.y; } inline Pos getBottomRight() const { return Pos(getRight(), getBottom()); } inline Pos getTopRight() const { return Pos(getRight(), getTop()); } inline Pos getTopLeft() const { return Pos(getLeft(), getTop()); } inline Pos getBottomLeft() const { return pos; } inline Pos getCenterPos() const { return pos + size / 2.0f; } OrthogonalLine getLeftLine() const; OrthogonalLine getRightLine() const; OrthogonalLine getTopLine() const; OrthogonalLine getBottomLine() const; void setCenterPos(const Pos &centerPos) { pos = centerPos - this->size / 2.0f; } bool overlapping(const Rectangle &rectangle); bool contains(const Pos &pos) const; }; }; #endif
true
a2960be1868f9c4099fc3086945cd02f93c1d8b9
C++
kkbwilldo/all-problems
/swea/correct/1952 [모의 SW 역량테스트] 수영장/file.cpp
UTF-8
744
2.625
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; const int MAX = 13; int testcase; int day,month1,month3,year; int minVal; int plan[MAX]; void allCase(int startM,int startC){ if(startM>=MAX) minVal = min(startC,minVal); else{ allCase(startM + 1, startC + plan[startM]*day); allCase(startM + 1, startC + month1); allCase(startM + 3, startC + month3); allCase(startM + 12, startC + year); } } int main () { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); freopen("input.txt","r",stdin); cin>>testcase; for(int test=1;test<=testcase;test++){ cin>>day>>month1>>month3>>year; for(int i=1;i<MAX;i++) cin>>plan[i]; minVal = year; allCase(1,0); cout<<"#"<<test<<" "<<minVal<<endl; } return 0; }
true
47d8a1fb9d04366438735b6b574aede7f63d266b
C++
sanjuchandra/Greedy-Algorithm
/DEFKIN - Defense of a Kingdom.cpp
UTF-8
1,163
2.78125
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; #define ll long long int main(){ int t; cin>>t; vector<int> x , y; while(t--){ int r , c , n; cin>>r>>c>>n; for(int i = 0 ; i < n ; i++){ int a , b; cin>>a>>b; x.push_back(a); y.push_back(b); } if(n == 0){ cout<<r*c<<endl; } else{ sort(x.begin() , x.end()); sort(y.begin() , y.end()); int prev_x = 0; int prev_y = 0; int max_delta_x = 0; int max_delta_y = 0; for(auto t : x){ max_delta_x = max(max_delta_x , t - prev_x - 1); prev_x = t; } max_delta_x = max(max_delta_x , r + 1 - x[n-1] - 1 ); for(auto t : y){ max_delta_y = max(max_delta_y , t - prev_y - 1); prev_y = t; } max_delta_y = max(max_delta_y , c + 1 - y[n-1] - 1 ); cout<<max_delta_x*max_delta_y<<endl; x.clear(); y.clear(); } } }
true
2a7e744120264ba6af7fe0152b8275a2589bcff9
C++
shreygupta2809/Among-Us-Maze
/source/game.h
UTF-8
926
2.609375
3
[]
no_license
#ifndef GAME_H #define GAME_H #include <glad/glad.h> #include <GLFW/glfw3.h> // Represents the current state of the game enum GameState { GAME_ACTIVE, GAME_WIN, GAME_OVER, GAME_LOSE }; // Game holds all game-related state and functionality. // Combines all game-related data into a single class for // easy access to each of the components and manageability. class Game { public: // game state GameState State; bool Keys[1024]; unsigned int Width, Height; // constructor/destructor Game(unsigned int width, unsigned int height); ~Game(); // initialize game state (load all shaders/textures/levels) void Init(); // game loop void ProcessInput(GLFWwindow *window, float dt); void Update(GLFWwindow *window, float dt); void Render(GLFWwindow *window); void Quit(GLFWwindow *window); void CreateObstacles(); void lightToggle(); }; #endif
true
3cbf9918e7fe8bbeab516e8b28dcc827cdfa69f1
C++
svens/pal
/pal/net/async/service.test.cpp
UTF-8
3,199
2.765625
3
[ "MIT" ]
permissive
#include <pal/net/async/service> #include <pal/net/test> #include <catch2/catch_approx.hpp> #include <catch2/catch_test_macros.hpp> namespace { // // Because OS poller may return early/late, this test is flaky // TEST_CASE("net/async/service", "[!mayfail]") { using namespace std::chrono_literals; using Catch::Approx; SECTION("make_service not enough memory") { pal_test::bad_alloc_once x; auto make_service = pal::net::async::make_service(); REQUIRE_FALSE(make_service); CHECK(make_service.error() == std::errc::not_enough_memory); } pal::net::async::request request, *request_ptr = nullptr; auto process = [&request_ptr](auto *request) { request_ptr = request; }; auto service = pal_try(pal::net::async::make_service()); SECTION("assign") { // meaningless test, just to increase coverage auto s = pal_try(pal::net::async::make_service()); s = std::move(service); } SECTION("post") { service.post(&request); service.run_once(process); CHECK(request_ptr == &request); } SECTION("post_after") { constexpr auto margin = 10ms; auto expected_runtime = 0ms; auto start = service.now(); SECTION("run_once: post immediately") { service.post_after(0ms, &request); service.run_once(process); CHECK(request_ptr == &request); } SECTION("run_once: no post") { service.post_after(100ms, &request); service.run_once(process); CHECK(request_ptr == nullptr); } SECTION("run_for: post immediately") { service.post_after(0ms, &request); service.run_for(100ms, process); CHECK(request_ptr == &request); } SECTION("run_for: post before") { service.post_after(100ms, &request); service.run_for(200ms, process); CHECK(request_ptr == &request); expected_runtime = 100ms; } SECTION("run_for: post at") { service.post_after(100ms, &request); service.run_for(100ms, process); CHECK(request_ptr == &request); expected_runtime = 100ms; } SECTION("run_for: post after") { service.post_after(200ms, &request); service.run_for(100ms, process); CHECK(request_ptr == nullptr); service.run_for(100ms, process); CHECK(request_ptr == &request); expected_runtime = 200ms; } SECTION("run: post immediately") { service.post_after(0ms, &request); service.run(process); CHECK(request_ptr == &request); } SECTION("run: post at") { service.post_after(100ms, &request); service.run(process); CHECK(request_ptr == &request); expected_runtime = 100ms; } SECTION("run_for: post multiple") { std::array<pal::net::async::request, 3> requests; service.post_after(50ms, &requests[0]); service.post_after(20ms, &requests[1]); service.post_after(70ms, &requests[2]); service.run_for(100ms, process); CHECK(request_ptr == &requests[1]); service.run_for(100ms, process); CHECK(request_ptr == &requests[0]); service.run_for(100ms, process); CHECK(request_ptr == &requests[2]); expected_runtime = 70ms; } auto runtime = std::chrono::duration_cast<decltype(expected_runtime)>(service.now() - start); CHECK(runtime.count() == Approx(expected_runtime.count()).margin(margin.count())); } } } // namespace
true
b1569e95f4fbd9730e5e55a8fd16255a69914b19
C++
FutaAlice/doujin-game-demo
/src/layer-title/giflabel.hpp
UTF-8
616
2.515625
3
[]
no_license
#pragma once #include <QLabel> #include <QMovie> #include <QResizeEvent> class GIFLabel : public QLabel { public: GIFLabel(QWidget *parentWidget) : QLabel(parentWidget) { } ~GIFLabel() { delete movie_; } void load(QString filename) { delete movie_; movie_ = new QMovie(filename); movie_->start(); setMovie(movie_); } protected: virtual void resizeEvent(QResizeEvent *e) { if (movie_) movie_->setScaledSize(e->size()); QLabel::resizeEvent(e); } private: QMovie *movie_ { nullptr }; };
true
8ba3a5264eaddb135e262f228d27bdd5b686cb20
C++
MYREarth/secret-weapon
/2014-03-02/j.cpp
UTF-8
2,420
2.546875
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <vector> #include <algorithm> using namespace std; typedef long long ll; struct point { int x,y,id; point(){} point(int x,int y):x(x),y(y){} }; inline point operator -(const point &a,const point &b) { return(point(a.x-b.x,a.y-b.y)); } inline bool operator <(const point &a,const point &b) { return(a.x<b.x || a.x==b.x && a.y<b.y); } inline int sign(ll x) { return(x<0?-1:x>0); } inline ll det(const point &a,const point &b) { return(ll(a.x)*b.y-ll(a.y)*b.x); } inline int side(const point &p,const point &a,const point &b) { return(sign(det(b-a,p-a))); } int m1,m2; point a[100010],up[100010],down[100010]; void convex(int n) { sort(a+1,a+n+1); for (int i=1;i<=n;i++) { while (m1>=2 && det(down[m1]-down[m1-1],a[i]-down[m1])<=0) m1--; down[++m1]=a[i]; } for (int i=n;i;i--) { while (m2>=2 && det(up[m2]-up[m2-1],a[i]-up[m2])<=0) m2--; up[++m2]=a[i]; } } point P,Q; ll best1,best2; void far(point *a,int m,const point &A,const point &B) { vector <point> tmp; int sgn=sign(det(B-A,a[2]-a[1])),l=1,r=m-1,ans; while (l<=r) { int mid=(l+r)>>1; if (sign(det(B-A,a[mid+1]-a[mid]))==sgn) ans=mid,l=mid+1; else r=mid-1; } tmp.push_back(a[1]); tmp.push_back(a[m]); tmp.push_back(a[ans]); if (ans>1) tmp.push_back(a[ans-1]); if (ans<m) tmp.push_back(a[ans+1]); for (int i=0;i<tmp.size();i++) { ll now=det(B-A,tmp[i]-A); if (now>=0 && now>best1) { best1=now; P=tmp[i]; } if (now<=0 && now<best2) { best2=now; Q=tmp[i]; } } } void work(const point &a,const point &b) { best1=-1; best2=1; far(down,m1,a,b); far(up,m2,a,b); if (best1!=-1 && best2!=1 && side(P,a,b)*side(Q,a,b)==-1) printf("%d %d\n",P.id,Q.id); else printf("0\n"); } int main() { int n; scanf("%d",&n); for (int i=1;i<=n;i++) { scanf("%d%d",&a[i].x,&a[i].y); a[i].id=i; } convex(n); int Q; scanf("%d",&Q); while (Q--) { point A,B; scanf("%d%d%d%d",&A.x,&A.y,&B.x,&B.y); if (n<=1) printf("0\n"); else work(A,B); } return(0); }
true
097519bdca9c6b9e8ac1326b9b1d63d3609d5a44
C++
liaoqingfu/ScreenCap
/src/configurationManager.hpp
UTF-8
692
3.03125
3
[ "MIT" ]
permissive
#ifndef CONFIGURATIONMANAGER_HPP #define CONFIGURATIONMANAGER_HPP #include <memory> #include <string> #include <boost/any.hpp> class ConfigurationManager { public: static std::unique_ptr<ConfigurationManager> create(); template< typename T> T getOption(const std::string& name) { return boost::any_cast<T>(getAny(name)); } template <typename T> void setOption(const std::string& name, T thing) { setAny(name,thing); } virtual ~ConfigurationManager() {} private: virtual boost::any getAny(const std::string& name) = 0; virtual void setAny(const std::string&name ,boost::any thing) = 0; }; #endif /* CONFIGURAIONMANAGER_HPP */
true
e07c367c908f6aecc98dae320e9a47288191749d
C++
codeoloco/cpp_primer
/exercises/ch02/showtime.cpp
UTF-8
421
4.0625
4
[]
no_license
// showtime.cpp - exercise 7 #include <iostream> void printTime(int, int); int main() { using namespace std; int hours; int mins; cout << "Enter the number of hours: "; cin >> hours; cout << "Enter the number of minutes: "; cin >> mins; printTime(hours, mins); return 0; } void printTime(int h, int m) { using namespace std; cout << "Time: " << h << ':' << m << endl; }
true
4401cf641e86124663cb2f13d09989934b4db525
C++
lucivpav/bomberman
/src/server.h
UTF-8
5,482
3.09375
3
[]
no_license
#ifndef SERVER_H #define SERVER_H #include <deque> #include <thread> #include <mutex> #include "map.h" #include "player.h" enum class ClientMessage : char; /** * @brief The ServerMessage struct represents a message the Server can * send to the Client. */ struct ServerMessage { /** * @brief The Type enum represents a type of the ServerMessage. */ enum class Type : char { MAP_SIZE, ///< format: val[3]: width height unused BLOCK, ///< format: val[3]: x y symbol SERVER_LIVES, ///< format: val[3]: lives unused unused SERVER_BOMBS, ///< format: val[3]: bombs unused unused CLIENT_LIVES, ///< format: val[3]: lives unused unused CLIENT_BOMBS, ///< format: val[3]: bombs unused unused CLIENT_SPEED_BONUS ///< format: val[3]: enabled unused unused }; /** * @brief The message values are not set. The caller is responsible for * setting up the message manually. */ ServerMessage(){} /** * @brief Creates a message with specific values. * @param type Type of the message. * @param val1 First item in the val[3] array to be set. * @param val2 Second item in the val[3] array to be set. * @param val3 Third item in the val[3] array to be set. */ ServerMessage(Type type, char val1, char val2 = 0, char val3 = 0) : type(type) { val[0] = val1; val[1] = val2; val[2] = val3; } /** * @brief The type of the message. */ Type type; /** * @brief The payload of the message. */ char val[3]; }; /** * @brief The Server class is responsible for hosting an online game and * maintaining a connection to the Client. It makes sure the Client gets * all the necessary notifications about the game state through it's * update() method. */ class Server { public: /** * @brief Prepares the Server for initial set up by setup(). */ Server(); /** * @brief Releases all resources in use by Server. * It includes calling disconnect(). */ ~Server(); /** * @brief Prepares the Server for use. * @param serverPlayer The Player representing the server side player. * @param clientPlayer The Player representing the client side player. * @param map The Map associated with the Game. */ void setup(const Player & serverPlayer, const Player & clientPlayer, const Map & map); /** * @brief Checks whether the Server is connected to the Client. * @return true if the Server is connected to the Client, false otherwise. */ bool isConnected(); /** * @brief Instructs the Server to start listening for incoming connection. * This method returns immediately. Call listeningFinished() to check * whether the listening process has ended. Then call isConnected() to * determine whether the listening process has been successful. * @warning Caller is responsible for calling setup() prior calling * this method. * @param address The address to listen on. * @param port The port to listen on. */ void listen(const char * address, const char * port); /** * @brief Checks whether the listening by listen() method has finished. * @return true if the listening by listen() method has finished, false * otherwise. */ bool listeningFinished(); /** * @brief Disconnects from the Client. If the Server is not connected to * a Client, the method does nothing. */ void disconnect(); /** * @brief Returns the first incoming message in an internal * queue. If there is no incoming message, the method return false. * The message gets removed from the internal queue after calling * this method. * @param message Outputs the incoming message. * @return true if there was an incoming message, false otherwise. */ bool getMessage(ClientMessage & message); /** * @brief Call this if the the connection to the * Client was successful. This method transfers all the necessary * information about the game from the Server, so that the game can * be started. */ void initOnlineGame(); /** * @brief Sends all the necessary information about the game state * to the Client to keep the Client updated. */ void update(); private: void listenThread(const char * address, const char * port); void closeSockets(); bool mCancelListening; std::mutex mCancelListeningLock; bool mListeningFinished; std::mutex mListeningFinishedLock; std::mutex mSocketLock; std::mutex mMessageLock; std::deque<ClientMessage*> mMessages; int mListenSocket; int mClientSocket; int prepareSrvSocket(const char * address, const char * port); void listen(); char ** mDisplay; int mPrevServerPlayerLives; int mPrevServerPlayerBombs; int mPrevClientPlayerLives; int mPrevClientPlayerBombs; bool mPrevClientSpeedBonus; const Player * mServerPlayer; const Player * mClientPlayer; const Map * mMap; void sendMessage(const ServerMessage & message); }; #endif
true
4b634fad01bf6b6e454381221de1624b03551a18
C++
micheldavalos/examen_edi18B_bicipuerto
/main.cpp
UTF-8
959
3.234375
3
[]
no_license
#include <iostream> #include "bicipuerto.h" using namespace std; int main() { Bicipuerto bicipuerto; string op; while (true) { cout << "1) Agregar bici" << endl; cout << "2) Mostrar bicis" << endl; cout << "0) Salir" << endl; getline(cin, op); if (op == "1") { Bici bici; string temp; double temp_d; cout << "id: "; getline(cin, temp); bici.setId(temp); cout << "tiempo: "; getline(cin, temp); temp_d = stod(temp); bici.setTiempo(temp_d); cout << "metros: "; getline(cin, temp); temp_d = stod(temp); bici.setMetros(temp_d); bicipuerto.agregarBici(bici); } else if (op == "2") { bicipuerto.mostrar(); } else if (op == "0") { break; } } return 0; }
true
95f02cb91a37893b14391e11b2c3887246ea27d0
C++
srod-prog-cwiczenia/GCC
/biblioteczneFunkcje.h
UTF-8
843
2.796875
3
[]
no_license
#include <string> #include <vector> using namespace std; /* Wyrzuca na ekran zawartosc lancucha, znak po znaku, podaje tez kody ASCII */ void dumpLancuch(char* str); /* Wypisuje komunikat na ekranie. TODO: Obudowac to w jakas sensowna ramke, itp */ void komunikat(string txt); void komunikat(int liczba); /* Wyswietla info o pustej opcji. wykorzystywane w pustych opcjach. */ void dummy(); /* Pytanie postaci Tak lub Nie. */ bool pytanieNT(string txt); /* Jak sama nazwa wskazuje, sprawdza czy istnieje zadany plik. Korzysta z funkcji stat, byc moze istnieje jednak prostszy sposob? */ bool istniejePlik (const char* nazwaPliku); /* Uruchamia proces i zwraca jego wynik. */ string uruchomieniePolecenia(string polecenie); /* Rozdziela lancuch na czesci */ vector<string> lancuch2Vector(const string &lancuch, char separator = '\n');
true
6491157219807dfbb9c5947edcbc35d6fef7e3fb
C++
shg9411/algo
/algo_cpp/bj9935.cpp
UTF-8
651
2.625
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; char str[1000020], bomb[40]; int len, blen, tmp = 0; bool ok; int main(void) { cin.tie(NULL); ios_base::sync_with_stdio(false); cin >> str >> bomb; len = strlen(str); blen = strlen(bomb); for (int i = 0; i < len; i++) { str[tmp] = str[i]; if (tmp >= blen - 1 && str[tmp] == bomb[blen - 1]) { ok = true; for (int j = 1; j < blen; j++) { if (str[tmp - j] != bomb[blen - 1 - j]) { ok = false; break; } } if (ok) tmp -= blen; } tmp++; } if (tmp > 0) { for (int i = 0; i < tmp; i++) cout << str[i]; } else cout << "FRULA"; return 0; }
true
738ada67ffc0f983e1dcb380856977788b83eb8c
C++
faniajime/searchAlgorithms
/SolucionadorASTAR.cpp
UTF-8
2,279
2.84375
3
[]
no_license
#include "SolucionadorASTAR.h" #include "Estado.h" #include "Solucion.h" #include "Lista.h" #include "Problema.h" #include <bits/stdc++.h> using namespace std; SolucionadorASTAR::SolucionadorASTAR(){ unexplored = new Lista(); explored = new Lista(); } Solucion* SolucionadorASTAR::solucione( Problema * problema) { int resuelto = 0; int depth = 0; int cost; Lista* frontera = new Lista(); Estado* estado = problema->getEstadoInicial(); NodoA* raiz = new NodoA(); raiz->estado = estado; raiz->padre = NULL; raiz->nivel = depth; explored->push_back(raiz->estado); resuelto = problema->esSolucion(estado); while(resuelto == 0) //|| !unexplored->isEmpty()) { cost = 10000; depth += 1; frontera = problema->getSiguientes(estado); //cout<<"Frontera "<<endl; //cout<<frontera<<endl; Lista::Iterador i = frontera->begin(); Lista::Iterador end = frontera->end(); for(i; i != end; ++i) { NodoA * nuevo = new NodoA(); nuevo->estado = *i; nuevo->padre = raiz;// raiz? nuevo->nivel = depth; unexplored->push_back(nuevo->estado); } Lista::Iterador j = unexplored->begin(); Lista::Iterador unexploredEnd = unexplored->end(); for(j;j!= unexploredEnd;++j) { if(cost>(calculateCost(problema->heuristica(*j),depth))) { cost = calculateCost(problema->heuristica(*j),depth); estado = *j; //explored->push_back(unexplored->pop_front()); } } explored->push_back(estado); //cout<<"Estado: "<<endl; //cout<<estado<<endl; if(problema->heuristica(estado)==0) { resuelto = 1; } } cout<<"resuelto"<<endl; solucion = retornarSolucion(); return solucion; } /* Calcular profundidad */ int SolucionadorASTAR :: calculateCost(int heuristic,int depth) { return heuristic + depth; } Solucion * SolucionadorASTAR::retornarSolucion(){ solucion = new Solucion(explored); return solucion; } /* Solucion * SolucionadorASTAR::solucioneRec(Problema * problema){ }*/
true
545f1a21b9cfd54a359d47ab008ea666b1bb7995
C++
hackwaretech/hackware-bot
/VMatrix.hpp
UTF-8
2,648
3.171875
3
[]
no_license
#pragma once #include <limits> #include "Vector3.hpp" class matrix3x4_t { public: matrix3x4_t() {}; matrix3x4_t(float _11, float _12, float _13, float _14, float _21, float _22, float _23, float _24, float _31, float _32, float _33, float _34) { m_flMatVal[0][0] = _11; m_flMatVal[0][1] = _12; m_flMatVal[0][2] = _13; m_flMatVal[0][3] = _14; m_flMatVal[1][0] = _21; m_flMatVal[1][1] = _22; m_flMatVal[1][2] = _23; m_flMatVal[1][3] = _24; m_flMatVal[2][0] = _31; m_flMatVal[2][1] = _32; m_flMatVal[2][2] = _33; m_flMatVal[2][3] = _34; } //----------------------------------------------------------------------------- // Creates a matrix where the X axis = forward // the Y axis = left, and the Z axis = up //----------------------------------------------------------------------------- void Init(const Vector3 &xAxis, const Vector3 &yAxis, const Vector3 &zAxis, const Vector3 &vekOrigin) { m_flMatVal[0][0] = xAxis.xAechse; m_flMatVal[0][1] = yAxis.xAechse; m_flMatVal[0][2] = zAxis.xAechse; m_flMatVal[0][3] = vekOrigin.xAechse; m_flMatVal[1][0] = xAxis.yAechse; m_flMatVal[1][1] = yAxis.yAechse; m_flMatVal[1][2] = zAxis.yAechse; m_flMatVal[1][3] = vekOrigin.yAechse; m_flMatVal[2][0] = xAxis.zAechse; m_flMatVal[2][1] = yAxis.zAechse; m_flMatVal[2][2] = zAxis.zAechse; m_flMatVal[2][3] = vekOrigin.zAechse; } //----------------------------------------------------------------------------- // Creates a matrix where the X axis = forward // the Y axis = left, and the Z axis = up //----------------------------------------------------------------------------- matrix3x4_t(const Vector3 &xAxis, const Vector3 &yAxis, const Vector3 &zAxis, const Vector3 &vekOrigin) { Init(xAxis, yAxis, zAxis, vekOrigin); } inline void SetOrigin(Vector3 const &p) { m_flMatVal[0][3] = p.xAechse; m_flMatVal[1][3] = p.yAechse; m_flMatVal[2][3] = p.zAechse; } inline void Invalidate(void) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { m_flMatVal[i][j] = std::numeric_limits<float>::infinity();; } } } inline float *operator[](int i) { return m_flMatVal[i]; } inline const float *operator[](int i) const { return m_flMatVal[i]; } inline float *base() { return &m_flMatVal[0][0]; } inline const float *base() const { return &m_flMatVal[0][0]; } float m_flMatVal[3][4]; }; class __declspec(align(16)) matrix3x4a_t : public matrix3x4_t { matrix3x4a_t &operator=(const matrix3x4_t& src) { memcpy(base(), src.base(), sizeof(float) * 3 * 4); return *this; }; };
true
ca3ae836f2ba1007c2aa67182dbfa6002fbe97b1
C++
darksun2000/Jeu-robot
/robot.h
UTF-8
1,147
3.03125
3
[]
no_license
#include <iostream> using namespace std; class robot{ public: double Xpos=0.0; double Ypos =0.0; char dir='n'; double x(); double y(); void avance(int n ); void tourn(); }; double robot::x(){ return Xpos ; } double robot::y(){ return Ypos; } void robot::avance(int n){ if(dir=='n'){ Ypos=Ypos+n; } else if(dir=='e'){ Xpos=Xpos+n; } else if(dir=='s'){ Ypos=Ypos-n; } else if(dir=='o'){ Xpos=Xpos-n; } } void robot::tourn(){ if(dir=='n'){ dir='e'; } else if(dir=='e'){ dir='s'; } else if(dir=='s'){ dir='o'; } else if(dir=='o'){ dir='n'; } } class rhp2 : public robot { int p =0; public : void av(char c ) { if (c=='n'){ Ypos++; } else if(c='s'){ Ypos--; } else if(c=='e'){ Xpos++; } else if(c=='o'){ Xpos--; } } void crayon(){ if(p==0){ p=1; } else if(p==1){ p=0; } } int crayonstate (){ return p ; } double Xrph(){ return Xpos+200; } double Yrhp(){ return Ypos-200; } rhp2(){ Xpos=0; Ypos=0; p=1; } };
true
2fbe179953d25de303568d879b32b528acece402
C++
haki-1/raster-graphics
/main.cpp
UTF-8
710
2.859375
3
[]
no_license
#include "cli.h" #include "session.h" #include <iostream> int main() { CommandLineInterface cli; std::vector<UserSession> sessions; std::string command; while (true) { std::cin >> command; cli.setCommand(command); cli.executeCommand(sessions); } // in class destr there must be delete on in-vector pointers, // but since we are in main, does i really need vector of us* // it might be better to be from objects!!!!!!!!!! // virt destr ? - yep // copy actually means that we create copy of pointers, so // memory becomes shared!!! // that's why we need copy-constructor to properly copy the // vector!!! return 0; }
true
3a853048a23303d634e29e35ad96ce0c94c87a4d
C++
kovtunsergey/mainrepo
/src/index.cpp
UTF-8
215
2.53125
3
[]
no_license
bool index(int x1, int y1, int x, int y) { if((x1==4)||(y1==4)) { return 0; } if((((x+1)==x1)&&(y1==y))||(((x-1)==x1)&&(y1==y))||(((y+1)==y1)&&(x1==x))||(((y-1)==y1)&&(x1==x))) { return 1; } return 0; }
true
680974545cf7c93bfe1e70656bb184203a8fcb14
C++
jasonchan117/ularProject
/ular/problem44.cpp
UTF-8
1,772
2.796875
3
[]
no_license
/************************************************************************* > File Name: problem44.cpp > Author: > Mail: > Created Time: 2018年04月29日 星期日 10时50分32秒 ************************************************************************/ #include<math.h> #include<iostream> #include<stdio.h> #include<inttypes.h> using namespace std; int a[100000005]={0}; long long getValue(long long n){ long long p=(n*(n*3-1))/2; return p; } int isPentagonal(long long x){ if(x<=100000000){ if(a[x]){ return 1; } } long long min=1; long long max=x; long long mid; while(min<=max){ long long temp; mid=(min+max)/2; temp=getValue(mid); if(x<temp){ max=mid-1; } else if(x>temp){ min=mid+1; } else if(x==temp) { if(x<=100000000&&a[x]==0){ a[x]=1; } return 1; } } return 0; } int newton(long long x){ long long temp=x/2; while(true){ long long temp2=((3/2)*temp*temp+x)/(3*temp-1/2); if(getValue(temp2)==x) return 1; if(temp2<=0) return 0; temp=temp2; } return 0; } int main(){ long long max=100000000; for(long long i=1;;i++){ long long p1,p2; p1=getValue(i); p2=getValue(i-1); if(p1<=100000000){ a[p1]=1; a[p2]=1; } if(p1-p2>max) break; for(long long j=i-1;j>=1;j--){ p2=getValue(j); if(p2<=100000000) a[p2]=1; if(p1-p2>=max) break; if(newton(p1+p2)&&newton(p1-p2)){ max=p1-p2; } } } printf("%lld",max); return 0; }
true
5abd18d35b9534e1bc8115df939658acfa4d8aea
C++
x86nick/leetcode
/Algorithm/SearchInRotatedSortedArray/SearchInRotatedSortedArray.cpp
UTF-8
3,224
3.984375
4
[ "BSD-3-Clause" ]
permissive
/* Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. */ #include <vector> #include <stdio.h> using namespace std; class Solution { public: // nlog(n) int search(vector<int>& nums, int target) { if (nums.empty()) { return -1; } int begin = 0; int end = nums.size() - 1; while (begin <= end) { int index = (begin + end + 1) /2; if (target == nums[index]) { return index; } if (nums[index] < nums[begin]) { if (target > nums[index] && target < nums[begin]) { begin = index + 1; } else { end = index -1; } } else { if (target < nums[index] && target >= nums[begin]) { end = index - 1; } else { begin = index + 1; } } } return -1; } // little slower, nlog(n) too. int search(vector<int>& nums, int target) { if (nums.empty()) { return -1; } if (nums.size() == 1) { return nums[0] == target ? 0 : -1; } int pivot = findPivot(nums); if (pivot != -1) { if (target < nums[0]) { return binarySearch(nums, pivot, nums.size() - 1, target); } else { return binarySearch(nums, 0, pivot - 1, target); } } else { return binarySearch(nums, 0, nums.size() - 1, target); } } int findPivot(vector<int>& nums) { for (int begin = 0, end = nums.size() - 1; begin < end;) { int index = (begin + end + 1) / 2; if (nums[index - 1] > nums[index]) { return index; } else { if (nums[index] > nums[0]) { begin = index; } else { end = index; } } } return -1; } int binarySearch(vector<int>& num, int begin, int end, int target) { while (begin <= end) { int index = (begin + end + 1) / 2; if (target == num[index]) { return index; } else if (target < num[index]) { end = index - 1; } else { begin = index + 1; } } return -1; } }; int main(int argc, char* argv[]) { vector<int> v = {3, 1}; Solution s; printf("%d\n", s.search(v, 3)); return 0; }
true
544f2a104f8001f0a59c1e93bfc1bf9061b2f2bd
C++
ltimaginea/Xinbiaozhun_cpp_Chengxusheji
/XinBiaoZhun_Cpp/Chapter4_Overload/OperatorOverloading2_Assign.cpp
UTF-8
2,876
3.796875
4
[ "MIT" ]
permissive
// 重载赋值运算符 "=" #include <iostream> #include <cstring> #pragma warning(disable:4996) using namespace std; class CString { private: char* str; public: CString() :str(NULL) {} CString(const char* s); CString(const CString& s); const char* c_str() const; CString& operator=(const char* s); CString& operator=(const CString& s); ~CString(); }; CString::CString(const char* s) // 类型转换构造函数,使得 CString s2 = "hello!"; 能够成立 { /* 这是为了应对这样的情况:CString s = "hello!"; s = "Shenzhou 8!"; 这时便需要释放先前分配的动态内存。 但是因为"="已经有被重载 CString& operator=(const char* s); ,这样的情况并不会触发这个类型转换构造函数,所以可以注释掉这里。 */ if (s) { str = new char[strlen(s) + 1]; strcpy(str, s); } else str = NULL; } CString::CString(const CString& s) // 深拷贝 { if (s.str) { str = new char[strlen(s.str) + 1]; strcpy(str, s.str); } else str = NULL; } const char* CString::c_str() const { return str; } CString& CString::operator=(const char* s) // 重载 "=",使得 obj="Good Luck," 能够成立 { char* str_tmp = NULL; if (s) { str_tmp = new char[strlen(s) + 1]; strcpy(str_tmp, s); } else str_tmp = NULL; if (str) delete[] str; str = str_tmp; return *this; } CString& CString::operator=(const CString& s) // 深拷贝 { if (this == &s) // 为了应对 s=s 这样的情况。其实这里的自赋值判断是多余的,因为下面的写法可以处理自赋值的情况,同时还是异常安全的。 return *this; char* str_tmp = NULL; if (s.str) { str_tmp = new char[strlen(s.str) + 1]; strcpy(str_tmp, s.str); } else str_tmp = NULL; if (str) delete[] str; str = str_tmp; return *this; } CString::~CString() { if (str) delete[] str; } int main() { CString s; s = "Good Luck,"; // 等价于 s.operator=("Good Luck,"); cout << s.c_str() << endl; CString s2 = "hello!"; cout << s2.c_str() << endl; s = "Shenzhou 8!"; // 等价于 s.operator=("Shenzhou 8!"); cout << s.c_str() << endl; CString& ss = s; CString& sss = s; sss = ss; // 第70,71行,s=s 的情况 CString s11, s12; s11 = "this"; s12 = "that"; s12 = s11; // 深拷贝 CString s21; s21 = "Transformers"; CString s22(s21); // 深拷贝 return 0; } // tips: // 1. C++规定,"=" 只能重载为成员函数。 // 2. 没有经过重载,"=" 的作用就是把左边的变量变得和右边的相等,即执行逐个字节拷贝的工作,对于指针变量,会使得两个指针指向同一个地方,这样的拷贝就叫做“浅拷贝”。 // 3. 将一个指针变量指向的内容复制到另一个指针变量指向的地方,这样的拷贝就叫做“深拷贝”。 // 4. 第70,71行是为了应付这样的情况:s=s;
true
3a91a0a2778f88aabbbe6802ea6dc222a622a7f3
C++
victornoriega/data-structures
/SegundoParcial/src/cola.cpp
UTF-8
970
3.296875
3
[]
no_license
#include "cola.h" #include <cstdlib> #include <iostream> cola::cola() { principio=NULL; ultimo=NULL; cuantos=0; //ctor } cola::~cola() { caja *p; while(principio){ p=principio; principio=p->siguiente; free(p); } } void cola::agregar(int a){ caja *p; p=(caja*)malloc(sizeof(caja)); p->valor=a; if(!principio){ p->siguiente=NULL; principio=p; ultimo=p; }else{ p->siguiente=NULL; ultimo->siguiente=p; ultimo=p; } cuantos++; } int cola::sacar(){ caja *p; int valor; if(!principio){ return VACIO; }else{ p=principio; principio=p->siguiente; valor=p->valor; free(p); cuantos--; } if(cuantos==0) ultimo=NULL; return valor; } void cola::pintar(){ caja *p; p=principio; while(p){ std::cout << p->valor << std::endl; p=p->siguiente; } }
true
b72b1ed7d5b2d0a43430597cdbda13f75b433230
C++
Jungjaewon/ProblemSolving
/16926_array_rotation1/16926_array_rotation1/16926_array_rotation1.cpp
UTF-8
2,333
3.203125
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <vector> /* 11 12 13 14 15 21 22 23 24 25 31 32 33 34 35 41 42 43 44 45 51 52 53 54 55 11 ~ 15 right 25 ~ 45 down 55 ~ 51 left 41 ~ 21 up 순으로 하면 처음 시도했던 방법보다 훨씬 깔끔하고 좋다. vector를 조정하면 시계 반시계 조정이 가능하다. shifting 할때 for문을 사용하면 훨씬 빨라질 수 있다. 대략 5배가량 빨라진다. */ using namespace std; int N, M, R; int temp; int arr[301][301]; void processing() { int start_x = 1; int start_y = 1; int end_x = N; int end_y = M; vector<int> temp_arr; while (start_x <= end_x && start_y <= end_y) { // read step // left direction for (int y = start_y; y <= end_y; ++y) { temp_arr.push_back(arr[start_x][y]); } // down direction for (int x = start_x + 1; x < end_x; ++x) { temp_arr.push_back(arr[x][end_y]); } // right direction for (int y = end_y; y >= start_y; --y) { temp_arr.push_back(arr[end_x][y]); } // upper direction for (int x = end_x - 1; x > start_x; --x) { temp_arr.push_back(arr[x][start_y]); } // shifting for (int i = 0; i < R; ++i) { int temp_int = temp_arr.front(); temp_arr.erase(temp_arr.begin()); temp_arr.push_back(temp_int); } // write step int cnt = 0; for (int y = start_y; y <= end_y; ++y) { arr[start_x][y] = temp_arr[cnt++]; } // down direction for (int x = start_x + 1; x < end_x; ++x) { arr[x][end_y] = temp_arr[cnt++]; } // right direction for (int y = end_y; y >= start_y; --y) { arr[end_x][y] = temp_arr[cnt++]; } // upper direction for (int x = end_x - 1; x > start_x; --x) { arr[x][start_y] = temp_arr[cnt++]; } temp_arr.clear(); start_x += 1; start_y += 1; end_x -= 1; end_y -= 1; } } int main() { freopen("input.txt","r",stdin); scanf("%d %d %d",&N, &M, &R); for (int i = 1; i <= N; ++i) { for (int j = 1; j <= M; ++j) { scanf("%d", &temp); arr[i][j] = temp; } } //for (int i = 0; i < R; ++i) { processing(); //} // print arr for (int i = 1; i <= N; ++i) { for (int j = 1; j <= M; ++j) { printf("%2d ", arr[i][j]); } printf("\n"); } }
true
06e58dd5e52e60094f604165aaf58389f515a0dc
C++
BDSuther/ProjectEuler
/016/16.cpp
UTF-8
1,262
4.0625
4
[]
no_license
#include <iostream> using namespace std; /* 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? */ int digitSum(int exponent){ unsigned int number[500] = {0}; int remExp = exponent; //how many exponents are remaining int finalIndex = 0; //the furthest index in the number array that contains numbers int exp; //the exponent we will go to int sum = 0; const int MAX_EXP = 28; //since using UNSIGNED INT we can only go up to 9*2^28 before we cause overflow. number[0] = 1; while (remExp > 0){ if (remExp > MAX_EXP){ exp = MAX_EXP; } else { exp = remExp; } for(int i = exp; i > 0; i--){ for(int j = 0; j <= finalIndex; j++){ number[j] *= 2; } } remExp -= exp; //move over the number into the number buckets so that each contains only one digit for(int i = 0; i < 499; i++){ number[i+1] += number[i]/10; number[i] = number[i] % 10; if (number[i+1] == 0){ finalIndex = i; //all number[finalIndex+1] and further are 0 break; } } } for (int i = 0; i <= finalIndex; i++){ sum += number[i]; } return sum; } int main (int argc, char* argv[]){ cout << "The sum of the digits of 2^1000 is " << digitSum(1000) << endl; }
true
450f48914b1070c56d45c1d4f1413e2c4ad2d8b4
C++
abidenm/HujoonROS
/src/SkillMate/src/HapticCommandPublisher.cpp
UTF-8
2,893
2.71875
3
[]
no_license
// -------------------------------------------------------- // // CKim - This ROS node reads HapticDevice command from // network and publishes it // -------------------------------------------------------- // #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <string> #include <time.h> #include "ros/ros.h" // ROS 기본 헤더 파일 #include <SkillMate/HapticCommand.h> // CKim - Automatically generated message Header #include <iostream> #include <fstream> using namespace std; int main(int argc, char* argv[]) { int sock; struct sockaddr_in server_addr; if(argc<3) { printf("Usage : %s <IP> <port> \n", argv[3]); exit(1); } // Client Socket sock = socket(PF_INET, SOCK_STREAM, 0); //======= ros::init(argc, argv, "HapticCmdPublisher"); //노드 초기화 ros::NodeHandle nh; //노드 핸들 선언 ros::Publisher haptic_pub = nh.advertise<SkillMate::HapticCommand>("HapticCmd", 100); ROS_INFO("Starting Haptic Node"); //==== // Connect to address memset(&server_addr, 0, sizeof(server_addr));//서버 주소 초기화 server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(argv[1]); server_addr.sin_port = htons(atoi(argv[2])); ROS_INFO("Connecting to Server!\n"); if(connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr))==-1) { printf("connect() error\n"); close(sock); exit(1); } ROS_INFO("Connected to Server!\n"); //ros::Rate loop_rate(10); //ros::WallTime currTime = ros::WallTime::now(); while(ros::ok()) { // ----------------------------------------------------------- // // CKim - This code is using no protocol. Just 6 doubles // ----------------------------------------------------------- // int leng, real_recv_len, real_recv_byte; leng = 6*sizeof(double) + 2*sizeof(int); char* str2 = new char[leng]; //길이 만큼 배열 동적할당 if (str2 == (char *) 0) { printf("memory error!\n"); exit(1); } memset(str2, 0, leng); real_recv_len = 0; real_recv_byte = 0; //받는 방법 2 : 받는 바이트 확인하며 받기 while (real_recv_len < leng) { real_recv_byte = read(sock, &str2[real_recv_len], leng - real_recv_len); real_recv_len += real_recv_byte; } double* val = (double*) str2; int* btn = (int*) (str2+6*sizeof(double)); SkillMate::HapticCommand msg; for(int i=0; i<3; i++) { msg.array[i] = val[i]; } for(int i=3; i<6; i++) { msg.array[i] = val[i]; }//*2000.0; } msg.btn[0] = btn[0]; msg.btn[1] = btn[1]; // ----------------------------------------------------------- // // 메시지를 퍼블리시 한다. haptic_pub.publish(msg); //loop_rate.sleep(); } close(sock); return 0; }
true
a1092c0b65f2809f3bda13b9c3b90b0dd18f63fa
C++
y2kiah/icarus
/Icarus/source/Render/Renderer.h
UTF-8
1,223
2.875
3
[]
no_license
/* Renderer.h Author: Jeff Kiah Orig.Date: 5/22/12 Description: Renderer is a base class to be implemented using static polymorphism and the curiously recurring template pattern (CRTP). http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern A #define can be used choose a specific implementation for at compile time. If it is required to support multiple renderers on the same platform (and within the same exe), a runtime decision can be made on which implementation to construct and passing the corresponding class in the template parameter. */ #pragma once class Platform; template <class Implementation> class Renderer_Base { protected: ///// VARIABLES ///// const Platform *m_pPlatform; ///// FUNCTIONS ///// // This class can't be instantiated directly explicit Renderer_Base(const Platform *pPlatform) : m_pPlatform(pPlatform) {} public: bool initRenderer() { return static_cast<Implementation*>(this)->initRenderer(); } void cleanup() { static_cast<Implementation*>(this)->cleanup(); } void render() { static_cast<Implementation*>(this)->render(); } virtual ~Renderer_Base() { cleanup(); } }; #if defined(WIN32) #include "Impl/Renderer_d3d11.h" #endif
true
d46f5111e1ea5e0d57df9dcd6ef8b7aaa436235d
C++
Zenikolas/PosixThreadPool
/test/threadPoolTest.cpp
UTF-8
2,310
3.125
3
[]
no_license
#include "ThreadPool.hpp" #include <atomic> #include <gtest/gtest.h> #include <gmock/gmock.h> class CallableMock { public: MOCK_METHOD0(run, void()); }; std::atomic<bool> start{false}; class Waiter { public: void run() { while(!start); } }; TEST(ThreadPoolTest, smoke) { threadUtils::ThreadPool threadPool(4); CallableMock callable; const size_t N = 200; EXPECT_CALL(callable, run()).Times(N); for (size_t i = 0; i < N; ++i) { EXPECT_TRUE(threadPool.Enqueue(callable)); } threadPool.StopBlocking(); ASSERT_FALSE(threadPool.Enqueue(callable)); } TEST(ThreadPoolTest, ordering) { using ::testing::InSequence; Waiter waiter; threadUtils::ThreadPool threadPool(1); const size_t lowCallableSize = 6; const size_t normalCallableSize = 4; const size_t highCallableSize = 6; CallableMock lowCallable[lowCallableSize]; CallableMock normalCallable[normalCallableSize]; CallableMock highCallable[highCallableSize]; { InSequence dummy; EXPECT_CALL(highCallable[0], run()); EXPECT_CALL(highCallable[1], run()); EXPECT_CALL(highCallable[2], run()); EXPECT_CALL(normalCallable[0], run()); EXPECT_CALL(highCallable[3], run()); EXPECT_CALL(highCallable[4], run()); EXPECT_CALL(highCallable[5], run()); EXPECT_CALL(normalCallable[1], run()); EXPECT_CALL(normalCallable[2], run()); EXPECT_CALL(normalCallable[3], run()); EXPECT_CALL(lowCallable[0], run()); EXPECT_CALL(lowCallable[1], run()); EXPECT_CALL(lowCallable[2], run()); EXPECT_CALL(lowCallable[3], run()); EXPECT_CALL(lowCallable[4], run()); EXPECT_CALL(lowCallable[5], run()); } threadPool.Enqueue(waiter); sleep(5); for (size_t i = 0; i < lowCallableSize; ++i) { EXPECT_TRUE(threadPool.Enqueue(lowCallable[i], threadUtils::ThreadPool::low)); } for (size_t i = 0; i < normalCallableSize; ++i) { EXPECT_TRUE(threadPool.Enqueue(normalCallable[i], threadUtils::ThreadPool::normal)); } for (size_t i = 0; i < highCallableSize; ++i) { EXPECT_TRUE(threadPool.Enqueue(highCallable[i], threadUtils::ThreadPool::high)); } start = true; threadPool.StopBlocking(); }
true
1fa0d6743ad68ecec1820ebac46bdd2e06176cdc
C++
charlesrwest/GoodBotLearning
/src/library/Experimenter.cpp
UTF-8
3,272
3.109375
3
[ "BSD-2-Clause" ]
permissive
#include "Experimenter.hpp" #include<random> #include<chrono> #include<set> #include<iostream> using namespace GoodBot; Investigator::Investigator(const InvestigatorRunConstraints& constraints, const std::function<double(const std::vector<double>&, const std::vector<int64_t>&)> objectiveFunction) : Objective(objectiveFunction), Constraints(constraints) { } template<class DataType> std::size_t GenerateHash(const std::vector<DataType>& data) { std::size_t hash = 0x0; for(const DataType& entry : data) { hash += std::hash<DataType>{}(entry); } return hash; } double Investigator::Optimize() { //Don't have a good mixed integer optimization method right now, so gonna do random sampling //Make random parameter generators std::vector<std::uniform_int_distribution<int64_t>> int_arg_generators; std::vector<std::uniform_real_distribution<double>> double_arg_generators; for(const std::pair<int64_t, int64_t>& integer_constraint : Constraints.IntegerConstraints) { int_arg_generators.emplace_back(integer_constraint.first, integer_constraint.second); } for(const std::pair<double, double>& double_constraint : Constraints.DoubleConstraints) { double_arg_generators.emplace_back(double_constraint.first, double_constraint.second); } std::random_device randomness; std::mt19937 generator(randomness()); auto GenerateIntegerArguments = [&]() { std::vector<int64_t> arguments; for(std::uniform_int_distribution<int64_t>& distribution : int_arg_generators) { arguments.emplace_back(distribution(generator)); } return arguments; }; auto GenerateDoubleArguments = [&]() { std::vector<double> arguments; for(std::uniform_real_distribution<double>& distribution : double_arg_generators) { arguments.emplace_back(distribution(generator)); } return arguments; }; auto GetCurrentTime = []() { return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); }; int64_t start_time = GetCurrentTime(); std::set<std::pair<std::size_t, std::size_t>> hashes; //Integer argument hash, double argument hash double smallest_value = std::numeric_limits<double>::max(); while((GetCurrentTime() - start_time) < Constraints.MaxRunTimeMilliSeconds) { try { //Generate and try random parameters std::vector<int64_t> integer_parameters = GenerateIntegerArguments(); std::vector<double> double_parameters = GenerateDoubleArguments(); std::pair<std::size_t, std::size_t> hash{GenerateHash(integer_parameters), GenerateHash(double_parameters)}; if(hashes.count(hash) > 0) { //Did this one already, so skip continue; } double value = Objective(double_parameters, integer_parameters); hashes.insert(hash); smallest_value = std::min(value, smallest_value); } catch(const std::exception& exception) { std::cout << "Got an exception, supressing" << std::endl; } } return smallest_value; }
true
698c35992e646728986cce3b82c443a22e3465a6
C++
iliescu6/GLT
/Engine/Engine/InputManager.h
UTF-8
1,092
2.78125
3
[]
no_license
#ifndef CINPUT_MANAGER #define CINPUT_MANAGER #include "includes.h" enum eMouseButtons { LEFT_MOUSE_BUTTON=0,MIDDLE_MOUSE_BUTTON,RIGHT_MOUSE_BUTTON }; #define INPUT cInputManager::getSingleton() class cInputManager { private: int m_currentKey[256]; int m_prevKey[256]; cVector2di m_mousePos; unsigned int m_mouseButtons[3]; private: cInputManager(); public: ~cInputManager(); static cInputManager* getSingleton() { static cInputManager* t=0; if(!t) t= new cInputManager(); return t; } static void Update(unsigned char wParam,int lParam, int MousePosX, int MousePosY); bool getKeyPressed( char key) { return m_currentKey[key]==1; } bool getKey(char key) { return (m_currentKey[key]!=0); } bool getMouseButtonState(eMouseButtons but) { return m_mouseButtons[but]!=0; } bool getKeyReleased(char key) { return (m_currentKey[key]==0)!=m_prevKey[key]; } cVector2di getMousePos() { POINT mouse; GetCursorPos(&mouse); m_mousePos.x=mouse.x; m_mousePos.y=mouse.y; return m_mousePos; } void Release() { delete getSingleton(); } }; #endif
true
ac5fc07509873583d94de65949a8773829dd2f6e
C++
karvotch/CPP_Code
/Practice/Practice/main4.cpp
UTF-8
2,685
3.265625
3
[]
no_license
//// //// main4.cpp //// Practice //// //// Created by Ronald Ginoti on 8/31/19. //// // //#include <iostream> //#include <ctime> //#include <cmath> //#include <chrono> // for std::chrono functions //using namespace std; // // //class Timer //{ //private: // // Type aliases to make accessing nested type easier // using clock_t = std::chrono::high_resolution_clock; // using second_t = std::chrono::duration<double, std::ratio<1> >; // // std::chrono::time_point<clock_t> m_beg; // //public: // Timer() : m_beg(clock_t::now()) // { // } // // void reset() // { // m_beg = clock_t::now(); // } // // double elapsed() const // { // return std::chrono::duration_cast<second_t>(clock_t::now() - m_beg).count(); // } //}; // // //int getRandomNumber(int min, int max) { // static constexpr double fraction {1.0 / (RAND_MAX + 1.0)}; // // return min + static_cast<int>((max - min + 1)) * (rand() * fraction); //} // // //class Point { //public: // int x, y; // // Point() { // x = getRandomNumber(1, 100); // y = getRandomNumber(1, 100); // } //}; // // //int getDistance(Point point1, Point point2) { // return (abs(point1.x - point2.x) + abs(point1.y - point2.y)); //} // // //int * getClosestPoints(Point *pointsArray, int arrayLength, Point vertex, int numberOfPointsToReturn) { // int distanceToPointsArray[arrayLength]; // int *closestDistanceIndex = new int[numberOfPointsToReturn]; // // for(int i = 0; i < arrayLength; i++) { // distanceToPointsArray[i] = getDistance(vertex, pointsArray[i]); // cout << i << ": " << distanceToPointsArray[i] << "\n" << endl; // } // // for(int i = 0; i < numberOfPointsToReturn; i++) { // int closestDistance = 200; // for(int j = 0; j < arrayLength; j++) { // if(distanceToPointsArray[j] < closestDistance) { // closestDistance = distanceToPointsArray[j]; // closestDistanceIndex[i] = j; // distanceToPointsArray[j] = 201; // } // } // } // // return closestDistanceIndex; //} // // // // //int main() { // Timer t; // srand((unsigned)time(NULL)); // // for(int i = 0; i < 100; i++) { // rand(); // } // // Point pointsArray[100]; // int arrayLength = sizeof(pointsArray) / (sizeof(int) * 2); // Point vertex; // int numberOfPointsToReturn = 2; // // int *result = getClosestPoints(pointsArray, arrayLength, vertex, numberOfPointsToReturn); //// for(int i = 0; i < 100; i++) { //// cout << pointsArray[i].x << " " << pointsArray[i].y << "\n" << endl; //// } // cout << vertex.x << " " << vertex.y << "\n" << endl; // cout << result[0] << " " << result[1] << endl; // // delete result; // // cout << fixed; // cout << "Time elapsed: " << t.elapsed() << " seconds\n"; // cout << scientific; // // return 0; //}
true
fa6770b2cb1ce12daec8a5fc13ca0fb9572a8473
C++
Prakhar-FF13/Competitive-Programming
/CodeForces/382A - Ksenia and Pan Scales.cpp
UTF-8
714
2.921875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main(){ string str; cin>>str; string str2; cin>>str2; string arr[2]; arr[0] = ""; arr[1] = ""; int ind=0; for(int i=0; i<str.length() ;i++){ if(str[i] == '|') { ind++; continue;} arr[ind] += str[i]; } int u = 0; while(arr[0].length() != arr[1].length() && u < str2.length()){ if(arr[0].length() < arr[1].length()) ind=0; else ind=1; arr[ind] += str2[u++]; } ind = 0; while(u < str2.length()){ arr[ind] += str2[u++]; ind = 1 - ind; } if(arr[0].length() != arr[1].length()) cout<<"Impossible"; else cout<<arr[0]<<"|"<<arr[1]; return 0; }
true
ec9b9cee63901f4f5a8164a7000df412f0c865ba
C++
AlexPy/impl-s
/generator.cpp
UTF-8
3,270
3.1875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <vector> #include <map> #include <set> #include <algorithm> #include <string> #include <queue> #include <iostream> #include "generator.h" #include<ctime> #define threshold 2000000 //threshold of 2 seconds for reseting the seed for rand() using namespace std; //generates a random connected graph of 'n' nodes that does not contain //.. loops, double edges and all edges have distinct weights vector<Edge*> generateGraph(int n) { set<int> weights; vector<Edge*> graph; map<int, vector<Edge*> > g; for (int i = 0; i<n; i++) { g[i] = *(new vector<Edge*>()); } if (n == 1) return graph; long long rtime; while (true) { //change seed if no valid edge was produced in more than 2 seconds (threshold) if ((timer() - rtime) > threshold) { rtime = timer(); } int src = rand() % n; int dest = rand() % n; int weight = rand() % ((long)n*(long)n); Edge *edge = new Edge(); edge->src = src; edge->dest = dest; edge->weight = -1; if (src == dest || contains(g, *edge) || contains(&weights, weight)) { continue; } edge->weight = weight; graph.insert(graph.end(), edge); g[src].insert(g[src].end(), edge); g[dest].insert(g[dest].end(), edge); weights.insert(weight); if (isConnected(g, n) && (graph.size() >= (n * 6))) break; rtime = timer(); } return graph; } //checks if the graph (i.e. 'm') contains the edge 'val' bool contains(map<int, vector<Edge*> > m, Edge val) { vector<Edge*>::iterator it; for (it = m[val.src].begin(); it != m[val.src].end(); it++) { if (edgeEquals(*it, &val)) return true; } return false; } //checks if the set of weights (i.e. 'myset') contains the value 'val' bool contains(set<int>* myset, int val) { return myset->find(val) != myset->end(); } //checks if two edges are equal. //Two edges are equal, if their endpoints are equal (unordered pairs of endpoints). bool edgeEquals(Edge* e1, Edge* e2) { return (e1->src == e2->src && e1->dest == e2->dest) || (e1->src == e2->dest && e1->dest == e2->src); } //checks if the graph given as input is connected bool isConnected(map<int, vector<Edge*> > g, int n) { bool *visited = new bool[n]; for (int i = 0; i<n; i++) { visited[i] = false; } queue<int> q; q.push(0); visited[0] = true; int count = 1; while (!q.empty()) { int node = q.front(); q.pop(); vector<Edge*>::iterator it; for (it = g[node].begin(); it != g[node].end(); it++) { //neighbour index int index = (*it)->getOtherEndpoint(node); if (index == -1) printf("error!!"); if (visited[index]) continue; q.push(index); visited[index] = true; count++; } } return count == n; } void print(vector<Edge*> g) { cout << "graph begin" << endl; vector<Edge*>::iterator it; for (it = g.begin(); it != g.end(); it++) { cout << (**it).src << " " << (**it).dest << " " << (**it).weight << endl; } cout << "graph end" << endl; } void print(set<int> s) { cout << "weights begin" << endl; set<int>::iterator it; for (it = s.begin(); it != s.end(); it++) { cout << (*it) << " "; } cout << endl; cout << "weights end" << endl; } void print(vector<int> s) { vector<int>::iterator it; for (it = s.begin(); it != s.end(); it++) { cout << (*it) << " "; } cout << endl; }
true
c3422b0af9f2ec0b5a7ba57d4495ac432789f058
C++
uytran20111999/Graph
/graph/Source.cpp
UTF-8
4,308
2.953125
3
[]
no_license
#include<iostream> #include<vector> #include<climits> #include<fstream> using namespace std; struct vertex { int key; int index; vertex * p; }; struct graph { vector<vertex> vertices; int numedges; int **edge; }; int ** creat2Darr (int n){ int ** u = new int*[n]; for (int i = 0; i < n; i++) { u[i] = new int[n]; } return u; } void del2d(int ** u,int n){ for (int i = 0; i < n; i++) { if (u[i] != nullptr)delete[]u[i]; } delete[]u; } bool isExist(const vector<vertex*> & a,vertex b) { for (int i = 0; i < a.size(); i++) { if (a[i]->index == b.index)return 1; int k = 0; } return 0; } vertex * ExtractMin(vector<vertex*>& a) { if (!a.empty()) { vertex* temp = a[0]; int j = 0; for (int i = 0; i < a.size(); i++) { if (temp->key > a[i]->key) { temp = a[i]; j = i; } } swap(a[j], a[a.size() - 1]); a.pop_back(); return temp; } else return NULL; } void MST_PRIME(graph & G , int i){ for (int r = 0; r < G.vertices.size(); r++) { G.vertices[r].index = r; G.vertices[r].key = INT_MAX; G.vertices[r].p = NULL; } G.vertices[i].key = 0; vector <vertex*> Q; for (int w = 0; w < G.vertices.size(); w++) { Q.push_back( &G.vertices[w]); } while (!Q.empty()) { vertex * u = ExtractMin(Q); for (int i = 0; i < G.numedges; i++) { if (G.edge[u->index][i] != -1) { if (isExist(Q, G.vertices[i]) && G.edge[u->index][i] < G.vertices[i].key) { G.vertices[i].p = u; G.vertices[i].key = G.edge[u->index][i]; } } } } } void printMST(graph& G) { for (int i = 0; i < G.vertices.size(); i++) { if (G.vertices[i].p != NULL) { cout << G.vertices[i].p->index << "-------------------" << G.vertices[i].index << " : " << G.vertices[i].key << endl; } } } void relax(vertex&u,vertex&v , graph & G){ if (v.key > u.key + G.edge[u.index][v.index]) { v.p = &u; v.key = u.key + G.edge[u.index][v.index]; } } void init(graph& G) { for (int r = 0; r < G.vertices.size(); r++) { G.vertices[r].index = r; G.vertices[r].key = INT_MAX; G.vertices[r].p = NULL; } } bool bellman(graph&G, int s) { init(G); G.vertices[s].key = 0; for (int z = 1; z <= G.vertices.size() - 1; z++) { for (int i = 0; i < G.numedges; i++) { for (int j = 0; j< G.numedges;j++){ if (G.edge[i][j] != INT_MAX) { relax(G.vertices[i], G.vertices[j], G); } } } } for (int i = 0; i < G.numedges; i++) { for (int j = 0; j< G.numedges; j++) { if (G.edge[i][j] != INT_MAX) { if (G.vertices[j].key > G.vertices[i].key + G.edge[i][j]) { return false; } } } } return true; } void printT(vertex s, vertex* p){ if (p->index == s.index) { cout << s.index; } else if (p->p != NULL) { printT(s, p->p); cout << "----->" << p->index; } else { cout << " no path " << endl; exit(0); } } void dijsktra(graph&G , int s){ init(G); G.vertices[s].key = 0; vector<vertex*> Q; for (int i = 0; i < G.vertices.size(); i++) { Q.push_back(&G.vertices[i]); } while (!Q.empty()) { vertex * u = ExtractMin(Q); for (int i = 0; i < G.numedges; i++) { if (G.edge[u->index][i] != INT_MAX) relax(*u, G.vertices[i], G); } } } void main(){ /* ifstream in("sample.txt"); int edges; in >> edges; graph G; G.numedges = edges; G.edge = creat2Darr(edges); for (int i = 0; i < edges; i++) { for (int j = 0; j < edges; j++) { int temp = -1; in >> temp; G.edge[i][j] = temp; } } G.vertices.resize(edges); MST_PRIME(G, 0); int sum = 0; for (int i = 0; i < G.vertices.size(); i++) { sum += G.vertices[i].key; } cout << sum << endl; printMST(G); del2d(G.edge, edges);*/ /* ifstream in("bellman.txt"); int edges; in >> edges; graph G; G.numedges = edges; G.edge = creat2Darr(edges); for (int i = 0; i < edges; i++) { for (int j = 0; j < edges; j++) { int temp = -1; in >> temp; G.edge[i][j] = temp; } } G.vertices.resize(edges); bellman(G, 0); printT(G.vertices[0], &G.vertices[1]); del2d(G.edge, edges);*/ ifstream in("dijsktra.txt"); int edges; in >> edges; graph G; G.numedges = edges; G.edge = creat2Darr(edges); for (int i = 0; i < edges; i++) { for (int j = 0; j < edges; j++) { int temp = -1; in >> temp; G.edge[i][j] = temp; } } G.vertices.resize(edges); dijsktra(G, 0); printT(G.vertices[0], &G.vertices[4]); del2d(G.edge, edges); }
true
af5bee98d6b3041e7ae87f71ed6ab69c0482400c
C++
b-xiang/hyrise-1
/src/lib/logical_query_plan/mock_node.cpp
UTF-8
3,736
2.609375
3
[ "MIT" ]
permissive
#include "mock_node.hpp" #include <memory> #include <string> #include <vector> #include "expression/lqp_column_expression.hpp" #include "statistics/table_statistics.hpp" #include "utils/assert.hpp" using namespace std::string_literals; // NOLINT namespace opossum { MockNode::MockNode(const ColumnDefinitions& column_definitions, const std::optional<std::string>& name) : AbstractLQPNode(LQPNodeType::Mock), _name(name), _constructor_arguments(column_definitions) {} MockNode::MockNode(const std::shared_ptr<TableStatistics>& statistics) : AbstractLQPNode(LQPNodeType::Mock), _constructor_arguments(statistics) {} LQPColumnReference MockNode::get_column(const std::string& name) const { const auto& column_definitions = this->column_definitions(); for (auto column_id = ColumnID{0}; column_id < column_definitions.size(); ++column_id) { if (column_definitions[column_id].second == name) return LQPColumnReference{shared_from_this(), column_id}; } Fail("Couldn't find column named '"s + name + "' in MockNode"); } const MockNode::ColumnDefinitions& MockNode::column_definitions() const { Assert(_constructor_arguments.type() == typeid(ColumnDefinitions), "Unexpected type"); return boost::get<ColumnDefinitions>(_constructor_arguments); } const boost::variant<MockNode::ColumnDefinitions, std::shared_ptr<TableStatistics>>& MockNode::constructor_arguments() const { return _constructor_arguments; } const std::vector<std::shared_ptr<AbstractExpression>>& MockNode::column_expressions() const { if (!_column_expressions) { _column_expressions.emplace(); auto column_count = size_t{0}; if (_constructor_arguments.type() == typeid(ColumnDefinitions)) { column_count = boost::get<ColumnDefinitions>(_constructor_arguments).size(); } else { column_count = boost::get<std::shared_ptr<TableStatistics>>(_constructor_arguments)->column_statistics().size(); } for (auto column_id = ColumnID{0}; column_id < column_count; ++column_id) { const auto column_reference = LQPColumnReference(shared_from_this(), column_id); _column_expressions->emplace_back(std::make_shared<LQPColumnExpression>(column_reference)); } } return *_column_expressions; } std::string MockNode::description() const { return "[MockNode '"s + _name.value_or("Unnamed") + "']"; } std::shared_ptr<TableStatistics> MockNode::derive_statistics_from( const std::shared_ptr<AbstractLQPNode>& left_input, const std::shared_ptr<AbstractLQPNode>& right_input) const { Assert(_constructor_arguments.type() == typeid(std::shared_ptr<TableStatistics>), "Can only return statistics from statistics mock node"); return boost::get<std::shared_ptr<TableStatistics>>(_constructor_arguments); } std::shared_ptr<AbstractLQPNode> MockNode::_on_shallow_copy(LQPNodeMapping& node_mapping) const { if (_constructor_arguments.type() == typeid(std::shared_ptr<TableStatistics>)) { return MockNode::make(boost::get<std::shared_ptr<TableStatistics>>(_constructor_arguments)); } else { return MockNode::make(boost::get<ColumnDefinitions>(_constructor_arguments)); } } bool MockNode::_on_shallow_equals(const AbstractLQPNode& rhs, const LQPNodeMapping& node_mapping) const { const auto& mock_node = static_cast<const MockNode&>(rhs); if (_constructor_arguments.which() != mock_node._constructor_arguments.which()) return false; if (_constructor_arguments.type() == typeid(ColumnDefinitions)) { return boost::get<ColumnDefinitions>(_constructor_arguments) == boost::get<ColumnDefinitions>(mock_node._constructor_arguments); } else { Fail("Comparison of statistics not implemented, because this is painful"); } } } // namespace opossum
true
ced6224148a7cfb72af0967bc02de44ddd94c388
C++
moulik-roy/SPOJ
/AE00.cpp
UTF-8
271
2.71875
3
[]
no_license
#include <iostream> using namespace std; int main(){ int N, i, j, count; cin>>N; for(i=2, count=1; i<=N; i++){ for(j=1; j*j<=i; j++){ if(i%j==0) count++; } } cout<<count<<"\n"; return 0; }
true
b381f35f2d34270b41b070adc5dde57ea2d7145d
C++
ardaOnal/CS201
/hw4/FlightMap.h
UTF-8
691
2.53125
3
[]
no_license
// Arda Onal 21903350 Section1 #ifndef __FLIGHTMAP_H #define __FLIGHTMAP_H #include "CityList.h" #include "FlightList.h" class FlightMap { public: FlightMap( const string cityFile, const string flightFile ); ~FlightMap(); void displayAllCities() const; void displayAdjacentCities( const string cityName ) const; void displayFlightMap() const; void findFlights( const string deptCity, const string destCity ) const; void findLeastCostFlight( const string deptCity, const string destCity ) const; void runFlightRequests( const string requestFile ) const; private: CityList cities; FlightList flights; int** cityMatrix; }; #endif
true
c2fdbe6bc737ba2b6e5a89a89fc9fa6dade1b247
C++
hackerlank/XEffect2D
/engine/XEffeEngine/XControl/XImageList.h
GB18030
3,481
2.546875
3
[]
no_license
#ifndef _JIA_XIMAGELIST_ #define _JIA_XIMAGELIST_ //++++++++++++++++++++++++++++++++ //Author: ʤ(JiaShengHua) //Version: 1.0.0 //Date: 2014.3.5 //-------------------------------- //һͼγеĿؼ #include "XButtonEx.h" #include "XSlider.h" #include <deque> namespace XE{ class XImageList:public XControlBasic { private: XBool m_isInited; public: enum XImageListEvent { IMGLST_INIT, IMGLST_RELEASE, IMGLST_SELECT_CHANGE, }; // void (*m_funInit)(void *,int ID); // void (*m_funRelease)(void *,int ID); // void (*m_funSelectChange)(void *,int ID); // void *m_pClass; //صIJ protected: void draw(); void drawUp(); void update(float stepTime); XBool mouseProc(float x,float y,XMouseState mouseState); //궯Ӧ XBool keyboardProc(int,XKeyState){return XFalse;} //Ƿ񴥷 private: float m_buttonWidth; //ҰťĿ XVector2 m_imageSize; //беͼƬ int m_showImageSum; int m_curSelectImageIndex; //ǰѡͼƬ int m_curShowImageIndex; //ǰʾͼƬʼ XButtonEx m_leftBtn; //ߵİť XButtonEx m_rightBtn; //ұߵİť XSlider m_imageSld; // std::deque<XSprite *> m_imageList; //ͼƬ void updateState(bool flag = true); //ʵʵݸ½ //static void imageListCtrCB(void * pClass,int id); static void ctrlProc(void *,int,int); public: XBool initWithoutSkin(float buttonWidth, //ҰťĿ const XVector2 &imageSize, //ͼƬijߴ int showImageSum); //ʾͼƬ XBool addImage(const char * filename); XBool addImage(const XTextureData &tex); //δʵ XBool addImage(const XSprite &sprite); //δʵ XImageList() :m_isInited(XFalse) // ,m_funInit(NULL) // ,m_funRelease(NULL) // ,m_funSelectChange(NULL) // ,m_pClass(NULL) { m_ctrlType = CTRL_OBJ_IMAGELIST; } ~XImageList() {release();} void release(); XBool isInRect(float x,float y); //xyǷϣxyĻľ XVector2 getBox(int order); //ȡĸ꣬ĿǰȲת using XObjectBasic::setPosition; //⸲ǵ void setPosition(float x,float y); using XObjectBasic::setScale; //⸲ǵ void setScale(float x,float y); void setTextColor(const XFColor&) {;} //ɫ XFColor getTextColor() const {return XFColor::white;} //ȡؼɫ using XObjectBasic::setColor; //⸲ǵ void setColor(float r,float g,float b,float a); void setAlpha(float a); void setCallbackFun(void (* funInit)(void *,int), void (* funRelease)(void *,int), void (* funSelectChange)(void *,int), void *pClass = NULL); void insertChar(const char *,int){;} XBool canGetFocus(float x,float y); //жϵǰǷԻý XBool canLostFocus(float,float){return XTrue;} //void setLostFocus(); //ʧȥ void disable(); void enable(); void setVisible(); void disVisible(); XBool setACopy(const XImageList &) //һ {//δʵ return XFalse; } //virtual void justForTest() {;} private://Ϊ˷ֹظֵƹ캯 XImageList(const XImageList &temp); XImageList& operator = (const XImageList& temp); }; #if WITH_INLINE_FILE #include "XImageList.inl" #endif } #endif
true
4c8f2e0bda045eb2fa3d91871b10e88f95e2bdeb
C++
vivisuke/NumberLink
/NumberLink/NumberLink/genQuestions.cpp
UTF-8
4,909
2.59375
3
[ "MIT" ]
permissive
#include <iostream> #include "Board.h" #include <random> using namespace std; typedef unsigned char uchar; typedef const char cchar; extern mt19937 g_mt; cchar *q2x2 = "11" ".."; cchar *q4x4 = "3..3" "24.." ".1.." ".214"; cchar *q4x4_2 = "1..." "...." "...." "1..."; cchar *q4x4_3 = "1..." "...." "...." "...1"; cchar *q5x5 = "32..4" "3...." "4...." "21.1." "....."; cchar *q5x5_2 = "5.54." "1.1.." "3.4.2" "6..2." ".63.."; cchar *q6x6 = "3....." ".4.31." "......" ".2...." ".1.4.2" "......"; cchar *q6x6_2 = ".3..2." "......" ".1.3.." ".2...." "......" ".....1"; cchar *q6x6_3 = "2...3." "......" "...11." "3....." "......" "2....."; int main(int argc, char *argv[]) { int WD = 6; int NP = 5; // if( argc >= 2 ) { WD = atoi(argv[1]); NP = atoi(argv[2]); } cout << "WD = " << WD << ", NP = " << NP << "\n\n"; #if 0 cchar *ptr; #if 0 Board bd(2); bd.setNumber(ptr = q2x2); #endif #if 0 Board bd(4); bd.setNumber(ptr = q4x4); #endif #if 1 Board bd(5); bd.setNumber(ptr = q5x5_2); #endif #if 0 Board bd(6); bd.setNumber(ptr = q6x6_3); #endif cout << bd.text() << "\n\n"; bool rc = bd.doSolve2(); if (rc) cout << "found.\n"; else cout << "failed.\n"; cout << bd.text2() << "\n"; if( rc ) { bd.setNumber(ptr); if( bd.isUniq() ) { cout << "uniq.\n"; cout << bd.textLink2() << "\n"; if( bd.doesIncludeMeaninglessLink() ) { cout << "Meaningless included.\n"; } else { cout << "Meaningless Not included.\n"; } } else cout << "Not uniq.\n"; cout << bd.text() << "\n\n"; } #endif #if 0 Board bd(4); for (int ix1 = 0; ix1 < bd.size(); ++ix1) { if( bd.number(ix1) != 0 ) continue; bd.setNumber(ix1, 1); for (int ix12 = ix1 + 2; ix12 < bd.size(); ++ix12) { if( bd.number(ix12) != 0 ) continue; if( ix12 > bd.width() && bd.number(ix12-bd.width()) == 1 ) continue; bd.setNumber(ix12, 1); for (int ix2 = ix1 + 1; ix2 < bd.size(); ++ix2) { if( bd.number(ix2) != 0 ) continue; bd.setNumber(ix2, 2); for (int ix22 = ix2 + 2; ix22 < bd.size(); ++ix22) { if( bd.number(ix22) != 0 ) continue; if( ix22 > bd.width() && bd.number(ix22-bd.width()) == 2 ) continue; bd.setNumber(ix22, 2); for (int ix3 = ix2 + 1; ix3 < bd.size(); ++ix3) { if( bd.number(ix3) != 0 ) continue; bd.setNumber(ix3, 3); for (int ix32 = ix3 + 2; ix32 < bd.size(); ++ix32) { if( bd.number(ix32) != 0 ) continue; if( ix32 > bd.width() && bd.number(ix32-bd.width()) == 3 ) continue; bd.setNumber(ix32, 3); if( bd.isUniq() ) { cout << bd.text() << "\n\n"; getchar(); } bd.setNumber(ix32, 0); } bd.setNumber(ix3, 0); } bd.setNumber(ix22, 0); } bd.setNumber(ix2, 0); } bd.setNumber(ix12, 0); } bd.setNumber(ix1, 0); } #endif Board bd(/*wd=*/WD); int cnt[] = {0, 0, 0, 0}; for (int i = 0; i < 10000; ++i) { bd.setRandom(/*NP=*/NP); bd.isUniq(); int n = bd.nSolved(); cnt[n] += 1; if( n == 1 ) { cout << bd.text() << "\n\n"; if( !bd.doesIncludeMeaninglessLink() ) cnt[3] += 1; } } for(auto c : cnt) { cout << c << "\n"; } #if 0 Board bd(/*wd=*/WD); for (int i = 0; i < 30; ++i) { bd.genRandom(/*NP=*/NP); cout << bd.text0() << "\n"; } #endif #if 0 Board bd(/*wd=*/WD); vector<int> pos; // リンク伸張可能な端点リスト for (int i = 0; i < NP; ++i) { for(;;) { int ix = g_mt() % bd.size(); if( bd.number(ix) == 0 ) { bd.setNumber(ix, i+1); pos.push_back(ix); break; } } } cout << bd.text2() << "\n\n"; vector<uchar> t; // 伸張可能先リスト t.reserve(4); while( !pos.empty() ) { int i = g_mt() % pos.size(); int ix = pos[i]; int x = ix % WD; int y = ix / WD; t.clear(); if( y != 0 && bd.number(ix - WD) == 0 ) t.push_back(LINK_UP); if( x != 0 && bd.number(ix - 1) == 0 ) t.push_back(LINK_LEFT); if( x != WD - 1 && bd.number(ix + 1) == 0 ) t.push_back(LINK_RIGHT); if( y != WD - 1 && bd.number(ix + WD) == 0 ) t.push_back(LINK_DOWN); if( t.empty() ) { // 伸張不可能だった場合 pos.erase(pos.begin() + i); } else { int n = bd.number(ix); auto dir = t[g_mt() % t.size()]; int ix2; for (;;) { switch( dir ) { case LINK_UP: ix2 = ix - WD; --y; break; case LINK_LEFT: ix2 = ix - 1; --x; break; case LINK_RIGHT: ix2 = ix + 1; ++x; break; case LINK_DOWN: ix2 = ix + WD; ++y; break; } if( x < 0 || x >= WD || y < 0 || y >= WD || bd.number(ix2) != 0 ) { break; } bd.orLink(ix, dir); ix = ix2; bd.orLink(ix, revDir(dir)); bd.setNumber(ix, n); pos[i] = ix; } cout << bd.text2() << "\n\n"; } } #endif return 0; }
true
0a60124aec3c8adbce064f7f8b738325c5fe8429
C++
adbjesus/mooutils
/tests/mooutils/orders.cpp
UTF-8
12,743
2.875
3
[ "MIT" ]
permissive
#include <catch2/catch.hpp> #include <mooutils/orders.hpp> // TODO improve sets/vectors generation constexpr size_t min_m{2}; constexpr size_t max_m{10}; // exclusive constexpr size_t repeats{50}; constexpr int min_v{0}; constexpr int max_v{100}; TEST_CASE("equivalent vectors", "[orders][dominance]") { auto m = GENERATE(range(min_m, max_m)); auto v1 = GENERATE_COPY(chunk(m, take(m + repeats, random(min_v, max_v)))); auto v2 = v1; REQUIRE(mooutils::equivalent(v1, v2) == true); REQUIRE(mooutils::weakly_dominates(v1, v2) == true); REQUIRE(mooutils::dominates(v1, v2) == false); REQUIRE(mooutils::strictly_dominates(v1, v2) == false); REQUIRE(mooutils::incomparable(v1, v2) == false); REQUIRE(mooutils::equivalent(v2, v1) == true); REQUIRE(mooutils::weakly_dominates(v2, v1) == true); REQUIRE(mooutils::dominates(v2, v1) == false); REQUIRE(mooutils::strictly_dominates(v2, v1) == false); REQUIRE(mooutils::incomparable(v2, v1) == false); } TEST_CASE("vector1 dominates vector2", "[orders][dominance]") { auto m = GENERATE(range(min_m, max_m)); auto v1 = GENERATE_COPY(chunk(m, take(m + repeats, random(min_v, max_v)))); auto ind = GENERATE_COPY(range(size_t(0), m)); auto v2 = v1; v2[ind] -= 1; REQUIRE(mooutils::equivalent(v1, v2) == false); REQUIRE(mooutils::weakly_dominates(v1, v2) == true); REQUIRE(mooutils::dominates(v1, v2) == true); REQUIRE(mooutils::strictly_dominates(v1, v2) == false); REQUIRE(mooutils::incomparable(v1, v2) == false); REQUIRE(mooutils::equivalent(v2, v1) == false); REQUIRE(mooutils::weakly_dominates(v2, v1) == false); REQUIRE(mooutils::dominates(v2, v1) == false); REQUIRE(mooutils::strictly_dominates(v2, v1) == false); REQUIRE(mooutils::incomparable(v2, v1) == false); } TEST_CASE("vector1 strictly dominates vector2", "[orders][dominance]") { auto m = GENERATE(range(min_m, max_m)); auto v1 = GENERATE_COPY(chunk(m, take(m + repeats, random(min_v, max_v)))); auto v2 = v1; std::for_each(v2.begin(), v2.end(), [](auto &v) { return v = v - 1; }); REQUIRE(mooutils::equivalent(v1, v2) == false); REQUIRE(mooutils::weakly_dominates(v1, v2) == true); REQUIRE(mooutils::dominates(v1, v2) == true); REQUIRE(mooutils::strictly_dominates(v1, v2) == true); REQUIRE(mooutils::incomparable(v1, v2) == false); REQUIRE(mooutils::equivalent(v2, v1) == false); REQUIRE(mooutils::weakly_dominates(v2, v1) == false); REQUIRE(mooutils::dominates(v2, v1) == false); REQUIRE(mooutils::strictly_dominates(v2, v1) == false); REQUIRE(mooutils::incomparable(v2, v1) == false); } TEST_CASE("incomparable vectors", "[orders][dominance]") { auto m = GENERATE(range(min_m, max_m)); auto v1 = GENERATE_COPY(chunk(m, take(m + repeats, random(min_v, max_v)))); auto ind1 = GENERATE_COPY(range(size_t(0), m)); auto ind2 = GENERATE_COPY(range(size_t(0), m)); if (ind1 != ind2) { auto v2 = v1; v2[ind1] += 1; v2[ind2] -= 1; REQUIRE(mooutils::equivalent(v1, v2) == false); REQUIRE(mooutils::weakly_dominates(v1, v2) == false); REQUIRE(mooutils::dominates(v1, v2) == false); REQUIRE(mooutils::strictly_dominates(v1, v2) == false); REQUIRE(mooutils::incomparable(v1, v2) == true); REQUIRE(mooutils::equivalent(v2, v1) == false); REQUIRE(mooutils::weakly_dominates(v2, v1) == false); REQUIRE(mooutils::dominates(v2, v1) == false); REQUIRE(mooutils::strictly_dominates(v2, v1) == false); REQUIRE(mooutils::incomparable(v2, v1) == true); } } TEST_CASE("equivalent vector and set", "[orders][dominance]") { auto n = GENERATE(size_t(1), 2, 10); auto m = GENERATE(range(min_m, max_m)); auto v = GENERATE_COPY(chunk(m, take(m + repeats, random(min_v, max_v)))); auto s = std::vector<decltype(v)>(n, v); REQUIRE(mooutils::equivalent(v, s) == true); REQUIRE(mooutils::weakly_dominates(v, s) == true); REQUIRE(mooutils::dominates(v, s) == false); REQUIRE(mooutils::strictly_dominates(v, s) == false); REQUIRE(mooutils::incomparable(v, s) == false); REQUIRE(mooutils::equivalent(s, v) == true); REQUIRE(mooutils::weakly_dominates(s, v) == true); REQUIRE(mooutils::dominates(s, v) == false); REQUIRE(mooutils::strictly_dominates(s, v) == false); REQUIRE(mooutils::incomparable(s, v) == false); } TEST_CASE("vector (strictly) dominates set", "[orders][dominance]") { auto n = GENERATE(size_t(1), 2, 5, 10); auto m = GENERATE(range(min_m, max_m)); auto v = GENERATE_COPY(chunk(m, take(m + repeats, random(min_v, max_v)))); auto inds = GENERATE_COPY(chunk(n, take(n, random(size_t(0), m - 1)))); auto s = std::vector<decltype(v)>(); s.reserve(n); for (auto ind : inds) { auto aux = v; aux[ind] -= 1; s.push_back(std::move(aux)); } REQUIRE(mooutils::equivalent(v, s) == false); REQUIRE(mooutils::weakly_dominates(v, s) == true); REQUIRE(mooutils::dominates(v, s) == true); REQUIRE(mooutils::strictly_dominates(v, s) == true); REQUIRE(mooutils::incomparable(v, s) == false); REQUIRE(mooutils::equivalent(s, v) == false); REQUIRE(mooutils::weakly_dominates(s, v) == false); REQUIRE(mooutils::dominates(s, v) == false); REQUIRE(mooutils::strictly_dominates(s, v) == false); REQUIRE(mooutils::incomparable(s, v) == false); } TEST_CASE("set dominates vector", "[orders][dominance]") { auto n = GENERATE(size_t(1), 2, 5, 10); auto m = GENERATE(range(min_m, max_m)); auto v = GENERATE_COPY(chunk(m, take(m + repeats, random(min_v, max_v)))); auto s = std::vector<decltype(v)>(n, v); auto ind1 = GENERATE_COPY(take(1, random(size_t(0), m - 2))); auto ind2 = GENERATE_COPY(take(1, random(ind1 + 1, m - 1))); auto aux = v; aux[ind1] -= 1; aux[ind2] += 1; s.push_back(std::move(aux)); REQUIRE(mooutils::equivalent(v, s) == false); REQUIRE(mooutils::weakly_dominates(v, s) == false); REQUIRE(mooutils::dominates(v, s) == false); REQUIRE(mooutils::strictly_dominates(v, s) == false); REQUIRE(mooutils::incomparable(v, s) == false); REQUIRE(mooutils::equivalent(s, v) == false); REQUIRE(mooutils::weakly_dominates(s, v) == true); REQUIRE(mooutils::dominates(s, v) == true); REQUIRE(mooutils::strictly_dominates(s, v) == false); REQUIRE(mooutils::incomparable(s, v) == false); } TEST_CASE("set strictly dominates vector", "[orders][dominance]") { auto n = GENERATE(size_t(1), 2, 5, 10); auto m = GENERATE(range(min_m, max_m)); auto v = GENERATE_COPY(chunk(m, take(m + repeats, random(min_v, max_v)))); auto s = std::vector<decltype(v)>(n, v); auto ind = GENERATE_COPY(take(1, random(size_t(0), m - 1))); auto aux = v; aux[ind] += 1; s.push_back(std::move(aux)); REQUIRE(mooutils::equivalent(v, s) == false); REQUIRE(mooutils::weakly_dominates(v, s) == false); REQUIRE(mooutils::dominates(v, s) == false); REQUIRE(mooutils::strictly_dominates(v, s) == false); REQUIRE(mooutils::incomparable(v, s) == false); REQUIRE(mooutils::equivalent(s, v) == false); REQUIRE(mooutils::weakly_dominates(s, v) == true); REQUIRE(mooutils::dominates(s, v) == true); REQUIRE(mooutils::strictly_dominates(s, v) == true); REQUIRE(mooutils::incomparable(s, v) == false); } TEST_CASE("incomparable vector and set", "[orders][dominance]") { auto n = GENERATE(size_t(1), 2, 5, 10); auto m = GENERATE(range(min_m, max_m)); auto aux = GENERATE_COPY(chunk(m * n, take(m * n + repeats, random(min_v, max_v)))); auto s = std::vector<decltype(aux)>(); auto first = aux.begin(); for (size_t i = 0; i < n; ++i) { auto next = first + static_cast<int>(m); s.emplace_back(first, next); first = next; } auto v = GENERATE_COPY(chunk(m, take(m, random(min_v, max_v)))); v[0] = min_v - 1; v[m - 1] = max_v + 1; REQUIRE(mooutils::equivalent(v, s) == false); REQUIRE(mooutils::weakly_dominates(v, s) == false); REQUIRE(mooutils::dominates(v, s) == false); REQUIRE(mooutils::strictly_dominates(v, s) == false); REQUIRE(mooutils::incomparable(v, s) == true); REQUIRE(mooutils::equivalent(s, v) == false); REQUIRE(mooutils::weakly_dominates(s, v) == false); REQUIRE(mooutils::dominates(s, v) == false); REQUIRE(mooutils::strictly_dominates(s, v) == false); REQUIRE(mooutils::incomparable(s, v) == true); } TEST_CASE("equivalent sets", "[orders][dominance]") { auto n = GENERATE(size_t(1), 2, 10); auto m = GENERATE(range(min_m, max_m)); auto aux = GENERATE_COPY(chunk(m * n, take(m * n + repeats, random(min_v, max_v)))); auto s1 = std::vector<decltype(aux)>(); auto first = aux.begin(); for (size_t i = 0; i < n; ++i) { auto next = first + static_cast<int>(m); s1.emplace_back(first, next); first = next; } auto s2 = s1; REQUIRE(mooutils::equivalent(s1, s2) == true); REQUIRE(mooutils::weakly_dominates(s1, s2) == true); REQUIRE(mooutils::dominates(s1, s2) == false); REQUIRE(mooutils::strictly_dominates(s1, s2) == false); REQUIRE(mooutils::incomparable(s1, s2) == false); REQUIRE(mooutils::equivalent(s2, s1) == true); REQUIRE(mooutils::weakly_dominates(s2, s1) == true); REQUIRE(mooutils::dominates(s2, s1) == false); REQUIRE(mooutils::strictly_dominates(s2, s1) == false); REQUIRE(mooutils::incomparable(s2, s1) == false); } TEST_CASE("set1 dominates set2", "[orders][dominance]") { auto n = GENERATE(size_t(1), 2, 10); auto m = GENERATE(range(min_m, max_m)); auto aux = GENERATE_COPY(chunk(m * n, take(m * n + repeats, random(min_v, max_v)))); auto s1 = std::vector<decltype(aux)>(); auto first = aux.begin(); for (size_t i = 0; i < n; ++i) { auto next = first + static_cast<int>(m); s1.emplace_back(first, next); first = next; } auto s2 = s1; auto v1 = GENERATE_COPY(chunk(m, take(m, random(min_v, max_v)))); v1[0] = min_v - 1; v1[m - 1] = max_v + 1; s1.push_back(std::move(v1)); REQUIRE(mooutils::equivalent(s1, s2) == false); REQUIRE(mooutils::weakly_dominates(s1, s2) == true); REQUIRE(mooutils::dominates(s1, s2) == true); REQUIRE(mooutils::strictly_dominates(s1, s2) == false); REQUIRE(mooutils::incomparable(s1, s2) == false); REQUIRE(mooutils::equivalent(s2, s1) == false); REQUIRE(mooutils::weakly_dominates(s2, s1) == false); REQUIRE(mooutils::dominates(s2, s1) == false); REQUIRE(mooutils::strictly_dominates(s2, s1) == false); REQUIRE(mooutils::incomparable(s2, s1) == false); } TEST_CASE("set1 strictly dominates set2", "[orders][dominance]") { auto n = GENERATE(size_t(1), 2, 10); auto m = GENERATE(range(min_m, max_m)); auto aux = GENERATE_COPY(chunk(m * n, take(m * n + repeats, random(min_v, max_v)))); auto inds = GENERATE_COPY(chunk(n, take(n, random(size_t(0), m - 1)))); auto s1 = std::vector<decltype(aux)>(); auto first = aux.begin(); for (size_t i = 0; i < n; ++i) { auto next = first + static_cast<int>(m); s1.emplace_back(first, next); first = next; } auto s2 = s1; for (size_t i = 0; i < n; ++i) { s1[i][inds[i]] += 1; } CAPTURE(s1, s2); REQUIRE(mooutils::equivalent(s1, s2) == false); REQUIRE(mooutils::weakly_dominates(s1, s2) == true); REQUIRE(mooutils::dominates(s1, s2) == true); REQUIRE(mooutils::strictly_dominates(s1, s2) == true); REQUIRE(mooutils::incomparable(s1, s2) == false); REQUIRE(mooutils::equivalent(s2, s1) == false); REQUIRE(mooutils::weakly_dominates(s2, s1) == false); REQUIRE(mooutils::dominates(s2, s1) == false); REQUIRE(mooutils::strictly_dominates(s2, s1) == false); REQUIRE(mooutils::incomparable(s2, s1) == false); } TEST_CASE("incomparable sets", "[orders][dominance]") { auto n = GENERATE(size_t(1), 2, 5, 10); auto m = GENERATE(range(min_m, max_m)); auto aux1 = GENERATE_COPY(chunk(m * n, take(m * n + repeats, random(min_v, max_v)))); auto s1 = std::vector<decltype(aux1)>(); auto first = aux1.begin(); for (size_t i = 0; i < n; ++i) { auto next = first + static_cast<int>(m); s1.emplace_back(first, next); first = next; } auto s2 = s1; auto v1 = GENERATE_COPY(chunk(m, take(m, random(min_v, max_v)))); v1[0] = min_v - 1; v1[m - 1] = max_v + 1; auto v2 = GENERATE_COPY(chunk(m, take(m, random(min_v, max_v)))); v2[0] = max_v + 1; v2[m - 1] = min_v - 1; s1.push_back(std::move(v1)); s2.push_back(std::move(v2)); REQUIRE(mooutils::equivalent(s1, s2) == false); REQUIRE(mooutils::weakly_dominates(s1, s2) == false); REQUIRE(mooutils::dominates(s1, s2) == false); REQUIRE(mooutils::strictly_dominates(s1, s2) == false); REQUIRE(mooutils::incomparable(s1, s2) == true); REQUIRE(mooutils::equivalent(s2, s1) == false); REQUIRE(mooutils::weakly_dominates(s2, s1) == false); REQUIRE(mooutils::dominates(s1, s2) == false); REQUIRE(mooutils::strictly_dominates(s1, s2) == false); REQUIRE(mooutils::incomparable(s1, s2) == true); }
true
7918bfbfd974776119eea7e723a34e65f965bbde
C++
andika-eka/praktikum-alpro-ilkom-undiksha-2k19
/modul 3/Otonan.cpp
UTF-8
3,714
2.890625
3
[]
no_license
#include <iostream> #include <cstdlib> #include <string> #include <conio.h> using namespace std; int kabisat(int start, int stop){ //menghitung jumlah tahun kabisat int days = (stop/4)-(start/4); days-=(stop/100)-(start/100); days +=(stop/400)-(start/400); return days; } int Tahun(int start, int stop){ //menghitung jumlah hari int days = 365*(stop-start); days +=kabisat(start,stop-1); return days; } int Hari(int tgl, int bln, int tahun){ //menghitung jumlah hari dari 1 january 1950 bool kabisat;// chekc apakah kabisat if (tahun %4 ==0){ kabisat=true; if(tahun%100==0){ kabisat=false; if (tahun%400==0){kabisat=true;} } }else {kabisat=false;} int Days_month[12]={0,31,59,90,120,151,181,212,243,273,304,334}; //jumlah hari sejak 1 januari int days; tgl--; if (bln<=2){ days = Days_month[bln]+tgl; } else{ days= Days_month[bln]+tgl; if(kabisat){days++;} } if(tahun>=1950){days+=Tahun(1950,tahun);} else{ days=Tahun(tahun,1950)-days; } return days; } int bulan (string bln){ string bulan_list[12]={"januari","februari","maret","april","mei","juni", "juli","agustus","september","oktober","november","desember"}; int bulan; for(int i=0;i<=12;i++){ if (bln ==bulan_list[i]){ bulan= i; break; } bulan =13; } return bulan; } int main(int argc, char *argv[]){ bool valid_input=true; int tgl,bln,tahun; if (argc==1){ string blnstr; cout<<"masukan tanggal lahir anda: "<<endl; cout<<"tanggal: "; cin >>tgl; cout<<"bulan :"; cin >>blnstr; bln =bulan(blnstr); cout<<"tahun :"; cin>>tahun; if(bln>12){ valid_input=false; } } else if(argc=4){ tgl=atoi(argv[1]); string blnstr(argv[2]); bln =bulan(blnstr); tahun=atoi(argv[3]); if(bln>12){ valid_input=false; } } if(valid_input){ int days = Hari(tgl,bln,tahun); string wara_7List[7]={"radite","soma","anggara","budha","respati","sukra","saniscara"}, wara_5List[5]={"wage", "kliwon","umanis","paing","pon"}, wukuList[30]={"kuningan","langkir","medangsia","pujut","pahang","krulut","merakih","tambir","medangkungan","matal", "uye","menail","prangbakat","bala","ugu","wayang","kelawu","dukut","watugunung","sinta", "landep","ukir","kulantir","tolu","gumbreg","wariga","warigadean","julungwangi","sungsang","dungulan"}; string wara_7, wara_5, wuku; if (tahun >=1950){ int x = days%7; wara_7=wara_7List[x]; x=days%5; wara_5=wara_5List[x]; x=(days/7)%30; wuku=wukuList[x]; } else{ int x = days%7; wara_7=wara_7List[7-x]; x=days%5; wara_5=wara_5List[5-x]; x=(days/7)%30; wuku=wukuList[30-(x+1)]; } cout<<"otonan : "<<wara_7<<" "<<wara_5<<" "<<wuku<<endl; }else{ cout<<"INPUT TIDAK VALID"<<endl <<"hari di input seperti contoh : 1 january 2000"<<endl <<"hari yang di input tidak boleh sebelum 1 january 1950"; } getch (); return 0; } //author : P andika EP 1915101029
true
a95a63dc7f74388bbde05b71f8823636ed7477cc
C++
oysiya/OnlineJudge
/BaekjoonOJ/1009_Divided process.cpp
UTF-8
254
2.515625
3
[]
no_license
#include <stdio.h> int main(int argc, char *argv[]) { int C,a,b,t,i; scanf("%d", &C); for(int c=0;c<C;c++) { scanf("%d %d",&a,&b); t = a%10; for(i=1;i<b;i++) { t *= a; t %= 10; } printf("%d\n",((t==0)?10:t)); } return 0; }
true
bcf1e428580787466bfb42dcbc54d8d4f500869b
C++
gurmaaan/AtlasKidney
/dialogs/authdialog.cpp
UTF-8
2,042
2.65625
3
[]
no_license
#include "authdialog.h" #include "ui_authdialog.h" AuthDialog::AuthDialog(DataBaseService& db, QWidget *parent) : QDialog(parent), ui(new Ui::AuthDialog), db(db) { ui->setupUi(this); // NOTE credentionals hard coding ui->login_le->setText(USER_LOGIN); ui->password_le->setText(USER_PASSWORD); } AuthDialog::~AuthDialog() { delete ui; } void AuthDialog::on_path_btn_clicked() { QString dir = QFileDialog::getExistingDirectory(this, AUTH_CHOSE_FOLDER, QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); setPath(dir); } void AuthDialog::setPath(QString path){ emit basePathChanged(path); ui->path_le->setText(path); } void AuthDialog::on_buttonBox_clicked(QAbstractButton *button) { QList<QAbstractButton*> btnList = ui->buttonBox->buttons(); if(button == btnList.at(0)) { // Ok button action if(db.checkLoginPass(ui->login_le->text(), ui->password_le->text()) && QDir(ui->path_le->text()).exists() && ui->password_le->text().length() > 0) { close(); this->accept(); } else { resetOption(); QMessageBox::critical(nullptr, AUTH_MSG_TITTLE, AUTH_MSG_BODY); } } else if (button == btnList.at(1)) { //Close button action closeOption(); }else if (button == btnList.at(2)) { //Reset button action resetOption(); } } bool AuthDialog::okOption(QString login, QString password) { bool accessGranted = ((ui->login_le->text() == login) && (ui->password_le->text() == password)) ? false : true; return accessGranted; } void AuthDialog::closeOption() { close(); } void AuthDialog::resetOption() { ui->password_le->clear(); ui->login_le->clear(); ui->path_le->clear(); }
true
7ecb865efa0f39cb839dc6f352059b2665a61142
C++
ErinTanaka/OperatingSystemsII
/testfolder/testresource.cpp
UTF-8
1,795
2.96875
3
[]
no_license
#include <iostream> #include <cstdlib> #include <pthread.h> #include <unistd.h> using namespace std; #define NUM_THREADS 7 #define MAX_THREADS 3 //global variables int numProcesses = 0; bool hitMaxThreads=false; int resource[4096]; bool canStartProcesses(){ if(numProcesses == MAX_THREADS || hitMaxThreads==true)return false; return true; } void *executeProcess(void *threadid) { long tid; tid = (long)threadid; while(true){ if(numProcesses == MAX_THREADS || hitMaxThreads==true){ numProcesses++; if (numProcesses==MAX_THREADS){ hitMaxThreads=true; } cout << "Thread ID: " << tid << " accessing resource " << endl; for (int i=0; i<4096; i++){ int temp = resource[i]; } cout << "Thread ID: " << tid << " finished" << endl; numProcesses--; if(numProcesses==0){ hitMaxThreads=false; } pthread_exit(NULL); } } } int main () { srand (time(NULL)); pthread_t threads[NUM_THREADS]; int i; for(i = 0; i < NUM_THREADS; i++ ) { // if(canStartProcesses()){ // cout << "Running thread: " << i << endl; pthread_create(&threads[i], NULL, executeProcess, (void *)i); // numProcesses++; // if (numProcesses==MAX_THREADS){ // hitMaxThreads=true; // } // } // else{ // cout << "Max threads hit waiting for resource" << endl; // pthread_join(threads[i-1], NULL); // pthread_join(threads[i-2], NULL); // pthread_join(threads[i-3], NULL); // cout << "resource available, moving on to thread: " << i << endl; // //sleep(1); // i--; // // } } for(int i=0; i<MAX_THREADS; i++){ pthread_join(threads[i], NULL); } //sleep(10); //cout << "Doneskis" << endl; return 0; }
true
6270fa4d503c976b4cf1496fe42a3324e3977acc
C++
Ghimli/new-ospgl
/src/universe/propagator/RK4Interpolated.h
UTF-8
1,036
2.59375
3
[ "BSD-3-Clause", "MIT" ]
permissive
#pragma once #include "SystemPropagator.h" // Implements a variation of RK4 which only samples the // solar system twice per time step, and interpolates // between samples. Appropiate for relatively small timesteps // and real-life-like systems as planetary variation is pretty // much linear over these scales class RK4Interpolated : public SystemPropagator { private: struct Derivative { glm::dvec3 dx; glm::dvec3 dv; }; PlanetarySystem* sys; PosVector t0_pos; PosVector t05_pos; PosVector t1_pos; MassVector masses; double t_0, t0, t1, tstep; template<bool get_closest> Derivative sample(CartesianState s0, Derivative d, double dt, PosVector& vec, size_t* closest); template<bool get_closest> glm::dvec3 acceleration(glm::dvec3 p, PosVector& vec, size_t* closest); public: virtual void initialize(PlanetarySystem* system, size_t body_count) override; virtual void prepare(double t0, double t, double tstep, PosVector& out_pos) override; virtual size_t propagate(CartesianState* state) override; };
true
2d7d9e65904dbd0bbfcaf0e5b3d081008c295337
C++
Catofes/RootScript
/RootExam/read_data.cpp
UTF-8
1,876
3.34375
3
[]
no_license
// // Created by herbertqiao on 12/21/16. // #include <iostream> #include <TFile.h> #include <TTree.h> #include <vector> #include <string> #include <TChain.h> #include <TMath.h> using namespace std; class ReadData { public: ReadData(string path); void print_distance(); void save_distance(); private: double get_a_distance(int entry); TChain *chain; vector<double> *x; vector<double> *y; vector<double> *z; vector<double> *weight; }; //This is the construct function. It read root file from path and bind the branch address. ReadData::ReadData(string path) { //Load the tree. chain = new TChain("Data"); chain->Add(path.c_str()); //Prepare the vector. x = 0, y = 0, z = 0, weight = 0; //Bind the branch. chain->SetBranchAddress("x", &x); chain->SetBranchAddress("y", &y); chain->SetBranchAddress("z", &z); chain->SetBranchAddress("weight", &weight); } //This function return the mass center's distance for a entry. double ReadData::get_a_distance(int entry) { int particle_number = x->size(); if (particle_number <= 0) return 0; double total_weight = 0; double total_weight_multiply_distance = 0; for (int i = 0; i < particle_number; i++) { double distance = TMath::Sqrt((*x)[i] * (*x)[i] + (*y)[i] * (*y)[i] + (*z)[i] * (*z)[i]); total_weight += (*weight)[i]; total_weight_multiply_distance += (*weight)[i] * distance; } return total_weight_multiply_distance / total_weight; } //This function print all entry's distance void ReadData::print_distance() { for (int i = 0; i < 100; i++) cout << "Center of entry " << i << " :" << get_a_distance(i) << endl; } //You need file void ReadData::save_distance() { } int main() { ReadData *read_data = new ReadData("input_data.root"); read_data->print_distance(); }
true
b605a4414158369e6bc0fbc7c0c2f722776175e8
C++
Syrdni/AiBattle
/code/Game/Messages/DiscoverySet.h
UTF-8
535
2.84375
3
[]
no_license
#pragma once //Message base class #include "ECS/Message.h" //Entity Class #include "ECS/Entity.h" /** Message used when an explorer discovers a set of resources or level objects. Note that a discovery set may contain some identical resources as a preivously sent set. @author Philip Stenmark */ class DiscoverySet : public Message { ECSMessageType(DiscoverySet); public: DiscoverySet(const Set<Ptr<Entity>>& set) : Discoveries(set) {}; // only contains entities with a discoverable component attached Set<Ptr<Entity>> Discoveries; };
true
58606df963487171d31e68499a3199c6f457c293
C++
KyleeValencia/Project-I
/Function/addfriend.cpp
UTF-8
1,050
3.25
3
[]
no_license
#include<stdio.h> #include<string.h> #include<stdlib.h> struct Node { char username[255];//username Node *next; } *head, *tail; Node *createNode(const char *username) { Node *newNode = (Node*)malloc(sizeof(Node)); strcpy(newNode->username, username); return newNode; } void pushHead(const char *username, Node** curr) { Node *temp = createNode(username); temp->next = *curr; *curr = temp; } void printUserList(Node * bingung){ printf("No. Username\n"); while(bingung){ int i=1; printf("%d %s",i,bingung->username); bingung = bingung->next; i++; } } int main(){ Node* A = NULL; // Node* USERS = NUll; <-- users that login // printUserList(userfromlogin); char friendusername[255]; printf("Which user do you wanr to add?\n"); printf(">>"); scanf("%s",friendusername); printf("--Your request has been sent to %s--\n",friendusername); pushHead(friendusername, &A); printf("Press enter to continue!\n"); }
true
4b92184caf93399ccb90a9f595efded2e6b5f03e
C++
mLenehanDCU/EE402
/Assignments/Assignment1/EE402Assignment1/Piano.h
UTF-8
545
2.609375
3
[]
no_license
/* * Piano.h * * Created on: 30 Oct 2018 * Author: mlenehan */ #ifndef PIANO_H_ #define PIANO_H_ #include <iostream> #include "Instrument.h" using std::string; class Piano: public Instrument { private: static int nextPianoSerialNumber; int serialNumber; void construct(); protected: int noOfKeys; public: Piano(); Piano(int, string, float, int); Piano(string, float, int); bool operator < (Piano); bool operator == (Piano); Piano operator + (Piano); virtual void display(); virtual ~Piano(); }; #endif /* PIANO_H_ */
true
9e293e8aef8dd06e6fdb2edd7e07fcd0ca9f28a8
C++
schadov/libwombat
/primitives/FullMatrix.h
UTF-8
2,311
2.71875
3
[]
no_license
#pragma once template<class RealT> class FullMatrix{ public: typedef std::map<unsigned int,RealT> Row; typedef std::vector<Row> MatrData; private: MatrData data_; //unsigned int nrows_,ncolumns; public: void set_value(unsigned int nrow,unsigned int ncolumn, RealT val){ if(data_.size()<=nrow) data_.resize(nrow+1); /*if(data_[nrow].size()<=ncolumn) data_[nrow].resize(ncolumn+1);*/ data_[nrow][ncolumn] = val; } RealT get_value(unsigned int x, unsigned int y){ return data_[x].find(y)->second; } void reserve(unsigned int sz){ data_.resize(sz); //std::for_each(data_.begin(),data_.end(),boost::bind(&Row::resize,_1,sz)); } const Row& row(unsigned int idx) const { return data_[idx]; } unsigned int rows()const{ return data_.size(); } }; template<class RealT> class CNCLoader{ template<class Fun> static bool parse_a(char* buf, Fun &cb){ char* c = buf; char* cn = buf; cn = strchr(c,' '); if(cn==0) return false; *cn = 0; unsigned int m = atoi(c); c = cn + 1; cn = strchr(c,' '); if(cn==0) return false; *cn = 0; unsigned int n = atoi(c); c = cn + 1; RealT a = static_cast<RealT>(atof(c)); cb(m,n,a); return true; } template<class Fun> static bool parse_b(char* buf, Fun &cb){ char* c = buf; char* cn = buf; cn = strchr(c,' '); if(cn==0) return false; *cn = 0; unsigned int m = atoi(c); c = cn + 1; RealT a = static_cast<RealT>(atof(c)); cb(m,a); return true; } template<class Funa,class Funb> static bool parse(char* buf, Funa &cba,Funb &cbb){ char* c = buf; char* cn = buf; cn = strchr(c,' '); if(cn==0) return false; *cn = 0; if(strcmp(c,"a")==0){ return parse_a(cn+1,cba); } if(strcmp(c,"b")==0){ return parse_b(cn+1,cbb); //return true; } return false; } public: template<class Fun,class Funb,class Fun2> static bool load(const wchar_t* file_name, Fun& cba,Funb& cbb,Fun2& cb2){ FILE* f = _wfopen(file_name,L"r"); if(!f) return false; unsigned int nline = 0; while (!feof(f)) { char buf[128] = {}; fgets(buf,128,f); if (nline>1){ parse(buf,cba,cbb); } else if(nline==0) { cb2(atoi(buf)); } nline++; } return true; } };
true
177a53de850e5054093319f43a064aac3adf4dfc
C++
NipunSyn/DSA-CPP
/Basic C++/Code/syntax/simple_switch.cpp
UTF-8
588
3.609375
4
[]
no_license
#include<iostream> using namespace std; int main() { int a, b; char c; cin>>a>>c>>b; switch (c) { case '+': cout<<a+b<<endl; break; case '-': cout<<a-b<<endl; break; case '*': cout<<a*b<<endl; break; case '/': if(b!=0) { cout<<a/b<<endl; }else{ cout<<"Denominator cannot be 0"; } break; default: cout<<"Operator is not valid"; break; } return 0; }
true
3bad301a67ed693aa6fd73dfab3c2fcbfde9d27c
C++
Alvtron/OpenGLGraphics
/OpenGL/OpenGL/Rectangle.h
UTF-8
512
3.125
3
[]
no_license
#pragma once #include "Vertex.h" class Rect : public Vertex { private: const float WIDTH = 1.0f, HEIGHT = 1.0f; /* Creates the rectangle. */ void createRectangle(float width, float height, vec3 position); public: /* Create a Rectangle object. Uses default sizes. */ Rect(); /* Create a Rectangle object with width and height. */ Rect(float width, float height); /* Create a Rectangle with width, height and position. */ Rect(float width, float height, vec3 position); /* De-constructor */ ~Rect(); };
true
f6148e4694b00b16e89923eb178e0fe3a9bf2bf3
C++
guilhermealbm/CC-UFMG
/pds2/lab1/01.02/rectangle.cpp
UTF-8
675
3.28125
3
[]
no_license
#include "rectangle.h" Rectangle::Rectangle(double width, double height){ _height = height; _width = width; } Rectangle::Rectangle(){ _height = 1.0; _width = 1.0; } double Rectangle::get_height(){ return _height; } double Rectangle::get_width(){ return _width; } void Rectangle::set_height(double height){ if (height > 0.0 && height < 20.0) _height = height; } void Rectangle::set_width(double width){ if (width > 0.0 && width < 20.0) _width = width; } double Rectangle::get_perimeter(){ return _width + _width + _height + _height; } double Rectangle::get_area(){ return _width * _height; }
true
8f1e864c88f90c3e269e17fd8b21e2311a515ef8
C++
marrujoalex/CollegeCourseWork
/C++ Class/hw4b/pwfile.cpp
UTF-8
2,372
3.53125
4
[]
no_license
/* Student ID#: 003914325 Name: Samuel Marrujo Date: 11/22/11 Professor: Dr. Murphy Class: CSCI202 Project: Homework 4 */ #include <string> #include <vector> #include <iostream> #include <fstream> #include "pwfile.h" #include "userpw.h" using namespace std; PasswordFile::PasswordFile(string f) { // The constructor accepts a filename, and reads the file one-line at a time and adds values to the entry vector. this->filename = f; ifstream infile; infile.open(this->filename.c_str()); if (infile.good()) { string user, pw; infile >> user >> pw; while (infile.good()) { UserPw person(user, pw); entry.push_back(person); infile >> user >> pw; } } else { cout << "File does not exist"; } infile.close(); } string PasswordFile::getFilename() { return filename; } vector<UserPw> PasswordFile::getFile() { return entry; } void PasswordFile::addpw(UserPw newentry) { //this adds a new user/password to entry and writes entry to the file filename entry.push_back(newentry); ofstream outfile; outfile.open(filename.c_str()); for (int i=0; i < entry.size(); i++) { outfile << entry[i].UserPw::getUser() << " " << entry[i].UserPw::getPassword() << endl; } outfile.close(); } bool PasswordFile::checkpw(string user, string password) { for (int i = 0; i < entry.size(); i++) { if (entry[i].UserPw::getUser() == user) { if (entry[i].UserPw::Checkpw(user, password)) { cout << "Entry successful!" << endl; return true; } else { cout << "Invalid Password." << endl; return false; } } } cout << "Invalid Username." << endl; return false; } void PasswordFile::updatepw(UserPw updateentry) { // This function accepts a username/password combination and changes the entry with the username to the password provided in updateentry } void PasswordFile::deletepw(UserPw deleteentry) { // This function accepts a username and deletes the entry with the username vector<UserPw>::iterator it; ofstream outfile; for (it = entry.begin(); it != entry.end(); it++) { if (*it == deleteentry) { entry.erase(it); } } outfile.open(filename.c_str()); for (int i=0; i < entry.size(); i++) { outfile << entry[i].UserPw::getUser() << " " << entry[i].UserPw::getPassword() << endl; } outfile.close(); }
true
91cc45bff6748f01997ee3bc37630e38490c6381
C++
lliuyingjie/jianzhi
/balance.cpp
UTF-8
607
3.0625
3
[]
no_license
#include<iostream> #include"tree.h" using namespace std; bool if_balance(tree& node, int& x) { if(node==NULL) { x = 0; return true; } int left,right; if(if_balance(node->l,left)&&if_balance(node->r,right)) { int dif= left-right; if( dif<=1&&dif>=-1) { x = 1+ ((left>right)?left:right); cout<<x<<endl; return true; } } return false; } bool judge_balance(tree& my_tree) { int x = 0; return if_balance(my_tree,x); } int main(){ tree my_tree = NULL; simple_build(my_tree); cout<<depth(my_tree)<<endl; if(!judge_balance(my_tree)) cout<<"fuck"<<endl; return 0; }
true
43f79c1dcf5cb1b6a4ea8725edacf770f5ffcc88
C++
AndreyMarkinPPC/ArduinoExamples
/door_lock_detector/door_lock_detector.ino
UTF-8
863
2.5625
3
[]
no_license
int echoPin = 7; int trigPin = 8; int ledPin = LED_BUILTIN; int buzzer = 6; int maximumRange = 10; int minimumRange = 0; long duration, distance; void setup() { Serial.begin(9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(ledPin, OUTPUT); pinMode(buzzer, OUTPUT); } void loop() { unsigned char i; digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = duration/58.2; if(distance < maximumRange) { Serial.println(distance); digitalWrite(ledPin, HIGH); for (i = 0; i < 80; i++) { digitalWrite(buzzer, HIGH); delay(15); digitalWrite(buzzer, LOW); delay(15); } } else { Serial.println(distance); digitalWrite(ledPin, LOW); } delay(5); }
true
526828df59e181ed1934ffb2b05a2334166abd93
C++
riyasachdeva-22/DS-Problems
/Strings/palindrome.cpp
UTF-8
466
2.671875
3
[]
no_license
#include <iostream> using namespace std; #include<bits/stdc++.h> bool helper(char s[],int st,int e) { if(st==e) return true; if(s[st]!=s[e]) return false; if(s[st]<e) return helper(s,st+1,e-1); } int main() { //code int t; cin>>t; while(t--) { int l; cin>>l; char s[l]; for(int i=0;i<l;i++) cin>>s[i]; int st=0; int e=l-1; if(helper(s,st,e)) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }
true
83a6fc0806d76f0c9c54b9283417023960e72de0
C++
sureshyhap/Schaums-Outlines-Programming-with-C-plus-plus
/Chapter 9/Problems/9/9.cpp
UTF-8
443
3.125
3
[]
no_license
#include <iostream> #include <string> const int CHAR_PER_LINE = 60; int main(int argc, char* argv[]) { std::string lines[10]; std::string s; int k = 0; while (std::getline(std::cin, s)) { int num_spaces = CHAR_PER_LINE - s.length(); for (int i = 0; i < num_spaces; ++i) { lines[k] += ' '; } lines[k++] += s; } int j = 0; while (!lines[j].empty()) { std::cout << lines[j++] << '\n'; } return 0; }
true
ded119e71ee5ffcace104f5beb17cca300c19b8e
C++
El-Maco/q-learning-project
/src/exceptions/qlearning-exception.cpp
UTF-8
360
2.609375
3
[ "MIT" ]
permissive
#include "qlearning-exception.hpp" namespace QLearningExceptions { QLearningRuntimeException::QLearningRuntimeException(std::string message) : std::runtime_error(message) {} QLearningException::QLearningException(std::string message) : message(message) {} const char* QLearningException::what() const throw() { return message.c_str(); } }
true
4e0468d708356c8fd02da2cf67a08e73b2193940
C++
deruikong/Competitive-Programming-sols
/USACO/tupletest.cpp
UTF-8
1,472
2.625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; struct point{ int a, b; bool operator <(const point& pt) const { return (a < pt.a) || (pt.a >= a && (b < pt.b)); } }; int main() { ifstream fin; ofstream fout; fin.open("triangles.in"); fout.open("triangles.out"); string b, e; vector<point> p; set<point> cmp; getline(fin,b); int a = stoi(b); double area = 0; for (int i = 0; i < a; i++) { getline(fin, b); stringstream cur(b); vector<int> d; point c; while (getline(cur, e, ' '))d.emplace_back(stoi(e)); c.a = d[0]; c.b = d[1]; p.emplace_back(c); } for(int i = 0; i < p.size(); i++) { for(int j = i; j < p.size(); j++) { if(p[i].a != p[j].a && p[i].b != p[j].b) { point p1, p2; p1.a = p[i].a; p1.b = p[j].b; p2.a = p[j].a; p2.b = p[i].b; if(cmp.find(p1) != cmp.end()) { cout << p1.a << p1.b; area+= abs(p[i].a-p[j].a)*abs(p[i].a-p[j].a)/2; } if(cmp.find(p2) != cmp.end()) { cout << p2.a << p2.b; area+= abs(p[i].a-p[j].a)*abs(p[i].a-p[j].a)/2; } } } } }
true
7348ab1804d2bf732411138999901d0e0e188965
C++
honeyaya/interview
/BinaryTree.cpp
UTF-8
1,382
3.609375
4
[]
no_license
#include <iostream> #include <stdio.h> #include <vector> #include <queue> using namespace std; struct TreeNode{ int val; TreeNode *left; TreeNode *right; }; TreeNode * CreateBitTree(){ int data; scanf("%d",&data); if(data == 0) return NULL; else{ TreeNode *tmp = new TreeNode(); tmp->val = data; tmp->left = CreateBitTree(); tmp->right = CreateBitTree(); return tmp; } } int countNode(TreeNode * root){ if(!root) return 0; return countNode(root->left) + countNode(root->right) + 1; } int getDepth(TreeNode * root){ if(!root) return 0; return max(getDepth(root->left),getDepth(root->right)) + 1; } void preorder(TreeNode * root){ if(root != NULL){ cout << root->val << " "; preorder(root->left); preorder(root->right); } } void print(vector<int> vc){ int len = vc.size(); for(int i = 0; i < len; i++) cout << vc[i] << " "; cout << endl; return ; } void levelTraverse(TreeNode * root){ queue<node*> qe; qe.push(root); while(!qe.empty()){ node* tmp = qe.top(); qe.pop(); if(tmp->left) { } } } int main(){ int n; TreeNode * bt = CreateBitTree(); //cout << "----" << endl; //preorder(bt); //int nodecnt = countNode(bt); //int depth = getDepth(bt); return 0; } /* 1 2 4 0 0 5 0 0 3 6 0 0 0 */
true
409f9977c175fb866774cc61a3fa1d858faa7bb8
C++
yculcarneee/leetcode-30-Day-challenge
/Merge Sorted Array/main.cpp
UTF-8
1,718
3.25
3
[]
no_license
class Solution { public: /* First Approach - vector<int> tempVector; for(int i = 0; i < m; i++) { tempVector.push_back(nums1[i]); } for(auto num : nums2) { tempVector.push_back(num); } sort(tempVector.begin(), tempVector.end()); for(int i = 0; i < m+n; i++) { nums1[i] = tempVector[i]; } */ /* Second Approach - int findFirstElemLarger(vector<int>& nums1, int num, int m) { for(int i = 0; i < m; i++) { if(nums1[i] > num) { return i; } } return m; } void insertElem(vector<int>& nums1, int num, int m, int idx) { for(int i = m; i > idx; i--) { nums1[i] = nums1[i-1]; } nums1[idx] = num; } void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { for(int i = 0; i < n; i++) { int idx = findFirstElemLarger(nums1, nums2[i], m); insertElem(nums1, nums2[i], m, idx); m++; } } */ void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int last = m + n - 1; int i = m - 1; int j = n - 1; while (last >= 0) { while(i >= 0 && j >= 0) { if(nums1[i] > nums2[j]) nums1[last--] = nums1[i--]; else nums1[last--] = nums2[j--]; } while (i >= 0) { nums1[last--] = nums1[i--]; } while(j >= 0) { nums1[last--] = nums2[j--]; } } } };
true
4860fde3b175d2334f47c9822e4f5263231c6518
C++
bo0st3r/pool_and_run
/include/ECS/Components/UIComponent.h
UTF-8
573
2.59375
3
[]
no_license
#ifndef UICOMPONENT_H #define UICOMPONENT_H #include <Component.h> #include <UITypeEnum.h> class UIComponent : public Component { public: UIComponent(UITypeEnum type = UITypeEnum::HealthBar, int data = -1); virtual ~UIComponent(); static inline const ComponentID ID = 10; virtual ComponentID getTypeId() const; UITypeEnum getUIType() const; int getDataValue() const; virtual std::string str() const; protected: private: UITypeEnum UIType; int dataValue; }; #endif // UICOMPONENT_H
true
92382ef59b617024a1e296c437379b967b5aba27
C++
ipr/qAudiotest
/IffContainer.h
UTF-8
4,107
2.53125
3
[]
no_license
///////////////////////////////////////////////////////// // // CIffContainer : generic IFF-format parser, // detailed parsing must be per file-type (format) // since IFF is more generic. // // (c) Ilkka Prusi, 2011 // #ifndef _IFFCONTAINER_H_ #define _IFFCONTAINER_H_ #include <stdint.h> #include <string> // chunk-node types #include "IffChunk.h" // I can't be arsed to else, // simple is best #include "MemoryMappedFile.h" // handling of the general IFF-FORM chunks in file // class CIffContainer { private: // keep header and related data CIffHeader *m_pHeader; protected: // standard IFF chunks std::string m_szName; // NAME std::string m_szAuthor; // AUTH std::string m_szAnnotations; // ANNO std::string m_szCopyright; // (c) protected: // (note, should make inline but also needed in inherited classes..) // byteswap methods uint16_t Swap2(const uint16_t val) const; uint32_t Swap4(const uint32_t val) const; //uint64_t Swap8(const uint64_t val) const; float SwapF(const float fval) const; //double SwapD(const double dval) const; // make tag from string uint32_t MakeTag(const char *buf) const; uint32_t GetValueAtOffset(const int64_t iOffset, CMemoryMappedFile &pFile) const; uint8_t *GetViewByOffset(const int64_t iOffset, CMemoryMappedFile &pFile) const; CIffHeader *ReadHeader(int64_t &iOffset, CMemoryMappedFile &pFile) const; CIffChunk *ReadNextChunk(int64_t &iOffset, CMemoryMappedFile &pFile) const; void ReadChunks(int64_t &iOffset, CIffHeader *pHeader, CMemoryMappedFile &pFile); protected: // methods which user might want to overload on inheritance // called on each found chunk when found: // user can process chunk-data immediately for single-pass handling. // // default implementation for few common chunk-types, // handle here if derived doesn't have different purpose.. // virtual void OnChunk(CIffChunk *pChunk, CMemoryMappedFile &pFile); // called on found file-header: // user can re-implement to allow certain types only // virtual bool IsSupportedType(CIffHeader *pHeader) { // generic: all supported return true; } // simple example: IFF-ILBM picture with chunk CMAP // -> create handler for that type of chunk. // (chunk handling can depend of what format data is stored in general IFF-file) // /* virtual CIffChunk *CreateChunkNode(CIffHeader *pHead, uint32_t iChunkID) { if (pHead->m_iFileID == ID_ILBM && iChunkID == ID_CMAP) { return new CIlbmCmap(); } // should return default-type if non-supported by inherited implementation? return new CIffChunk(); // ..although it can be skipped if implementation doesn't support such chunk.. //return nullptr; } */ // similar to above but for (optional) sub-chunks /* virtual CIffSubChunk *CreateSubChunkNode(CIffHeader *pHead, CIffChunk *pChunk, uint32_t iSubChunkID) { if (pHead->m_iFileID == ID_XXXX && pChunk->m_iChunkID == ID_YYYY && iSubChunkID == ID_ZZZZ) { return new CXYZ(); } // should return null when there is no sub-chunk return nullptr; } */ // for inherited classes, get access to private member CIffHeader *GetHeader() const { return m_pHeader; } // use MakeTag("...") and call this in inherited class CIffChunk *GetChunkById(const uint32_t uiFourccID) const { CIffHeader *pHead = GetHeader(); if (pHead != nullptr) { return GetNextChunkById(pHead->m_pFirst, uiFourccID); } // not opened/processed file? return nullptr; } // in case file has multiple chunks with same identifier, locate next CIffChunk *GetNextChunkById(CIffChunk *pPrevChunk, const uint32_t uiFourccID) const { CIffChunk *pChunk = pPrevChunk; while (pChunk != nullptr) { if (pChunk->m_iChunkID == uiFourccID) { // found -> return to caller return pChunk; } pChunk = pChunk->m_pNext; } // not found, incomplete file? return nullptr; } public: CIffContainer(void); virtual ~CIffContainer(void); CIffHeader *ParseIffFile(CMemoryMappedFile &pFile); // TODO:? //CIffHeader *ParseIffBuffer(CMemoryMappedFile &pFile); }; #endif // ifndef _IFFCONTAINER_H_
true
38e80a7116fc67a1fd4522923e1a4a565cf68062
C++
wjcskqygj2015/RStream
/src/apps/pr_cf.cpp
UTF-8
6,518
2.59375
3
[]
no_license
// /* // * pagerank.cpp // * // * Created on: Aug 10, 2017 // * Author: Zhiqiang // */ // // #include "../core/engine.hpp" // #include "../core/scatter.hpp" // #include "../core/gather.hpp" // #include "../core/global_info.hpp" // // #include "../core/aggregation.hpp" // #include "../utility/ResourceManager.hpp" // // using namespace RStream; // // class MC : public MPhase { //public: // MC(Engine & e, unsigned int maxsize) : MPhase(e, maxsize){}; // ~MC() {}; // // bool filter_join(MTuple_join & update_tuple){ // return false; // } // // bool filter_collect(MTuple & update_tuple){ // return false; // } // // bool filter_join_clique(MTuple_join_simple& update_tuple){ // return update_tuple.get_added_element()->id <= update_tuple.at(update_tuple.get_size() - 2).id; // } //}; // // struct Update_PR : BaseUpdate{ // float rank; // // Update_PR(int _target, float _rank) : BaseUpdate(_target), rank(_rank) {}; // // Update_PR() : BaseUpdate(0), rank(0.0) {} // // std::string toString(){ // return "(" + std::to_string(target) + ", " + std::to_string(rank) + ")"; // } // }__attribute__((__packed__)); // // // struct Vertex_PR : BaseVertex { // int degree; // float rank; // float sum; // }__attribute__((__packed__)); // // inline std::ostream & operator<<(std::ostream & strm, const Vertex_PR& vertex){ // strm << "[" << vertex.id << "," << vertex.degree << ", " << vertex.rank << "]"; // return strm; // } // // void init(char* data, VertexId id) { // struct Vertex_PR * v = (struct Vertex_PR*)data; // v->degree = 0; // v->sum = 0; // v->rank = 1.0f; // v->id = id; // } // // Update_PR * generate_one_update_init(Edge * e, Vertex_PR * v) { // Update_PR * update = new Update_PR(e->target, 1.0f / v->degree); // return update; // } // // Update_PR * generate_one_update(Edge * e, Vertex_PR * v) { // Update_PR * update = new Update_PR(e->target, v->rank / v->degree); // return update; // } // // void apply_one_update(Update_PR * update, Vertex_PR * dst_vertex) { // dst_vertex->sum += update->rank; // dst_vertex->rank = 0.15 + 0.85 * dst_vertex->sum; // } // // // bool filter_vertex(Vertex_PR & vertex){ //// std::cout << vertex << std::endl; //// return vertex.rank > 10000 || vertex.rank < 1000; // return vertex.rank < 1200; // } // // // int main(int argc, char ** argv) { // if(argc != 7){ // std::cerr << "Usage: input-graph, #partition-1, #iteration, out-file, #partition-2, maxsize" << std::endl; // return 0; // } // // Engine e(std::string(argv[1]), atoi(argv[2]), 0); // // //========================================================== page-ranking ======================================================= // // get running time (wall time) // auto start_pagerank = std::chrono::high_resolution_clock::now(); // // std::cout << "--------------------Init Vertex--------------------" << std::endl; // e.init_vertex<Vertex_PR>(init); // std::cout << "--------------------Compute Degre--------------------" << std::endl; // e.compute_degree<Vertex_PR>(); // // int num_iters = atoi(argv[3]); // // Scatter<Vertex_PR, Update_PR> scatter_phase(e); // Gather<Vertex_PR, Update_PR> gather_phase(e); // // for(int i = 0; i < num_iters; i++) { // std::cout << "--------------------Iteration " << i << "--------------------" << std::endl; // // Update_Stream in_stream; // if(i == 0) { // in_stream = scatter_phase.scatter_with_vertex(generate_one_update_init); // } else { // in_stream = scatter_phase.scatter_with_vertex(generate_one_update); // } // // gather_phase.gather(in_stream, apply_one_update); // // Global_Info::delete_upstream(in_stream, e); // } // // // auto end_pagerank = std::chrono::high_resolution_clock::now(); // std::chrono::duration<double> diff_pagerank = end_pagerank - start_pagerank; // std::cout << "Finish page-ranking. Running time : " << diff_pagerank.count() << " s\n"; // // // //========================================================== filtering ======================================================= // // get running time (wall time) // auto start_filter = std::chrono::high_resolution_clock::now(); // // std::string out_file = argv[4]; // scatter_phase.prune_graph(filter_vertex, out_file); // // auto end_filter = std::chrono::high_resolution_clock::now(); // std::chrono::duration<double> diff_filter = end_filter - start_filter; // std::cout << "Finish filtering. Running time : " << diff_filter.count() << " s\n"; // // //========================================================== clique-finding ======================================================= // // Engine ec(out_file, atoi(argv[5]), 1); // std::cout << Logger::generate_log_del(std::string("finish preprocessing"), 1) << std::endl; // // // get running time (wall time) // auto start_clique = std::chrono::high_resolution_clock::now(); // // MC mPhase(ec, atoi(argv[6])); // Aggregation agg(ec, false); // // //init: get the edges stream // std::cout << Logger::generate_log_del(std::string("init"), 1) << std::endl; // Update_Stream up_stream = mPhase.init_clique(); // mPhase.printout_upstream(up_stream); // // Update_Stream up_stream_new; // Update_Stream clique_stream; // // for(unsigned int i = 0; i < mPhase.get_max_size() - 2; ++i){ // std::cout << "\n\n" << Logger::generate_log_del(std::string("Iteration ") + std::to_string(i), 1) << std::endl; // // //join on all keys // std::cout << "\n" << Logger::generate_log_del(std::string("joining"), 2) << std::endl; // up_stream_new = mPhase.join_all_keys_nonshuffle_clique(up_stream); // mPhase.delete_upstream(up_stream); // mPhase.printout_upstream(up_stream_new); // // //collect cliques // std::cout << "\n" << Logger::generate_log_del(std::string("collecting"), 2) << std::endl; // clique_stream = agg.aggregate_filter_clique(up_stream_new, mPhase.get_sizeof_in_tuple()); // mPhase.delete_upstream(up_stream_new); // mPhase.printout_upstream(clique_stream); // // up_stream = clique_stream; // } // //clean remaining stream files // std::cout << std::endl; // mPhase.delete_upstream(up_stream); // // //delete all generated files // std::cout << "\n\n" << Logger::generate_log_del(std::string("cleaning"), 1) << std::endl; // ec.clean_files(); // // auto end_clique = std::chrono::high_resolution_clock::now(); // std::chrono::duration<double> diff_clique = end_clique - start_clique; // std::cout << "Finish clique-finding. Running time : " << diff_clique.count() << " s\n"; // // } // // //
true
ee417eaa8841c62fa7ac175cbb50206b1390ca6f
C++
Happy-Ferret/CuarzoOS
/Code/CFramework/Headers/CImage.h
UTF-8
973
2.640625
3
[ "Apache-2.0" ]
permissive
#ifndef CIMAGE_H #define CIMAGE_H #include <QWidget> #include <QPainter> #include <QBitmap> class CImage : public QWidget { Q_OBJECT public: CImage(QWidget *parent = nullptr); CImage(QPixmap image,QWidget *parent = nullptr); CImage(QPixmap image,QSize size,QWidget *parent = nullptr); CImage(QPixmap image,QColor color,QWidget *parent = nullptr); void setImage(QPixmap image); void setBorderRadius(uint radius); void setImageColor(QColor color); void setBorderColor(QColor color); void setBorderWidth(uint width); void enableColor(bool mode); void setOpacity(float opacity = 0.5); bool colorEnabled(){return _colorEnabled;} private: QPixmap _image; QColor _imageColor = QColor("#444444"); QColor _borderColor = QColor("#444444"); uint _borderRadius = 0; uint _borderWidth = 0; float _opacity = 1.0; bool _colorEnabled = false; void paintEvent(QPaintEvent *); }; #endif // CIMAGE_H
true
d1b2b0f117706ea54160b9749af171ccf7ab9cda
C++
hky5820/Registration_Tooth_ICP
/Registration_Tooth_ICP/calc_alignment.cpp
UTF-8
3,628
3
3
[]
no_license
#include "calc_alignment.h" float calc_mat_element(vector<float> &param1, vector<float> &param2, float avg1, float avg2) { float sum = 0; size_t size = param1.size(); for (int i = 0; i < size; i++) { sum += (param1[i] - avg1) * (param2[i] - avg2); } return sum; } void calc_mat_cross_covariance(vector<float> &vec_for_cross_cov_x1, vector<float> &vec_for_cross_cov_y1, vector<float> &vec_for_cross_cov_z1, vector<float> &vec_for_cross_cov_x2, vector<float> &vec_for_cross_cov_y2, vector<float> &vec_for_cross_cov_z2, XYZ avg1, XYZ avg2, Matrix3f &mat_cross_covariance) { mat_cross_covariance(0, 0) = calc_mat_element(vec_for_cross_cov_x1, vec_for_cross_cov_x2, avg1.x, avg2.x); mat_cross_covariance(0, 1) = calc_mat_element(vec_for_cross_cov_x1, vec_for_cross_cov_y2, avg1.x, avg2.y); mat_cross_covariance(0, 2) = calc_mat_element(vec_for_cross_cov_x1, vec_for_cross_cov_z2, avg1.x, avg2.z); mat_cross_covariance(1, 0) = calc_mat_element(vec_for_cross_cov_y1, vec_for_cross_cov_x2, avg1.y, avg2.x); mat_cross_covariance(1, 1) = calc_mat_element(vec_for_cross_cov_y1, vec_for_cross_cov_y2, avg1.y, avg2.y); mat_cross_covariance(1, 2) = calc_mat_element(vec_for_cross_cov_y1, vec_for_cross_cov_z2, avg1.y, avg2.z); mat_cross_covariance(2, 0) = calc_mat_element(vec_for_cross_cov_z1, vec_for_cross_cov_x2, avg1.z, avg2.x); mat_cross_covariance(2, 1) = calc_mat_element(vec_for_cross_cov_z1, vec_for_cross_cov_y2, avg1.z, avg2.y); mat_cross_covariance(2, 2) = calc_mat_element(vec_for_cross_cov_z1, vec_for_cross_cov_z2, avg1.z, avg2.z); } void calc_alignment(vector<pair<XYZ, XYZ>> &pair_closest_point, Matrix4f &mat_result_of_alignment) { // translation XYZ sum1(0.0), sum2(0.0), avg1, avg2; size_t size = pair_closest_point.size(); for (int i = 0; i < size; i++) { sum1.x += pair_closest_point[i].first.x; sum1.y += pair_closest_point[i].first.y; sum1.z += pair_closest_point[i].first.z; sum2.x += pair_closest_point[i].second.x; sum2.y += pair_closest_point[i].second.y; sum2.z += pair_closest_point[i].second.z; } avg1.x = sum1.x / (float)size; avg1.y = sum1.y / (float)size; avg1.z = sum1.z / (float)size; avg2.x = sum2.x / (float)size; avg2.y = sum2.y / (float)size; avg2.z = sum2.z / (float)size; // calc_centroid mat_result_of_alignment(0, 3) = avg2.x - avg1.x; mat_result_of_alignment(1, 3) = avg2.y - avg1.y; mat_result_of_alignment(2, 3) = avg2.z - avg1.z; //cout << "trans x : " << avg2.x - avg1.x << "\n"; //cout << "trans y : " << avg2.y - avg1.y << "\n"; //cout << "trans z : " << avg2.z - avg1.z << "\n"; // rotation vector<float> vec_for_cross_cov_x1, vec_for_cross_cov_y1, vec_for_cross_cov_z1, // pi - cs, qi - ct vec_for_cross_cov_x2, vec_for_cross_cov_y2, vec_for_cross_cov_z2; for (int i = 0; i < size; i++) { vec_for_cross_cov_x1.push_back(pair_closest_point[i].first.x); vec_for_cross_cov_y1.push_back(pair_closest_point[i].first.y); vec_for_cross_cov_z1.push_back(pair_closest_point[i].first.z); vec_for_cross_cov_x2.push_back(pair_closest_point[i].second.x); vec_for_cross_cov_y2.push_back(pair_closest_point[i].second.y); vec_for_cross_cov_z2.push_back(pair_closest_point[i].second.z); } Matrix3f mat_cross_covariance; calc_mat_cross_covariance(vec_for_cross_cov_x1, vec_for_cross_cov_y1, vec_for_cross_cov_z1, vec_for_cross_cov_x2, vec_for_cross_cov_y2, vec_for_cross_cov_z2, avg1, avg2, mat_cross_covariance); JacobiSVD<MatrixXf> svd(mat_cross_covariance, ComputeFullU | ComputeFullV); Matrix3f mat_rot = svd.matrixV() * svd.matrixU().transpose(); mat_result_of_alignment.topLeftCorner(3, 3) = mat_rot; }
true
0e74145eff189e0da232bb8c350380b0f86ed66a
C++
iFihy1475/C_C-
/C_CPP_STL/C_CPP_STL/pair_ex2.cpp
UTF-8
908
3.4375
3
[]
no_license
#include <iostream> #include <utility> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { vector <pair<int, string>> v; v.push_back(pair<int, string>(3, "Song")); v.push_back(pair<int, string>(6, "Nam")); v.push_back(pair<int, string>(1, "Joo")); v.push_back(pair<int, string>(4, "Okay")); v.push_back(pair<int, string>(2, "start")); v.push_back(pair<int, string>(2, "end")); cout << "=== After sort === " << endl; vector < pair<int, string>>::iterator iter; for (iter = v.begin(); iter != v.end(); ++iter) { cout << "[" << iter->first << ", " << iter->second << "]" << endl; } cout << endl; sort(v.begin(), v.end()); for (iter = v.begin(); iter != v.end(); ++iter) { cout << "[" << iter->first << ", " << iter->second << "]" << endl; } cout << endl; return 0; }
true
7b9c550e49cf6c3bb9d2dc356fd631fb9bc59eba
C++
runvs/QuasarRush
/src/jamtemplate/sfml/rect_lib.hpp
UTF-8
2,195
2.640625
3
[]
no_license
#ifndef GUARD_JAMTEMPLATE_RECT_LIB_GUARD_HPP #define GUARD_JAMTEMPLATE_RECT_LIB_GUARD_HPP #include "rect_base.hpp" #include <SFML/Graphics/Rect.hpp> namespace jt { class Rect final : public rectBase { public: Rect() : m_rect { 0.0f, 0.0f, 0.0f, 0.0f } { } Rect(float left, float top, float width, float height) : m_rect { left, top, width, height } { } Rect(sf::FloatRect const& v) : m_rect { v } { } ~Rect() = default; Rect(jt::Rect const&) = default; Rect(jt::Rect&&) = default; Rect& operator=(jt::Rect const&) = default; Rect& operator=(jt::Rect&&) = default; operator sf::FloatRect() const { return m_rect; } sf::FloatRect m_rect; float left() const override { return m_rect.left; }; float top() const override { return m_rect.top; }; float width() const override { return m_rect.width; }; float height() const override { return m_rect.height; }; float& left() override { return m_rect.left; }; float& top() override { return m_rect.top; }; float& width() override { return m_rect.width; }; float& height() override { return m_rect.height; }; }; class Recti final : public rectiBase { public: Recti() : Recti { 0, 0, 0, 0 } { } Recti(int left, int top, int width, int height) : m_rect { left, top, width, height } { } Recti(sf::IntRect const& v) : m_rect { v } { } ~Recti() = default; Recti(jt::Recti const&) = default; Recti(jt::Recti&&) = default; Recti& operator=(jt::Recti const&) = default; Recti& operator=(jt::Recti&&) = default; operator sf::IntRect() const { return m_rect; } sf::IntRect m_rect; int left() const override { return m_rect.left; }; int top() const override { return m_rect.top; }; int width() const override { return m_rect.width; }; int height() const override { return m_rect.height; }; int& left() override { return m_rect.left; }; int& top() override { return m_rect.top; }; int& width() override { return m_rect.width; }; int& height() override { return m_rect.height; }; }; } // namespace jt #endif
true
df7c5b0c71996f03c2439f9a3da483047520f3a1
C++
OpenGene/gencore
/src/pair.cpp
UTF-8
9,234
2.59375
3
[ "MIT" ]
permissive
#include "pair.h" #include "bamutil.h" #include <memory.h> Pair::Pair(Options* opt){ mLeft = NULL; mRight = NULL; mLeftScore = NULL; mRightScore = NULL; mMergeReads = 1; mReverseMergeReads = 0; mMergeLeftDiff = 0; mMergeRightDiff = 0; mOptions = opt; mIsDuplex = false; mCssDcsTagWritten = false; } Pair::~Pair(){ if(mLeft) { bam_destroy1(mLeft); mLeft = NULL; } if(mRight) { bam_destroy1(mRight); mRight = NULL; } if(mLeftScore) { delete[] mLeftScore; mLeftScore = NULL; } if(mRightScore) { delete[] mRightScore; mRightScore = NULL; } } void Pair::setDuplex(int mergeReadsOfReverseStrand) { mIsDuplex = true; mReverseMergeReads = mergeReadsOfReverseStrand; } void Pair::writeSscsDcsTag() { if(mCssDcsTagWritten) { error_exit("The SSCS/DCS tag has already been written!"); } if(mLeft) writeSscsDcsTagBam(mLeft); if(mRight) writeSscsDcsTagBam(mRight); mCssDcsTagWritten = true; } void Pair::writeSscsDcsTagBam(bam1_t* b) { const char cssTag[2] = {'F','R'}; // forward strand read count const char dcsTag[2] = {'R','R'}; // reverse strand read number char type = 'C'; unsigned short val = min(mMergeReads, 65535); int ret = bam_aux_append(b, cssTag, type, 1, (uint8_t*)&val); if(ret != 0) error_exit("Failed to write the consensus reads tag (CR) to BAM"); if(mIsDuplex) { unsigned short valReverse = min(mReverseMergeReads, 65535); ret = bam_aux_append(b, dcsTag, type, 1, (uint8_t*)&valReverse); if(ret != 0) error_exit("Failed to write the duplex consensus reads tag (DR) to BAM"); } } void Pair::assignNonOverlappedScores(uint8_t* qual, int start, int end, char* scores) { for(int i=start;i<end;i++) { uint8_t q = qual[i]; scores[i] = qual2score(q); } } char Pair::qual2score(uint8_t q) { if(mOptions->highQuality <= q) return mOptions->scoreOfNotOverlappedHighQual; else if(mOptions->moderateQuality <= q) return mOptions->scoreOfNotOverlappedModerateQual; else if(mOptions->lowQuality <= q) return mOptions->scoreOfNotOverlappedLowQual; else return mOptions->scoreOfNotOverlappedBadQual; } void Pair::computeScore() { if(mLeft) { if(mLeftScore == NULL) { mLeftScore = new char[mLeft->core.l_qseq]; memset(mLeftScore, mOptions->scoreOfNotOverlappedModerateQual, mLeft->core.l_qseq); } } if(mRight) { if(mRightScore == NULL) { mRightScore = new char[mRight->core.l_qseq]; memset(mRightScore, mOptions->scoreOfNotOverlappedModerateQual, mRight->core.l_qseq); } } if(mLeftScore && mRightScore) { int leftMOffset, leftMLen, rightMOffset, rightMLen; BamUtil::getMOffsetAndLen(mLeft, leftMOffset, leftMLen); BamUtil::getMOffsetAndLen(mRight, rightMOffset, rightMLen); if(leftMLen>0 && rightMLen>0) { int posDis = mRight->core.pos - mLeft->core.pos; int leftStart, rightStart, cmpLen; if(posDis >=0 ) { leftStart = leftMOffset + posDis; rightStart = rightMOffset; cmpLen = min(leftMLen - posDis, rightMLen); } else { leftStart = leftMOffset; rightStart = rightMOffset - posDis; cmpLen = min(leftMLen, rightMLen + posDis); } uint8_t* lseq = bam_get_seq(mLeft); uint8_t* rseq = bam_get_seq(mRight); uint8_t* lqual = bam_get_qual(mLeft); uint8_t* rqual = bam_get_qual(mRight); if(mLeft) { assignNonOverlappedScores(lqual, 0, min(mLeft->core.l_qseq, leftStart), mLeftScore); assignNonOverlappedScores(lqual, max(0, leftStart+cmpLen), mLeft->core.l_qseq, mLeftScore); } if(mRight) { assignNonOverlappedScores(rqual, 0, min(mRight->core.l_qseq, rightStart), mRightScore); assignNonOverlappedScores(rqual, max(0, rightStart+cmpLen), mRight->core.l_qseq, mRightScore); } for(int i=0; i<cmpLen; i++) { int l = leftStart + i; int r = rightStart + i; uint8_t lbase, rbase; uint8_t lq = lqual[l]; uint8_t rq = rqual[r]; if(l%2 == 1) lbase = lseq[l/2] & 0xF; else lbase = (lseq[l/2]>>4) & 0xF; if(r%2 == 1) rbase = rseq[r/2] & 0xF; else rbase = (rseq[r/2]>>4) & 0xF; // matched pair, score += 4 if(lbase == rbase) { uint8_t q = (lq + rq) / 2; char score = qual2score(q) + 4; mLeftScore[l] = score; mRightScore[r] = score; continue; } else { // modify the Q Scores since the bases are mismatched // In the overlapped region, if a base and its pair are mismatched, its quality score will be adjusted to: max(0, this_qual - pair_qual) lqual[l] = max(0, (int)lq - (int)rq); rqual[r] = max(0, (int)rq - (int)lq); uint8_t q = 0; if(lq >= rq ) { mLeftScore[l] = qual2score(lq - rq) - 3; mRightScore[r] = 0; } else { mLeftScore[l] = 0; mRightScore[r] = qual2score(rq - lq) -3; } } } } } } char* Pair::getLeftScore() { if(!mLeftScore) computeScore(); return mLeftScore; } char* Pair::getRightScore() { if(!mRightScore) computeScore(); return mRightScore; } void Pair::setLeft(bam1_t *b) { if(mLeft) bam_destroy1(mLeft); mLeft = b; mUMI = BamUtil::getUMI(mLeft, mOptions->umiPrefix); mLeftCigar = BamUtil::getCigar(mLeft); } void Pair::setRight(bam1_t *b) { if(mRight) bam_destroy1(mRight); mRight = b; string umi = BamUtil::getUMI(mRight, mOptions->umiPrefix); if(!mUMI.empty() && umi!=mUMI) { cerr << "Mismatched UMI of a pair of reads" << endl; if(mLeft) { cerr << "Left:" << endl; BamUtil::dump(mLeft); } if(mRight) { cerr << "Right:" << endl; BamUtil::dump(mRight); } error_exit("The UMI of a read pair should be identical, but we got " + mUMI + " and " + umi ); } else mUMI = umi; mRightCigar = BamUtil::getCigar(mRight); } bool Pair::pairFound() { return mLeft != NULL && mRight != NULL; } int Pair::getLeftRef() { if(mLeft == NULL) return -1; return mLeft->core.tid; } int Pair::getLeftPos() { if(mLeft == NULL) return -1; return mLeft->core.pos; } int Pair::getRightRef() { if(mRight == NULL) return -1; return mRight->core.tid; } int Pair::getRightPos() { if(mRight == NULL) return -1; return mRight->core.pos; } int Pair::getTLEN() { if(mLeft != NULL) return abs(mLeft->core.isize); else if(mRight != NULL) return abs(mRight->core.isize); else return -1; } string Pair::getQName() { if(mLeft != NULL) return BamUtil::getQName(mLeft); else if(mRight != NULL) return BamUtil::getQName(mRight); else return ""; } Pair::MapType Pair::getMapType() { if(mLeft == NULL || mRight == NULL) return Unknown; int lref = getLeftRef(); int rref = getRightRef(); if(lref == rref) { if(lref >= 0) return ProperlyMapped; else return NoneMapped; } if(lref<0 && rref>=0) return OnlyRightMapped; if(lref>=0 && rref<0) return OnlyLeftMapped; if(lref != rref) return CrossRefMapped; return Unknown; } string Pair::getLeftCigar() { return mLeftCigar; } string Pair::getRightCigar() { return mRightCigar; } string Pair::getUMI() { return mUMI; } bool Pair::isDupWith(Pair* other) { if(!pairFound() || !other->pairFound()) return false; if(getLeftRef() != other->getLeftRef() || getRightRef() != other->getRightRef()) return false; if(getLeftPos() != other->getLeftPos() || getRightPos() != other->getRightPos()) return false; int umiDiff = 0; for(int i=0; i<mUMI.length() && i<other->mUMI.length(); i++) { if(mUMI[i] != other->mUMI[i]) umiDiff++; } if(umiDiff>1) return false; return true; } void Pair::dump() { cerr << "merged by " << mMergeReads << " forward reads, diff (" << mMergeLeftDiff << ", " << mMergeRightDiff << ")" << endl; if(mLeft){ cerr << "left:" << endl; BamUtil::dump(mLeft); } if(mRight) { cerr << "right:" << endl; BamUtil::dump(mRight); } }
true
6350c4881973fed593cd067128e8d9f68768ed7c
C++
HannahMuetzel/AVLTree
/AVLTree/AVLTree.cpp
UTF-8
7,290
3.609375
4
[]
no_license
#include "AVLTree.h" #include <ostream> #include <string> /* AVLTree() constructor initializes size to 0 and root to NULL pointer Runtime: theta(1) */ AVLTree::AVLTree() { size = 0; //number of nodes in the tree initialized to 0 root = NULL; //root initialized to null ptr } /* bool insertAVL(int, int) Adds a node to a tree in an attempt to create an AVL tree. Rotations are implemented, but apparently, incorrectly. Runtime: theta(n^3) */ bool AVLTree::insertAVL(int key, int value) { //inc tree size by 1 if going to return true, else don't increment it Node* newNode = new Node(key, value, NULL, NULL); int arbitrary = 0; if (!find(key, arbitrary)) { if (root == NULL) { size++; root = newNode; extra.push_back(*root); return true; } else { insertHelperAVL(root, key, value); //Check if off balance if (recursiveGetHeight(newNode->lc) - recursiveGetHeight(newNode->rc) >= 2) { //If offbalance, rotate as needed if (key <= root->lc->key) { SLR(newNode); } else { DLR(newNode); } } //Check if off balance if (recursiveGetHeight(newNode->lc) - recursiveGetHeight(newNode->rc) <= -2) { //If offbalance, rotate as needed if (key >= root->rc->key) { SRR(newNode); } else { DRR(newNode); } } size++; extra.push_back(*newNode); return true; } } //Failed to add the node return false; }; /* void insertHelperAVL(node ptr, int, int) Recursively inserts node into tree, based on key value. Runtime: theta(logn) */ void AVLTree::insertHelperAVL(Node*& node, int key, int value) { //Reached end of tree? if (node == NULL) { node = new Node(key, value, NULL, NULL); } //Go left else if (key > node->key) { insertHelperAVL(node->lc, key, value); } //Or go right else if (key > node->key) { insertHelperAVL(node->rc, key, value); } }; /* bool insertHelper(Node ptr ref, Node ptr) Recursively inserts a node based on key into tree. Also adds key values into a vector in order to use in findRange function later. Runtime: theta(logn) */ bool AVLTree::insertHelper(Node*& rootNode, Node* newNode) { if (newNode->key < rootNode->key) { if (rootNode->lc == NULL) { rootNode->lc = newNode; extra.push_back(*newNode); return true; } else { insertHelper(rootNode->lc, newNode); } } else { if (rootNode->rc == NULL) { rootNode->rc = newNode; extra.push_back(*newNode); return true; } else { insertHelper(rootNode->rc, newNode); } } }; /* bool insert(int, int) Inserts a new node to the tree, linking it to the previous node based on key value by sending it to the recursive insertHelper function. Node->key values are added to a vector in order to use later in findRange function. Runtime: theta(1) */ bool AVLTree::insert(int key, int value) { //inc tree size by 1 if going to return true, else don't increment it Node* newNode = new Node(key, value, NULL, NULL); int arbitrary = 0; int balance = 0; if (!find(key, arbitrary)) { if (root == NULL) { size++; root = newNode; extra.push_back(*root); return true; } else { insertHelper(root, newNode); size++; return true; } } //Failed to add the node return false; }; /* int getSize() Returns the size of the tree, aka number of nodes. Runtime: theta(1) */ int AVLTree::getSize() { return size; }; /* int getHeight() calls recursiveGetHeight to recursively get the height if root is not null. The entire height of the tree will be the maximum of leftHeight or rightHeight, which is returned. Runtime: theta(1) */ int AVLTree::getHeight() { //The max height of the tree will be whichever side of the tree is higher //check to see if root is NULL if (root == NULL) { //if it is, then height = 0 return 0; } else { //otherwise, find the max height recursively by passing the root int maxHeight = recursiveGetHeight(root); return maxHeight; } }; /* int recursiveGetHeight(Node ptr) Runs through the tree recursively and keeps track of the max height. The entire height of the tree will be the maximum of leftHeight or rightHeight, which is returned. Runtime: theta(n) */ int AVLTree::recursiveGetHeight(Node* currNode) { //check to see if root is NULL if (currNode == NULL) { //if it is, then height = 0 return 0; } else { //otherwise, recursively find the left max height int leftHeight = recursiveGetHeight(currNode->lc); //then, recursively find the right max height int rightHeight = recursiveGetHeight(currNode->rc); //compare the two //the max height will be the greater of the two heights +1 for the root node if (leftHeight > rightHeight) { return leftHeight + 1; } else { return rightHeight + 1; } } }; /* void print() recursively calls inorderLvls(Node ptr, int) to print the tree with proper spacing. Runtime: theta(1) */ void AVLTree::print() { //do inorder traversal of tree recursively, printing as we go inorderLvls(root, 0); }; /* void inorderLvls(Node ptr, int) Recursive function that prints the nodes in an inorder traversal, adding proper spacings along the way. Runtime: theta(n) */ void AVLTree::inorderLvls(const Node* curr, int lvl) { if (curr == 0) { return; } inorderLvls(curr->rc, lvl + 1); cout << string(lvl, '\t') << "(" << curr->key << ", " << curr->value << ")" << endl; inorderLvls(curr->lc, lvl + 1); }; /* SLR(Node) Single Left Rotate Used to rotate nodes of AVL Tree Runtime: theta(1) */ void AVLTree::SLR(Node*& node) { Node* other = node->lc; node->lc = other->rc; other->rc = node; node = other; }; /* DLR(Node) Double Left Rotate Used to rotate nodes of AVL Tree Runtime: theta(1) */ void AVLTree::DLR(Node*& node) { SRR(node->lc); SLR(node); }; /* SRR(Node) Single Right Rotate Used to rotate nodes of AVL Tree Runtime: theta(1) */ void AVLTree::SRR(Node*& node) { Node* other = node->rc; node->rc = other->lc; other->lc = node; node = other; }; /* DRR(Node) Double Right Rotate Used to rotate nodes of AVL Tree Runtime: theta(1) */ void AVLTree::DRR(Node*& node) { SLR(node->rc); SRR(node); }; /* bool find(int, int ref) Starts at root, checks the values, and returns if the key is in the tree or not. Value is then set. Runtime: theta(logn) */ bool AVLTree::find(int key, int& value) { Node* check = root; //start at root, compare passed values to Node check //if the root is empty then there are no keys, return false if (check == NULL) { return false; }; while (check->key != key) { if (check != NULL) { if (check->key > key) { value = check->value; check = check->lc; } else { value = check->value; check = check->rc; } if (check == NULL) { value = value; return false; } } } //return false b/c key was not found in the tree return false; }; /* vector<int> findRange(int, int) Runs through the stored vector of keys and checks to see if they're in the range. If they are in the range, then they are placed into the inRange vector and returned. Runtime: theta(n) */ std::vector<int> AVLTree::findRange(int lowkey, int highkey) { std::vector<int> inRange; for (auto it = extra.begin(); it < extra.end(); it++) { if (it->key >= lowkey && it->key <= highkey) { inRange.push_back(it->key); inRange.push_back(it->value); } } return inRange; };
true
c6298522b0b814c9749ca3f807e7d0096cd3f008
C++
xhsimonmo/C90-compiler-translator
/include/declaration_list.hpp
UTF-8
1,035
2.6875
3
[]
no_license
#ifndef ast_declaration_list #define ast_declaration_list #include "ast.hpp" // declaration_list // : declaration {$$ = $1; std::cerr << "declaration list 1" << std::endl;} // | declaration_list declaration {$$ = new declaration_list($1, $2); std::cerr << "declaration list 2" << std::endl;} // ; class declaration_list : public astnode{ public: declaration_list(treeptr o, treeptr t){p_o = o; p_t = t;} ~declaration_list(){delete p_o; delete p_t;} //void translate(string& pyout); virtual void translate(string& pyout)const override; virtual void compile(mips& mp) const override; private: treeptr p_o; treeptr p_t; string cname = "declaration_list"; }; // void declaration_list::compile(mips& mp)const{ // p_o -> compile(mp); // mips another_mp; // p_t ->compile(another_mp); // } // void declaration_list::translate(string& pyout)const{ // debug(cname); // string l; // string r; // // p_o->translate(l); // p_t->translate(r); // pyout = l + "\n" + r; // } #endif
true
2ea79c56dfaeaae461643ec3b5373f9421f1be66
C++
currant77/interview-preparation
/data-structures/LinkedList.h
UTF-8
18,127
4.03125
4
[]
no_license
/** * @file LinkedList.h * @author Taylor Curran * @brief Linked list with iterators * @version 0.1 * @date 2020-06-16 * * @copyright Copyright (c) 2020 * */ #ifndef LINKED_LIST_H #define LINKED_LIST_H #include "stddef.h" // size_t #include <stdexcept> // std::out_of_range, std::invalid_argument #include <algorithm> // std::swap #include <iterator> // std::bidirectional_iterator_tag #include "Node.h" // DoublyLinkedListNode /** * @brief Linked list of values of type T; supports * operations by index and via iterators * @tparam T - the type of the values stored in the list */ template<class T> class LinkedList { public: // Forward declarations class iterator; class const_iterator; // Give iterators access to private members friend class iterator; friend class const_iterator; LinkedList(); ~LinkedList(); LinkedList(const LinkedList<T>& other); LinkedList<T>& operator=(const LinkedList<T>& other); /** * @brief Returns true if the list is empty; false otherwise */ bool empty() const; /** * @brief Returns the number of values in the list */ size_t size() const; /** * @brief Returns a reference to the value at the * position given by \p index * @throw std::out_of_range if \p index is not in range [0, size()) */ T& operator[](size_t index); /** * @brief Returns a constant reference to the value at the * position given by \p index * @throw std::out_of_range if \p index is not in range [0, size()) */ const T& operator[](size_t index) const; /** * @brief Returns an iterator to the beginning of the list */ iterator begin(); /** * @brief Returns a constant iterator to the beginning of the list */ const_iterator cbegin() const; /** * @brief Returns an iterator to the end of the list */ iterator end(); /** * @brief Returns a constant iterator to the end of the list */ const_iterator cend() const; /** * @brief Inserts \p value at the front of the list * * @param value */ void push_front(const T& value); /** * @brief Inserts \p value at the end of the list * * @param value */ void push_back(const T& value); /** * @brief Inserts \p value at the given \p index * @throw std::out_of_range if \p index is not in range [0, size()] */ void insert(size_t index, const T& value); /** * @brief Inserts \p value at the given \p position * @throw std::invalid_argument if iterator is not for this list * @return iterator - iterator that points to the newly inserted value */ iterator insert(iterator position, const T& value); /** * @brief Removes the value at the front of the list * @throw std::invalid_argument if list is empty */ void pop_front(); /** * @brief Removes the value at the end of the list * @throw std::invalid_argument if list is empty */ void pop_back(); /** * @brief Removes the value at \p index from the list * @throw std::out_of_range if \p index is not in range [0, size()) */ void remove(size_t index); /** * @brief Removes the value at \p position from the list * @throw std::out_of_range if \p position == list.end() * @throw std::invalid_argument if iterator is not for this list * @return iterator - iterator that points to the next value * after the value that was removed; if the last element was * removed, points to list.end(). */ iterator remove(iterator position); /** * @brief Removes all the values from the list */ void clear(); private: // Members DoublyLinkedListNode<T>* head; DoublyLinkedListNode<T>* tail; size_t num_entries; /** * @brief Returns a pointer to the node at \p index * @throw std::out_of_range if \p index is not in [0,size()) */ DoublyLinkedListNode<T>* find(size_t index) const; }; template<class T> class LinkedList<T>::iterator { public: // Definitions typedef std::bidirectional_iterator_tag iterator_category; ~iterator(){ } iterator(const iterator& it) // Copy constructor { list = it.list; node = it.node; } iterator& operator=(const iterator& it) // Assignment operator { list = it.list; node = it.node; return *this; } /** * @brief Returns a reference to the currently referenced item * or if iterator is not for this list */ T& operator*() const // Dereference { if(node == NULL) throw std::invalid_argument("Iterator equal to end()"); else return node->data; } /** * @brief Returns an pointer to referenced item. T must be * a class or struct - enforced by compiler. * @throw std::invalid_argument if the iterator is equal to end() */ T* operator->() const { if(node == NULL) throw std::invalid_argument("Iterator equal to end()"); else return &(node->data); } /** * @brief Advances the iterator * @throw std::invalid_argument if the iterator is equal to end() * @return iterator& - iterator to the next position */ iterator& operator++() // Prefix increment { if(node == NULL) throw std::invalid_argument("Iterator equal to end()"); else { node = node->next; return *this; } } /** * @brief Advances the iterator * @throw std::invalid_argument if the iterator is equal to end() * @return iterator& - iterator to the current position */ iterator operator++(int) // Postfix increment { iterator copy = *this; ++(*this); return copy; } /** * @brief Moves the iterator backwards * @throw std::invalid_argument if the iterator is equal to begin() * @return iterator& - interator to the previous position */ iterator& operator--() // Prefix decrement { if(node == list->head) throw std::invalid_argument("Iterator equal to begin()"); if(node == NULL) node = list->tail; else node = node->prev; return *this; } /** * @brief Moves the iterator backwards * @throw std::invalid_argument if the iterator is equal to begin() * @return iterator& - iterator to the current position */ iterator operator--(int) // Postfix decrement { iterator copy = *this; --(*this); return copy; } /** * @brief Compares iterators for equality; returns * true if both refer to the same position in the same list */ bool operator==(const iterator& other) { return node == other.node; } bool operator!=(const iterator& other) { return !(operator==(other)); } private: // Only LinkedList<T> has access to private constructor friend class LinkedList<T>; iterator(LinkedList<T>* list, DoublyLinkedListNode<T>* node) : list(list), node(node){ } DoublyLinkedListNode<T>* node; LinkedList<T>* list; }; template<class T> class LinkedList<T>::const_iterator { public: // Definitions typedef std::bidirectional_iterator_tag iterator_category; ~const_iterator(){ } const_iterator(const const_iterator& it) // Copy constructor { list = it.list; node = it.node; } const_iterator& operator=(const const_iterator& it) // Assignment operator { list = it.list; node = it.node; return *this; } /** * @brief Returns a const reference to the currently referenced item * @throw std::invalid_argument if the iterator is equal to end() */ const T& operator*() const // Dereferencing { if(node == NULL) throw std::invalid_argument("Iterator equal to end()"); else return node->data; } /** * @brief Returns a const pointer to referenced item. T must be * a class or struct - enforced by compiler. * @throw std::invalid_argument if the iterator is equal to end() */ const T* operator->() const { if(node == NULL) throw std::invalid_argument("Iterator equal to end()"); else return &(node->data); } /** * @brief Advances the iterator * @throw std::invalid_argument if the iterator is equal to end() * @return const_iterator& - const iterator to the next position */ const_iterator& operator++() // Prefix increment { if(node == NULL) throw std::invalid_argument("Iterator equal to end()"); else { node = node->next; return *this; } } /** * @brief Advances the iterator * @throw std::invalid_argument if the iterator is equal to end() * @return const_iterator& - const iterator to the current position */ const_iterator operator++(int) // Postfix incremen { const_iterator copy = *this; ++(*this); return copy; } /** * @brief Moves the iterator backwards * @throw std::invalid_argument if the iterator is equal to begin() * @return const_iterator& - const iterator to the previous position */ const_iterator& operator--() // Prefix decrement { if(node == list->head) throw std::invalid_argument("Iterator equal to begin()"); if(node == NULL) node = list->tail; else node = node->prev; return *this; } /** * @brief Moves the iterator backwards * @throw std::invalid_argument if the iterator is equal to begin() * @return const_iterator& - const iterator to the current position */ const_iterator operator--(int) // Postfix decrement { const_iterator copy = *this; --(*this); return copy; } /** * @brief Compares iterators for equality; returns * true if both refer to the same position in the same list */ bool operator==(const const_iterator& other) { return node == other.node; } bool operator!=(const const_iterator& other) { return !(operator==(other)); } private: friend class LinkedList<T>; const_iterator(const LinkedList<T>* list, const DoublyLinkedListNode<T>* node) : list(list), node(node){ } const DoublyLinkedListNode<T>* node; const LinkedList<T>* list; }; template<class T> LinkedList<T>::LinkedList() { head = NULL; tail = NULL; num_entries = 0; } template<class T> LinkedList<T>::~LinkedList() { DoublyLinkedListNode<T>* temp; while(head != NULL) { temp = head; head = head->next; delete temp; } } template<class T> LinkedList<T>::LinkedList(const LinkedList<T>& other) { head = NULL; tail = NULL; num_entries = 0; for(auto it = other.begin(); it != end(); ++it) { push_back(*it); } } template<class T> LinkedList<T>& LinkedList<T>::operator=(const LinkedList<T>& other) { LinkedList<T> temp(other); std::swap(temp); return *this; } template<class T> bool LinkedList<T>::empty() const { return !num_entries; } template<class T> size_t LinkedList<T>::size() const { return num_entries; } template<class T> T& LinkedList<T>::operator[](size_t index) { return find(index)->data; } template<class T> const T& LinkedList<T>::operator[](size_t index) const { T& value = operator[](index); return value; } template<class T> typename LinkedList<T>::iterator LinkedList<T>::begin() { return iterator(this, head); } template<class T> typename LinkedList<T>::const_iterator LinkedList<T>::cbegin() const { return const_iterator(this, head); } template<class T> typename LinkedList<T>::iterator LinkedList<T>::end() { return iterator(this, NULL); } template<class T> typename LinkedList<T>::const_iterator LinkedList<T>::cend() const { return const_iterator(this, NULL); } template<class T> void LinkedList<T>::push_front(const T& value) { head = new DoublyLinkedListNode<T>(value, NULL, head); // Update next node if(head->next) head->next->prev = head; // Update tail if(tail == NULL) tail = head; num_entries++; } template<class T> void LinkedList<T>::push_back(const T& value) { tail = new DoublyLinkedListNode<T>(value, tail, NULL); // Update previous node if(tail->prev) tail->prev->next = tail; // Update head if(head == NULL) head = tail; num_entries++; } template<class T> void LinkedList<T>::insert(size_t index, const T& value) { // Insert at head if(index == 0) push_front(value); // Insert at tail else if(index == num_entries) push_back(value); // Insert in middle else { DoublyLinkedListNode<T>* prev = find(index - 1); DoublyLinkedListNode<T>* next = prev->next; DoublyLinkedListNode<T>* insert = new DoublyLinkedListNode<T>(value, prev, next); insert->next->prev = insert; insert->prev->next = insert; num_entries++; } } template<class T> typename LinkedList<T>::iterator LinkedList<T>::insert(iterator pos, const T& value) { if(pos.list != this) throw std::invalid_argument("Iterator does no match list"); // Insert at head else if(pos.node == head) { push_front(value); return begin(); } // Insert at tail else if(pos.node == NULL) { push_back(value); return iterator(this, tail); } // Insert in middle else { DoublyLinkedListNode<T>* next = pos.node; DoublyLinkedListNode<T>* prev = next->prev; DoublyLinkedListNode<T>* insert = new DoublyLinkedListNode<T>(value, prev, next); insert->next->prev = insert; insert->prev->next = insert; num_entries++; return iterator(this, insert); } } template<class T> void LinkedList<T>::pop_front() { if(!num_entries) throw std::out_of_range("Cannot pop_front() on an empty list"); DoublyLinkedListNode<T>* temp = head; head = head->next; if(head) head->prev = NULL; else tail = NULL; delete temp; num_entries--; } template<class T> void LinkedList<T>::pop_back() { if(!num_entries) throw std::out_of_range("Cannot pop_back() on an empty list"); DoublyLinkedListNode<T>* temp = tail; tail = tail->prev; if(tail) tail->next = NULL; else head = NULL; delete temp; num_entries--; } template<class T> void LinkedList<T>::remove(size_t index) { // Remove from front if(index == 0) pop_front(); else if(index == num_entries - 1) pop_back(); else { DoublyLinkedListNode<T>* re = find(index); re->next->prev = re->prev; re->prev->next = re->next; delete re; num_entries--; } } template<class T> typename LinkedList<T>::iterator LinkedList<T>::remove(iterator pos) { if(pos.list != this) throw std::invalid_argument("Iterator does no match list"); if(empty()) throw std::invalid_argument("Cannot remove item from empty list"); if(pos == end()) throw std::invalid_argument("Iterator equal to end()"); iterator ret(this, pos.node->next); // Remove from head if(pos == begin()) pop_front(); // Remove from tail else if(pos.node == tail) pop_back(); // Remove from middle else { DoublyLinkedListNode<T>* erase = pos.node; erase->next->prev = erase->prev; erase->prev->next = erase->next; delete erase; num_entries--; } return ret; } template<class T> void LinkedList<T>::clear() { DoublyLinkedListNode<T>* temp; while(head != NULL) { temp = head; head = head->next; delete temp; } tail = NULL; num_entries = 0; } template<class T> DoublyLinkedListNode<T>* LinkedList<T>::find(size_t index) const { // Check bounds if(index < 0 || index >= num_entries) { throw std::out_of_range("Index must be in range [0,size())"); } DoublyLinkedListNode<T>* n = head; for(size_t i = 0; i != index; i++) n = n->next; return n; } #endif
true
17e5896ceba5fe7751b5b7973f6ab1fa78102445
C++
palomaalves/Desafios-em-linguagem-C
/codigoCelulaLista.cpp
ISO-8859-1
5,173
3.375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> /* A altura de uma clula c em uma lista encadeada a distncia entre c e o fim da lista. Mais precisamente, a altura de c o nmero de passos do caminho que leva de c at a ltima clula da lista. Escreva uma funo que calcule a altura de uma dada clula. */ #include <stdio.h> #include <stdlib.h> typedef struct Node { int num; struct Node *prox; }node; int tam; void inicia(node *LISTA); int menu(void); void opcao(node *LISTA, int op); node *criaNo(); void insereFim(node *LISTA); void insereInicio(node *LISTA); void exibe(node *LISTA); void libera(node *LISTA); void insere (node *LISTA); node *retiraInicio(node *LISTA); node *retiraFim(node *LISTA); node *retira(node *LISTA); int main(void) { node *LISTA = (node *) malloc(sizeof(node)); if(!LISTA){ printf("Sem memoria disponivel!\n"); exit(1); }else{ inicia(LISTA); int opt; do{ opt=menu(); opcao(LISTA,opt); }while(opt); free(LISTA); return 0; } } void inicia(node *LISTA) { LISTA->prox = NULL; tam=0; } int menu(void) { int opt; printf("Escolha a opcao\n"); printf("0. Sair\n"); printf("1. Zerar lista\n"); printf("2. Exibir lista\n"); printf("3. Adicionar node no inicio\n"); printf("4. Adicionar node no final\n"); printf("5. Escolher onde inserir\n"); printf("6. Retirar do inicio\n"); printf("7. Retirar do fim\n"); printf("8. Escolher de onde tirar\n"); printf("Opcao: "); scanf("%d", &opt); return opt; } void opcao(node *LISTA, int op) { node *tmp; switch(op){ case 0: libera(LISTA); break; case 1: libera(LISTA); inicia(LISTA); break; case 2: exibe(LISTA); break; case 3: insereInicio(LISTA); break; case 4: insereFim(LISTA); break; case 5: insere(LISTA); break; case 6: tmp= retiraInicio(LISTA); printf("Retirado: %3d\n\n", tmp->num); break; case 7: tmp= retiraFim(LISTA); printf("Retirado: %3d\n\n", tmp->num); break; case 8: tmp= retira(LISTA); printf("Retirado: %3d\n\n", tmp->num); break; default: printf("Comando invalido\n\n"); break; } } int vazia(node *LISTA) { if(LISTA->prox == NULL) return 1; else return 0; } node *aloca() { node *novo=(node *) malloc(sizeof(node)); if(!novo){ printf("Sem memoria disponivel!\n"); exit(1); }else{ printf("Novo elemento: "); scanf("%d", &novo->num); return novo; } } void insereFim(node *LISTA) { node *novo=aloca(); novo->prox = NULL; if(vazia(LISTA)) LISTA->prox=novo; else{ node *tmp = LISTA->prox; while(tmp->prox != NULL) tmp = tmp->prox; tmp->prox = novo; } tam++; } void insereInicio(node *LISTA) { node *novo=aloca(); node *oldHead = LISTA->prox; LISTA->prox = novo; novo->prox = oldHead; tam++; } void exibe(node *LISTA) { system("clear"); if(vazia(LISTA)){ printf("Lista vazia!\n\n"); return ; } node *tmp; tmp = LISTA->prox; printf("Lista:"); while( tmp != NULL){ printf("%5d", tmp->num); tmp = tmp->prox; } printf("\n "); int count; for(count=0 ; count < tam ; count++) printf(" ^ "); printf("\nOrdem:"); for(count=0 ; count < tam ; count++) printf("%5d", count+1); printf("\n\n"); } void libera(node *LISTA) { if(!vazia(LISTA)){ node *proxNode,*atual; atual = LISTA->prox; while(atual != NULL){ proxNode = atual->prox; free(atual); atual = proxNode; } } } void insere(node *LISTA) { int pos, count; printf("Em que posicao, [de 1 ate %d] voce deseja inserir: ",tam); scanf("%d", &pos); if(pos>0 && pos <= tam){ if(pos==1){ insereInicio(LISTA); }else{ node *atual = LISTA->prox, *anterior=LISTA; node *novo=aloca(); for(count=1 ; count < pos ; count++){ anterior=atual; atual=atual->prox; } anterior->prox=novo; novo->prox = atual; tam++; } }else printf("Elemento invalido\n\n"); } node *retiraInicio(node *LISTA){ if(LISTA->prox == NULL){ printf("Lista ja esta vazia\n"); return NULL; }else{ node *tmp = LISTA->prox; LISTA->prox = tmp->prox; tam--; return tmp; } } node *retiraFim(node *LISTA){ if(LISTA->prox == NULL){ printf("Lista ja vazia\n\n"); return NULL; }else{ node *ultimo = LISTA->prox, *penultimo = LISTA; while(ultimo->prox != NULL){ penultimo = ultimo; ultimo = ultimo->prox; } penultimo->prox = NULL; tam--; return ultimo; } } node *retira(node *LISTA) { int opt, count; printf("Que posicao, [de 1 ate %d] voce deseja retirar: ", tam); scanf("%d", &opt); if(opt>0 && opt <= tam){ if(opt==1) return retiraInicio(LISTA); else{ node *atual = LISTA->prox, *anterior=LISTA; for(count=1 ; count < opt ; count++){ anterior=atual; atual=atual->prox; } anterior->prox=atual->prox; tam--; return atual; } }else{ printf("Elemento invalido\n\n"); return NULL; } }
true
f46c1815ed5d1cf6acb333295474392d22903df9
C++
m-peko/booleval
/include/booleval/token/token.hpp
UTF-8
5,057
2.75
3
[ "MIT" ]
permissive
/* * Copyright (c) 2019, Marin Peko * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef BOOLEVAL_TOKEN_HPP #define BOOLEVAL_TOKEN_HPP #include <optional> #include <string_view> #include <type_traits> #include <booleval/token/token_type.hpp> #include <booleval/token/token_type_utils.hpp> namespace booleval::token { /** * @class token * * Represents all tokens ('and', 'or', 'eq', ...). */ class token { public: constexpr token() noexcept = default; constexpr token( token && rhs ) noexcept = default; constexpr token( token const & rhs ) noexcept = default; constexpr token( token_type const type ) noexcept : type_ ( type ) , value_( to_token_keyword( type ) ) {} constexpr token( std::string_view const value ) noexcept : type_ ( to_token_type( value ) ) , value_( value ) {} constexpr token( token_type const type, std::string_view const value ) noexcept : type_ ( type ) , value_( value ) {} token & operator=( token && rhs ) noexcept = default; token & operator=( token const & rhs ) noexcept = default; [[ nodiscard ]] constexpr bool operator==( token const & rhs ) const noexcept { return type_ == rhs.type_ && value_ == rhs.value_; } ~token() noexcept = default; /** * Sets the token type. * * @param type Token type */ constexpr void type( token_type const type ) noexcept { if ( type != type_ ) { type_ = type; value_ = to_token_keyword( type ); } } /** * Gets the token type. * * @return Token type */ [[ nodiscard ]] constexpr token_type type() const noexcept { return type_; } /** * Sets the token value. * * @param value Token value */ constexpr void value( std::string_view const value ) noexcept { type_ = to_token_type( value ); value_ = value; } /** * Gets the token value. * * @return Token value */ [[ nodiscard ]] constexpr std::string_view value() const noexcept { return value_; } /** * Checks whether the token is of the specified type. * * @return True if the token is of the specified type, false otherwise */ [[ nodiscard ]] constexpr bool is( token_type const type ) const noexcept { return type_ == type; } /** * Checks whether the token is not of the specified type. * * @return True if the token is not of the specified type, false otherwise */ [[ nodiscard ]] constexpr bool is_not( token_type const type ) const noexcept { return type_ != type; } /** * Checks whether the token is of the first or second specified type. * * @return True if the token is of the first or second specified type, false otherwise */ [[ nodiscard ]] constexpr bool is_one_of ( token_type const first, token_type const second ) const noexcept { return is( first ) || is( second ); } /** * Checks whether the token is one of the multiple specified types. * * @return True if the token is one of the multiple specified types, false otherwise */ template< typename ... TokenType > [[nodiscard]] constexpr bool is_one_of ( token_type const first, token_type const second, TokenType const ... nth ) const noexcept { return is( first ) || is_one_of( second, nth ... ); } private: token_type type_ { token_type::unknown }; std::string_view value_{}; }; } // namespace booleval::token #endif // BOOLEVAL_TOKEN_HPP
true
6da49147035538fbc88175b5b8dfd2ef17ec5bc3
C++
qis/vcpkg-test
/src/dtz/main.cpp
UTF-8
589
2.578125
3
[ "BSL-1.0" ]
permissive
#include <gtest/gtest.h> #include <dtz.hpp> const auto g_tzdata_initialized = []() { dtz::initialize(); return true; }(); TEST(date, date) { constexpr auto ymd = date::year{ 2019 } / date::month{ 1 } / 1; constexpr auto tp = std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds>{ date::sys_days{ ymd } }; ASSERT_EQ(tp.time_since_epoch(), std::chrono::seconds{ 1546300800 }); } TEST(date, tz) { const auto stp = std::chrono::system_clock::now(); const auto ztp = date::make_zoned(date::current_zone(), stp); ASSERT_EQ(stp, ztp.get_sys_time()); }
true