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
42439ede6e11a2a0003e96592b12f29389a3b9ff
C++
aleksa2808/buffer-overflow-exploits
/scenario3/p3.cpp
UTF-8
936
3.453125
3
[]
no_license
#include <cstdio> #include <cstring> class BaseGreeter { public: void setName(char *s_name) { strcpy(name, s_name); } virtual void greet() = 0; protected: char name[256]; }; class ClassyGreeter : public BaseGreeter { public: virtual void greet() { printf("Good day %s!\n", name); } }; class SeafaringGreeter : public BaseGreeter { public: virtual void greet() { printf("Ahoy %s!\n", name); } }; int main(int argc, char **argv) { char name[512]; printf("And what do we call you?\n"); fgets(name, sizeof(name), stdin); name[strlen(name) - 1] = '\0'; ClassyGreeter *cg = new ClassyGreeter(); SeafaringGreeter *sg = new SeafaringGreeter(); cg->setName(name); sg->setName(name); // select a greeter based on the provided name BaseGreeter *g = strlen(name) % 2 == 0 ? (BaseGreeter *)cg : (BaseGreeter *)sg; g->greet(); }
true
ea10190ab17240bbce55bc77143671b2b4722bb9
C++
NeuroWhAI/CodeAdapter
/CodeAdapter/ListBox.h
UTF-8
1,867
2.703125
3
[ "MIT" ]
permissive
#ifndef __CA__LIST_BOX_H__ #define __CA__LIST_BOX_H__ #include <memory> #include <vector> #include "BasicDeclaration.h" #include "Control.h" #include "Point.h" #include "String.h" BEGIN_NAMESPACE_CA_UI class ListBox : public Control { private: USING_CA(i32); USING_CA_DRAWING(Point); USING_CA_DRAWING(PointF); USING_CA_DRAWING(Transform); USING_CA_DRAWING(Graphics); USING_CA_UTILITY(String); public: ListBox(); ListBox(const ListBox& right); virtual ~ListBox(); protected: PointF m_itemMargin; protected: std::vector<String> m_item; private: i32 m_selectedIndex; protected: std::unique_ptr<VerticalScrollBar> m_verticalBar; public: ValueEventHandler WhenSelectedIndexChanged; public: virtual void onSelectedIndexChanged(const ValueEventArgs& args); protected: virtual void onMove(const EventArgs& args) override; virtual void onResize(const EventArgs& args) override; virtual void onTouchDown(const TouchEventArgs& args) override; protected: virtual void onUpdateControl(const Transform& parentTransform, const PointF& parentCursor, const Transform& localTransform, const PointF& localCursor) override; virtual void onDrawControl(Graphics& g, const Transform& parentTransform) override; public: ListBox& operator= (const ListBox& right); public: void setItemMargin(const PointF& margin); const PointF& getItemMargin() const; public: void addItem(const String& text); void insertItem(i32 index, const String& text); void removeItem(const String& text); void removeItemAt(i32 index); i32 itemIndexOf(const String& text) const; void clearItems(); i32 getItemCount() const; i32 getItemHeight() const; public: bool hasSelectedItem() const; i32 getSelectedIndex() const; void selectItemAt(i32 index); void deselectItem(); protected: void updateScrollBar(); }; END_NAMESPACE_CA_UI #endif
true
df2e93f87fd4ca3dc13a182ff2078f989d3f2fbc
C++
jjmalarkey/cs261_p1
/reporter.cpp
UTF-8
4,642
2.90625
3
[]
no_license
#include "reporter.h" #include <iostream> #include <iomanip> #include <string> #include <utility> reporter::reporter() { } reporter::reporter(productiondb &db) { //the only constructor because without a db to connect is useless connection = &db; db.getTables(&stationList); } reporter::~reporter() { stationList.clear(); connection = NULL; } void reporter::prettyPrintFull(query * reportQuery) { //strategy: do no sorting - the response data and order should already be alphabetized //header format print: std::string calendar[13] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Tot"}; std::cout << "Station: " << reportQuery->station << "\n\n"; std::cout.width(19); for(int i = 0; i < 13; i++) { std::cout << std::right << calendar[i]; std::cout.width(8); } std::cout << std::endl << std::left; std::map<std::string, int>::iterator dataPtr; //table body: for(std::map<std::string, int>::iterator resIt = reportQuery->response[12].begin(); resIt != reportQuery->response[12].end(); resIt++) { std::cout << std::left; std::cout.width(11); std::cout << resIt->first; for(std::vector<std::map<std::string, int>>::iterator station = reportQuery->response.begin(); station != reportQuery->response.end(); station++) { dataPtr = station->find(resIt->first); std::cout.width(8); std::cout << std::right << dataPtr->second; } std::cout << std::endl; } std::cout << std::endl; } void reporter::prettyPrintStation(query * reportQuery, std::map<std::string, int > * resources) { //strategy: use fixed order of station list to order response table //header format print: printf("*******%4d*******\n", reportQuery->year); //table std::vector<int> stationTotal(stationList.size(), 0); std::vector<int>::iterator stationTotalIt; std::cout.width(22); for(std::vector<std::string>::iterator station = stationList.begin(); station != stationList.end(); station++) { std::cout << std::right << *station; std::cout.width(11); } std::cout << std::endl << std::left; std::map<std::string, int>::iterator dataPtr; //data for(std::map<std::string, int>::iterator resIt = resources->begin(); resIt != resources->end(); resIt++) { stationTotalIt = stationTotal.begin(); std::cout << resIt->first; std::cout.width(11); for(std::vector<std::map<std::string, int>>::iterator station = reportQuery->response.begin(); station != reportQuery->response.end(); station++) { dataPtr = station->find(resIt->first); std::cout << std::right << dataPtr->second; std::cout.width(11); *stationTotalIt += dataPtr->second; stationTotalIt++; } std::cout << std::left << std::endl; } std::cout << " Total" << std::right; std::cout.width(11); for(stationTotalIt = stationTotal.begin(); stationTotalIt != stationTotal.end(); stationTotalIt++) { std::cout << std::right << *stationTotalIt; std::cout.width(11); } std::cout << std::endl << std::endl; } void reporter::printFullReport(int year) { printf("*******%4d*******\n\n", year); for(std::vector<std::string>::iterator it = stationList.begin(); it != stationList.end(); it++) { query reportQuery(*it, year); connection->getStationMonthly(&reportQuery); prettyPrintFull(&reportQuery); } } void reporter::printStationReport(int year) { query totalReport("NONE", year); //query subQuery("none", year); std::map<std::string, int> resources; for(std::vector<std::string>::iterator it = stationList.begin(); it != stationList.end(); it++) { query subQuery(*it, year); // subQuery.station = *it; connection->getStationYearly(&subQuery); for(std::map<std::string, int>::iterator it = subQuery.response[0].begin(); it != subQuery.response[0].end(); it++) { std::map<std::string, int>::iterator mit = resources.find(it->first); if(mit == resources.end()) resources[it->first] = 1; } totalReport.response.push_back(subQuery.response[0]); } /* for( auto x : resources ) { std::cout << x.first << "\t"; } */ //std::cout << "\n"; //populate entries with no resource count for(std::vector<std::map<std::string, int>>::iterator vit = totalReport.response.begin(); vit != totalReport.response.end(); vit++) { // for(std::vector<std::map<std::string, int>>::iterator vit = subQuery.response.begin(); vit != subQuery.response.end(); vit++) { for(std::map<std::string, int>::iterator mit = resources.begin(); mit != resources.end(); mit++) { std::map<std::string, int>::iterator it = vit->find(mit->first); if(it == vit->end()) (*vit)[mit->first] = 0; } } //prettyPrintStation(&subQuery, &resources); prettyPrintStation(&totalReport, &resources); }
true
ddcb4c9c02e6fc0fbdf6504f9fa1f46f66f2c50e
C++
RapidWorkers/ProblemSolving
/BOJ/세그먼트 트리/1615.cpp
UTF-8
1,279
3.046875
3
[]
no_license
//Segment tree and inversion counting #include <iostream> #include <vector> #include <algorithm> #include <cmath> #include <map> #include <set> using namespace std; //Fast query/modify from codeforces http://codeforces.com/blog/entry/18051 int query(vector<int>& t, int n, int l, int r) { // sum on interval [l, r) int res = 0; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l & 1) res += t[l++]; if (r & 1) res += t[--r]; } return res; } void modify(vector<int>& t, int n, int p, int value) { // set value at position p for (t[p += n] = value; p > 1; p >>= 1) t[p >> 1] = t[p] + t[p ^ 1]; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int N, M; cin >> N >> M; vector<pair<int, int>> graph; int h = ceil(log2(N)); int szTree = (1 << (h + 1)); vector<int> segTree(szTree); int from, to; for (int i = 0; i < M; i++)//O(n) { cin >> to >> from; graph.push_back(make_pair(N - from, N - to)); } sort(graph.rbegin(), graph.rend()); long long crossed = 0; for (int i = 0; i < M; i++) { int curIdx = graph[i].second;//get value crossed += query(segTree, szTree >> 1, 0, curIdx); modify(segTree, szTree >> 1, curIdx, query(segTree, szTree >> 1, curIdx, curIdx+1)+1); } cout << crossed; return 0; }
true
f12f858aec91f9b3478b22dceacdfa7ec2021ebd
C++
Sima214/vff-struct
/src/ssce/clock.hpp
UTF-8
1,114
2.796875
3
[]
no_license
#ifndef SSCE_CLOCK_HPP #define SSCE_CLOCK_HPP #include <cfloat> #include <stdint.h> #if defined(__linux__) #define INTERNAL_STORAGE 2 #elif defined(__APPLE__) #define INTERNAL_STORAGE 0 #elif defined(_WIN32) #define INTERNAL_STORAGE 1 #else #error "Unknown platform." #endif namespace ssce{ class Clock { public: //Last measurement. float delta; //Mean delta since last reset. float avg; //Smallest delta since last reset. float min; //Biggest delta since last reset. float max; /* * Constructor. */ Clock(): min(FLT_MAX), max(FLT_MIN), count_query(0), delta_sum(0) {}; /* * Start measuring. */ void start(); /* * Stops measurement and calculates * new delta and updates statistics. */ void stop(); /* * Resets clock counters and statistics. */ void reset() { this->count_query = 0; this->delta_sum = 0; this->max = FLT_MIN; this->min = FLT_MAX; } private: int64_t intcnt[INTERNAL_STORAGE]; int64_t count_query; double delta_sum; }; } #endif /*SSCE_CLOCK_HPP*/
true
deab59319c550a2a4279d0be9de2d530db5e7b0a
C++
Flare-k/Algorithm
/재귀/하노이탑_재귀_11729.cpp
UTF-8
915
3.296875
3
[]
no_license
#include <iostream> #include <utility> #include <vector> #define endl "\n" using namespace std; int cnt = 0; vector<pair<int, int> > ans; void honoiTop(int num, int from, int by, int to) { cnt++; if (num == 1) { ans.push_back(make_pair(from, to)); } else { honoiTop(num - 1, from, to, by); // n-1개의 원판을 1번에서부터(from) 3번을 거쳐(by) 2번으로(to) 가게한다. ans.push_back(make_pair(from, to)); honoiTop(num - 1, by, from, to); // 그런다음 2번에 있는 원판을(from) 1번을 거쳐(by) 3번으로(to) 마무리한다. } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; honoiTop(n, 1, 2, 3); cout << cnt << endl; for (int i = 0; i < ans.size(); i++) { cout << ans[i].first << " " << ans[i].second << endl; } return 0; }
true
19912a90fc041cd3dcb909d2ee2b802c094c0081
C++
jentlestea1/obs_xslt
/obs/src/cpp/FDIR/DC_StuckDataProfile.h
UTF-8
4,342
2.796875
3
[]
no_license
// // Copyright 2004 P&P Software GmbH - All Rights Reserved // // DC_StuckDataProfile.h // // Version 1.1 // Date 07.01.03 (Version 1.0) // 01.10.03 (Version 1.1) // Author A. Pasetti (P&P Software), R. Totaro // // Change Record: // Version 1.1: replaced double and int with TD_Float and TD_Integer #ifndef DC_StuckDataProfileH #define DC_StuckDataProfileH #include "../GeneralInclude/ForwardDeclarations.h" #include "../GeneralInclude/BasicTypes.h" #include "MonitoringProfile.h" /** * Default component implementing a "stuck data" monitoring profile. * This monitoring profile reports a "deviation from profile" if the * value of the monitored variable remains unchanged for more * a certain number of consecutive activations. * The number of consecutive activations that the * monitored variable must remain unchanged before the monitoring check is * detected is called the <i>stuck threshold</i>. * The stuck threshold is a settable parameter. Its value must be * greater than zero. * <p> * This type of check only makes sense for monitored variables of * integer type. The version of the monitoring check for variables * of doble type is therefore implemented as a dummy operation * that always returns "deviation from profile has been detected". * @author Alessandro Pasetti (P&P Software GmbH) * @author Roberto Totaro * @version 1.1 */ class DC_StuckDataProfile: public MonitoringProfile { private: unsigned int stuckThreshold; unsigned int counter; TD_Integer previousValue; protected: /** * Check whether the monitored value is stuck. * If it is, a "devation from profile" is reported. * A pseudo-code implementation for this method is as follows: <PRE> * if ( value == previousValue ) * { counter++; * previousValue = value; * if (counter == stuckThreshold) * { counter = 0; * return MON_PROFILE_DEVIATION; * } * else * return NO_MON_PROFILE_DEVIATION; * } * else * counter = 0; * previousValue = value; * return NO_MON_PROFILE_DEVIATION; </PRE> * <p> * The value of <code>previousValue</code> and <code>counter</code> * are initialized by the constructor and by method <code>reset</code>. * Spurious triggerings can occurr either after a reset or after the * component is created. * @see #reset * @see #DC_StuckDataProfile * @param value the value of the monitored variable * @return true if the monitored variable is stuck, false otherwise */ virtual bool doProfileCheck(TD_Integer value); /** * Dummy implementation of a monitoring check that always returns "deviation * from profile detected". * This operation should never be called since stuck data monitoring checks on * non-integer variables may give unpredictable results due to numerical * precision errors. * @param value the value of the monitored variable * @return always returns true */ virtual bool doProfileCheck(TD_Float value); public: /** * Instantiate a stuck data profile. * The class identifier is set, the stuck threshold is initialized to 0 to * signify that the component is not yet configured, and the component is * reset. */ DC_StuckDataProfile(void); /** * Set the stuck threshold. * @see #doProfileCheck * @param stuckThreshold the value of the stuck threshold */ void setStuckThreshold(unsigned int stuckThreshold); /** * Get the stuck thresholde. * @see #setStuckThreshold * @return the value of the stuck threshold */ unsigned int getStuckThreshold(void) const; /** * Perform a class-specific configuration check on the monitoring * profile: verify that the stuck threshold has a value greater than zero. * @return true if the monitoring profile is configured, false otherwise. */ virtual bool isObjectConfigured(void); /** * Reset the stuck value profile check. With reference to the * implementation of method <code>doProfileCheck(TD_Integer)</code>, a call to * this method causes the variable <code>counter</code> to be reset to * zero and the variable <code>previousValue</code> to be reset to * PREVIOUS_VALUE_INIT. */ virtual void reset(void); }; #endif
true
cc301e830225c12e14f1f67eab6f25372acadd22
C++
blackbbc/plot
/bilibili/functionhelper.cpp
GB18030
2,467
2.640625
3
[]
no_license
#include "functionhelper.h" #include "config.h" #include "mathparser.h" FunctionHelper::FunctionHelper() { initialParser(); } FunctionHelper::FunctionHelper (LPTSTR raw, DWORD color, FUNC_TYPE type) { initialParser(); this->_raw = new TCHAR[128]; wcscpy(this->_raw, raw); this->_color = color; this->_type = type; if (type == FUNC) { char *buffer = new char[128]; wcstombs(buffer, raw, 128); this->_func = preProcessing(buffer); this->_rpn = getRPN(this->_func); } } void FunctionHelper::updateXVec() { INT i; DOUBLE gapX = getXRangeLength() / FUNCTION_WIDTH; for (i = 0; i < FUNCTION_WIDTH; i++) { xVec[i] = X_RANGE_LEFT + gapX * i; } } void FunctionHelper::updateYVec() { INT i; for (i = 0; i < FUNCTION_WIDTH; i++) { yVec[i] = getY(xVec[i]); } } void FunctionHelper::addPoint(double x, double y) { xVec[index] = x; yVec[index] = y; index++; } void FunctionHelper::setColor(DWORD color) { _color = color; } DWORD FunctionHelper::getColor() { return _color; } FUNC_TYPE FunctionHelper::getType() { return _type; } void FunctionHelper::setFunc(LPTSTR raw) { wcscpy(this->_raw, raw); char *buffer = new char[128]; wcstombs(buffer, raw, 128); this->_func = preProcessing(buffer); this->_rpn = getRPN(this->_func); } LPTSTR FunctionHelper::getFunc() { return this->_raw; } DOUBLE FunctionHelper::getY(DOUBLE x) { return countexp(this->_rpn, x); } void FunctionHelper::draw(HDC &hdc) { BOOL isFirst = TRUE; DOUBLE percentX, percentY; INT i; DOUBLE XLength = getXRangeLength(); DOUBLE YLength = getYRangeLength(); HPEN hpen; HPEN hpenOld; hpen = CreatePen(PS_SOLID, 2, _color); hpenOld = (HPEN)SelectObject(hdc, hpen); if (_type == FUNC) { updateXVec(); updateYVec(); index = FUNCTION_WIDTH; } for (i = 0; i < index; i++) { //yֵǷ̫󣬲ҪƣǺ if (_type == FUNC) if (isnan(yVec[i]) || abs(yVec[i]) > max(abs(Y_RANGE_LEFT), abs(Y_RANGE_RIGHT)) * 2) { isFirst = TRUE; continue; } percentX = (xVec[i] - X_RANGE_LEFT) / XLength; percentY = (yVec[i] - Y_RANGE_LEFT) / YLength; percentY = 1 - percentY; if (isFirst == TRUE) { MoveToEx(hdc, (INT)(FUNCTION_WIDTH * percentX), (INT)(FUNCTION_HEIGHT * percentY), NULL); isFirst = FALSE; } else { LineTo(hdc, (INT)(FUNCTION_WIDTH * percentX), (INT)(FUNCTION_HEIGHT * percentY)); } } SelectObject(hdc, hpenOld); DeleteObject(hpenOld); DeleteObject(hpen); }
true
f7c6cb38ddfbf663448e8d1306ea58f9942ee670
C++
lkk-cxks/-
/大作业.cpp
GB18030
955
2.6875
3
[]
no_license
#include<bits/stdc++.h> #define min(x,y) ((x) > (y)?(y):(x)) //using namespace std; int edit(char *S,char *T) { int sLen = strlen(S); int tLen = strlen(T); int dp[sLen+1][tLen+1]; int i = 0; int j = 0; for ( i = 1;i <= sLen;i++) dp[i][0] = i; for ( j = 1;j <= tLen;j++) dp[0][j] = j; for ( i = 1;i <= sLen;i++) { for (j = 1;j <= tLen;j++) { if (S[i-1] == T[j-1]) { dp[i][j] = dp[i-1][j-1]; } else { dp[i][j] = 1 + min(min(dp[i-1][j],dp[i][j-1]),dp[i-1][j-1]);//עmin } } } return dp[sLen][tLen]; } int main() { char S[1000],T[1000]; printf("ԭ\n"); gets(S); printf("Ŀ괮\n"); gets(T); printf("С\n"); printf("%d\n",edit(S,T)); return 0; }
true
60e4265e89ebaa581cee3a0d4a891a8ba825b780
C++
wayne155/Algorithm
/main.cpp
UTF-8
1,605
3.078125
3
[]
no_license
#include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; int findSubStringWindow(string s, int start){ int hashStr[256] = {-1}; for (int i = 0; i < 256; i++) hashStr[i] = -1; int n = s.size() , ans= 0 ; for(int start =0 ,end = 0 ; end < n ; end++){ //如果存在就更新 start 位置 if(hashStr[s[end]] != -1){ //这句之后无需 remove start = max( hashStr[s[end]] + 1, start); } ans = max(ans, end - start + 1); hashStr[s[end]] = end; } return ans; } bool isPermulation( string s1, string s2){ if(s1.size() >= s2.size( )) return false; int hashVal1[128] = {0}; int hashVal2[128] = {0}; for(int i = 0;i < s1.size(); i ++){ hashVal1[s1[i]] ++; } for(int i = 0;i < s2.size(); i ++){ hashVal2[s2[i]] ++; } for(int i =0 ; i< 128; i++){ if(hashVal1[i] != hashVal2[i] ) return false; } return true; } bool checkInclusion(string s1, string s2) { // for(int i =0 ; i< s2.size() - s1.size() + 1 ; i ++){ // if(isPermulation(s1 , s2.substr(i, s1.size()))) // return true; // } return false; } int changeVector(vector<int> a){ a[0] = 0; return 1; } int main(){ vector<int> aa; aa.push_back(3); aa.push_back(4); aa.push_back(5); for(int i= 0 ; i < 3 ; i ++){ printf("%d ", aa[i]); } changeVector(aa); for(int i= 0 ; i < 3 ; i ++){ printf("%d ", aa[i]); } // checkInclusion("ba", "aaab"); }
true
c9513728c06920023059897315783dc1fc6f4b18
C++
Anil1111/COSC1436
/Samples/Chapter 6/FunctionWithReturnValue/common.h
UTF-8
685
3.5625
4
[ "MIT" ]
permissive
/* * COSC 1436 * * Provides some common functions needed in applications. */ #pragma once #include <iostream> using namespace std; /* * Determines if the numeric value is even. * * PARAMETERS: * value = The value to check. * RETURNS: * True if the value is even or false otherwise. */ bool IsEven ( int value ) { return value % 2 == 0; } /* * Determines if the numeric value is odd. * * PARAMETERS: * value = The value to check. * RETURNS: * True if the value is odd or false otherwise. */ bool IsOdd ( int value ) { return value % 2 != 0; } /// Waits for the user to press ENTER void WaitForEnter ( ) { cout << "Press ENTER" << endl; cin.get(); }
true
9d7494376ad53cdbbe95af954d99d82de29518f5
C++
bvan-dyc/CPPPool
/J01/ex02/main.cpp
UTF-8
489
2.859375
3
[]
no_license
#include <iostream> #include <string> #include <time.h> #include <stdlib.h> #include "Zombie.hpp" #include "ZombieEvent.hpp" int main(void) { ZombieEvent Zevent; srand(time(NULL)); Zombie ZombieA = Zombie("Adam", "Stack"); Zombie ZombieB = Zombie("Eve", "Stack"); ZombieA.announce(void); ZombieB.announce(void); Zevent.setZombieType("Heap"); Zombie *ZombieC = Zevent.randomChump(void); Zombie *ZombieD = Zevent.randomChump(void); delete ZombieC; delete ZombieD; return(0); }
true
4b85a464f6c1b0ebc3be46e95bbee5ed40cd90b5
C++
modulo-/SDP-2016-Team-F
/arduino/debug/manualMotor/manualMotor.ino
UTF-8
2,835
2.65625
3
[]
no_license
#include "SDPArduino.h" #include <Wire.h> int i = 0; /* Motor mapping 0 0 - Left motor (polarity reversed) 1 - Right motor (polarity reversed) 2 - Middle motor (left is 'forward') 3 - kicker 4 - flippers 5 - nothing */ void setup() { SDPsetup(); helloWorld(); } void loop() { react(); } void react() { char input; input = Serial.read(); switch (input) { case '8': Serial.println("forward"); motorBackward(0, 100); motorBackward(1, 100); motorStop(2); break; case '2': Serial.println("backward"); motorForward(0, 100); motorForward(1, 100); motorStop(2); break; case '5': Serial.println("stop"); motorStop(0); motorStop(1); motorStop(2); break; case '6': Serial.println("right"); motorForward(0, 0); motorBackward(1,65); motorBackward(2,100); break; case '4': Serial.println("left"); motorBackward(0,65); motorForward(1, 0); motorForward(2, 100); break; case '9': Serial.println("forwards clockwise"); motorBackward(0, 100); motorForward(1, 50); motorBackward(2, 100); break; case '7': Serial.println("forwards anticlockwise"); motorForward(0, 50); motorBackward(1, 100); motorForward(2, 100); break; case '3': Serial.println("backwards clockwise"); motorBackward(0, 50); motorForward(1, 100); motorBackward(0, 50); motorBackward(2, 100); break; case '1': Serial.println("backwards anticlockwise"); motorForward(0, 100); motorBackward(1, 50); motorForward(2, 100); break; //flippers open case 'k': Serial.write("flippers open\r\n"); motorForward(5, 80); delay(300); motorStop(5); break; //flippers close <<<<<<< HEAD case 'l': Serial.write("flippers close\r\n"); motorBackward(5, 80); delay(300); motorStop(5); break; // //left flipper open // case 'a': // Serial.println("left flipper open"); // motorForward(4, 80); // delay(300); // motorStop(4); // break; // // //left flipper close // case 's': // Serial.println("left flipper close"); // motorBackward(4, 80); // delay(300); // motorStop(4); // break; <<<<<<< HEAD //kick case 'h': Serial.write("kicker down\r\n"); motorForward(3, 100); delay(300); motorStop(3); break; // kicker down case 'j': Serial.write("kick\r\n"); motorBackward(3, 30); // kick case 'y': Serial.println("kick"); motorBackward(3, 100); delay(300); motorForward(3, 30); delay(100); motorStop(3); break; } }
true
f856eb33398c9b8697fb614f0f20bc9b6f052c80
C++
Eulring/ACM-ICPC_model
/String/Tire_tree.cpp
UTF-8
809
2.765625
3
[]
no_license
#include <stdio.h> #include <string.h> #include <iostream> using namespace std; typedef long long ll; struct Tire{ int v; Tire *next[26]; }root; void update(char *str){ int len=strlen(str); Tire *p=&root,*q; for(int i=0;i<len;i++){ int id=str[i]-'a'; if(p->next[id]==NULL){ q=(Tire*) malloc(sizeof(Tire)); q->v=1; for(int j=0;j<26;j++) q->next[j]=NULL; p->next[id]=q; p=p->next[id]; } else { p->next[id]->v++; p=p->next[id]; } } } int query(char *str){ int len=strlen(str); Tire *p=&root ; for(int i=0;i<len;i++){ int id=str[i]-'a'; p=p->next[id]; if(p==NULL) return 0; } return p->v; } int main() { char s[111]; while(gets(s)&&s[0]!='\0') update(s); while(scanf("%s",s)!=EOF) cout<<query(s)<<endl; }
true
5c4f1a3e6a2fac3ace2678a0f7dadb619cf829a9
C++
ACTIONFENIX/diploma
/utility.cpp
UTF-8
835
3.015625
3
[]
no_license
#include "utility.h" void saveMatrix(const Matrix &m, const std::string& fullname) { std::ofstream file(fullname); for (size_t i = 0; i < m.rows(); ++i) { for (size_t j = 0; j < m.columns(); ++j) { file << m[i][j] << " "; } file << std::endl; } file.close(); } bool isInteger(double i) { return i == double(int(i)); } double dateID(const date& src) { return src.Minute() + src.Hour() * 100 + src.Day() * 10000 + src.Month() * 1000000; } date restoreFromID(int id) { date dt; dt.setMonth(id / 1000000); id -= id / 1000000 * 1000000; dt.setDay(id / 10000); id -= id / 10000 * 10000; dt.setHour(id / 100); id -= id / 100 * 100; dt.setMinute(id); return dt; } template<typename... Args> Matrix fromMatrixx(Args... args) { }
true
972bc795b0c35a8968254622cdd80f691d0ad938
C++
mafemello/Lab-AdvancedAlgorithms
/[2nd WEEK]/ip.cpp
UTF-8
646
2.921875
3
[]
no_license
/* Advanced Algorithms Lab I Exercise 3 - IPs Maria Fernanda Lucio de Mello nUSP: 11320860 */ #include <iostream> #include <vector> #include <stdio.h> #include <utility> #include <string> #include <map> #include <algorithm> #include<queue> #include <assert.h> using namespace std; int main (void) { int servers = 0, commands = 0; cin >> servers >> commands; map <string,string> m; for (int i = 0; i < servers; i++) { string name, ips; cin >> name >> ips; ips += ';'; m[ips] = name; } for (int i = 0; i < commands; i++) { string com, ip; cin >> com >> ip; cout << com << " " << ip << " " << "#" << m[ip] << endl; } return 0; }
true
1700018e9a77e4bcaf8a69ec49f29d177cdf0b9e
C++
taejin0323/Algorithm_Study
/HackerRank/Implementation/12.drawingBook.cpp
UHC
766
3.25
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int solve(int n, int p) { int ans = 0; int front = p / 2; int back = (n / 2 - p / 2); if (front<back) ans = front; else ans = back; return ans; } /* ... ------------------------------------------------- int solve(int n, int p){ int answer = 0; if (p <= n / 2) { for (int i = 0; i <= n / 2; i += 2) { if (i == p || (i + 1) == p) { break; } answer++; } } else { for (int j = n; j >= n / 2; j -= 2) { if (j == p || (j - 1) == p) { // Ȧ ¦ 츦 ؾϴµ... break; } answer++; } } return answer; } */ int main(){ int n, p; cin >> n >> p; int result = solve(n, p); cout << result << endl; return 0; }
true
d635b37d0d9cc0fae4a49e0fe0184ac8fb5571ad
C++
nerooc/preoop_labs
/Lab07/MyString.h
UTF-8
921
3.5625
4
[ "MIT" ]
permissive
#pragma once #include <iostream> #include <cstring> class MyString//klasa MyString { public: MyString(const char* napis) //konstruktor { _napis = (char*)napis; } ~MyString() // "głośny" destruktor { std::cout << "- deleting " << this->_napis << std::endl; } void append(MyString&); //funkcja dodająca do napisu void replace(const MyString&); //funkcja wstawiająca napis na miejsce innego static void swap(MyString &str1, MyString &str2) { char* temp = str1._napis; str1._napis = str2._napis; str2._napis = temp; return; } //funkcja zamieniająca napisy miejscami char* str() const; //funkcja zwracająca napis private: char* _napis; //składnik klasy };
true
39d8299bf2982d69d6a4897ae54d7ab7df06ba33
C++
chiaminchuang/Leetcode
/Easy/496-Next Greater Element I/496.cpp
UTF-8
691
2.921875
3
[]
no_license
class Solution { public: vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) { int position[10000]; for(int i = 0; i < nums.size(); ++i) position[nums[i]] = i; vector<int> nextGreater; for(int i = 0; i < findNums.size(); ++i) { for(int j = position[findNums[i]]+1; j < nums.size() && nextGreater.size() != i+1; ++j) if(findNums[i] < nums[j]) nextGreater.push_back(nums[j]); if(nextGreater.size() != i+1) nextGreater.push_back(-1); } return nextGreater; } };
true
7f971824e867381f17c3b170ed75bc0f2bcd88c9
C++
Akanksha494/CPP
/May2021/LUCKY02.cpp
UTF-8
347
3.09375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int check(int n){ string s= to_string(n); for(auto i : s){ if(i=='3'||i=='7'){} else return 0; } return 1; } int main() { int n,t; cin >> t; while(t--){ cin >> n; if(check(n)==1) { cout << "LUCKY"<< endl; } else cout << "BETTER LUCK NEXT TIME" << endl; } return 0; }
true
9572f569d96015387e1db19cedb622365aad3789
C++
ths-rwth/carl
/src/carl-arith/ran/interval/Evaluation.h
UTF-8
13,203
2.515625
3
[ "MIT" ]
permissive
#pragma once #include <carl-arith/interval/Interval.h> #include <carl-arith/poly/umvpoly/functions/IntervalEvaluation.h> #include <carl-arith/interval/Evaluation.h> #include <carl-arith/constraint/BasicConstraint.h> #include <carl-arith/constraint/Simplification.h> #include "Ran.h" #include "helper/AlgebraicSubstitution.h" #include <boost/logic/tribool_io.hpp> #include <optional> #include <carl-arith/poly/ctxpoly/ContextPolynomial.h> namespace carl { /** * Evaluate the given polynomial with the given values for the variables. * Asserts that all variables of p have an assignment in m and that m has no additional assignments. * * Returns std::nullopt if some unassigned variables are still contained in p after plugging in m. * * @param p Polynomial to be evaluated * @param m Variable assignment * @return Evaluation result */ template<typename Number> std::optional<IntRepRealAlgebraicNumber<Number>> evaluate(MultivariatePolynomial<Number> p, const Assignment<IntRepRealAlgebraicNumber<Number>>& m, bool refine_model = true) { CARL_LOG_DEBUG("carl.ran.interval", "Evaluating " << p << " on " << m); CARL_LOG_TRACE("carl.ran.interval", "Substitute rationals"); for (const auto& [var, ran] : m) { if (!p.has(var)) continue; if (refine_model) { CARL_LOG_TRACE("carl.ran.interval", "Refine " << var << " = " << ran); static Number min_width = Number(1) / (Number(1048576)); // 1/2^20, taken from libpoly while (!ran.is_numeric() && ran.interval().diameter() > min_width) { ran.refine(); } } if (ran.is_numeric()) { CARL_LOG_TRACE("carl.ran.interval", "Substitute " << var << " = " << ran); substitute_inplace(p, var, MultivariatePolynomial<Number>(ran.value())); } } if (p.is_number()) { CARL_LOG_DEBUG("carl.ran.interval", "Returning " << p.constant_part()); return IntRepRealAlgebraicNumber<Number>(p.constant_part()); } CARL_LOG_TRACE("carl.ran.interval", "Remaing polynomial: " << p); CARL_LOG_TRACE("carl.ran.interval", "Create interval map"); std::map<Variable, Interval<Number>> var_to_interval; for (const auto& [var, ran] : m) { if (p.has(var)) { assert(!ran.is_numeric()); var_to_interval.emplace(var, ran.interval()); } } CARL_LOG_TRACE("carl.ran.interval", "Interval map: " << var_to_interval); assert(!var_to_interval.empty()); if (var_to_interval.size() == 1) { CARL_LOG_TRACE("carl.ran.interval", "Single interval"); auto poly = carl::to_univariate_polynomial(p); assert(poly.main_var() == var_to_interval.begin()->first); CARL_LOG_TRACE("carl.ran.interval", "Consider univariate poly " << poly); if (sgn(m.at(var_to_interval.begin()->first), poly) == Sign::ZERO) { CARL_LOG_DEBUG("carl.ran.interval", "Returning " << IntRepRealAlgebraicNumber<Number>()); return IntRepRealAlgebraicNumber<Number>(); } } CARL_LOG_TRACE("carl.ran.interval", "Interval evaluation"); Interval<Number> interval = carl::evaluate(p, var_to_interval); if (interval.is_point_interval()) { CARL_LOG_DEBUG("carl.ran.interval", "Interval is point interval " << interval); return IntRepRealAlgebraicNumber<Number>(interval.lower()); } CARL_LOG_TRACE("carl.ran.interval", "Compute result polynomial"); Variable v = fresh_real_variable(); std::vector<UnivariatePolynomial<MultivariatePolynomial<Number>>> algebraic_information; for (const auto& [var, ran] : m) { if (var_to_interval.find(var) == var_to_interval.end()) continue; assert(!ran.is_numeric()); algebraic_information.emplace_back(replace_main_variable(ran.polynomial_int(), var).template convert<MultivariatePolynomial<Number>>()); } // substitute RANs with low degrees first std::sort(algebraic_information.begin(), algebraic_information.end(), [](const auto& a, const auto& b){ return a.degree() > b.degree(); }); auto res = ran::interval::algebraic_substitution(UnivariatePolynomial<MultivariatePolynomial<Number>>(v, {MultivariatePolynomial<Number>(-p), MultivariatePolynomial<Number>(1)}), algebraic_information); if (!res) { return std::nullopt; } res = carl::squareFreePart(*res); // Note that res cannot be zero as v is a fresh variable in v-p. CARL_LOG_TRACE("carl.ran.interval", "res = " << *res); CARL_LOG_TRACE("carl.ran.interval", "var_to_interval = " << var_to_interval); CARL_LOG_TRACE("carl.ran.interval", "p = " << p); CARL_LOG_TRACE("carl.ran.interval", "-> " << interval); CARL_LOG_TRACE("carl.ran.interval", "Compute sturm sequence"); auto sturm_seq = sturm_sequence(*res); // the interval should include at least one root. CARL_LOG_TRACE("carl.ran.interval", "Refine intervals"); assert(!carl::is_zero(*res)); assert(carl::is_root_of(*res, interval.lower()) || carl::is_root_of(*res, interval.upper()) || count_real_roots(sturm_seq, interval) >= 1); while (!interval.is_point_interval() && (carl::is_root_of(*res, interval.lower()) || carl::is_root_of(*res, interval.upper()) || count_real_roots(sturm_seq, interval) != 1)) { CARL_LOG_TRACE("carl.ran.interval", "Refinement step"); // refine the result interval until it isolates exactly one real root of the result polynomial for (const auto& [var, ran] : m) { if (var_to_interval.find(var) == var_to_interval.end()) continue; ran.refine(); if (ran.is_numeric()) { substitute_inplace(p, var, MultivariatePolynomial<Number>(ran.value())); for (const auto& entry : m) { if (!p.has(entry.first)) var_to_interval.erase(entry.first); } } else { var_to_interval[var] = ran.interval(); } } CARL_LOG_TRACE("carl.ran.interval", "Interval evaluation"); interval = carl::evaluate(p, var_to_interval); } CARL_LOG_DEBUG("carl.ran.interval", "Result is " << *res << " " << interval); if (interval.is_point_interval()) { return IntRepRealAlgebraicNumber<Number>(interval.lower()); } else { return IntRepRealAlgebraicNumber<Number>(*res, interval); } } template<typename Number> boost::tribool evaluate(const BasicConstraint<MultivariatePolynomial<Number>>& c, const Assignment<IntRepRealAlgebraicNumber<Number>>& m, bool refine_model = true, bool use_root_bounds = true) { CARL_LOG_DEBUG("carl.ran.interval", "Evaluating " << c << " on " << m); if (!use_root_bounds) { CARL_LOG_DEBUG("carl.ran.interval", "Evaluate constraint by evaluating poly"); auto res = evaluate(c.lhs(), m); if (!res) return boost::indeterminate; else return evaluate(sgn(res), c.relation()); } else { MultivariatePolynomial<Number> p = c.lhs(); CARL_LOG_TRACE("carl.ran.interval", "p = " << p); for (const auto& [var, ran] : m) { if (!p.has(var)) continue; if (refine_model) { static Number min_width = Number(1) / (Number(1048576)); // 1/2^20, taken from libpoly while (!ran.is_numeric() && ran.interval().diameter() > min_width) { ran.refine(); } } if (ran.is_numeric()) { substitute_inplace(p, var, MultivariatePolynomial<Number>(ran.value())); CARL_LOG_TRACE("carl.ran.interval", "Substituting numeric value p["<<ran.value()<<"/"<<var<<"] = " << p); } } if (p.is_number()) { CARL_LOG_DEBUG("carl.ran.interval", "Left hand side is constant"); return carl::evaluate(p.constant_part(), c.relation()); } BasicConstraint<MultivariatePolynomial<Number>> constr = constraint::create_normalized_constraint(p, c.relation()); if (constr.is_consistent() != 2) { CARL_LOG_DEBUG("carl.ran.interval", "Constraint already evaluates to value"); return constr.is_consistent(); } p = constr.lhs(); CARL_LOG_TRACE("carl.ran.interval", "p = " << p << " (after simplification)"); std::map<Variable, Interval<Number>> var_to_interval; for (const auto& [var, ran] : m) { if (p.has(var)) { assert(!ran.is_numeric()); var_to_interval.emplace(var, ran.interval()); } } Interval<Number> interval = carl::evaluate(p, var_to_interval); { CARL_LOG_TRACE("carl.ran.interval", "Interval evaluation of " << p << " under " << var_to_interval << " results in " << interval); auto int_res = carl::evaluate(interval, constr.relation()); CARL_LOG_TRACE("carl.ran.interval", "Obtained " << interval << " " << constr.relation() << " 0 -> " << (indeterminate(int_res) ? -1 : (bool)int_res)); if (!indeterminate(int_res)) { CARL_LOG_DEBUG("carl.ran.interval", "Result obtained by interval evaluation"); return (bool)int_res; } } CARL_LOG_DEBUG("carl.ran.interval", "Evaluate constraint using resultants and root bounds"); assert(var_to_interval.size() > 0); if (var_to_interval.size() == 1) { CARL_LOG_TRACE("carl.ran.interval", "Single interval"); auto poly = carl::to_univariate_polynomial(p); assert(poly.main_var() == var_to_interval.begin()->first); CARL_LOG_TRACE("carl.ran.interval", "Consider univariate poly " << poly); if (sgn(m.at(var_to_interval.begin()->first), poly) == Sign::ZERO) { CARL_LOG_DEBUG("carl.ran.interval", "Got " << IntRepRealAlgebraicNumber<Number>()); return evaluate(Sign::ZERO, constr.relation()); } } // compute the result polynomial Variable v = fresh_real_variable(); std::vector<UnivariatePolynomial<MultivariatePolynomial<Number>>> algebraic_information; for (const auto& [var, ran] : m) { if (var_to_interval.find(var) == var_to_interval.end()) continue; assert(!ran.is_numeric()); algebraic_information.emplace_back(replace_main_variable(ran.polynomial_int(), var).template convert<MultivariatePolynomial<Number>>()); } // substitute RANs with low degrees first std::sort(algebraic_information.begin(), algebraic_information.end(), [](const auto& a, const auto& b){ return a.degree() > b.degree(); }); auto res = ran::interval::algebraic_substitution(UnivariatePolynomial<MultivariatePolynomial<Number>>(v, {MultivariatePolynomial<Number>(-p), MultivariatePolynomial<Number>(1)}), algebraic_information); // Note that res cannot be zero as v is a fresh variable in v-p. if (!res) { return boost::indeterminate; } CARL_LOG_DEBUG("carl.ran.interval", "res = " << *res); CARL_LOG_DEBUG("carl.ran.interval", "var_to_interval = " << var_to_interval); CARL_LOG_DEBUG("carl.ran.interval", "p = " << p); CARL_LOG_DEBUG("carl.ran.interval", "-> " << interval); // Let pos_lb a lower bound on the positive real roots and neg_ub an upper bound on the negative real roots // Then if the zero of res is in the interval (neg_ub,pos_lb), then it must be zero. // compute root bounds auto pos_lb = lagrangePositiveLowerBound(*res); CARL_LOG_TRACE("carl.ran.interval", "positive root lower bound: " << pos_lb); if (pos_lb == 0) { // no positive root exists CARL_LOG_DEBUG("carl.ran.interval", "p <= 0"); if (constr.relation() == Relation::GREATER) { return false; } else if (constr.relation() == Relation::LEQ) { return true; } } auto neg_ub = lagrangeNegativeUpperBound(*res); CARL_LOG_TRACE("carl.ran.interval", "negative root upper bound: " << neg_ub); if (neg_ub == 0) { // no negative root exists CARL_LOG_DEBUG("carl.ran.interval", "p >= 0"); if (constr.relation() == Relation::LESS) { return false; } else if (constr.relation() == Relation::GEQ) { return true; } } if (pos_lb == 0 && neg_ub == 0) { // no positive or negative zero exists CARL_LOG_DEBUG("carl.ran.interval", "p = 0"); return evaluate(Sign::ZERO, constr.relation()); } assert(!carl::is_zero(*res)); // refine the interval until it is either positive or negative or is contained in (neg_ub,pos_lb) CARL_LOG_DEBUG("carl.ran.interval", "Refine until interval is in (" << neg_ub << "," << pos_lb << ") or interval is positive or negative"); while (!((neg_ub < interval.lower() || neg_ub == 0) && (interval.upper() < pos_lb || pos_lb == 0))) { for (const auto& [var, ran] : m) { if (var_to_interval.find(var) == var_to_interval.end()) continue; ran.refine(); if (ran.is_numeric()) { substitute_inplace(p, var, MultivariatePolynomial<Number>(ran.value())); for (const auto& entry : m) { if (!p.has(entry.first)) var_to_interval.erase(entry.first); } } else { var_to_interval[var] = ran.interval(); } } interval = carl::evaluate(p, var_to_interval); auto int_res = carl::evaluate(interval, constr.relation()); if (!indeterminate(int_res)) { CARL_LOG_DEBUG("carl.ran.interval", "Got result"); return (bool)int_res; } } CARL_LOG_DEBUG("carl.ran.interval", "p = 0"); return evaluate(Sign::ZERO, constr.relation()); } } template<typename Coeff, typename Ordering, typename Policies> auto evaluate(const ContextPolynomial<Coeff, Ordering, Policies>& p, const Assignment<typename ContextPolynomial<Coeff, Ordering, Policies>::RootType>& a) { return evaluate(MultivariatePolynomial<Coeff, Ordering, Policies>(p.content()), a); } template<typename Coeff, typename Ordering, typename Policies> auto evaluate(const BasicConstraint<ContextPolynomial<Coeff, Ordering, Policies>>& p, const Assignment<typename ContextPolynomial<Coeff, Ordering, Policies>::RootType>& a) { return evaluate(BasicConstraint<MultivariatePolynomial<Coeff, Ordering, Policies>>(MultivariatePolynomial<Coeff, Ordering, Policies>(p.lhs().content()), p.relation()), a); } }
true
a654f5d9840f68e83d3e443552d1d5b255319c98
C++
bsella/fltk_Emergence
/src/gui/toolbox/toolbox.cpp
UTF-8
1,620
2.828125
3
[]
no_license
#include "toolbox.h" #include <FL/fl_draw.H> #include "toolbox_category.h" #include <cstring> std::list<Item*> Toolbox::toolbox_items; Toolbox::Toolbox(int x, int y, int w, int h):Graphics_View(x,y,w,h){ items= &toolbox_items; } Toolbox::~Toolbox(){} int Toolbox::content_height; void Toolbox::mouse_wheel_event(int, int dy){ static unsigned int step= 10; if(dy>0){ scroll_y+= step; if(scroll_y + h() > content_height) scroll_y= content_height - h(); }else if(dy<0){ scroll_y-= step; if(scroll_y < 0) scroll_y= 0; } redraw(); } void Toolbox::update_content_height(){ content_height= 0; for(auto* item : toolbox_items) content_height+= item->_h; } void Toolbox::add(Toolbox_Item* item){ toolbox_items.push_back(item); update_content_height(); } Toolbox_Category* Toolbox::add_category(const char* cat, const char* icon){ Toolbox_Category* category; for(Item* tb_item : toolbox_items){ category= dynamic_cast<Toolbox_Category*>(tb_item); if(category && strcmp(category->text,cat)==0) return category; } category= new Toolbox_Category(cat, icon); Toolbox::add(category); return category; } void Toolbox::remove(Toolbox_Item* item){ toolbox_items.remove(item); update_content_height(); } void Toolbox::draw(){ fl_draw_box(box(), x(), y(), w(), h(), color()); int y_offset = y(); for(const auto i : *items){ i->_w= w()-4; i->_x= x()+2; i->_y= y_offset+2 - scroll_y; y_offset+= i->_h; ((Toolbox_Item*)i)->draw(); } } void Toolbox::mouse_click_event(int x, int y, int button){ Graphics_View::mouse_click_event(x,y,button); update_content_height(); redraw(); }
true
4b0c7cd43ac7d51da885acd406c0bb5e699e0915
C++
AsmitaKakkar/C-
/calculator.cpp
UTF-8
1,583
3.703125
4
[]
no_license
//*******SIMPLE CALCULATOR*********** #include<iostream> #include<conio.h> using namespace std; void printmenu() { system("cls"); cout<<"1. addition"<<endl; cout<<"2. substraction"<<endl; cout<<"3. multiplication"<<endl; cout<<"4. division"<<endl; cout<<"5. modolu"<<endl; cout<<"6. exit"<<endl; } int main() { do { printmenu(); int choice,a,b,sum; cout<<"Enter your choice:"; cin>>choice; switch(choice) { case 1: { cout<<"Enter two numbers:"; cin>>a>>b; cout<<"sum="<<a+b<<endl; cout<<"Press any key to continue....."; getch(); break; } case 2: { cout<<"Enter two numbers:"; cin>>a>>b; int difference; cout<<"difference="<<a-b<<endl; cout<<"Press any key to continue......"; getch(); break; } case 3: { cout<<"Enter two numbers:"; cin>>a>>b; cout<<"result="<<a*b<<endl; cout<<"Press any key to continue...."; getch(); break; } case 4: { cout<<"Enter two numbers:"; cin>>a>>b; cout<<"result="<<a/b<<endl; cout<<"Press any key to continue....."; getch(); break; } case 5: { cout<<"Enter two numbers:"; cin>>a>>b; cout<<"result="<<a%b<<endl; cout<<"Press any key to continue......"; getch(); break; } case 6: { exit(1); } default: { cout<<"ERROR!!Wrong choice!!"<<endl; cout<<"Please select correct option!!"<<endl; cout<<"Press any key to continue....."; getch(); } } } while(1); return 0; }
true
1e56214e6a727ebfb2f39fd29394b3d677f4d2b6
C++
ShinraTensei/libVDFS
/examples/extract.cpp
UTF-8
710
2.921875
3
[]
no_license
#include "../VDFS.hpp" #include <iostream> #include <fstream> std::string getFilename(const char* name) { int i; for (i = 0; *(name + i) != ' '; ++i); return std::string(name, i); } int main(int argc, char* argv[]) { if (argc != 3) { std::cout << "Need a filename and index as arguments\n"; return 1; } vdfs::File file; const char* filename = argv[1]; if (!file.openFromFile(filename)) { return 1; } vdfs::word index = std::stoul(argv[2]); auto entry = file.getEntry(index); std::ifstream in(filename); in.seekg(entry.offset); char* buffer = new char[entry.size]; in.read(buffer, entry.size); std::ofstream out(getFilename(entry.name)); out.write(buffer, entry.size); }
true
7e851ea2e59291be3a843580f8e22e75e6b6ded8
C++
lindenis-org/lindenis-v833-package
/avs/libconfigutils/files/src/libs/utils/WavUtils.cpp
UTF-8
2,624
2.59375
3
[]
no_license
#include <stdio.h> #include <errno.h> #include <string.h> #include "utils/WavUtils.h" namespace AW { //for read int WavUtils::create(const std::string &file, const std::string& mode) { int ret = FileUtils::create(file, mode); if(ret < 0) return ret; ret = FileUtils::read((char*)&header, sizeof(header)); if(ret < 0) return ret; m_flag = Flag::READ; return 0; } //for write int WavUtils::create(const std::string &file, const std::string& mode, uint32_t bits_pre_sample, uint32_t num_channels, uint32_t sample_rate) { header.riff_id = ID_RIFF; header.riff_sz = 0; header.riff_fmt = ID_WAVE; header.fmt_id = ID_FMT; header.fmt_sz = 16; header.audio_format = FORMAT_PCM; header.num_channels = num_channels; header.sample_rate = sample_rate; header.bits_per_sample = bits_pre_sample; header.byte_rate = (header.bits_per_sample / 8) * header.num_channels * header.sample_rate; header.block_align = header.num_channels * (header.bits_per_sample / 8); header.data_id = ID_DATA; int ret = FileUtils::create(file, mode); if(ret < 0) return ret; FileUtils::write((char*)&header, sizeof(struct wav_header)); /* ret = FileUtils::seek(sizeof(struct wav_header), SEEK_SET); if(ret < 0){ printf("1seek fail: %s\n", strerror(errno)); } */ return 0; } void WavUtils::release() { if(m_flag == Flag::READ) { FileUtils::release(); return; } //long frames_read = FileUtils::tell() - sizeof(struct wav_header); //frames_read = frames_read/(header.num_channels * header.bits_per_sample/8); //printf("frame read is 0x%x\n", frames_read); header.data_sz = FileUtils::tell() - sizeof(struct wav_header); header.riff_sz = FileUtils::tell() - 8; char * p = (char*)&header; /* for(int i =0; i < sizeof(struct wav_header); i++){ if(i % 16 == 0) printf("\n"); if(i % 8 == 0) printf(" "); printf("%02x ", p[i]); } printf("\n"); */ int ret = FileUtils::seek(0L, SEEK_SET); if(ret < 0){ printf("2seek fail: %s\n", strerror(errno)); } FileUtils::write(p, sizeof(struct wav_header)); FileUtils::release(); } int WavUtils::write(const char *buf, int len) { return FileUtils::write(buf, len * header.num_channels * header.bits_per_sample/8); } int WavUtils::read(char *buf, int len) { int ret = FileUtils::read(buf, len * header.num_channels * header.bits_per_sample/8); if(ret <= 0) return ret; return ret/(header.num_channels * header.bits_per_sample/8); } }
true
2344f30ab2678c257ae35ee9ac4719156c2226b3
C++
nickyrasch/arduino_reference_programs
/reference_files/sweeping_distance_sensor/sweeping_distance_sensor.ino
UTF-8
2,300
3.359375
3
[]
no_license
// SWEEPING DISTANCE SENSOR #include <Servo.h> const int SERVO=9; // Servo on Pin 9 const int IR=0; // IR Distance Sensor on Analog pin 0 const int LED1=3; // LED Output 1 const int LED2=5; // LED Output 2 const int LED3=6; // LED Output 3 const int LED4=11; // LED Output 4 Servo myServo; // Servo object int dist1 = 0; // Quadrant 1 Distance int dist2 = 0; // Quadrant 2 Distance int dist3 = 0; // Quadrant 3 Distance int dist4 = 0; // Quadrant 4 Distance void setup() { myServo.attach(SERVO); // Attach the servo pinMode(LED1, OUTPUT); // Set LED to OUTPUT pinMode(LED2, OUTPUT); // Set LED to OUTPUT pinMode(LED3, OUTPUT); // Set LED to OUTPUT pinMode(LED4, OUTPUT); // Set LED to OUTPUT } void loop() { dist1 = readDistance(15); // Measure IR Distance at 15 degrees analogWrite(LED1, dist1); // Adjust LED brightness delay(300); // Delay before next measurement dist1 = readDistance(65); // Measure IR Distance at 65 degrees analogWrite(LED2, dist2); // Adjust LED brightness delay(300); // Delay before next measurement dist1 = readDistance(115); // Measure IR Distance at 115 degrees analogWrite(LED3, dist3); // Adjust LED brightness delay(300); // Delay before next measurement dist1 = readDistance(165); // Measure IR Distance at 165 degrees analogWrite(LED4, dist4); // Adjust LED brightness delay(300); // Delay before next measurement } int readDistance(int pos){ myServo.write(pos); // Move to given position delay(600); // Wait for servo to move int dist = analogRead(IR); // Read IR sensor dist = map(dist, 50, 500, 0, 255); // scale it to LED range dist = constrain(dist, 0, 255); // Constrain it return dist; // Return scaled distance }
true
f06fa950d8c3ee12f6b38dc775ed759646357e45
C++
martinogden/mer
/src/ast/elaborator/expr.cpp
UTF-8
2,406
2.6875
3
[ "Unlicense" ]
permissive
#include "ast/elaborator/expr.hpp" #include "type/canonicaliser.hpp" ExprElaborator::ExprElaborator(SymTab<TypePtr>& env, Map<FunTypePtr>& funTypes, Map<StructTypePtr>& structTypes) : env(env), funTypes(funTypes), structTypes(structTypes) {} ExprPtr ExprElaborator::get(ExprPtr& expr) { expr->accept(*this); return std::move(retval); } TypePtr ExprElaborator::get(TypePtr& type) { TypeCanonicaliser canon(env, structTypes); return canon.get(type); } void ExprElaborator::ret(ExprPtr expr) { retval = std::move(expr); } void ExprElaborator::visit(CallExpr& expr) { std::string id = expr.identifier; // FIXME: temporary hack std::string label = (id == "main") ? "__c0_main" : id; if (!funTypes.exists(id)) errors.add("attempt to call undeclared function: " + id, expr.token); std::vector<ExprPtr> args; for (auto& arg : expr.args) args.push_back( get(arg) ); ret( std::make_unique<CallExpr>(expr.token, label, std::move(args)) ); } void ExprElaborator::visit(TernaryExpr& expr) { ret( std::make_unique<TernaryExpr>(expr.token, get(expr.cond), get(expr.then), get(expr.otherwise)) ); } void ExprElaborator::visit(BinaryExpr& expr) { ret( std::make_unique<BinaryExpr>(expr.token, expr.op, get(expr.left), get(expr.right)) ); } void ExprElaborator::visit(UnaryExpr& unary) { ret( std::make_unique<UnaryExpr>(unary.token, unary.op, get(unary.expr)) ); } void ExprElaborator::visit(LiteralExpr& expr) { ret( std::make_unique<LiteralExpr>(expr.token, expr.type, expr.as) ); } void ExprElaborator::visit(IdExpr& expr) { ret( std::make_unique<IdExpr>(expr.token, expr.identifier) ); } void ExprElaborator::visit(SubscriptExpr& expr) { ret( std::make_unique<SubscriptExpr>(expr.token, get(expr.left), get(expr.right)) ); } void ExprElaborator::visit(ArrowExpr& expr) { ExprPtr e = std::make_unique<DerefExpr>(expr.expr->token, get(expr.expr)); ret( std::make_unique<DotExpr>(expr.token, std::move(e), expr.identifier) ); } void ExprElaborator::visit(DotExpr& expr) { ret( std::make_unique<DotExpr>(expr.token, get(expr.expr), expr.identifier) ); } void ExprElaborator::visit(DerefExpr& ptr) { ret( std::make_unique<DerefExpr>(ptr.token, get(ptr.expr)) ); } void ExprElaborator::visit(AllocExpr& alloc) { ExprPtr e = alloc.expr != nullptr ? get(alloc.expr) : nullptr; ret( std::make_unique<AllocExpr>(alloc.token, get(alloc.typeParam), std::move(e)) ); }
true
75fa2add268844993947fc119f1312a6e954aa31
C++
ms2295/Compiler_Project
/Program_4_Part_1_Lexical_Analyzer.cpp
UTF-8
8,546
2.953125
3
[]
no_license
/* Name: Manjot Singh Date: December 5, 2018 Class: CS280 Professor: Gerard Ryan Assignment: Program 4 Part 1 Lexical Analyzer File */ #include <iostream> #include <stdlib.h> #include <cctype> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <fstream> #include <map> #include <iterator> #include "tokens.h" Token getNextToken(istream *in, int *linenum) { enum LexState { BEGIN, INID, INCONST, INSTRING, ONE_EQUAL, ONE_EXCLAMATION, ONE_GREATER_THAN, ONE_LESS_THAN, ONE_AND, ONE_OR, COMMENT }; LexState lexstate = BEGIN; string lexeme; char ch; while(in->get(ch)) { if( ch == '\n' ) { (*linenum)++; } switch( lexstate ) { case BEGIN: if( isspace(ch) ) { continue; } lexeme += ch; if( isalpha(ch) ) { lexstate = INID; } else if( isdigit(ch) ) { lexstate = INCONST; } else if( ch == '"' ) { lexstate = INSTRING; } else if( ch == '+' ) { return Token(PLUS, lexeme, *linenum); } else if( ch == '-' ) { return Token(MINUS, lexeme, *linenum); } else if( ch == '*' ) { return Token(STAR, lexeme, *linenum); } else if( ch == '/' ) { return Token(SLASH, lexeme, *linenum); } else if( ch == '(' ) { return Token(LPAREN, lexeme, *linenum); } else if( ch == ')' ) { return Token(RPAREN, lexeme, *linenum); } else if( ch == ';' ) { return Token(SC, lexeme, *linenum); } else if( ch == '=' ) { lexstate = ONE_EQUAL; } else if( ch == '!' ) { lexstate = ONE_EXCLAMATION; } else if( ch == '>' ) { lexstate = ONE_GREATER_THAN; } else if( ch == '<' ) { lexstate = ONE_LESS_THAN; } else if( ch == '&' ) { lexstate = ONE_AND; } else if( ch == '|' ) { lexstate = ONE_OR; } else if( ch == '#' ) { lexeme.clear(); lexstate = COMMENT; } else { return Token(ERR, lexeme, *linenum); } break; case INID: if(lexeme == "print") { if (ch != '\n') { in->putback(ch); } return Token(PRINT, lexeme, *linenum); } else if(lexeme == "if") { if (ch != '\n') { in->putback(ch); } return Token(IF, lexeme, *linenum); } else if(lexeme == "then") { if (ch != '\n') { in->putback(ch); } return Token(THEN, lexeme, *linenum); } else if(lexeme == "true") { if (ch != '\n') { in->putback(ch); } return Token(TRUE, lexeme, *linenum); } else if(lexeme == "false") { if (ch != '\n') { in->putback(ch); } return Token(FALSE, lexeme, *linenum); } lexeme += ch; if( isalpha(ch) || isdigit(ch) ) { lexstate = INID; } else { if (ch != '\n') { in->putback(ch); } lexeme.pop_back(); return Token(IDENT, lexeme, *linenum); } break; case INCONST: lexeme += ch; if( isdigit(ch) ) { lexstate = INCONST; } else if ( isalpha(ch) ) { if (ch != '\n') { in->putback(ch); } return Token(ERR, lexeme, *linenum); } else { if (ch != '\n') { in->putback(ch); } lexeme.pop_back(); return Token(ICONST, lexeme, *linenum); } break; case INSTRING: if( ch == '"' ) { lexeme.erase(0,1); return Token(SCONST, lexeme, *linenum); } lexeme += ch; if( ch == '\n' ) { return Token(ERR, lexeme, *linenum); } else { lexstate = INSTRING; } break; case ONE_EQUAL: lexeme += ch; if( ch == '=' ) { return Token(EQ, lexeme, *linenum); } else { if (ch != '\n') { in->putback(ch); } lexeme.pop_back(); return Token(ASSIGN, lexeme, *linenum); } break; case ONE_EXCLAMATION: lexeme += ch; if( ch == '=' ) { return Token(NEQ, lexeme, *linenum); } else { if (ch != '\n') { in->putback(ch); } lexeme.pop_back(); return Token(ERR, lexeme, *linenum); } break; case ONE_GREATER_THAN: lexeme += ch; if( ch == '=' ) { return Token(GEQ, lexeme, *linenum); } else { if (ch != '\n') { in->putback(ch); } lexeme.pop_back(); return Token(GT, lexeme, *linenum); } break; case ONE_LESS_THAN: lexeme += ch; if( ch == '=' ) { return Token(LEQ, lexeme, *linenum); } else { if (ch != '\n') { in->putback(ch); } lexeme.pop_back(); return Token(LT, lexeme, *linenum); } break; case ONE_AND: lexeme += ch; if( ch == '&' ) { return Token(LOGICAND, lexeme, *linenum); } else { if (ch != '\n') { in->putback(ch); } lexeme.pop_back(); return Token(ERR, lexeme, *linenum); } break; case ONE_OR: lexeme += ch; if( ch == '|' ) { return Token(LOGICOR, lexeme, *linenum); } else { if (ch != '\n') { in->putback(ch); } lexeme.pop_back(); return Token(ERR, lexeme, *linenum); } break; case COMMENT: if( ch == '\n') { char nextChar = in->peek(); ch = nextChar; lexstate = BEGIN; } else { lexstate = COMMENT; } break; } } return Token(DONE, lexeme, *linenum); }
true
193cf216495b445c8a9a0b2cd3e1efe722b76e1f
C++
pfnet/intern-coding-tasks
/2017/ml/random_action.cc
UTF-8
1,027
3.0625
3
[]
no_license
#include <iostream> #include <vector> void get_observation(std::vector<double>& obs, bool& done) { std::string stat; std::cin >> stat; if (stat == "obs") { obs.resize(4); for (int i = 0; i < 4; ++i) std::cin >> obs[i]; done = false; } else if (stat == "done") { done = true; } } int main() { for (int episode = 1; episode <= 10; ++episode) { std::cerr << "###### Episode " << episode << " ######" << std::endl; std::cout << "r" << std::endl; std::vector<double> obs; bool done; get_observation(obs, done); std::cerr << "Initial observation:"; for (auto& x : obs) std::cerr << x << " "; std::cerr << std::endl; for (int step = 0; ; ++step) { int action = (rand() % 2) ? 1 : -1; std::cout << "s " << action << std::endl; get_observation(obs, done); std::cerr << "Step " << step << " :"; for (auto& x : obs) std::cerr << x << " "; std::cerr << std::endl; if (done) break; } } std::cout << "q" << std::endl; }
true
03683751d3ac861044e4ce694bed30eea41c9f55
C++
codenuri/CPP1
/SECTION1/04_VARIABLE2/string2.cpp
UTF-8
252
3.09375
3
[]
no_license
#include <iostream> #include <string> void foo( const char* s) { printf("foo : %s\n", s); } int main() { std::string s = "hello"; foo(s); // error foo((const char*)s); // error foo( s.c_str() ); // ok }
true
a669c8c263a53adc4f57e5f41f907df3daf8d394
C++
victoryckl/ctools
/mylib/IntSetBST.h
UTF-8
502
2.921875
3
[ "MIT" ]
permissive
class IntSetBST { public: IntSetBST(int maxlements, int maxval) { root = 0; n = 0; } ~IntSetBST(); int size() { return n; } void insert(int t) { root = rinsert(root, t); } void report(int * x) { v = x; vn = 0; traverse(root); } protected: private: int n, *v, vn; struct node { int val; node * left, * right; node(int i){val = i; left = right = 0;} }; node * root; node * rinsert(node * p, int t); void traverse(node * p); void DeleteNode(IntSetBST::node * p); };
true
5240aa99130c032b97106aa6f8ca08bc09e2f083
C++
magdalennaniewinska/Cybermysz
/zcpp/mainwindow.cpp
UTF-8
1,519
2.640625
3
[]
no_license
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> #include <QElapsedTimer> QElapsedTimer maze_timer; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); timer = new QTimer(); connect(timer, SIGNAL(timeout()), this, SLOT(timer_func())); scene = new QGraphicsScene(this); ui->graphicsView->setScene(scene); QBrush redBrush(Qt::red); QPen blashpen(Qt::black); blashpen.setWidth(6); mouse = scene->addRect(10,10,100,100,blashpen, redBrush); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_maze_choosing_activated(const QString &arg1) { ui->instructions->setText("Ok great! Now is time to choose your mouse."); } void MainWindow::on_mouse_choosing_activated(const QString &arg1) { ui->instructions->setText("Now we are ready to try to go through the maze. Keep fingers crossed, click start button and watch how your mouse are doing ;)"); } void MainWindow::on_start_pushButton_clicked() { maze_timer.start(); timer->start(10); } void MainWindow::timer_func() { int time_past = maze_timer.elapsed(); QString time_past_text = QString("%1:%2:%3").arg( time_past / 60000 , 2, 10, QChar('0')) .arg((time_past % 60000) / 1000, 2, 10, QChar('0')) .arg(((time_past % 60000) % 1000) /10, 2, 10, QChar('0')); ui->stopwatch->setText(time_past_text); }
true
cad517ef88c164bfd196608db73178d0e6c4f69e
C++
GOAT095/cpp
/m08/ex01/main.cpp
UTF-8
540
2.625
3
[]
no_license
#include "span.hpp" int main() { Span sp = Span(5); sp.addNumber(5); sp.addNumber(3); sp.addNumber(17); sp.addNumber(9); sp.addNumber(11); // sp.addNumber(80); //for error test try { std::cout << sp.shortestSpan() << std::endl; } catch(const std::exception & e) { std::cerr << "this bitch empty\n"; } try { std::cout << sp.longestSpan() << std::endl; } catch(const std::exception & e) { std::cerr << "this bitch empty\n"; } }
true
e6c833f1d92725b001979fe0afa4e32143f2bf28
C++
Robin-P/arcade
/lib/opengl/srcs/class/menu.cpp
UTF-8
2,145
2.703125
3
[]
no_license
// // EPITECH PROJECT, 2018 // arcade // File description: // LIB SFML MENU // #include "opengl.hpp" void u_opengl::initMenu(std::map<std::string, void *> &game_lib_name, std::map<std::string, void *> &graphics_lib_name) { this->GraphicsPathName = ""; this->GamePathName = ""; this->createButtons(game_lib_name, this->buttons_games, GAMES_LIB_PATH, GAMES_LIB_EXT, sf::Vector2f(this->width - 300, 300)); this->createButtons(graphics_lib_name, this->buttons_graphics, GRAPHICS_LIB_PATH, GRAPHICS_LIB_EXT, sf::Vector2f(100, 300)); this->createBackgrounds(game_lib_name); this->createScoreboard(game_lib_name); } arcade::menuLeave u_opengl::leaveMenu() { if (!this->GamePathName.empty()) { this->cleanRessources(); if (!GamePathName.empty()) { this->createSound("start", "./audio/sound/" + my_substr(this->GamePathName, GAMES_LIB_PATH, GAMES_LIB_EXT) + "/start.wav"); this->playSound("start"); } return {arcade::menuLeave::GAME, this->GamePathName}; } else if (!this->GraphicsPathName.empty()) return {arcade::menuLeave::GRAPHIC, this->GraphicsPathName}; return {arcade::menuLeave::EXIT, std::string()}; } arcade::menuLeave u_opengl::menu(std::map<std::string, void *> &game_lib_name, std::map<std::string, void *> &graphics_lib_name) { sf::Event event{}; this->state = arcade::MENU; this->initMenu(game_lib_name, graphics_lib_name); this->createSound("click", SOUND_PATH + std::string("/click.ogg")); while (this->state == arcade::MENU && this->window.isOpen() && this->GamePathName.empty() && this->GraphicsPathName.empty()) { this->clearWindow(); this->mouseAction(); std::unique_ptr<sf::Sprite> &background = this->backgrounds[this->indexBackgrounds]; this->window.draw(*background); this->drawMenuText(); this->displayPrompt(); this->displayScoreboard("ARIAL", this->indexBackgrounds, 40, sf::Color::Black, sf::Color::White, sf::Vector2f(this->width / 2 - 125, this->height / 2)); this->displayWindow(); while (this->window.pollEvent(event)) this->opengl_event(event); } this->clearWindow(); return this->leaveMenu(); }
true
054d5cca2ae081a7cb30dd0146e7fa39f4a87b9c
C++
TresSheep/sigma
/src/Frontend/AST/Union.h
UTF-8
521
2.546875
3
[]
no_license
#pragma once #include <string> #include "Expression.h" namespace Frontend::AST { class Union : public Expression { public: Union(std::string id, std::vector<std::unique_ptr<Expression>> body); ~Union(); std::unique_ptr<Backend::CodeGen::IR::Value> GenerateCode(std::shared_ptr<Backend::CodeGen::IR::IRContext> context, Backend::CodeGen::IR::IRGenerator& irGenerator) override; private: std::string m_id; std::vector<std::unique_ptr<Expression>> m_body; }; }
true
8958c243d4d1fd41360bd07dac262c1b6e86c314
C++
xunilrj/sandbox
/books/3D Math Primer for Graphics and Game Development/include/autocheck/classifier.hpp
UTF-8
3,051
3.046875
3
[ "Apache-2.0" ]
permissive
#ifndef AUTOCHECK_CLASSIFIER_HPP #define AUTOCHECK_CLASSIFIER_HPP #include <unordered_map> #include <sstream> #include "function.hpp" #include "apply.hpp" namespace autocheck { template <typename... Args> class classifier { public: typedef typename predicate<Args...>::type pred_t; typedef std::function<std::string (const Args&...)> tagger_t; private: pred_t is_trivial; size_t num_trivial; std::vector<tagger_t> taggers; std::unordered_map<std::string, size_t> tag_cloud; public: classifier() : is_trivial(never()), num_trivial(0), taggers(), tag_cloud() {} classifier& trivial(const pred_t& pred) { is_trivial = pred; return *this; } classifier& collect(const tagger_t& tagger) { taggers.push_back(tagger); return *this; } template < typename Func, typename Enable = typename std::enable_if< !std::is_convertible< typename std::result_of<Func(const Args&...)>::type, std::string >::value >::type > classifier& collect(const Func& func) { taggers.push_back( [=] (const Args&... args) -> std::string { std::ostringstream ss; ss << func(args...); return ss.str(); }); return *this; } classifier& classify(const pred_t& pred, const std::string& label) { taggers.push_back( [=] (const Args&... args) { return (pred(args...)) ? label : ""; }); return *this; } void check(const std::tuple<Args...>& args) { if (apply<pred_t>(is_trivial, args)) ++num_trivial; std::string tags; for (tagger_t& tagger : taggers) { std::string tag = apply<tagger_t>(tagger, args); if (tag.empty()) continue; if (!tags.empty()) tags += ", "; tags += tag; } if (!tags.empty()) ++tag_cloud[tags]; } size_t trivial() const { return num_trivial; } distribution distro() const { return distribution(tag_cloud.begin(), tag_cloud.end()); } }; template <typename Classifier> Classifier&& trivial( const typename Classifier::pred_t& pred, Classifier&& cls) { cls.trivial(pred); return std::forward<Classifier>(cls); } template <typename Classifier> Classifier&& collect(const typename Classifier::tagger_t& tagger, Classifier&& cls) { cls.collect(tagger); return std::forward<Classifier>(cls); } /* Missing lexical casting collect combinator, but no need until the * combinators can be used. */ template <typename Classifier> Classifier&& classify(const typename Classifier::pred_t& pred, const std::string& label, Classifier&& cls) { cls.classify(pred, label); return std::forward<Classifier>(cls); } } #endif
true
3ac788c3342300545bbabafc5aaa6898b34ce800
C++
linjinze999/BUPTSSE2013
/Lab/大三(上)/算法分析与设计_2013/分治法/DivideAndConquer/DivideAndConquer/Maximum.cpp
GB18030
992
2.71875
3
[]
no_license
#include<iostream> #include<time.h> using namespace std; int Maximun(int data[], int length, int& left, int& right)//Ӵ { int i, cur_left, cur_right; int cur_max, max; cur_max = max = left = right = cur_left = cur_right = 0; for(i = 0; i < length; ++i) { cur_max += data[i]; if(cur_max > 0) { cur_right = i; if(max < cur_max) { max = cur_max; left = cur_left; right = cur_right; } } else { cur_max = 0; cur_left = cur_right = i + 1; } } return max; }; void setString(int data[],int data_length)//ɴ { srand((int)time(0)); int r=rand()%100; int t = rand()%67; for(int i=0;i<data_length;i++) { if(t>33) data[i] = 0-r; else data[i]=r; if(r==0) r=1; r=(r*157)%100; if(t==0) t=1; t=(t*143)%67; } };
true
a217a7beb50bc9ac07f39ae5a92a92dd6569e44b
C++
leeeyupeng/leeeyupeng.github.io
/project/algorithm/hdu/src/2112.shortestpath_2.cpp
UTF-8
2,251
2.59375
3
[]
no_license
#include"hdu.h" #define CHARNUMS 256 #define VERTICEMAX 152 #define MAXLENGTH 32 #define TIMEMAX 101 class Solution{ public: int getshotestpath(vector<vector<int>>& matrix,int start,int end){ auto cmp = [](pair<int,int>& a,pair<int,int>& b){ if(a.second == b.second){ return a.first > b.first; } return a.second > b.second; }; priority_queue<pair<int,int>,vector<pair<int,int>>,decltype(cmp)> pq(cmp); pq.push({start,0}); vector<char> visit(VERTICEMAX,0); pair<int,int> top; while(!pq.empty()){ top = pq.top(); pq.pop(); visit[top.first] = 1; if(top.first == end){ return top.second; } for(int i = 0; i < VERTICEMAX; i ++){ if(visit[i] == 0 && matrix[top.first][i]!=INT_MAX) { pq.push({i,top.second + matrix[top.first][i]}); } } } return -1; } }; // int main() // { // int n; // while(scanf("%d",&n)!=EOF){ // if(n==-1){break;} // Solution solution; // int cnt = 0; // map<string,int> map; // string start,end; // cin>>start>>end; // if(map.find(start) == map.end()){map.insert({start,cnt++});} // if(map.find(end) == map.end()){map.insert({end,cnt++});} // int startid = map[start]; // int endid = map[end]; // vector<vector<int>> matrix(VERTICEMAX,vector<int>(VERTICEMAX,INT_MAX)); // int t; // int sid; // int eid; // for(int i = 0; i < n; i ++){ // string s,e; // cin>>s>>e>>t; // if(map.find(s) == map.end()){map.insert({s,cnt++});} // if(map.find(e) == map.end()){map.insert({e,cnt++});} // sid = map[s]; // eid = map[e]; // matrix[sid][eid] = min(matrix[sid][eid],t); // matrix[eid][sid] = matrix[sid][eid]; // } // int ret = solution.getshotestpath(matrix,startid,endid); // printf("%d\n",ret); // } // return 0; // }
true
aeb6ecee6663a0a5f224bec502b6ee11a9a695b5
C++
DarrellWulff/ElementEngine
/ElementEngine/src/Math/Quaternion.cpp
UTF-8
2,681
3.484375
3
[ "MIT" ]
permissive
#include "Quaternion.h" #include <cmath> #include "MathFunctions.h" #include "Vector3.h" Quaternion::Quaternion(float thetaAngle, float xVal, float yVal, float zVal) { float halfTheta = thetaAngle * 0.5f; double sinFactor = sin(halfTheta); w = (float) cos(sinFactor); x = (float) sinFactor * xVal; y = (float) sinFactor * yVal; z = (float) sinFactor * zVal; float axisMag = std::sqrt(w * w + x * x + y * y + z * z); x = x / axisMag; y = y / axisMag; z = z / axisMag; } void Quaternion::set(float wVal, float xVal, float yVal, float zVal) { w = wVal; x = xVal; y = yVal; z = zVal; } void Quaternion::set(Quaternion quatVal) { w = quatVal.w; x = quatVal.x; y = quatVal.y; z = quatVal.z; } void Quaternion::operator=(Quaternion const& rhs) { w = rhs.w; x = rhs.x; y = rhs.y; z = rhs.z; } Quaternion Quaternion::operator*(Quaternion const &q2) { float newX = x * q2.w + y * q2.z - z * q2.y + w * q2.x; float newY = -x * q2.z + y * q2.w + z * q2.x + w * q2.y; float newZ = x * q2.y - y * q2.x + z * q2.w + w * q2.z; float newW = -x * q2.x - y * q2.y - z * q2.z + w * q2.w; this->renormalize(); return Quaternion(newW, newX, newY, newZ); } float Quaternion::magnitude() { return std::sqrt(w * w + x * x + y * y + z * z); } Quaternion Quaternion::inverse() { return Quaternion(-w, -x, -y, -z); } void Quaternion::renormalize() { float angleValue = std::sqrt(1 - w * w); Vector3 vectorComp = Vector3::fromQuaternion(*this).normalize(); x = vectorComp.x; y = vectorComp.y; z = vectorComp.z; } Quaternion Quaternion::applyQuatRotation(Quaternion quatRotation) { Quaternion rotatedQuat = this->inverse() * quatRotation * (*this); return rotatedQuat; } Quaternion Quaternion::applyLocalQuatRotation(Quaternion quatRotation) { Quaternion localQuatRot = this->applyQuatRotation(quatRotation); localQuatRot = *this * localQuatRot; return localQuatRot; } Quaternion Quaternion::quaternionSLERP(Quaternion toQuat, float t) { Vector3 fromVec = Vector3::fromQuaternion(*this).normalize(); Vector3 toVec = Vector3::fromQuaternion(toQuat).normalize(); float dotBetween = fromVec.dot(toVec); if (dotBetween > SLERP_DOT_THRESHOLD) { Quaternion slerpResult = Quaternion::fromVector((fromVec + (toVec - fromVec) * t)); return slerpResult; } dotBetween = MathFunctions::clamp(dotBetween, -1, 1); float angleBetween = std::acos(dotBetween); float theta = angleBetween * t; Vector3 basisVector = (toVec - fromVec * dotBetween).normalize(); return Quaternion::fromVector(fromVec * cos(theta) + toVec * sin(theta)); } Quaternion Quaternion::fromVector(Vector3 fromVec) { return Quaternion(0, fromVec.x, fromVec.y, fromVec.z); }
true
f10e7bca5bdcd8bfb14af0bf54435f1a1d7c5569
C++
yekm/bench
/tasks/vector_length_test/vec_algs.hpp
UTF-8
12,370
2.875
3
[ "MIT" ]
permissive
#ifndef VEC_ALGS_H #define VEC_ALGS_H #include "algorithm.hpp" #include "vec_task.hpp" #include "mpl.hpp" #include <algorithm> #include "utils/dbg.hpp" #include "bexception.hpp" class vec_template : public Algorithm { public: vec_template() : Algorithm("template unrolling") {} private: template <int N> inline void switcher(int v, const VecTask::g_type::container_type &d, std::vector<float> & l) { if (v == N) count<N>(&d[0], d.size()/N, l); else switcher<N/2>(v, d, l); } template <int N> void count(const float * v, std::size_t c, std::vector<float> & l) { D() << "count<" << N << ">"; for (std::size_t i = 0; i < c; i++) { l.push_back(mpl::vlen<N>::value(v+i*N)); } } virtual void do_run(TaskData & td, std::unique_ptr<AResult> & r) override { const VecTask::g_type::container_type &d = static_cast<VecTask::g_type&>(td).get_const(); std::unique_ptr<VecResult> res(new VecResult()); res->lengths.reserve(VecTask::num_vectors); D() << "vector: " << d; switcher<VecTask::max_vec_len>(td.get_n()/VecTask::num_vectors, d, res->lengths); D() << "lengths: " << res->lengths; r->set_custom_result(std::move(res)); } }; template <> inline void vec_template::switcher<1>(int, const VecTask::g_type::container_type &, std::vector<float> &) { throw BException("unsupported vector length " + get_name()); } class vec_loop : public Algorithm { public: vec_loop() : Algorithm("loop unrolling") {} private: template <int N> inline void switcher(int v, const VecTask::g_type::container_type &d, std::vector<float> & l) { if (v == N) count<N>(&d[0], d.size()/N, l); else switcher<N/2>(v, d, l); } template <int N> void count(const float * v, std::size_t c, std::vector<float> & l) { for (std::size_t i = 0; i < c; i++) { float sum = 0; for (int j = 0; j < N; j++) sum += v[i*N+j] * v[i*N+j]; l.push_back(sqrt(sum)); } } virtual void do_run(TaskData & td, std::unique_ptr<AResult> & r) override { const VecTask::g_type::container_type &d = static_cast<VecTask::g_type&>(td).get_const(); std::unique_ptr<VecResult> res(new VecResult()); res->lengths.reserve(VecTask::num_vectors); D() << "vector: " << d; switcher<VecTask::max_vec_len>(td.get_n()/VecTask::num_vectors, d, res->lengths); D() << "lengths: " << res->lengths; r->set_custom_result(std::move(res)); } }; template <> inline void vec_loop::switcher<1>(int, const VecTask::g_type::container_type &, std::vector<float> &) { throw BException("unsupported vector length " + get_name()); } class vec_handmade : public Algorithm { public: vec_handmade() : Algorithm("handmade unrolling") {} private: template <int N> inline void switcher(int v, const VecTask::g_type::container_type &d, std::vector<float> & l) { if (v == N) count<N>(&d[0], d.size()/N, l); else switcher<N/2>(v, d, l); } template <int N> void count(const float *, std::size_t, std::vector<float> &) { throw BException("unsupported vector length" + get_name()); } virtual void do_run(TaskData & td, std::unique_ptr<AResult> & r) override { const VecTask::g_type::container_type &d = static_cast<VecTask::g_type&>(td).get_const(); std::unique_ptr<VecResult> res(new VecResult()); res->lengths.reserve(VecTask::num_vectors); D() << "vector: " << d; switcher<VecTask::max_vec_len>(td.get_n()/VecTask::num_vectors, d, res->lengths); D() << "lengths: " << res->lengths; r->set_custom_result(std::move(res)); } }; template <> inline void vec_handmade::switcher<1>(int, const VecTask::g_type::container_type &, std::vector<float> &) { throw BException("unsupported vector length" + get_name()); } template<> void vec_handmade::count<2>(const float * v, std::size_t c, std::vector<float> & l) { constexpr int N = 2; for (std::size_t i = 0; i < c; i++) { float sum = v[i*N+0]*v[i*N+0] + v[i*N+1]*v[i*N+1]; l.push_back(sqrt(sum)); } } template<> void vec_handmade::count<4>(const float * v, std::size_t c, std::vector<float> & l) { constexpr int N = 4; for (std::size_t i = 0; i < c; i++) { float sum = v[i*N+0]*v[i*N+0] + v[i*N+1]*v[i*N+1] + v[i*N+2]*v[i*N+2] + v[i*N+3]*v[i*N+3]; l.push_back(sqrt(sum)); } } template<> void vec_handmade::count<8>(const float * v, std::size_t c, std::vector<float> & l) { constexpr int N = 8; for (std::size_t i = 0; i < c; i++) { float sum = v[i*N+0]*v[i*N+0] + v[i*N+1]*v[i*N+1] + v[i*N+2]*v[i*N+2] + v[i*N+3]*v[i*N+3] + v[i*N+4]*v[i*N+4] + v[i*N+5]*v[i*N+5] + v[i*N+6]*v[i*N+6] + v[i*N+7]*v[i*N+7] ; l.push_back(sqrt(sum)); } } template<> void vec_handmade::count<16>(const float * v, std::size_t c, std::vector<float> & l) { constexpr int N = 16; for (std::size_t i = 0; i < c; i++) { float sum = v[i*N+0]*v[i*N+0] + v[i*N+1]*v[i*N+1] + v[i*N+2]*v[i*N+2] + v[i*N+3]*v[i*N+3] + v[i*N+4]*v[i*N+4] + v[i*N+5]*v[i*N+5] + v[i*N+6]*v[i*N+6] + v[i*N+7]*v[i*N+7] + v[i*N+ 8]*v[i*N+ 8] + v[i*N+ 9]*v[i*N+ 9] + v[i*N+10]*v[i*N+10] + v[i*N+11]*v[i*N+11] + v[i*N+12]*v[i*N+12] + v[i*N+13]*v[i*N+13] + v[i*N+14]*v[i*N+14] + v[i*N+15]*v[i*N+15] ; l.push_back(sqrt(sum)); } } template<> void vec_handmade::count<32>(const float * v, std::size_t c, std::vector<float> & l) { constexpr int N = 32; for (std::size_t i = 0; i < c; i++) { float sum = v[i*N+0]*v[i*N+0] + v[i*N+1]*v[i*N+1] + v[i*N+2]*v[i*N+2] + v[i*N+3]*v[i*N+3] + v[i*N+4]*v[i*N+4] + v[i*N+5]*v[i*N+5] + v[i*N+6]*v[i*N+6] + v[i*N+7]*v[i*N+7] + v[i*N+ 8]*v[i*N+ 8] + v[i*N+ 9]*v[i*N+ 9] + v[i*N+10]*v[i*N+10] + v[i*N+11]*v[i*N+11] + v[i*N+12]*v[i*N+12] + v[i*N+13]*v[i*N+13] + v[i*N+14]*v[i*N+14] + v[i*N+15]*v[i*N+15] + v[i*N+16]*v[i*N+16] + v[i*N+17]*v[i*N+17] + v[i*N+18]*v[i*N+18] + v[i*N+19]*v[i*N+19] + v[i*N+20]*v[i*N+20] + v[i*N+21]*v[i*N+21] + v[i*N+22]*v[i*N+22] + v[i*N+23]*v[i*N+23] + v[i*N+24]*v[i*N+24] + v[i*N+25]*v[i*N+25] + v[i*N+26]*v[i*N+26] + v[i*N+27]*v[i*N+27] + v[i*N+28]*v[i*N+28] + v[i*N+29]*v[i*N+29] + v[i*N+30]*v[i*N+30] + v[i*N+31]*v[i*N+31] ; l.push_back(sqrt(sum)); } } template<> void vec_handmade::count<64>(const float * v, std::size_t c, std::vector<float> & l) { constexpr int N = 64; for (std::size_t i = 0; i < c; i++) { float sum = v[i*N+0]*v[i*N+0] + v[i*N+1]*v[i*N+1] + v[i*N+2]*v[i*N+2] + v[i*N+3]*v[i*N+3] + v[i*N+4]*v[i*N+4] + v[i*N+5]*v[i*N+5] + v[i*N+6]*v[i*N+6] + v[i*N+7]*v[i*N+7] + v[i*N+8]*v[i*N+8] + v[i*N+9]*v[i*N+9] + v[i*N+10]*v[i*N+10] + v[i*N+11]*v[i*N+11] + v[i*N+12]*v[i*N+12] + v[i*N+13]*v[i*N+13] + v[i*N+14]*v[i*N+14] + v[i*N+15]*v[i*N+15] + v[i*N+16]*v[i*N+16] + v[i*N+17]*v[i*N+17] + v[i*N+18]*v[i*N+18] + v[i*N+19]*v[i*N+19] + v[i*N+20]*v[i*N+20] + v[i*N+21]*v[i*N+21] + v[i*N+22]*v[i*N+22] + v[i*N+23]*v[i*N+23] + v[i*N+24]*v[i*N+24] + v[i*N+25]*v[i*N+25] + v[i*N+26]*v[i*N+26] + v[i*N+27]*v[i*N+27] + v[i*N+28]*v[i*N+28] + v[i*N+29]*v[i*N+29] + v[i*N+30]*v[i*N+30] + v[i*N+31]*v[i*N+31] + v[i*N+32]*v[i*N+32] + v[i*N+33]*v[i*N+33] + v[i*N+34]*v[i*N+34] + v[i*N+35]*v[i*N+35] + v[i*N+36]*v[i*N+36] + v[i*N+37]*v[i*N+37] + v[i*N+38]*v[i*N+38] + v[i*N+39]*v[i*N+39] + v[i*N+40]*v[i*N+40] + v[i*N+41]*v[i*N+41] + v[i*N+42]*v[i*N+42] + v[i*N+43]*v[i*N+43] + v[i*N+44]*v[i*N+44] + v[i*N+45]*v[i*N+45] + v[i*N+46]*v[i*N+46] + v[i*N+47]*v[i*N+47] + v[i*N+48]*v[i*N+48] + v[i*N+49]*v[i*N+49] + v[i*N+50]*v[i*N+50] + v[i*N+51]*v[i*N+51] + v[i*N+52]*v[i*N+52] + v[i*N+53]*v[i*N+53] + v[i*N+54]*v[i*N+54] + v[i*N+55]*v[i*N+55] + v[i*N+56]*v[i*N+56] + v[i*N+57]*v[i*N+57] + v[i*N+58]*v[i*N+58] + v[i*N+59]*v[i*N+59] + v[i*N+60]*v[i*N+60] + v[i*N+61]*v[i*N+61] + v[i*N+62]*v[i*N+62] + v[i*N+63]*v[i*N+63] ; l.push_back(sqrt(sum)); } } template<> void vec_handmade::count<128>(const float * v, std::size_t c, std::vector<float> & l) { constexpr int N = 128; for (std::size_t i = 0; i < c; i++) { float sum = v[i*N+0]*v[i*N+0] + v[i*N+1]*v[i*N+1] + v[i*N+2]*v[i*N+2] + v[i*N+3]*v[i*N+3] + v[i*N+4]*v[i*N+4] + v[i*N+5]*v[i*N+5] + v[i*N+6]*v[i*N+6] + v[i*N+7]*v[i*N+7] + v[i*N+8]*v[i*N+8] + v[i*N+9]*v[i*N+9] + v[i*N+10]*v[i*N+10] + v[i*N+11]*v[i*N+11] + v[i*N+12]*v[i*N+12] + v[i*N+13]*v[i*N+13] + v[i*N+14]*v[i*N+14] + v[i*N+15]*v[i*N+15] + v[i*N+16]*v[i*N+16] + v[i*N+17]*v[i*N+17] + v[i*N+18]*v[i*N+18] + v[i*N+19]*v[i*N+19] + v[i*N+20]*v[i*N+20] + v[i*N+21]*v[i*N+21] + v[i*N+22]*v[i*N+22] + v[i*N+23]*v[i*N+23] + v[i*N+24]*v[i*N+24] + v[i*N+25]*v[i*N+25] + v[i*N+26]*v[i*N+26] + v[i*N+27]*v[i*N+27] + v[i*N+28]*v[i*N+28] + v[i*N+29]*v[i*N+29] + v[i*N+30]*v[i*N+30] + v[i*N+31]*v[i*N+31] + v[i*N+32]*v[i*N+32] + v[i*N+33]*v[i*N+33] + v[i*N+34]*v[i*N+34] + v[i*N+35]*v[i*N+35] + v[i*N+36]*v[i*N+36] + v[i*N+37]*v[i*N+37] + v[i*N+38]*v[i*N+38] + v[i*N+39]*v[i*N+39] + v[i*N+40]*v[i*N+40] + v[i*N+41]*v[i*N+41] + v[i*N+42]*v[i*N+42] + v[i*N+43]*v[i*N+43] + v[i*N+44]*v[i*N+44] + v[i*N+45]*v[i*N+45] + v[i*N+46]*v[i*N+46] + v[i*N+47]*v[i*N+47] + v[i*N+48]*v[i*N+48] + v[i*N+49]*v[i*N+49] + v[i*N+50]*v[i*N+50] + v[i*N+51]*v[i*N+51] + v[i*N+52]*v[i*N+52] + v[i*N+53]*v[i*N+53] + v[i*N+54]*v[i*N+54] + v[i*N+55]*v[i*N+55] + v[i*N+56]*v[i*N+56] + v[i*N+57]*v[i*N+57] + v[i*N+58]*v[i*N+58] + v[i*N+59]*v[i*N+59] + v[i*N+60]*v[i*N+60] + v[i*N+61]*v[i*N+61] + v[i*N+62]*v[i*N+62] + v[i*N+63]*v[i*N+63] + v[i*N+64]*v[i*N+64] + v[i*N+65]*v[i*N+65] + v[i*N+66]*v[i*N+66] + v[i*N+67]*v[i*N+67] + v[i*N+68]*v[i*N+68] + v[i*N+69]*v[i*N+69] + v[i*N+70]*v[i*N+70] + v[i*N+71]*v[i*N+71] + v[i*N+72]*v[i*N+72] + v[i*N+73]*v[i*N+73] + v[i*N+74]*v[i*N+74] + v[i*N+75]*v[i*N+75] + v[i*N+76]*v[i*N+76] + v[i*N+77]*v[i*N+77] + v[i*N+78]*v[i*N+78] + v[i*N+79]*v[i*N+79] + v[i*N+80]*v[i*N+80] + v[i*N+81]*v[i*N+81] + v[i*N+82]*v[i*N+82] + v[i*N+83]*v[i*N+83] + v[i*N+84]*v[i*N+84] + v[i*N+85]*v[i*N+85] + v[i*N+86]*v[i*N+86] + v[i*N+87]*v[i*N+87] + v[i*N+88]*v[i*N+88] + v[i*N+89]*v[i*N+89] + v[i*N+90]*v[i*N+90] + v[i*N+91]*v[i*N+91] + v[i*N+92]*v[i*N+92] + v[i*N+93]*v[i*N+93] + v[i*N+94]*v[i*N+94] + v[i*N+95]*v[i*N+95] + v[i*N+96]*v[i*N+96] + v[i*N+97]*v[i*N+97] + v[i*N+98]*v[i*N+98] + v[i*N+99]*v[i*N+99] + v[i*N+100]*v[i*N+100] + v[i*N+101]*v[i*N+101] + v[i*N+102]*v[i*N+102] + v[i*N+103]*v[i*N+103] + v[i*N+104]*v[i*N+104] + v[i*N+105]*v[i*N+105] + v[i*N+106]*v[i*N+106] + v[i*N+107]*v[i*N+107] + v[i*N+108]*v[i*N+108] + v[i*N+109]*v[i*N+109] + v[i*N+110]*v[i*N+110] + v[i*N+111]*v[i*N+111] + v[i*N+112]*v[i*N+112] + v[i*N+113]*v[i*N+113] + v[i*N+114]*v[i*N+114] + v[i*N+115]*v[i*N+115] + v[i*N+116]*v[i*N+116] + v[i*N+117]*v[i*N+117] + v[i*N+118]*v[i*N+118] + v[i*N+119]*v[i*N+119] + v[i*N+120]*v[i*N+120] + v[i*N+121]*v[i*N+121] + v[i*N+122]*v[i*N+122] + v[i*N+123]*v[i*N+123] + v[i*N+124]*v[i*N+124] + v[i*N+125]*v[i*N+125] + v[i*N+126]*v[i*N+126] + v[i*N+127]*v[i*N+127] ; l.push_back(sqrt(sum)); } } #endif // VEC_ALGS_H
true
b053ef8620f81bb262caaa14ec58296abd0f59ce
C++
CodingWD/course
/c/chenmingming/chapter04/ex4.30.cpp
UTF-8
329
3.0625
3
[]
no_license
#include<iostream> #include<cstring> using namespace std; int main() { const char *c1 ="good "; const char *c2 ="emotion"; size_t len = strlen(c1) + strlen(c2); char *c = new char[len]; strcpy(c,c1); strcat(c,c2); cout << c << endl; string s1="bad "; string s2 = "behavior!"; string s; s=s1+s2; cout << s << endl; }
true
80984430433a8f842159443e6b1e9e914ecc8d68
C++
junierr/hdoj
/3555.cpp
GB18030
932
2.578125
3
[]
no_license
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; long long dp[20][20][20]; int a[30]; long long dfs(long long pos,int pre,int sta,bool limit){ //pos:ǰλ;pre:һλֵ;sta:n/ǰ49n,0/ǰ治49limit:false/һλ;true:һλ) if(pos==-1) return sta!=0; if(!limit&&dp[pos][pre][sta]!=-1) return dp[pos][pre][sta]; int up=limit?a[pos]:9; long long ans=0; for(int i=0;i<=up;i++){ if(pre==4&&i==9) ans+=dfs(pos-1,i,sta+1,limit&&i==up); else ans+=dfs(pos-1,i,sta||0,limit&&i==up); } if(!limit) dp[pos][pre][sta]=ans; return ans; } long long solve(long long x){ int pos=0; while(x){ a[pos++]=x%10; x/=10; } return dfs(pos-1,0,0,true); } int main(){ int T; long long r; scanf("%d",&T); memset(dp,-1,sizeof(dp)); while(T--){ scanf("%lld",&r); printf("%lld\n",solve(r)); } return 0; }
true
6d89f001796aa9e1a17e0938cfade836df5278a3
C++
prv1/Data-Structures-Alghorithms
/Maze/Maze/Source.cpp
UTF-8
6,949
3.359375
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include "Point2D.h" using namespace std; enum Direction { RIGHT = 0, DOWN = 1, LEFT = 2, UP = 3 }; // Prototypes template<typename T, size_t mazeX, size_t mazeY> void printMaze(T (&maze)[mazeX][mazeY]) { system("cls"); for (int i = 0; i < mazeX; ++i) { for (int j = 0; j < mazeY; ++j) { cout << maze[i][j]; } cout << endl; } } template<typename T, size_t mazeX, size_t mazeY> Point2D& checkDirection(Direction &currentDirection, T(&maze)[mazeX][mazeY], Point2D& playerLocation) { bool isAble = false; Direction originalDirection = currentDirection; int checkedCounter = 0; const int check_x[] = { 1, 0, -1, 0 }, check_y[] = { 0, 1, 0, -1 }; int direction = 0; while (!isAble) { switch (currentDirection) { case RIGHT: direction = 0; isAble = traverseMaze(maze, playerLocation, check_x[currentDirection], check_y[currentDirection]); cout << "isAble: " << isAble << endl; if (!isAble && checkedCounter == 0) { checkedCounter++; currentDirection = DOWN; // look opposite direction } else if (!isAble && checkedCounter == 1) { checkedCounter++; currentDirection = LEFT; } else if (!isAble && checkedCounter >= 2) { currentDirection = UP; originalDirection = DOWN; checkedCounter = 0; } if (isAble) { checkedCounter = 0; originalDirection = currentDirection; } cout << "Counter: " << checkedCounter << endl; break; case DOWN: direction = 1; isAble = traverseMaze(maze, playerLocation, check_x[direction], check_y[direction]); if (!isAble && checkedCounter == 0) { checkedCounter++; currentDirection = LEFT; } else if (!isAble && checkedCounter == 1) { checkedCounter++; currentDirection = UP; } else if (!isAble && checkedCounter >= 2) { currentDirection = RIGHT; originalDirection = LEFT; checkedCounter = 0; } if (isAble) { checkedCounter = 0; originalDirection = currentDirection; } break; case LEFT: direction = 2; if (!isAble && checkedCounter == 0) { checkedCounter++; currentDirection = UP; } else if (!isAble && checkedCounter == 1) { checkedCounter++; currentDirection = RIGHT; } else if (!isAble && checkedCounter >= 2) { currentDirection = DOWN; originalDirection = UP; checkedCounter = 0; } if (isAble) { checkedCounter = 0; originalDirection = currentDirection; } //currentDirection = UP; //cout << "LEFT" << endl; break; case UP: direction = 3; if (!isAble && checkedCounter == 0) { checkedCounter++; currentDirection = RIGHT; } else if (!isAble && checkedCounter == 1) { checkedCounter++; currentDirection = DOWN; } else if (!isAble && checkedCounter >= 2) { currentDirection = LEFT; originalDirection = RIGHT; checkedCounter = 0; } if (isAble) { checkedCounter = 0; originalDirection = currentDirection; } break; default: cout << ""; } cout << "isAble: " << isAble << endl; cout << "checkedCounter: " << checkedCounter << endl; cout << "Current Direction: " << currentDirection << endl; cout << "Original Direction: " << originalDirection << endl; system("pause"); } checkedCounter = 0; originalDirection = currentDirection; return playerLocation; } //void traverseMaze() template<typename T, size_t mazeX, size_t mazeY> bool traverseMaze(T (&maze)[mazeX][mazeY], Point2D& playerLocation, int newX, int newY) { //bool isEnd = false; cout << "Checking..." << endl; if ((maze[playerLocation.getX() + newX][playerLocation.getY() + newY] != 'X' || maze[playerLocation.getX() + newX][playerLocation.getY() + newY] != 'x') && maze[playerLocation.getX() + newX][playerLocation.getY() + newY] == '.') { maze[playerLocation.getX()][playerLocation.getY()] = '+'; newX = playerLocation.getX() + newX; newY = playerLocation.getY() + newY; maze[newX][newY] = '@'; playerLocation.setX(newX); playerLocation.setY(newY); printMaze(maze); // prints entire maze cout << " true 2" << endl; return true; } else if (maze[playerLocation.getX() + newX][playerLocation.getY() + newY] == 'X' || maze[playerLocation.getX() + newX][playerLocation.getY() + newY] == 'x') { cout << "Wall is here" << endl; return false; } else if (maze[playerLocation.getX() + newX][playerLocation.getY() + newY] == '+') { maze[playerLocation.getX()][playerLocation.getY()] = 'x'; newX = playerLocation.getX() + newX; newY = playerLocation.getY() + newY; maze[newX][newY] = '@'; playerLocation.setX(newX); playerLocation.setY(newY); printMaze(maze); // prints entire maze cout << "true 3" << endl; return true; }else if (maze[playerLocation.getX() + newX][playerLocation.getY() + newY] == 'E') { newX = playerLocation.getX() + newX; newY = playerLocation.getY() + newY; maze[newX][newY] = '@'; playerLocation.setX(newX); playerLocation.setY(newY); printMaze(maze); // prints entire maze cout << "true 1" << endl; return true; } maze[playerLocation.getX()][playerLocation.getY()] = '@'; printMaze(maze); // prints entire maze system("pause"); cout << "false" << endl; return false; } int main(int argc, char** argv) { Point2D start(0, 0); Point2D current(0, 0); Point2D end; Direction currentDirection;// = RIGHT; const int mazeX = 7, mazeY = 7; string line; char maze[mazeX][mazeY]; if (argc != 2) { cerr << "Usage: " << argv[0] << " data-file" << endl; system("pause"); return EXIT_FAILURE; } // open the file ifstream inputFileStream(argv[1]); if (!inputFileStream) { cerr << "Could not open the text file!" << endl; system("pause"); return EXIT_FAILURE; } for (int i = 0; i < mazeX; ++i) { inputFileStream >> line; for (int j = 0; j < mazeY; ++j) { maze[i][j] = line.at(j); if (line.at(j) == 'S') start(i, j); if (line.at(j) == 'E') end(i, j); if (start.getY() == j) current = start; } } line = ""; printMaze(maze); cout << endl << start << " " << end << " " << current << endl; currentDirection = RIGHT; if (currentDirection != RIGHT || currentDirection != LEFT || currentDirection != UP || currentDirection != DOWN) currentDirection = RIGHT; while (current != end) { //while(current != end) { //cout << "Counting: " << i << endl; current = checkDirection(currentDirection, maze, current); cout << current << endl; // display current location of player //} //current = end; } cout << endl << start << " " << end << " " << current << endl; cout << "You WIN!!!!!"; inputFileStream.close(); system("pause"); return 0; }
true
2312db3970f3b35ce1d86c67423fea00847efe1c
C++
MAvdB-88/IceFieldCreator
/src/Utils.cpp
UTF-8
2,981
2.71875
3
[]
no_license
// MIT License // Copyright (c) 2020 Marnix van den Berg <m.a.vdberg88@gmail.com> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "Utils.h" #include "Vector2.h" #include <numeric> namespace utils { IndexPair makePair(int i, int j) { if (i >= j) { return (IndexPair(i, j)); } else { return (IndexPair(j, i)); } }; Vector2 mean(const std::vector<Vector2>& poly) { Vector2 sum = std::accumulate(poly.begin(), poly.end(), Vector2(0.0, 0.0)); return sum / double(poly.size()); } bool isConvexPolygon(const std::vector<Vector2>& poly) { if (poly.size() < 3) { return false; } double val(0.0); Vector2 pBegin = poly[0]; Vector2 pEnd = poly[poly.size() - 1]; if ((pEnd - pBegin).length2() > DBL_EPSILON) //Polygon not closed { Vector2 p0 = poly[poly.size() - 1]; Vector2 p1 = poly[0]; Vector2 p2 = poly[1]; Vector2 v0 = p1 - p0; Vector2 v1 = p2 - p1; val = v0.cross(v1); p0 = poly[poly.size() - 2]; p1 = poly[poly.size() - 1]; p2 = poly[0]; v0 = p1 - p0; v1 = p2 - p1; double val2 = v0.cross(v1); if (val * val2 < DBL_EPSILON) //val and val2 have different signs { return false; } } else //Fist and last point are the same { if (poly.size() < 4) { return false; } Vector2 p0 = poly[poly.size() - 2]; Vector2 p1 = poly[0]; Vector2 p2 = poly[1]; Vector2 v0 = p1 - p0; Vector2 v1 = p2 - p1; val = v0.cross(v1); p0 = poly[poly.size() - 3]; p1 = poly[poly.size() - 2]; p2 = poly[0]; v0 = p1 - p0; v1 = p2 - p1; double val2 = v0.cross(v1); if (val * val2 < DBL_EPSILON) //val and val2 have different signs { return false; } } for (int i = 0; i < poly.size() - 2; i++) { Vector2 p0 = poly[i]; Vector2 p1 = poly[i + size_t(1)]; Vector2 p2 = poly[i + size_t(2)]; Vector2 v0 = p1 - p0; Vector2 v1 = p2 - p1; double val2 = v0.cross(v1); if (val * val2 < DBL_EPSILON) //val and val2 have different signs { return false; } } return true; } }
true
fae7bf584f81ac9f2eb2b56386651de7f5121ba1
C++
hubartstephane/Code
/libraries/chaos/src/Windowing/LinearComposerLayout.cpp
UTF-8
2,930
2.875
3
[]
no_license
#include "chaos/ChaosPCH.h" #include "chaos/ChaosInternals.h" namespace chaos { // ===================================================================== // LinearComposerLayout implementation // ===================================================================== aabox2 LinearComposerLayout::ComputePlacement(aabox2 const& placement, size_t index, size_t count) const { aabox2 result; bool reverse_horizontal = (horizontal_mode == LinearComposerLayoutMode::REVERSED); bool reverse_vertical = (vertical_mode == LinearComposerLayoutMode::REVERSED); aabox2 placement_copy = placement; if (orientation == Orientation::VERTICAL) { std::swap(placement_copy.position.x, placement_copy.position.y); std::swap(placement_copy.size.x, placement_copy.size.y); std::swap(reverse_horizontal, reverse_vertical); } // compute the result as if the orientation was horizontal if (max_count <= 0) // a single line/row { if (reverse_horizontal) index = (count - 1) - index; float cell_size = placement_copy.size.x / float(count); result.size.x = cell_size; result.size.y = placement_copy.size.y; result.position.x = float(index) * cell_size; result.position.y = 0; result.position += placement_copy.position; } else { #if 0 size_t line_count = (count + max_count - 1) / max_count; size_t x = index % max_count; size_t y = index / max_count; size_t cell_on_line = (y == line_count - 1) ? // the number of cells for this line count - y * max_count : max_count; glm::vec2 cell_size = { 0.0f, 0.0f }; int offset = 0; if (fill_mode == LinearComposerLayoutFillMode::EXPANDED) { cell_size = placement_copy.size / glm::vec2(float(cell_on_line), float(line_count)); } else { cell_size = placement_copy.size / glm::vec2(float(max_count), float(line_count)); if (fill_mode == LinearComposerLayoutFillMode::UNIFORM_CENTERED) offset = int((placement_copy.size.x - cell_size.x * cell_on_line) * 0.5f); } glm::vec2 p = { float(x), float(y) }; glm::ivec2 position = auto_cast_vector(p * cell_size); glm::ivec2 next_position = auto_cast_vector(p * cell_size + cell_size); if (reverse_horizontal) { std::swap(position.x, next_position.x); position.x = placement_copy.size.x - position.x; next_position.x = placement_copy.size.x - next_position.x; offset = -offset; } if (reverse_vertical) { std::swap(position.y, next_position.y); position.y = placement_copy.size.y - position.y; next_position.y = placement_copy.size.y - next_position.y; } result.size = next_position - position; result.position = position + glm::ivec2(offset, 0); #endif } // correct orientation if (orientation == Orientation::VERTICAL) { std::swap(result.position.x, result.position.y); std::swap(result.size.x, result.size.y); } return result; } }; // namespace chaos
true
b2dc6ea24d4b1e89e34d162c3eabc48171540359
C++
poojitha2002/The-Complete-FAANG-Preparation
/1]. DSA/1]. Data Structures/03]. Recursion/C++/_1)_Print_Subset_Strings.cpp
UTF-8
350
3.359375
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; void printSub(string str, string curr, int index) { if(index == str.length()) { cout<<curr<<" "; return; } printSub(str, curr, index + 1); printSub(str, curr+str[index], index + 1); } int main() { string str = "ABC"; cout<<"Sub Strings:- "; printSub(str, "", 0); cout<<endl; return 0; }
true
3c0158168e238f071caca4bfbbbd84bbb68bb8f8
C++
CasualCoder91/N_Body
/src/LookupTable.cpp
UTF-8
2,598
3.203125
3
[]
no_license
#include "LookupTable.h" LookupTable::LookupTable(std::string filename, std::string delimiter) { this->delimiter = delimiter; this->fileName = filename; init(); } bool LookupTable::isEmpty(){ return map.empty(); } double LookupTable::get(double key){ std::map<double, double>::iterator low, prev; low = map.lower_bound(key); // lowest value above used key if (low == map.end()) { std::cout << "UhOh! No matching value found in LookupTable.." << std::endl; std::cin.clear(); std::cin.get(); return -1; } else if (low == map.begin()) { return low->second; } else { prev = std::prev(low); //next lower value if ((key - prev->first) < (low->first - key)) //if previous value closer to key return prev->second; else return low->second; } } void LookupTable::setMap(std::vector<double> keys, std::vector<double> values){ if (keys.size() != values.size()) { throw "Vector size must be equal"; } for (int i = 0; i < keys.size(); i++) { map.insert(std::make_pair(keys[i], values[i])); } } void LookupTable::makeFile(std::string pFileName, std::string header){ if (pFileName.size() != 0) fileName = pFileName; std::ofstream file(filePath + fileName); if (header.size()>0) file << header << '\n'; //no NOT parallel this one for (std::map<double,double>::const_iterator it = map.begin();it != map.end(); ++it){ file << it->first << ", " << it->second << '\n'; } file.close(); } void LookupTable::init(){ std::string line; std::ifstream file(filePath+fileName); double key, value; while (std::getline(file, line)) { std::string firstToken = line.substr(0, line.find(delimiter)); if (checkIsDouble(firstToken)) { size_t pos = line.find(delimiter); key = std::stod(line.substr(0, pos)); line.erase(0, pos + delimiter.length()); value = std::stod(line, nullptr); map.insert(std::make_pair(key, value)); } } if (map.size() == 0 && debug) { std::cout << "Map initialization failed. File not found or corrupted:" << std::endl; std::cout << "Path: " << filePath << " | Filename: " << fileName << std::endl; std::cin.get(); } } bool LookupTable::checkIsDouble(std::string inputString) { char* end; double result = strtod(inputString.c_str(), &end); if (end == inputString.c_str() || *end != '\0') return false; return true; }
true
8ea6daf5ca2fe355ecf28f337fa93b7c14ccdaf1
C++
Callidon/cbastien
/src/interpreter.cpp
UTF-8
4,198
3.21875
3
[ "MIT" ]
permissive
/* * Fonctions d'interprétations du Pseudo code * Auteurs : Pierre Gaultier et Thomas Minier */ #include "interpreter.hpp" #include <functional> #include <iostream> #include <string> using namespace std; /* * Méthode exécutant une série d'instructions en Pcode */ void execute(PcodeStack& pile_pcode, int nb_vars) { int co = 0; int spx = nb_vars - 1; ExecStack pile_x(pile_pcode.size(), 0); while (pile_pcode[co] != STOP) { interprete(pile_pcode, pile_x, co, spx); } } /* * Méthode interprétant la prochaine instruction en Pcode dans une pile * d'instructions */ void interprete(PcodeStack& pile_pcode, ExecStack& pile_x, int& co, int& spx) { auto operateur = [&](function<int(int, int)> op) { pile_x[spx - 1] = op(pile_x[spx - 1], pile_x[spx]); spx--; co++; }; switch (pile_pcode[co]) { // Instructions de chargement case LDA: { spx++; pile_x[spx] = pile_pcode[co + 1]; co = co + 2; } break; case LDV: { spx++; pile_x[spx] = pile_x[pile_pcode[co + 1]]; co = co + 2; } break; case LDC: { spx++; pile_x[spx] = pile_pcode[co + 1]; co = co + 2; } break; // Instructions de saut case JMP: { co = pile_pcode[co + 1]; } break; case JIF: { if (pile_x[spx] == 0) { co = pile_pcode[co + 1]; } else { co = co + 2; } spx--; } break; case JSR: { // Non implémenté car non nécessaire pour cette itération du projet } break; case RSR: { // Non implémenté car non nécessaire pour cette itération du projet } break; // Opérateurs relationnels case SUP: { operateur([](int a, int b) -> int { return a > b; }); } break; case SUPE: { operateur([](int a, int b) -> int { return a >= b; }); } break; case INF: { operateur([](int a, int b) -> int { return a < b; }); } break; case INFE: { operateur([](int a, int b) -> int { return a <= b; }); } break; case EQ: { operateur([](int a, int b) -> int { return a == b; }); } break; case DIFF: { operateur([](int a, int b) -> int { return a != b; }); } break; // Instructions I/O case RD: { string input; spx++; cout << "Input : "; cin >> input; pile_x[spx] = atoi(input.c_str()); co++; } break; case RDLN: { string input; spx++; cout << "Input : "; cin >> input; cout << endl; pile_x[spx] = atoi(input.c_str()); co++; } break; case WRT: { cout << pile_x[spx]; spx++; co++; } break; case WRTLN: { cout << pile_x[spx] << endl; spx++; co++; } break; // Opérateurs mathématiques case ADD: { operateur([](int a, int b) -> int { return a + b; }); } break; case MOINS: { operateur([](int a, int b) -> int { return a - b; }); } break; case DIV: { operateur([](int a, int b) -> int { return a / b; }); } break; case MULT: { operateur([](int a, int b) -> int { return a * b; }); } break; case NEQ: { pile_x[spx] = 0 - pile_x[spx]; co++; } break; case INC: { pile_x[spx]++; co++; } break; case DEC: { pile_x[spx]--; co++; } break; // Opérateurs logiques case AND: { operateur([](int a, int b) -> int { return a && b; }); } break; case OR: { operateur([](int a, int b) -> int { return a || b; }); } break; case NOT: { pile_x[spx] = (!pile_x[spx]); co++; } break; // Instructions supplémentaires case AFF: { pile_x[pile_x[spx - 1]] = pile_x[spx]; spx = spx - 2; co++; } break; case STOP: { // Jamais interpreté } break; case INDA: { // Non implémenté car non nécessaire pour cette itération du projet } break; case INDV: { // Non implémenté car non nécessaire pour cette itération du projet } break; // cas par défaut default: { cerr << "Erreur : instruction (" << pile_pcode[co] << ") non reconnue" << endl; exit(0); } break; } }
true
ef9b78751d1f8906e4b09cb731d2eaf842c2afa0
C++
GabbyLayr/Algoritmos_Foruns_Aulas
/E1.NotasAlunos.cpp
ISO-8859-1
704
3.390625
3
[]
no_license
//Escrever um programa que declare um vetor de reais e leia e apresentar em tela as notas de 30 alunos. #include<stdio.h> //biblioteca de entrada e sada: pintf e scanf #include<locale.h> //biblioteca para utilizao de acentos grficos: setlocale int main(){ setlocale (LC_ALL, "portuguese"); //acentuao grfica float notas[5]; // armazena nmeros reais com preciso simples int contador, i; //ENTRADA: printf("Declarao das notas dos alunos:\n"); for (contador = 0; contador < 30; contador++){ printf("Digite a nota:\n", contador + 1); scanf("%f", &notas[i]); } printf("\nNota declarada aluno %d: %f\n", contador + 1, notas[i]); return 0; }
true
52ba74a8de9a6285abb13110fd4af575191bf027
C++
ValentinAriela/clase-6
/Ejercicio5.cpp
UTF-8
387
3.421875
3
[]
no_license
#include <stdio.h> int main () { float numero1; float numero2; float multiplicacion; printf("Ingresar el primer números de la forma X.X:\n"); scanf("%f", &numero1); printf("Ingresar el segundo números de la forma Y.Y:\n"); scanf("%f", &numero2); multiplicacion = numero1 * numero2; printf("La multiplicacion de los numeros es:%f\n", multiplicacion); return 0; }
true
c4bb6e7144ffc2271de8fb5ff35e53cb6bd443c4
C++
jimh0311/MMO_Fighter
/Client/PunisherActionGame/CPlayerObject.h
UHC
1,109
2.8125
3
[]
no_license
#pragma once #include "stdafx.h" class CPlayerObject : public CBaseObject { /* CBaseObject ִ ġ. Ÿ. Virtual ൿѴ. */ enum enDIRECTION { LEFT = false, RIGHT = true }; public: CPlayerObject(int id, int type, int x, int y, bool isMy, int hp) :CBaseObject(id, type, x, y) { _bIsMyPlayer = isMy; _iHP = hp; _bDirection = LEFT; _dwActionNow = dfACTION_STAND; SetActionStand(); } bool Action(); bool Draw(); // ActionMsg ó Լ bool ActionMsgProc(); //Sprite ù߳? void SetActionMove(); void SetActionStand(); void SetActionAttack1(); void SetActionAttack2(); void SetActionAttack3(); void SetHP(int hp) { _iHP = hp; } bool IsMyPlayer() { return _bIsMyPlayer; } bool GetDirection() { return _bDirection; } void Demaged(int hp) { _iHP = hp; } private: bool _bIsMyPlayer; // TRUE , FALSE ٸ . int _iHP; // DWORD _dwActionNow; DWORD _dwActionOld; // // bool _bDirection; // LEFT == 0 ; RIGHT == 1; };
true
62aea71b8fa1470d3ccd52eef367fbfc54e214ea
C++
davekessener/VerteilteSysteme
/A3/src/monitor.h
UTF-8
1,183
3.03125
3
[]
no_license
#ifndef VS_SYNCBUF_H #define VS_SYNCBUF_H #include <mutex> #include "util.h" namespace vs { template < typename T, typename Mutex = std::mutex, typename Lock = std::unique_lock<Mutex> > class Monitor { public: typedef Monitor<T, Mutex, Lock> Self; typedef T value_type; typedef Mutex mutex_type; typedef Lock lock_type; private: T mObj; mutex_type mMtx; public: Monitor( ) { } template<typename TT> Monitor(TT&& o) : mObj(std::forward<TT>(o)) { } template<typename TT> void set(TT&&); T get( ); template<typename F> auto access(F&& f) -> decltype(f(mObj)); Monitor(const Self&) = delete; Self& operator=(const Self&) = delete; }; template<typename T, typename M, typename L> template<typename TT> void Monitor<T, M, L>::set(TT&& o) { lock_type guard(mMtx); mObj = std::forward<TT>(o); } template<typename T, typename M, typename L> T Monitor<T, M, L>::get(void) { lock_type guard(mMtx); return mObj; } template<typename T, typename M, typename L> template<typename F> auto Monitor<T, M, L>::access(F&& f) -> decltype(f(mObj)) { lock_type guard(mMtx); return f(mObj); } } #endif
true
5c31469c336aee3747293e65704e82e9d6aa61bf
C++
grahfoster/UECPPD
/Sections/Sec_02/TripleX/TripleX/TripleX.cpp
UTF-8
4,886
3.609375
4
[]
no_license
/* A simple yet flavorful code-breaking game in which the user is tasked with guessing three integer values given their sum and product. With each of the twelve levels, the maximum potential size of the numbers increases, making for a greater arithmetic challenge. If the player solves all twelve puzzles, they win the game; if they fail, they are informed of their loss and shown a summary of their progress. */ #include <vector> #include <iostream> #include <ctime> // Names for each riddle-protected gate const std::vector<std::string> Gates{ "the Nile", "Amon-Ra", "Mut", "Geb", "Osiris", "Isis", "Thoth", "Horus", "Anubis", "Seth", "Bastet", "Sekhmet" }; // Ordinal numbers to describe gate position const std::vector<std::string> Ordinals{ "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "last" }; // Introduce user to game void PrintIntroduction() { std::cout << " /\\ \n" " /__\\ \n" " /_| _\\ \n" " /_|_ _|\\ \n" " /__ _|_ _\\ `_,\n" " /_|__ |_ |\\ - (_)-\n" " /_|__|_ _ | _\\ ' `\n" " / __| _|_ | _ \\ \n" "_ - / _ | __ | __ | _\\ _ - _ - _ - _ - _ TRIPLE X _ - _ - _ - _ -\n\n" "After months of arduous excavation, you have finally uncovered the\n" "entrance to the Lost Pyramid of Khaset. As you make your way through\n" "the winding crypt, a bright-eyed sphinx suddenly appears, blocking\n" "your path.\n\n"; } // Pose riddle to user and indicate if answer is correct bool PoseRiddle(const int CurrentGate) { const int Difficulty = CurrentGate + 1; // Offset index by 1 const int CodeA = rand() % Difficulty + Difficulty; const int CodeB = rand() % Difficulty + Difficulty; const int CodeC = rand() % Difficulty + Difficulty; const int CodeSum = CodeA + CodeB + CodeC; const int CodeProduct = CodeA * CodeB * CodeC; std::cout << // Print riddle and prompt user for input "\"You have reached the Gate of " << Gates[CurrentGate] << ", " << Ordinals[CurrentGate] << " barrier of twelve,\"\n" "says the sphinx. \"If you would venture deeper still, then rack\n" "your brains to solve this riddle:\n" "Added we are " << CodeSum << ".\n" "Multiplied we make " << CodeProduct << ".\n" "Speak to me these numbers three, and I will show the path you\n" "seek.\"\n"; int GuessA = 0; int GuessB = 0; int GuessC = 0; std::cin.ignore(std::cin.rdbuf()->in_avail()); std::cin >> GuessA >> GuessB >> GuessC; // Get user input if (!std::cin) // Handle non-integer input throw std::exception("The sphinx takes only integers!\n"); if (GuessA + GuessB + GuessC == CodeSum && // Check if answer is correct GuessA * GuessB * GuessC == CodeProduct) return true; return false; } // Inform user of success or failure void PrintOutcome(const bool bIsCorrect, const int CurrentGate) { if (bIsCorrect) { std::cout << // Print success message "\nThe sphinx lowers its head with a smile. There is a puff of\n" "smoke, sudden darkness, then silence. When the pitch-black cloud\n" "clears away, you find the path ahead open. Taking your torch in\n" "hand, you forge ahead into the depths of the crypt.\n"; if (CurrentGate < Gates.size()) // Print lead-in to next riddle std::cout << "Before long, another sphinx bars the way.\n\n"; return; } std::cout << // Print failure message "\nA frown appears on the sphinx's face. Pity fills its eyes.\n" "\"Alas,\" it speaks, \"These numbers three are not the ones I need.\n" "I am afraid your journey is at an end. You made it to the Gate of\n" << Gates[CurrentGate] << ", " << Ordinals[CurrentGate] << " of two and ten.\"\n\n" "Sorry! You didn't beat the game.\n"; } // Inform user they have beaten game void PrintVictory() { std::cout << // Print victory message "Seconds pass, then minutes. For the better part of an hour you grope\n" "along the dry stone walls, delving further and further into the\n" "ancient ruin. Finally, turning into a wide passage you see a light\n" "at the end of the corridor. Torches burn in bronze braziers, lining\n" "the walls of a small, square room. On a raised platform at its\n" "center lies the tomb of Anakhaten, first nomarch of Khaset.\n\n" "Congratulations! You beat the game.\n"; } int main() { PrintIntroduction(); srand(time(NULL)); // Ensure randomness in riddle generation int CurrentGate = 0; // Start at first gate while (CurrentGate < Gates.size()) { try { if (!PoseRiddle(CurrentGate)) { PrintOutcome(false, CurrentGate); return 0; // Wrong answer ends the game } PrintOutcome(true, CurrentGate); ++CurrentGate; // Proceed to next gate } catch (std::exception & e) { std::cerr << e.what() << '\n'; std::cin.clear(); } catch (...) { std::cerr << "Unexpected error.\n"; return 1; } } PrintVictory(); }
true
809de5d46dd104b8b2f1fc342e04fb4cdf1e462f
C++
pmdiano/shuati
/cpp/308-Range-Sum-Query-2D---Mutable/solution.cpp
UTF-8
1,619
3.203125
3
[]
no_license
class NumMatrix { vector<vector<int>> mat; vector<vector<int>> bit; int M, N; void updateBIT(int row, int col, int val) { int diff = val - mat[row][col]; mat[row][col] = val; row++, col++; for (int i = row; i <= M; i += i & (-i)) { for (int j = col; j <= N; j += j & (-j)) { bit[i][j] += diff; } } } int getSum(int row, int col) { int sum = 0; row++, col++; for (int i = row; i > 0; i -= i & (-i)) { for (int j = col; j > 0; j -= j & (-j)) { sum += bit[i][j]; } } return sum; } public: NumMatrix(vector<vector<int>> &matrix) : M(0), N(0) { if (matrix.empty() || matrix[0].empty()) { return; } M = matrix.size(), N = matrix[0].size(); mat = vector<vector<int>>(M, vector<int>(N, 0)); bit = vector<vector<int>>(M+1, vector<int>(N+1, 0)); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { updateBIT(i, j, matrix[i][j]); } } } void update(int row, int col, int val) { updateBIT(row, col, val); } int sumRegion(int row1, int col1, int row2, int col2) { return getSum(row1-1, col1-1) + getSum(row2, col2) - getSum(row1-1, col2) - getSum(row2, col1-1); } }; // Your NumMatrix object will be instantiated and called as such: // NumMatrix numMatrix(matrix); // numMatrix.sumRegion(0, 1, 2, 3); // numMatrix.update(1, 1, 10); // numMatrix.sumRegion(1, 2, 3, 4);
true
025261dcb0256e277f55fe0afd3bd0a49611a567
C++
kovleventer/FoD
/src/gui/popup.h
UTF-8
1,735
2.84375
3
[ "MIT" ]
permissive
#pragma once #include <SDL.h> #include <string> #include "basicgui.h" #include "button.h" #include "../util/point.h" #include "../player/item.h" #include "../core/animatabletexture.h" /*! * @author kovlev */ /*! * @enum PopupType * Offers two opion on popup types * One has only one button while the other has two * The yes-no popup offers no special functionality, so it is never used yet */ enum class PopupType { POPUP_OK, POPUP_YESNO }; /*! * @class Popup * Displays a popup which is closed by clicking the OK button * Supports displaying text and item textures */ class Popup : public BasicGUI { public: //Custom position popups Popup(int xp, int yp, int wp, int hp, PopupType type); Popup(SDL_Rect dimensionRect, PopupType type); //Auto-center popupss Popup(int width, int height, PopupType type); Popup(Dimension dimension, PopupType type); ~Popup(); void render(); ATexture* backgroundT; ATexture* foregroundT; //Getters PopupType getPopupType(); std::string getText(); int getTextSize(); Item* getItem(int index); //Setters //NOTE dont use this void setPopupType(PopupType newPopupType); void setText(std::string newText); void setTextSize(int newTextSize); void addItem(Item* itemToAdd); void setItemList(std::vector<Item*> newItemList); //Never use all of them Button* buttonOK; Button* buttonYES; Button* buttonNO; //Event handling void handleLeftClickEvent(int xp, int yp); static const Dimension DEFAULT_DIM; private: //The width and the height of the used buttons Dimension buttonDimensions; //Padding of the text area int padding; //The type of the popup PopupType popupType; std::string text; int textSize; std::vector<Item*> items; };
true
96a66657130cabbc911e2ed1bee51296cd95c0be
C++
iLCSoft/LCIO
/src/cpp/include/UTIL/LCWarning.h
UTF-8
1,532
3.21875
3
[ "BSD-3-Clause" ]
permissive
// -*- C++ -*- #ifndef UTIL_LCWARNING_H #define UTIL_LCWARNING_H 1 #include<map> #include<string> #include<iostream> namespace UTIL { /** Utility class to show warnings in LCIO. * * The maximum amount of warnings printed is configurable and per default set to 10. * * Warnings are shown one last time when application ends. * * @author engels * @version */ class LCWarning { public: static LCWarning& getInstance(); // singleton class /** register a new warning * * id = "a_unique_string_to_identify_the_warning" * txt = "the world will end tomorrow, leave the room immediately and go get some fun ;)" * max = the maximum amount of times to display the warning */ void registerWarning( const std::string& id, const std::string& txt, int max=10 ) ; /** print the warning text associated to the given id */ void printWarning( const std::string& id ) ; private: // singleton settings LCWarning( std::ostream& outstream=std::cerr ); ~LCWarning(); //{} LCWarning( const LCWarning& ) ; LCWarning & operator=(const LCWarning &); struct _warning_cfg_struct{ std::string txt{}; int max{0}; int counter{0}; }; std::map< std::string, _warning_cfg_struct > _warning_cfg{} ; // warning configurations std::map< std::string, _warning_cfg_struct >::iterator _warning_cfg_it{} ; // iterator std::ostream& _outstream ; // where warnings get printed }; // class } // namespace UTIL #endif /* ifndef UTIL_LCWARNING_H */
true
768e7fe12b5a1aa4fae3e6a030b4176ab2d4b206
C++
opus-meum/LoggerWavesInIce
/InitializeEEPROM/InitializeEEPROM.ino
UTF-8
2,219
3.328125
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// initialize the EEPROM gestion for the loggers #include <EEPROM.h> // the addresses should correspond to the logger parameters // address in which stores if the EEPROM has been used to generate file numbers before int address_init = 0; // address in which stores the current file numbering int address_numberReset = 1; void setup() { // wait to let the time to open the serial delay(5000); // start serial Serial.begin(115200); // read the parameters in EEPROM int initialized_before = EEPROM.read(address_init); long value_before = EEPROMReadlong(address_numberReset); Serial.println(); Serial.print("Content of address_init: "); Serial.print(initialized_before); Serial.println(); Serial.print("Content of address_numberReset: "); Serial.print(value_before); Serial.println(); EEPROM.write(address_init,0); EEPROMWritelong(address_numberReset,0); Serial.println(); Serial.println("EEPROM reseted!"); } void loop() { // nothing to do } // This function will write a 4 byte (32bit) long to the eeprom at // the specified address to address + 3. void EEPROMWritelong(int address, long value) { //Decomposition from a long to 4 bytes by using bitshift. //One = Most significant -> Four = Least significant byte byte four = (value & 0xFF); byte three = ((value >> 8) & 0xFF); byte two = ((value >> 16) & 0xFF); byte one = ((value >> 24) & 0xFF); //Write the 4 bytes into the eeprom memory. EEPROM.write(address, four); EEPROM.write(address + 1, three); EEPROM.write(address + 2, two); EEPROM.write(address + 3, one); } // This function will take and assembly 4 byte of the Eeprom memory // in order to form a long variable. long EEPROMReadlong(long address) { //Read the 4 bytes from the eeprom memory. long four = EEPROM.read(address); long three = EEPROM.read(address + 1); long two = EEPROM.read(address + 2); long one = EEPROM.read(address + 3); //Return the recomposed long by using bitshift. return ((four << 0) & 0xFF) + ((three << 8) & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF); }
true
1e20da19ff546b09c907a0002fbf2b3032de6fee
C++
sorokin/mpl_demo
/push_back.h
UTF-8
277
2.515625
3
[]
no_license
#pragma once #include "node.h" template <typename List, int Value> struct push_back { typedef node<List::data, typename push_back<typename List::next, Value>::result> result; }; template <int Value> struct push_back<nil, Value> { typedef node<Value, nil> result; };
true
14a0bdc43282d647be8129f808186618b17758e2
C++
Diivon/Glc
/include/GC/wrap.h
UTF-8
5,279
2.828125
3
[]
no_license
#pragma once #include <string> #include "GC/Optional.h" namespace gc{ namespace priv{ template<class T, class Tr, class All, template<class Y, class A> class C> struct StringWrapperSplitHelper{}; template<class T, class Tr, class All, class Y> struct StringWrapperAsHelper0{}; template<class T, class Tr, class All, template<class I> class Y> struct StringWrapperAsHelper1{}; template<class T, class Tr, class All, template<class I, class II> class Y> struct StringWrapperAsHelper2{}; } template<class T, class Tr, class All> class StringWrapper{ const std::basic_string<T, Tr, All> & _str; template<class Y, class YY, class YYY> friend StringWrapper<Y, YY, YYY> wrap(const std::basic_string<Y, YY, YYY> & str); StringWrapper(const std::basic_string<T, Tr, All> & str): _str(str){} using this_t = StringWrapper<T, Tr, All>; public: template<class F> this_t & foreach(F && f){for(const auto & i: _str) f(i); return *this;} template<class F> this_t & exec(F && f){f(); return *this;} template<class F> this_t & look(F && f){f(_str); return *this;} const std::basic_string<T, Tr, All> & getString(){return _str;} template<template<class Y, class A> class C> auto split(T delimiter) const noexcept{return priv::StringWrapperSplitHelper<T, Tr, All, C>::get(_str, delimiter);} template<class Y> auto as() const noexcept{return priv::StringWrapperAsHelper0<T, Tr, All, Y>::get(_str);} template<template<class A>class Y> auto as() const noexcept{return priv::StringWrapperAsHelper1<T, Tr, All, Y>::get(_str);} template<template<class A, class AA>class Y> auto as() const noexcept{return priv::StringWrapperAsHelper2<T, Tr, All, Y>::get(_str);} }; template<class T, class Tr, class All> StringWrapper<T, Tr, All> wrap(const std::basic_string<T, Tr, All> & str){ return StringWrapper<T, Tr, All>(str); } namespace priv{ #define GC_REGISTER_STRING_WRAPPER_AS0_HELPER(_arg_type_, _func_name_)\ template<class T, class Tr, class All>struct StringWrapperAsHelper0<T, Tr, All, _arg_type_>{\ static inline Optional<_arg_type_> get(const std::basic_string<T, Tr, All> & str){\ IF_FAIL( return _func_name_(str) ){return fail_exception;}}} #define GC_REGISTER_STRING_WRAPPER_AS2_HELPER(_arg_type_)\ template<class T, class Tr, class All>\ struct StringWrapperAsHelper2<T, Tr, All, _arg_type_>{\ template<class Y>static inline gc::Optional<_arg_type_<T>> get(Y const & s){\ try{_arg_type_<T> result;\ for (const auto & i : s) result.emplace_back(i);\ return result;}catch(std::exception & e){return e;}}} #define GC_REGISTER_STRING_WRAPPER_SPLIT_HELPER(_arg_type_)\ template<class T, class Tr, class All>\ struct StringWrapperSplitHelper<T, Tr, All, _arg_type_>{\ static inline Optional<_arg_type_<std::basic_string<T, Tr, All>>> get(const std::basic_string<T, Tr, All> & s, T delimiter){\ try{_arg_type_<std::basic_string<T>> result;\ const T * str = s.c_str();\ do{ const char *begin = str;\ while ( *str != delimiter && *str ) str++;\ result.push_back( std::basic_string<T, Tr, All>( begin, str ));\ } while ( 0 != *str++ );return result;}catch(std::exception & e){return e;}}}; GC_REGISTER_STRING_WRAPPER_AS0_HELPER(float, std::stof); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(double, std::stod); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(long double, std::stold); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(I16, std::stoi); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(I32, std::stoi); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(I64, std::stoi); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(U16, std::stoul); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(U32, std::stoul); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(U64, std::stoul); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(short, std::stoi); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(int, std::stoi); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(long, std::stoi); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(long long, std::stoi); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(unsigned short,std::stoul); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(unsigned int, std::stoul); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(unsigned long,std::stoul); GC_REGISTER_STRING_WRAPPER_AS0_HELPER(unsigned long long,std::stoul); #ifdef _VECTOR_ GC_REGISTER_STRING_WRAPPER_SPLIT_HELPER(std::vector); GC_REGISTER_STRING_WRAPPER_AS2_HELPER(std::vector); #endif #ifdef _LIST_ GC_REGISTER_STRING_WRAPPER_SPLIT_HELPER(std::list); GC_REGISTER_STRING_WRAPPER_AS2_HELPER(std::list); #endif #ifdef _DEQUE_ GC_REGISTER_STRING_WRAPPER_SPLIT_HELPER(std::deque); GC_REGISTER_STRING_WRAPPER_AS2_HELPER(std::deque); #endif #ifdef _FORWARD_LIST_ GC_REGISTER_STRING_WRAPPER_SPLIT_HELPER(std::forward_list); GC_REGISTER_STRING_WRAPPER_AS2_HELPER(std::forward_list); #endif #ifdef _STACK_ GC_REGISTER_STRING_WRAPPER_SPLIT_HELPER(std::stack); GC_REGISTER_STRING_WRAPPER_AS2_HELPER(std::stack); #endif #ifdef _QUEUE_ GC_REGISTER_STRING_WRAPPER_SPLIT_HELPER(std::queue); GC_REGISTER_STRING_WRAPPER_AS2_HELPER(std::queue); #endif #undef GC_REGISTER_STRING_WRAPPER_AS0_HELPER #undef GC_REGISTER_STRING_WRAPPER_AS2_HELPER #undef GC_REGISTER_STRING_WRAPPER_SPLIT_HELPER } }
true
5a9b51f004563d190606ad438523f05ce324113d
C++
haoyuan2016/leetcode
/Q63.cpp
UTF-8
775
2.609375
3
[]
no_license
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { if(obstacleGrid.empty()) return 0; int m = obstacleGrid.size(), n = obstacleGrid[0].size(); vector<int> dp(n, 0); for(int i = 0; i < n; i++) { if(obstacleGrid[m - 1][n - i - 1] == 0) dp[i] = 1; else break; } int cur = m - 1; while(cur >= 1) { for(int i = 0; i <= n - 1; i++) { if(obstacleGrid[cur - 1][n - i - 1] == 1) dp[i] = 0; else dp[i] = dp[i] + dp[i - 1]; } cur--; } return dp[n - 1]; } };
true
07b2121cb1cd00599584d6ab5501a6ef810d5418
C++
barani008/C-programs
/Data structures/Trees/Kth Smallest Element in a BST.cpp
UTF-8
894
3.828125
4
[]
no_license
/** Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements. Follow up: What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int count = 0; int kthVal = 0; int kthSmallest(TreeNode* root, int k) { if(root==NULL) return -1; int ret = kthSmallest(root->left, k); count++; if(count==k) kthVal = root->val; ret = kthSmallest(root->right, k); return kthVal; } };
true
6b6193bc2459f3a6b3269ec223fb7a0ce39a5773
C++
renatomatz/finance_cpp
/option_pricing/option_pricing.h
UTF-8
2,346
2.53125
3
[]
no_license
#pragma once #include <algorithm> #include <cmath> #include <unordered_map> #include <set> #include "ts_getters.h" using namespace std; // Constants unsigned char QUIET = 0, INIT = 1, STEPS = 2, FINAL = 4, VERBOSE = 7 ; enum OptionKind { call=1, put=-1 }; unordered_map<string, OptionKind> OptionKindStringMap { {"call", call}, {"put", put} }; enum OptionStyle { european=0, american=1 }; unordered_map<string, OptionStyle> OptionStyleStringMap { {"american", american}, {"european", european} }; // Classes struct OptionPricing { typedef _TSGetter<float> *FloatGetter; private: void init(double S, FloatGetter U, FloatGetter D, double DeltaT, FloatGetter R); double S; FloatGetter U; FloatGetter D; double DeltaT; FloatGetter R; double K; unordered_map<OptionStyle, double> cache_; void ClearCache(); int Check(); double Alpha1(int step); double Alpha2(int step); double Beta1(int step); double Beta2(int step); void PriceOptionHelper(OptionKind kind, OptionStyle style, double K, unsigned char opts); double PriceFuturesHelper(double K); public: OptionPricing(double S, FloatGetter U, FloatGetter D, double DeltaT, FloatGetter R); OptionPricing(); ~OptionPricing(); double getS(); double getU(int step); double getD(int step); double getR(int step); double getDeltaT(); double getK(); void setS(double val); void setU(FloatGetter val); void setD(FloatGetter val); void setDeltaT(double val); void setR(FloatGetter val); void setK(double val); double BondRet(int step); double* StockPrice(); double* BondPrice(); double Price1(int step); double Price2(int step); double PriceSecurity(double a[], int step); double PriceOption(OptionKind kind, OptionStyle style, double K, unsigned char opts); double PriceOption(OptionKind kind, OptionStyle style, unsigned char opts); double PriceOption(OptionKind kind, OptionStyle style, double K); double PriceOption(OptionKind kind, OptionStyle style); double PriceFutures(double K); double PriceFutures(); };
true
783a6e5550b860d42c18b2cdcdea60da93d2b3af
C++
efrenhdez2112/INAOEgit
/Tarea_2.cpp
UTF-8
973
3.578125
4
[]
no_license
#include<iostream> using namespace std; void sumav(float vec1[], float vec2[], float vec3[], int tam) { float *ptrvec1 = vec1; float *ptrvec2 = vec2; float *ptrvec3 = vec3; for (int i; i<tam; i++) { *vec3 = (*vec1 + *vec2); *vec1++; *vec2++; *vec3++; } } int main() { int numval; const int tamvec = 1000; float vec1[tamvec]; float vec2[tamvec]; float vec3[tamvec]; cout<<"Ingrese el numero total de valores en el vector: "; cin>>numval; for(int i=0; i<numval; i++) { cout<<"Ingrese el valor numero "<<i+1<<" para el vector #1: "; cin>>vec1[i]; } for(int i=0; i<numval; i++) { cout<<"Ingrese el valor numero "<<i+1<<" para el vector #2: "; cin>>vec2[i]; } sumav(vec1, vec2, vec3, numval); cout<<"La suma de los dos vectores es: "<<endl; for (int i=0; i<numval; i++) { cout<<vec3[i]<<", "; } return 0; }
true
3ea521441b29e8e35b5ec6faac8f155b7fc67e13
C++
jerrychen44/cci_algorithm_fundamentals_cpp
/Ch04.Trees and Graphs/4.5_Validate_BST_jerry/4.5_Validate_BST_1_in_order_traversal_jerry.cpp
UTF-8
1,944
3.65625
4
[]
no_license
#include <iostream> #include <vector> #include "tree_utility.cpp" bool checkBST(TreeNode* node,int *lastest_traversaled_node){ if(node == nullptr){ //hit the end std::cout << " hit the end, node = nullptr, return true" << std::endl; return true; } std::cout << "node->data: " << node->data << ", lastest_traversaled_node = " << *lastest_traversaled_node << std::endl; //check / recrse left if( !checkBST(node->left,lastest_traversaled_node) ){ std::cout << " !checkBST(node.left), return false" << std::endl; return false; } //check current node, current should > lastest_traversaled_node if(*lastest_traversaled_node !=-99999 && node->data <= *lastest_traversaled_node){ std::cout << " *lastest_traversaled_node !=0 && node->data <= *lastest_traversaled_node, return false" << std::endl; return false; } *lastest_traversaled_node = node->data; std::cout << " set lastest_traversaled_node to " << *lastest_traversaled_node << std::endl; //check / recurse right if( !checkBST(node->right,lastest_traversaled_node) ){ std::cout << " !checkBST(node.right), return false" << std::endl; return false; } return true; //All good } int main(){ //construct a tree for example //int A[] = {1, 2, 3, 4, 5, 6, 7}; int A[] = {1, 9, 3, 4, 5, 6, 7}; std::vector<int> arr (A, A + sizeof(A) / sizeof(A[0]) ); TreeNode *root = createMinBST(arr); //printPreorder(root); /* Convert List to BST {1,2,3,4,5,6,7} 4 / \ 2 6 / \ / \ 1 3 5 7 */ int lastest_traversaled_node = -99999; int rst = checkBST(root, &lastest_traversaled_node); std::cout << "checkBST: " << rst << std::endl; freeTree(root); return 0; }
true
b35bc088593cf6ff10016665da0da17b84815d16
C++
RuneKokNielsen/TopAwaRe
/inc/ext/json/JSONConfigurationTree.hpp
UTF-8
1,355
2.71875
3
[ "MIT" ]
permissive
#ifndef JSON_CONFIGURATION_TREE_HPP #define JSON_CONFIGURATION_TREE_HPP #include "ConfigurationTree.hpp" #include "json.hpp" using json = nlohmann::json; /** * JSON backend for interfacing with JSON configuration files. * Based on the nlohmann JSON implementation: https://github.com/nlohmann/json **/ class JSONConfigurationTree: ConfigurationTreeBackend{ public: JSONConfigurationTree(){}; JSONConfigurationTree(json j): _j(j){}; ~JSONConfigurationTree(){}; template<typename T> T get(string field); string getString(string field); float getFloat(string field); vector<float> getVecFloat(string field); vector<vector<float>> getVecVecFloat(string field); vector<vector<vector<float>>> getVecVecVecFloat(string field); int getInt(string field); vector<int> getVecInt(string field); bool getBool(string field); JSONConfigurationTree* getChild(string field); vector<ConfigurationTreeBackend*> getChildren(string field); bool hasField(string field); JSONConfigurationTree* loadFile(string path); void merge(ConfigurationTreeBackend* conf); protected: json _j; }; template<typename T> T JSONConfigurationTree::get(string field){ try{ return _j[field].get<T>(); }catch(nlohmann::detail::exception e){ throw ConfigurationException("Error reading key " + field + " : " + e.what()); } } #endif
true
5ff9bf997ffc5d0ad939630599dec85adb201a26
C++
zhang35/qt-dataViewer
/readdatawidget.cpp
WINDOWS-1252
1,801
2.71875
3
[]
no_license
#include "readdatawidget.h" #include "ui_readdatawidget.h" #include <QDebug> ReadDataWidget::ReadDataWidget(QWidget *parent) : QWidget(parent), ui(new Ui::ReadDataWidget) { ui->setupUi(this); this->setWindowTitle(tr("¼빤")); } ReadDataWidget::~ReadDataWidget() { delete ui; } void ReadDataWidget::on_pushButton_extract_clicked() { QString data = ui->textEdit->toPlainText(); QList<QString> list; QString coordinate = ""; int i = 0; int count = 0; while(1) { bool isEnd = false; while (data[i]<'0' || data[i]>'9') { i++; if (i>=data.length()) { isEnd = true; break; } } if (isEnd){ break; } while (data[i]>='0' && data[i]<='9') { coordinate.append(data[i]); i++; if (i>=data.length()) { isEnd = true; break; } } switch (count){ case 0: coordinate.append(""); break; case 1: coordinate.append(""); break; case 2: coordinate.append(""); list.append(coordinate); coordinate = ""; break; } count = (count+1)%3; if (isEnd){ break; } } QString x, y; for (int j=0; j<list.size(); j++){ if (j%2==0) { x = list.at(j); } else { y = list.at(j); qDebug()<< QString("E"+ x + "N" + y); } } }
true
82f99160769957e9dca40571097c6dd8ea25609c
C++
DonRumata710/NetCowork
/Generator/main.cpp
UTF-8
1,682
2.90625
3
[ "MIT" ]
permissive
#include <iostream> #include <filesystem> #include "interface.lexer.hpp" #include "interface.parser.hpp" #include "printer.h" int main(int argc, char** argv) { std::vector<std::filesystem::path> input; std::string output_folder; for(int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-i") == 0) { for(; i < argc && argv[i + 1][0] != '-'; ++i) input.push_back(argv[i + 1]); --i; } else if (strcmp(argv[i], "-o") == 0) { output_folder = argv[i + 1]; ++i; } } if (input.empty()) { std::cout << "There is nothing to parse\n"; return -1; } if (output_folder.empty()) output_folder = "."; try { for (const auto& filename : input) { InterfaceModel model; std::vector<std::string> errors; if (!std::filesystem::exists(filename)) { std::cerr << "File \"" << filename.string() << "\" does not exists"; return -2; } std::ifstream file(filename); yy::scanner scanner(file, &std::cout); yy::parser parser(filename.parent_path().string(), scanner, model, errors); int res = parser.parse(); if (res) { throw std::runtime_error("Parsing was failed with code " + std::to_string(res) + "\n"); } Printer p(output_folder); model.print(p); } } catch (const std::exception& err) { std::cerr << err.what() << '\n'; return -3; } return 0; }
true
b70e042b5344fb0731485a434abf021fee939751
C++
feechka-patrick/OOP_labs
/laba6/8.cpp
UTF-8
587
3.546875
4
[]
no_license
#include <iostream> #include <stdlib.h> #include <math.h> #include <vector> using namespace std; const int LIMIT = 10; class safearay { private: vector<int> array; public: safearay(){ array.resize(LIMIT); for (int i=0; i<LIMIT; i++) array[i] = i + 1; } void putel(int ind, int num){ if (ind >= 0 && ind < LIMIT - 1){ array.insert(array.begin() + ind, num); } } int getel(int ind){ if (ind >= 0 && ind < LIMIT - 1){ return array[ind]; } } }; int main() { safearay sal; int temp = 12345; sal.putel (7, temp); temp = sal.getel(7); cout << temp; }
true
7f56f97d2ab1f6fbba86c1c0f965299d11eed0b4
C++
KiaFarhang/Big-C-
/chapter_4/ex11.cpp
UTF-8
1,509
4.03125
4
[]
no_license
#include <iostream> #include <math.h> using namespace std; /* Calculates the Julian date of a given day. @param year - the given year. @param month - the given month. @param day - the given day. @return jul - The date as a Julian date. */ long julian(int year, int month, int day) { if(year < 0) { year++; } if(month > 2) { month++; } else { month += 13; year--; } long jul = floor(365.25 * year) + floor(30.6001 * month) + day + 1720995.0; if(jul < 2299171) { return jul; } else { int ja = 0.01 * year; jul = jul + 2 - ja + 0.25 * ja; return jul; } } void jul_to_date(long jul, int& year, int& month, int&day) { if(jul > 2299160) { long jalpha = ((jul - 1867216) - 0.25) / 36524.25; jul = jul + 1 + jalpha - (int)(0.25 * jalpha); } long jb = jul + 1524; long jc = 6680.0 + (jb - 2439870 - 122.1)/365.25; long jd = 365 * jc + (0.25 * jc); int je = (jb - jd)/30.6001; day = jb - jd - (long)(30.6001 * je); month = je - 1; year = (int)(jc - 4715); if(month > 12) { month-= 12; } if(month > 2) { year--; } if(year < 1) { year--; } } int main() { int year; int month; int day; cout << "Enter a date in the following format: 2016 9 22 " << endl; cin >> year >> month >> day; cout << "How many days back would you like to go? "; int n; cin >> n; long jul = julian(year, month, day) - n; jul_to_date(jul, year, month, day); cout << "That was day " << day << " in month " << month << " of year " << year << endl; return 0; }
true
94c087474530e4f5269b63937fe3ddaf55499428
C++
TomHarte/CLK
/Storage/Disk/DiskImage/Formats/D64.hpp
UTF-8
1,002
2.78125
3
[ "MIT" ]
permissive
// // D64.hpp // Clock Signal // // Created by Thomas Harte on 01/08/2016. // Copyright 2016 Thomas Harte. All rights reserved. // #ifndef D64_hpp #define D64_hpp #include "../DiskImage.hpp" #include "../../../FileHolder.hpp" namespace Storage::Disk { /*! Provides a @c Disk containing a D64 disk image: a decoded sector dump of a C1540-format disk. */ class D64: public DiskImage { public: /*! Construct a @c D64 containing content from the file with name @c file_name. @throws Storage::FileHolder::Error::CantOpen if this file can't be opened. @throws Error::InvalidFormat if the file doesn't appear to contain a .D64 format image. */ D64(const std::string &file_name); // implemented to satisfy @c Disk HeadPosition get_maximum_head_position() final; using DiskImage::get_is_read_only; std::shared_ptr<Track> get_track_at_position(Track::Address address) final; private: Storage::FileHolder file_; int number_of_tracks_; uint16_t disk_id_; }; } #endif /* D64_hpp */
true
c9e246c3cdff171b1a1851c1669b1c1988986099
C++
lowzhao/3391New
/354.2.cpp
UTF-8
601
3.28125
3
[]
no_license
#include <stdio.h> #include <iostream> using namespace std; int main() { int T; int digit,digit2,result; cin >> T; while (T--) { result = 0; for (int i = 0;i < 4; i++) { cin >> digit; result += digit % 10; digit /= 10; digit2 = digit % 10 * 2; result += digit2 % 10 + digit2 / 10; digit /= 10; result += digit % 10; digit /= 10; digit2 = digit % 10 * 2; result += digit2 % 10 + digit2 / 10; } if (result % 10) { cout << "Invalid" << endl; } else { cout << "Valid" << endl; } } return 0; }
true
39a907c03c53bb0316b920cb2433118e24aaecc7
C++
fil1190/creating-a-grid-of-game
/GridGroupItem.cpp
UTF-8
4,716
2.609375
3
[]
no_license
#include "GridGroupItem.h" #include "HexagonalCell.h" GridGroupItem::GridGroupItem(NumberOfCells numberOfCells, QObject *parent, GridType typeGrid): _typeGrid(typeGrid), _numberOfCells(numberOfCells), QObject(parent) { _sceneSize.setHeight(1000); _sceneSize.setWidth(1000); creatingGrid(); } GridGroupItem::~GridGroupItem(){ deleteObjects(); } void GridGroupItem::deleteObjects(){ for (int i = 0; i < _grid.size(); ++i) for (int j = 0; j < _grid.at(i).size(); ++j) delete _grid.at(i).at(j); } QSizeF GridGroupItem::getSceneSize() const{ QSize sceneSize; sceneSize.setWidth((_serviceData.cellSize.width() * _numberOfCells.inColumn)+0.5*_serviceData.cellSize.width()); sceneSize.setHeight((_serviceData.cellSize.height()*3.0/4.0 * (_numberOfCells.inRow-1.0))+ _serviceData.cellSize.height()); return sceneSize; } void GridGroupItem::creatingGrid(){ QPointF coordinates(0,0); QVector <GridItem*> gridLine; calculateServiceData(); for (int i = 0; i < _numberOfCells.inRow; ++i){ for (int j = 0; j < _numberOfCells.inColumn; ++j){ _serviceData.coordinatesOfCenter = calculateNewCoordinatesForCenter(coordinates, i, j); gridLine.push_back(creatingGridCell()); gridLine.at(j)->setCoordinatesOfCell(QPoint(i,j)); this->addToGroup(gridLine.at(j)); } _grid.push_back(gridLine); gridLine.clear(); } } QPointF GridGroupItem::calculateNewCoordinatesForCenter(QPointF &oldCoordinates, const int numberTheRow, const int numberTheColumn){ switch(_typeGrid){ case GridType::hexagonOddR: centerForHexagonOddR(oldCoordinates, numberTheRow, numberTheColumn); break; default: // FEX ME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! return oldCoordinates; break; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } return oldCoordinates; } QPointF GridGroupItem::centerForHexagonOddR(QPointF &oldCoordinates, const int numberTheRow, const int numberTheColumn) { if (numberTheColumn) oldCoordinates.setX(oldCoordinates.x() + _serviceData.biasFromCenter.inWidth); else { if (!(numberTheRow%2)) oldCoordinates.setX(0.0 + (_serviceData.biasFromCenter.inWidth/2.0)); else oldCoordinates.setX(0.0 + _serviceData.biasFromCenter.inWidth); if(numberTheRow) oldCoordinates.setY(oldCoordinates.y() + _serviceData.biasFromCenter.inHeight); else oldCoordinates.setY(oldCoordinates.y() + _serviceData.biasFromCenter.inHeight*2.0/3.0); } return oldCoordinates; } void GridGroupItem::calculateServiceData() { IGridCell *gridCell = creatingGridCellForServiceData(); _serviceData = gridCell->calculateServiceData(_sceneSize, _numberOfCells.inRow, _numberOfCells.inColumn); delete gridCell; } GridItem* GridGroupItem::creatingGridCell() { switch(_typeGrid) { case GridType::hexagonOddR: return (new GridItem(new HexagonalCell(), _serviceData, this)); break; case GridType::hexagonEvenR: return (new GridItem(new HexagonalCell(), _serviceData, this)); break; case GridType::hexagonOddQ: return (new GridItem(new HexagonalCell(OrientHexagon::flat_topped), _serviceData, this)); break; case GridType::hexagonEvenQ: return (new GridItem(new HexagonalCell(OrientHexagon::flat_topped), _serviceData, this)); break; default: // FEX ME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! return (new GridItem(new HexagonalCell(), _serviceData, this)); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! break; } } IGridCell* GridGroupItem::creatingGridCellForServiceData() { switch(_typeGrid) { case GridType::hexagonOddR: case GridType::hexagonEvenR: return new HexagonalCell(); break; case GridType::hexagonOddQ: case GridType::hexagonEvenQ: return new HexagonalCell(OrientHexagon::flat_topped); break; default: // FEX ME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! return (new HexagonalCell()); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } }
true
26eece9772b8713256f1e7991adcf475b5fac755
C++
Jeon-JongChan/Programmers
/RectangularWidth.cpp
UTF-8
660
2.953125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; long long solution(vector<vector<int> > rectangles) { long long answer = -1; // [실행] 버튼을 누르면 출력 값을 볼 수 있습니다. cout << "Hello Cpp" << endl; for each(auto start in rectangles) { for each(auto value in rectangles) { if(start[0] <= value[0] && start[0] > value[2]) { if(start[3] <= value[1] && start[3] > value[3]) { } else { } } } } return answer; }
true
60bcb26e0065d9051261f7de1903f11c1a6c9d47
C++
wxr031/DSA
/graph/print_all_patha.cpp
UTF-8
864
3.0625
3
[]
no_license
#include <iostream> class Graph { int vertex; std::list<int> *adj; std::vector<int> indegree; public: Graph(int); ~Graph(); void add_edge(int, int); void dfs(); }; Graph::Graph(int v) { vertex = v; adj = new std::list<int>[v]; indegree.resize(v, 0); } Graph::~Graph() { delete[] adj; } void Graph::add_edge(int source, int dest) { adj[source].push_back(dest); } bool Graph::color(int curr, int v, int label, std::vector<int> &ancestor, std::vector<bool> &visited) { if(curr == v) return true; visited[curr] = true; for(std::list<int>::iterator it = adj[curr].begin(); it != adj[curr].end(); ++it) { if(!visited[*it]) { if(dfs(*it, v, label, ancestor, visited)) { } } } } void Graph::LCA(int v1, int v2) { std::vector<bool> visited(vertex, false); std::vector<int> ancestor(vertex, 0); enum { v1_anc = 1, cmn_anc }; dfs() }
true
b6dba79672211a86b608a7ded4af99fe2b1db072
C++
Paryul10/Competetive-Coding
/CodeForces/Div2/EducationalRound44/a.cpp
UTF-8
579
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int size = n / 2; int in[size], e[size], o[size]; int ed = 0, od = 0; int c = 1; for (int i=0; i<size; i++) { cin >> in[i]; } sort (in, in + size); for (int i=0; i<size; i++) { e[i] = c + 1; o[i] = c; c += 2; } for (int i=0; i<size; i++) { ed += abs(in[i] - e[i]); od += abs(in[i] - o[i]); } if (ed <= od) cout << ed << "\n"; else cout << od << "\n"; return 0; }
true
4cc0cb834e9d1542a468ca06215ea9f9d3ed757e
C++
haomiao/WinCommon
/src/common_base/smart_log.cpp
UTF-8
5,443
2.625
3
[ "MIT" ]
permissive
#include "stdafx.h" #include <time.h> #include "smart_log.h" #include "string_helper.h" namespace { #define LEVEL_STR_SIZE 4 static std::string levelStr[LEVEL_STR_SIZE] = { "INFO", "WARNING", "ERROR", "FATAL", }; #define SAFE_CLOSE_HANDLE(obj) \ { \ if (obj != nullptr) \ { \ ::CloseHandle( obj ); \ obj = nullptr; \ } \ } } CStoredThread::CStoredThread(HANDLE logHandle, MemBufferPtr pBuffer, unsigned int bufferSize, COutPutBaseSink *pOutPutSink) :CThread("StoreLogThread"), m_logHandle(logHandle), m_pBuffer(pBuffer), m_pOutPutSink(pOutPutSink), m_bufferSize( bufferSize ) { } CStoredThread::~CStoredThread() { } void CStoredThread::Run() { if ( m_pOutPutSink != nullptr) { m_pOutPutSink->Write( m_pBuffer->GetBuffer(), m_bufferSize ); m_pOutPutSink->Flush(); m_pBuffer->ReAlloc( 0 ); } if (m_logHandle != nullptr) { ::SetEvent( m_logHandle ); } } CSmartLog::CSmartLog(): m_logBuffer(new CMemBuffer() ), m_logBufferBak(new CMemBuffer() ), m_bufferSize( 10 * 1024 ), m_pOutPutSink(COutPutConsoleSink::GetInstance() ), m_threadCtr(nullptr), m_logBufferSize(0), m_logBufferBakSize(0) { m_logHandle = ::CreateEvent( NULL, TRUE, TRUE, NULL ); m_logHandleBak = ::CreateEvent( NULL, TRUE, TRUE, NULL ); } CSmartLog::~CSmartLog() { if ( m_threadPtr ) { m_threadCtr.Join(); } DealLogStoreFinished(); SAFE_CLOSE_HANDLE( m_logHandle ); SAFE_CLOSE_HANDLE( m_logHandleBak ); } void CSmartLog::SetBufferSize( unsigned int bufferSize ) { m_bufferSize = bufferSize; m_logBuffer->Alloc( m_bufferSize ); m_logBufferBak->Alloc( m_bufferSize ); } void CSmartLog::SetTargetSink( COutPutBaseSink *pOutPutSink ) { DealLogStoreFinished(); m_pOutPutSink = pOutPutSink; } void CSmartLog::WriteLog( LOG_LEVEL logLevel, const void * logStr, int len ) { std::string tempLogStr; __time64_t ltime; _time64( &ltime ); tm localTm; if ( _localtime64_s( &localTm, &ltime ) == 0 ) { tempLogStr = StringFormatA( "[%04d-%02d-%02d %02d:%02d:%02d] [%s]: %s\n", localTm.tm_year + 1900, localTm.tm_mon + 1, localTm.tm_mday, localTm.tm_hour, localTm.tm_min, localTm.tm_sec, levelStr[logLevel].c_str(), std::string( (const char *)logStr ,len).c_str() ); } AutoLock lock( &m_logLock ); LogToSink( tempLogStr ); } void CSmartLog::WriteLog( LOG_LEVEL logLevel, const std::string & logStr ) { WriteLog( logLevel, logStr.c_str(), logStr.length() ); } void CSmartLog::WriteLog( LOG_LEVEL logLevel, const char * logStr ) { WriteLog( logLevel, logStr, strlen(logStr) ); } void CSmartLog::LogToSink( const std::string &tempLogStr ) { if ( m_logHandle != nullptr && ::WaitForSingleObject( m_logHandle, 0 ) == WAIT_OBJECT_0 ) { size_t logStrSize = tempLogStr.length(); size_t logBufferSize = m_logBuffer->GetSize(); if ( logBufferSize <= logStrSize + m_logBufferSize ) { m_logBuffer->ReAlloc( logBufferSize + logStrSize ); } memcpy_s( (void *)( (char *)m_logBuffer->GetBuffer() + m_logBufferSize ), m_logBuffer->GetSize(), tempLogStr.c_str(), logStrSize ); m_logBufferSize += logStrSize; if ( m_logBufferSize >= m_bufferSize ) { ::ResetEvent( m_logHandle ); m_threadCtr.Join(); m_threadPtr = new CStoredThread( m_logHandle, m_logBuffer, m_logBufferSize, m_pOutPutSink ); m_threadCtr = m_threadPtr->Start(); m_logBufferSize = 0; } } else if ( m_logHandleBak != nullptr && ::WaitForSingleObject( m_logHandleBak, 0 ) == WAIT_OBJECT_0 ) { size_t logStrSize = tempLogStr.length(); size_t logBufferBakSize = m_logBufferBak->GetSize(); if ( logBufferBakSize <= logStrSize + m_logBufferBakSize ) { m_logBufferBak->ReAlloc( logBufferBakSize + logStrSize ); } memcpy_s( (void *)( (char *)m_logBufferBak->GetBuffer() + m_logBufferBakSize ), m_logBufferBak->GetSize(), tempLogStr.c_str(), logStrSize ); m_logBufferBakSize += logStrSize; if ( m_logBufferBakSize >= m_bufferSize ) { ::ResetEvent( m_logHandleBak ); m_threadCtr.Join(); m_threadPtr = new CStoredThread( m_logHandleBak, m_logBufferBak, m_logBufferBakSize, m_pOutPutSink ); m_threadCtr = m_threadPtr->Start(); m_logBufferBakSize = 0; } } } void CSmartLog::DealLogStoreFinished() { if ( m_logHandle != nullptr && ::WaitForSingleObject( m_logHandle, 0 ) == WAIT_OBJECT_0 && m_logBufferSize != 0 ) { ::ResetEvent( m_logHandle ); m_threadCtr.Join(); m_threadPtr = new CStoredThread( m_logHandle, m_logBuffer, m_logBufferSize, m_pOutPutSink ); m_threadCtr = m_threadPtr->Start(); m_logBufferSize = 0; } else if ( m_logHandleBak != nullptr && ::WaitForSingleObject( m_logHandleBak, 0 ) == WAIT_OBJECT_0 && m_logBufferBakSize != 0 ) { ::ResetEvent( m_logHandleBak ); m_threadCtr.Join(); m_threadPtr = new CStoredThread( m_logHandleBak, m_logBufferBak, m_logBufferBakSize, m_pOutPutSink ); m_threadCtr = m_threadPtr->Start(); m_logBufferBakSize = 0; } }
true
f0a10926217a1d6ae5b35f54a42e7a2fd492bacd
C++
wohlleby/372_final_project_slave
/src/timer.cpp
UTF-8
1,724
2.984375
3
[]
no_license
// Description: This file implements functions that utilize the timers //----------------------------------------------------------------------// #include "timer.h" #include <Arduino.h> /* Initialize timer 1, you should not turn the timer on here. * You will need to use CTC mode */ void initTimer1(){ //Set timer 1 to CTC: TCCR1A &= ~(1 << WGM10 | 1 << WGM11); TCCR1B &= ~(1 << WGM13); TCCR1B |= (1 << WGM12); // set clock/prescalar for timer 0 to be clk/256 TCCR1B &= ~(1 << CS10 | 1 << CS11); TCCR1B |= (1 << CS12); OCR1AH = 0x00; OCR1AL = 0x40; } void initTimer3(){ TCCR3B |= (1 << WGM32); TCCR3B &= ~(1 << CS30 | 1 << CS32 | 1 << CS31); } /* This delays the program an amount specified by unsigned int delay. * Use timer 1. Keep in mind that you need to choose your prescalar wisely * such that your timer is precise to 1 millisecond and can be used for 125 * 100 milliseconds */ void delayMs(unsigned int delay){ TCNT1H = 0; TCNT1L = 0; TCCR1B &= ~(1 << CS10 | 1 << CS11); TCCR1B |= (1 << CS12); unsigned int i = 0; for(i =0; i < delay; i++){ TIFR1 |= (1 << OCF1A); while(!(TIFR1 & (1 << OCF1A))){ } } TCCR1B&= ~(1 << CS12); } void delayS(unsigned int delay) { unsigned int ticks = 15625*delay; TCNT3H = 0; TCNT3L = 0; //clear timer OCR3AH = ticks >> 8; OCR3AL = ticks & 0x00FF; //calculate high and low count amounts TCCR3B |= (1 << CS30 | 1 << CS32); TCCR3B &= ~(1 << CS31); //turn on the timer while(!(TIFR3 & (1 << OCF3A))); //do nothing until flag TIFR3 |= (1 << OCF3A); //clear flag TCCR3B &= ~(1 << CS31 | 1 << CS30 | 1 << CS32); //turn off timer }
true
555b659e91de18e272a52a3fd5a28cca8ed1483d
C++
lnlp/Led
/src/Led.h
UTF-8
1,307
3.484375
3
[ "MIT" ]
permissive
/* Led.h * * Description: Arduino library for controlling LEDs via GPIOs in a simple and straightforward way. * Makes controlling LEDs easy using clean and simple code (e.g. on, off, toggle, flash). * * Author: Leonel Lopes Parente * License: MIT (see LICENSE file in repository root) * */ #ifndef LED_H_ #define LED_H_ #include <Arduino.h> class Led { public: enum class State {Off, On}; enum class ActiveLevel {Low = LOW, High = HIGH}; Led( const uint8_t pin, const ActiveLevel activeLevel, const State initialState = State::Off, const uint8_t pinmode = OUTPUT); // Certain MCUs/Arduino cores also support OUTPUT_OPEN_DRAIN. State state() const; void setState(const State state); bool isOn() const; bool isOff() const; uint8_t pin() const; ActiveLevel activeLevel() const; void on(); void off(); void toggle(); void flash( const uint8_t count = 2, const uint16_t onTimeMs = 160, const uint16_t offTimeMs = 160, const uint16_t leadOffTimeMs = 200, const uint16_t trailOffTimeMs = 300); private: uint8_t pin_; ActiveLevel activeLevel_; State state_; Led(); // Disable parameterless public constructor. }; #endif // LED_H_
true
4d5d964708d567390866007f1ad48c2029cacafa
C++
Blssel/Algorithm-Practice
/PAT/level-A/A1011.cpp
GB18030
634
2.8125
3
[]
no_license
// A1011.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include<cstdio> int main() { double table[3][3]; double max[3];//ÿλôŶӦεֵ char rel[3] = { 'W', 'T', 'L' }; int select[3];//ѡ for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ scanf("%lf", &table[j]); if (*table[j]> max[i]){ max[i] = *table[j]; select[i] = j; } } } double profit; profit = (max[0] * max[1] * max[2] * 0.65 - 1) * 2; printf("%c %c %c %.2lf", rel[select[0]], rel[select[1]], rel[select[2]], profit); return 0; }
true
273dfb7e6ed3d746e87cf4f6a9f2a024adbd5407
C++
UrosKrstic/Fakultet
/Godina2/OO1/2015Lab3/Z3Poruka/Tekstualna.h
UTF-8
333
2.515625
3
[]
no_license
#ifndef _tekstualna_h_ #define _tekstualna_h_ #include "Poruka.h" #include <string> using namespace std; class Tekstualna : public Poruka { private: string tekst_; protected: void pisi(ostream &izlaz) const override { izlaz << tekst_; } public: Tekstualna(string tekst) : tekst_(tekst) {} Tekstualna() = default; }; #endif
true
fc8a1960ccce62931da424fc7d7b00469d6105cf
C++
linsallyzhao/earlyobjects-exercises
/2015/chapter_8/examples/Stats.h
UTF-8
1,460
3.65625
4
[]
no_license
#ifndef STATS_H #define STATS_H #include <iostream> class Stats { private: double data[30]; int count; public: Stats() { count = 0; } bool storeValue(double n); double getOne(int index) { return data[index]; } double total(); double average(); int highest(); int lowest(); }; bool Stats::storeValue(double n) { bool put = true; if (count < 29) { data[count] = n; count++; } else { std::cout << "Too many data!"; put = false; } return put; } double Stats::total() { double total = 0; for (int index = 0; index < count; index++) { total += data[index]; } return total; } double Stats::average() { double avg = total() / count; return avg; } int Stats::highest() { int index = 0; double highest = data[0]; int record = 0; for (index = 1; index < count; index++) { if (data[index] > highest) { highest = data[index]; record = index; } } return record; } int Stats::lowest() { int index = 0; double lowest = data[0]; int record = 0; for (index = 1; index < count; index++) { if (data[index] < lowest) { lowest = data[index]; record = index; } } return record; } #endif
true
1a7e3bb115f691863a8e129201a522f29fc05cdb
C++
shockzort/tld
/src/core/Box.cc
UTF-8
3,790
3.078125
3
[]
no_license
#include "core/Box.hpp" Box::Box(double x1, double y1, double x2, double y2) { this->id = 0; this->x1 = x1; this->y1 = y1; this->x2 = x2; this->y2 = y2; this->width = x2 - x1 + 1; this->height = y2 - y1 + 1; this->mean = 0.0; this->variance = 0.0; this->overlap = 0.0; this->nrOfPoints = 0.0; this->isValid = false; } Box::Box(int id, double x1, double y1, double x2, double y2) { this->id = id; this->x1 = x1; this->y1 = y1; this->x2 = x2; this->y2 = y2; this->width = x2 - x1 + 1; this->height = y2 - y1 + 1; this->mean = 0.0; this->variance = 0.0; this->overlap = 0.0; this->nrOfPoints = 0.0; this->isValid = false; } Box* Box::move(double dx, double sx, double dy, double sy) { Box* box = new Box(id, x1 - sx + dx, y1 - sy + dy, x2 + sx + dx, y2 + sy + dy); return box; } Box* Box::clone() { Box* clone = new Box(id, x1, y1, x2, y2); return clone; } Box* Box::sum(Box* other) { this->x1 = (this->x1 + other->x1); this->y1 = (this->y1 + other->y1); this->x2 = (this->x2 + other->x2); this->y2 = (this->y2 + other->y2); return this; } Box* Box::divide(int n) { this->x1 = this->x1 / n; this->x2 = this->x2 / n; this->y1 = this->y1 / n; this->y2 = this->y2 / n; return this; } void Box::print() { printf("Box(%a, %a, %a, %a)\n", x1, y1, x2, y2); } string Box::toString() { stringstream ss; ss << "Box(" << id << ", " << x1 << ", " << y1 << ", " << x2 << ", " << y2; return ss.str(); } string Box::toTLDString() { stringstream ss; ss << (x1 + 1.0) << "," << (y1 + 1.0) << "," << (x2 + 1.0) << "," << (y2 + 1.0); return ss.str(); } const char* Box::toCharArr() { string str = this->toString(); return str.c_str(); } Option<Box*> Box::fromLine(string line) { StringStream stream = StringStream(line, ','); double x1 = stod(stream.next()); double y1 = stod(stream.next()); double x2 = stod(stream.next()); double y2 = stod(stream.next()); if (isnan(x1) || isnan(x2) || isnan(y1) || isnan(y2)) { Option<Box*> none = Option<Box*>(); return none; } Box* box = new Box(x1, y1, x2, y2); Option<Box*> maybeBox = Option<Box*>(box); return maybeBox; } double Box::computeOverlap(Box* b1, Box* b2) { double x11 = b1->x1; double x12 = b1->x2; double y11 = b1->y1; double y12 = b1->y2; double x21 = b2->x1; double x22 = b2->x2; double y21 = b2->y1; double y22 = b2->y2; if (x11 > x22 || y11 > y22 || x12 < x21 || y12 < y21) { return 0; } double intersectionX = MIN_DOUBLE(x12, x22) - MAX_DOUBLE(x11, x21) + 1; double intersectionY = MIN_DOUBLE(y12, y22) - MAX_DOUBLE(y11, y21) + 1; double intersection = intersectionX * intersectionY; double area1 = (x12 - x11 + 1) * (y12 - y11 + 1); double area2 = (x22 - x21 + 1) * (y22 - y21 + 1); double overlap = intersection / (area1 + area2 - intersection); if (overlap > 1.0) { printf("Compare:\n"); printf("\t%s:\n", b1->toCharArr()); printf("\t%s:\n", b2->toCharArr()); printf("MIN(%g, %g) = %g\n", x12, x22, MIN_DOUBLE(x12, x22)); printf("MAX(%g, %g) = %g\n", x11, x21, MAX_DOUBLE(x11, x21)); printf("MIN(%g, %g) = %g\n", y12, y22, MIN_DOUBLE(y12, y22)); printf("MAX(%g, %g) = %g\n", y11, y21, MAX_DOUBLE(y11, y21)); printf("INTx: %g\n", intersectionX); printf("INTy: %g\n", intersectionY); printf("INTxy: %g\n", intersection); printf("AREA1: %g\n", area1); printf("AREA2: %g\n", area2); } return overlap; }
true
1a3998d6e36fb5ce56c3171b28ab31e1938b6c74
C++
blockspacer/HQEngine
/HQEngine/Source/HQGrowableArray.h
UTF-8
4,053
3.171875
3
[ "MIT" ]
permissive
/* Copyright (C) 2010-2013 Le Hoang Quyen (lehoangq@gmail.com) This program is free software; you can redistribute it and/or modify it under the terms of the MIT license. See the file COPYING.txt included with this distribution for more information. */ #ifndef _GROWABLE_ARRAY_ #define _GROWABLE_ARRAY_ #ifndef WIN32 #include <cstdlib> #endif #include "HQPrimitiveDataType.h" #include "HQAssert.h" /*------------------------------------------------- template class HQGrowableArray - implements an array that has growable size ------------------------------------------------*/ template <class T> class HQGrowableArray { public: HQGrowableArray(hq_uint32 growQuantity = 20); HQGrowableArray(hq_uint32 initCapacity , hq_uint32 growQuantity = 20); ~HQGrowableArray(); bool Add(const T& item);//add a copy of item to the end of array using copy constuctor T& operator[](size_t index);//member access T& operator[](hq_ubyte8 index);//member access T& operator[](hq_int32 index);//member access T& operator[](hq_ushort16 index);//member access const T& operator[](size_t index) const;//member access const T& operator[](hq_ubyte8 index) const;//member access const T& operator[](hq_int32 index) const;//member access const T& operator[](hq_ushort16 index) const;//member access operator T*() {return elements;}//casting operator operator const T*() const {return elements;}//casting operator size_t Size(){return size;}//current size void Clear(); protected: T* elements; size_t size; size_t capacity; hq_uint32 growQuantity; }; template <class T> HQGrowableArray<T>::HQGrowableArray(hq_uint32 _growQuantity) :elements(NULL) , size(0) , capacity(0), growQuantity(_growQuantity) { } template <class T> HQGrowableArray<T>::HQGrowableArray(hq_uint32 initCapacity , hq_uint32 _growQuantity) : size(0), capacity(initCapacity) , growQuantity(_growQuantity) { this->elements = (T*) malloc(capacity * sizeof(T)); if (this->elements == NULL) throw std::bad_alloc(); } template <class T> HQGrowableArray<T>::~HQGrowableArray() { Clear(); } template <class T> void HQGrowableArray<T>::Clear() { if(elements) { free(elements); elements = NULL; } size = 0; capacity = 0; } template <class T> bool HQGrowableArray<T>::Add(const T& item) { if(this->size >= this->capacity)//we use all available slots,so alloc more slots for additional items { size_t newMaxSize=this->capacity + growQuantity;//addition <growQuantity> slots for future use T* newPtr=(T*)realloc(elements,newMaxSize * sizeof(T)); if(newPtr==NULL) return false; elements=newPtr; this->capacity = newMaxSize; } new (elements + size) T(item); size++; return true; } template <class T> inline T& HQGrowableArray<T>::operator [](size_t index) { HQ_ASSERT(index < this->size); return elements[index]; } template <class T> inline T& HQGrowableArray<T>::operator [](hqint32 index) { HQ_ASSERT(index < this->size && index >= 0); return elements[index]; } template <class T> inline T& HQGrowableArray<T>::operator [](hq_ushort16 index) { HQ_ASSERT(index < this->size); return elements[index]; } template <class T> inline T& HQGrowableArray<T>::operator [](hq_ubyte8 index) { HQ_ASSERT(index < this->size); return elements[index]; } template <class T> inline const T& HQGrowableArray<T>::operator [](size_t index) const { HQ_ASSERT(index < this->size); return elements[index]; } template <class T> inline const T& HQGrowableArray<T>::operator [](hq_ushort16 index) const { HQ_ASSERT(index < this->size); return elements[index]; } template <class T> inline const T& HQGrowableArray<T>::operator [](hq_ubyte8 index) const { HQ_ASSERT(index < this->size); return elements[index]; } template <class T> inline const T& HQGrowableArray<T>::operator [](hqint32 index) const { HQ_ASSERT(index < this->size && index >= 0); return elements[index]; } #endif
true
445f7db0add91b4e6a7ae2a7b20add43fa118883
C++
Anna-Zvankovich/Zvankovich
/KR-1/kr1().cpp
UTF-8
2,002
3.21875
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; const int N = 256; void ShowContentsFile(char*); int main() { char fileNameFirst[N], fileNameSecond[N]; cout << "Please, enter the name of source files: " << endl;//1.txt and 2.txt and 3.txt cout << "1st file: "; cin.getline(fileNameFirst, N, '\n'); cout << "2nd file: "; cin.getline(fileNameSecond, N, '\n'); char fileNameNew[N]; cout << "Please, enter the name of result file: " << endl; cin.getline(fileNameNew, N, '\n'); cout << "Sourse files: " << endl; ShowContentsFile(fileNameFirst); ShowContentsFile(fileNameSecond); ifstream streamIn1(fileNameFirst); if (!streamIn1.is_open()) { cout << "Cannot open file to read!" << endl; } ifstream streamIn2(fileNameSecond); if (!streamIn2.is_open()) { cout << "Cannot open file to read!" << endl; } ofstream out(fileNameNew); if (!out.is_open()) { cout << "Cannot open file to read!" << endl; } int count = 0, term1, term2; while (true) { streamIn1 >> term1; streamIn2 >> term2; while (!streamIn2.eof() && !streamIn1.eof()) { if (term2 >= term1) { out << term1 << " "; streamIn1 >> term1; } else { out << term2 << " "; streamIn2 >> term2; } } if (streamIn1.eof()) { while (!streamIn2.eof()) { out << term2 << " "; streamIn2 >> term2; } break; } if (streamIn2.eof()) { while (!streamIn1.eof()) { out << term1 << " "; streamIn1 >> term1; } break; } } cout << "New array: " << endl; ShowContentsFile(fileNameNew); } void ShowContentsFile(char* fileName) { ifstream streamIn; streamIn.open(fileName); if (!streamIn.is_open()) { cout << " Cannot open file " << fileName << " to read!" << endl; system("pause"); exit(1); } char string[N] = ""; while (!streamIn.eof()) { streamIn.getline(string, N, '\n'); cout << string << endl; } }
true
13c1be9508f4151dfe3361b6a40f5a4ec6876c85
C++
mayd/tcom
/src/HandleSupport.h
UTF-8
4,531
2.875
3
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-newlib-historical" ]
permissive
// $Id$ #ifndef HANDLESUPPORT_H #define HANDLESUPPORT_H #include <tcl.h> #include <string> #include "tcomApi.h" #include "Singleton.h" // This class represents an association from a handle to an application object. // A handle maps to an object of this class. class TCOM_API InternalRep { protected: Tcl_Interp *m_interp; Tcl_Command m_command; ClientData m_clientData; Tcl_HashEntry *m_pNameEntry; // number of Tcl_Obj instances that are handles to this object long m_handleCount; public: InternalRep( Tcl_Interp *interp, Tcl_ObjCmdProc *pCmdProc, ClientData clientData); virtual ~InternalRep(); // Get handle name. std::string name() const; // Get pointer to the application object. ClientData clientData () const { return m_clientData; } void incrHandleCount(); long decrHandleCount(); }; // This class extends InternalRep to associate with a specific application // object class. The class takes ownership of the passed in application object // and is responsible for deleting it. template<class AppType> class AppInternalRep: public InternalRep { public: AppInternalRep ( Tcl_Interp *interp, Tcl_ObjCmdProc *pCmdProc, AppType *pAppObject): InternalRep(interp, pCmdProc, pAppObject) { } virtual ~AppInternalRep(); }; template<class AppType> AppInternalRep<AppType>::~AppInternalRep () { delete reinterpret_cast<AppType *>(clientData()); } // Handles are instances of Tcl's cmdName type which this class hijacks in // order to map handles to application objects. class TCOM_API CmdNameType { // pointer to Tcl cmdName type static Tcl_ObjType *ms_pCmdNameType; // saved Tcl cmdName type static Tcl_ObjType ms_oldCmdNameType; // Tcl type functions static void freeInternalRep(Tcl_Obj *pObj); static void dupInternalRep(Tcl_Obj *pSrc, Tcl_Obj *pDup); static void updateString(Tcl_Obj *pObj); static int setFromAny(Tcl_Interp *interp, Tcl_Obj *pObj); friend class Singleton<CmdNameType>; static Singleton<CmdNameType> ms_singleton; CmdNameType(); ~CmdNameType(); public: // Get instance of this class. static CmdNameType &instance(); // Create handle. Tcl_Obj *newObj(Tcl_Interp *interp, InternalRep *pRep); }; // Maps string representation of handle to internal representation. There's an // instance of this class associated with each Tcl interpreter that loads the // extension. class TCOM_API HandleNameToRepMap { Tcl_Interp *m_interp; // handle string representation to internal representation map Tcl_HashTable m_handleMap; static void deleteInterpProc(ClientData clientData, Tcl_Interp *interp); static void exitProc(ClientData clientData); ~HandleNameToRepMap(); public: HandleNameToRepMap(Tcl_Interp *interp); // Get instance associated with the Tcl interpreter. static HandleNameToRepMap *instance(Tcl_Interp *interp); // Insert handle to object mapping. Tcl_HashEntry *insert(const char *handleStr, InternalRep *pRep); // Get the object represented by the handle. InternalRep *find(Tcl_Obj *pHandle) const; // Remove handle to object mapping. static void erase(Tcl_HashEntry *pNameEntry); }; // This class provides functions to map handles to objects of a specific // application class. template<class AppType> class HandleSupport { // Tcl command that implements the operations of the object Tcl_ObjCmdProc *m_pCmdProc; public: HandleSupport (Tcl_ObjCmdProc *pCmdProc): m_pCmdProc(pCmdProc) { } // Create a handle and associate it with an application object. Takes // ownership of the application object and is responsible for deleting it. Tcl_Obj *newObj(Tcl_Interp *interp, AppType *pAppObject); // Get the application object represented by the handle. If the handle // is invalid, return 0. AppType *find(Tcl_Interp *interp, Tcl_Obj *pHandle) const; }; template<class AppType> Tcl_Obj * HandleSupport<AppType>::newObj (Tcl_Interp *interp, AppType *pAppObject) { AppInternalRep<AppType> *pRep = new AppInternalRep<AppType>( interp, m_pCmdProc, pAppObject); return CmdNameType::instance().newObj(interp, pRep); } template<class AppType> AppType * HandleSupport<AppType>::find (Tcl_Interp *interp, Tcl_Obj *pObj) const { InternalRep *pRep = HandleNameToRepMap::instance(interp)->find(pObj); if (pRep == 0) { return 0; } return reinterpret_cast<AppType *>(pRep->clientData()); } #endif
true
baef639232132917cd845e198a087fdf329e357f
C++
Gurman8r/ML
/include/ML/Graphics/Color.hpp
UTF-8
4,695
3.015625
3
[ "MIT" ]
permissive
#ifndef _ML_COLOR_HPP_ #define _ML_COLOR_HPP_ #include <ML/Graphics/Export.hpp> #include <ML/Core/Matrix.hpp> #include <ML/Core/StandardLib.hpp> namespace ml { /* * * * * * * * * * * * * * * * * * * * */ namespace detail { template < class To, class From > static constexpr tvec4<To> color_cast(const tvec4<From> & value) { return (tvec4<To>)value; } static constexpr vec4b color_cast(vec4f const & value) { return { static_cast<byte_t>(value[0] * 255.f), static_cast<byte_t>(value[1] * 255.f), static_cast<byte_t>(value[2] * 255.f), static_cast<byte_t>(value[3] * 255.f) }; } static constexpr vec4f color_cast(vec4b const & value) { return { static_cast<float_t>(value[0]) / 255.f, static_cast<float_t>(value[1]) / 255.f, static_cast<float_t>(value[2]) / 255.f, static_cast<float_t>(value[3]) / 255.f }; } } /* * * * * * * * * * * * * * * * * * * * */ template <class T> struct BasicColor final { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ using type = typename T; using rgb_t = typename tvec3<type>; using rgba_t = typename tvec4<type>; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ constexpr BasicColor(rgba_t const & value) : m_value { value } { } constexpr BasicColor(rgb_t const & rgb, type a) : m_value { rgb[0], rgb[1], rgb[2], a } { } constexpr BasicColor(type rgba) : m_value { rgba, rgba, rgba, rgba } { } constexpr BasicColor(type r, type g, type b) : m_value { r, g, b, 1.0f } { } constexpr BasicColor(type r, type g, type b, type a) : m_value { r, g, b, a } { } template <class U> constexpr BasicColor(const tvec4<U> & value) : m_value { detail::color_cast(value) } { } template <class U> constexpr BasicColor(const BasicColor<U> & copy) : m_value { detail::color_cast(copy.rgba()) } { } constexpr BasicColor() : m_value { 0 } { } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ inline operator rgba_t &() { return m_value; } constexpr operator rgba_t const &() const { return m_value; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ inline type & operator[](size_t i) { return m_value[i]; } constexpr type const & operator[](size_t i) const { return m_value[i]; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ constexpr auto r() const -> type const & { return m_value[0]; } constexpr auto g() const -> type const & { return m_value[1]; } constexpr auto b() const -> type const & { return m_value[2]; } constexpr auto a() const -> type const & { return m_value[3]; } constexpr auto rgb() const -> const rgb_t { return (rgb_t)m_value; } constexpr auto rgba() const -> rgba_t const & { return m_value; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ private: rgba_t m_value; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ }; /* * * * * * * * * * * * * * * * * * * * */ ML_USING Color = BasicColor<float_t>; ML_USING Color32 = BasicColor<byte_t>; /* * * * * * * * * * * * * * * * * * * * */ template <class T> inline ML_SERIALIZE(std::ostream & out, const BasicColor<T> & value) { return out << value.rgba(); } /* * * * * * * * * * * * * * * * * * * * */ namespace Colors { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ static constexpr Color clear { 0.0f, 0.0f, 0.0f, 0.0f }; static constexpr Color white { 1.0f, 1.0f, 1.0f, 1.0f }; static constexpr Color gray { 0.5f, 0.5f, 0.5f, 1.0f }; static constexpr Color black { 0.0f, 0.0f, 0.0f, 1.0f }; static constexpr Color red { 1.0f, 0.0f, 0.0f, 1.0f }; static constexpr Color green { 0.0f, 1.0f, 0.0f, 1.0f }; static constexpr Color blue { 0.0f, 0.0f, 1.0f, 1.0f }; static constexpr Color cyan { 0.0f, 1.0f, 1.0f, 1.0f }; static constexpr Color yellow { 1.0f, 1.0f, 0.0f, 1.0f }; static constexpr Color magenta { 1.0f, 0.0f, 1.0f, 1.0f }; static constexpr Color violet { 0.5f, 0.0f, 1.0f, 1.0f }; static constexpr Color lime { 0.5f, 1.0f, 0.0f, 1.0f }; static constexpr Color orange { 1.0f, 0.5f, 0.0f, 1.0f }; static constexpr Color fuchsia { 1.0f, 0.0f, 0.5f, 1.0f }; static constexpr Color aqua { 0.0f, 1.0f, 0.5f, 1.0f }; static constexpr Color azure { 0.0f, 0.5f, 1.0f, 1.0f }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ }; /* * * * * * * * * * * * * * * * * * * * */ } #endif // !_ML_COLOR_HPP_
true
d5a89bb6f153719d732c17661734e68efc9f5b50
C++
NunoRCurado/CastleWar
/Interface.cpp
UTF-8
7,212
2.765625
3
[]
no_license
#include "Interface.h" #include "Jogo.h" #include "Colonia.h" #include "Terreno.h" Interface::~Interface() { } bool Interface::verificaComando(int controlo) { Desenho d; Mapa *mapa = jogo.getMapa(); if (comObj.getArg1() != "DIM" && controlo == 0) { d.limpaLinhaProntoAvisos(); cout << "ERRO! Insira primeiro o tamanho do mapa" << endl; return false; } else if(comObj.getArg1() == "DIM" && controlo == 0){ if ((atoi(comObj.getArg2().c_str()) < 0 || atoi(comObj.getArg3().c_str()) < 0)){ d.limpaLinhaProntoAvisos(); cout << "ERRO! Mapa demasiado pequeno" << endl; return false; } else { mapa->criarMapa(atoi(comObj.getArg2().c_str()), atoi(comObj.getArg3().c_str())); d.limpaLinhaProntoAvisos(); cout << "Mapa feito" << endl; return true; } } else if (comObj.getArg1() != "MOEDAS" && controlo == 1) { d.limpaLinhaProntoAvisos(); cout << "ERRO! Insira primeiro o numero de moedas" << endl; return false; } else if (comObj.getArg1() == "MOEDAS" && controlo == 1) { if (atoi(comObj.getArg2().c_str()) <= 20) { d.limpaLinhaProntoAvisos(); cout << "ERRO! Numero de moedas muito reduzido, insira valor maior que 20" << endl; return false; } else { jogo.setMoedasInicial(atoi(comObj.getArg2().c_str())); //verificao se introduzir strings d.limpaLinhaProntoAvisos(); cout << "Moedas inseridas" << endl; return true; } } else if (comObj.getArg1() != "OPONENTES" && controlo == 2) { d.limpaLinhaProntoAvisos(); cout << "ERRO! Insira primeiro o numero de jogadores " << endl; return false; } else if (comObj.getArg1() == "OPONENTES" && controlo == 2) { if (atoi(comObj.getArg2().c_str()) <= 0) { d.limpaLinhaProntoAvisos(); cout << "ERRO!Insira numero de jogadores valido" << endl; return false; } else { jogo.setNumeroJogadores(atoi(comObj.getArg2().c_str())+1); char id = 'A'; for (int i = 0; i < jogo.getNumeroJogadores(); i++) { mapa->setColonias(new Colonia(jogo, jogo.getMoedasInicial(), id, i+1, 1)); d.escreveEmInfo(3 + i); c.setTextColor(mapa->getColonias().at(i)->getCor()); cout << "Jogador " << id; id++; } c.setTextColor(7); mapa->focoMapa(0, 0); d.limpaLinhaProntoAvisos(); cout << jogo.getNumeroJogadores() << " jogadores criados"; return true; } } d.limpaLinhaProntoAvisos(); if (atoi(comObj.getArg3().c_str()) > mapa->getNumeroLinha() || atoi(comObj.getArg4().c_str()) > mapa->getNumeroColuna()) { d.limpaLinhaProntoAvisos(); cout << "ERRO! Numero de linha/coluna invalido" << endl; return false; } else { bool flag = mapa->verificaEdificios(atoi(comObj.getArg3().c_str()), atoi(comObj.getArg4().c_str()), comObj.getArg2(), 10); if (flag == false){ return false; } else { int y = mapa->converteCoordenadasemPosicao(atoi(comObj.getArg3().c_str()), atoi(comObj.getArg4().c_str())); for(int i = 0; i< mapa->getColonias().size();i++) if (mapa->getColonias().at(i)->getId() == comObj.getArg2()[0]) { int x = mapa->getColonias().at(i)->getEdificios()->at(0)->getTerreno()->getPosicao(); mapa->getTerreno().at(x)->getEdificios()->setTerreno(mapa->getTerreno().at(y)); mapa->getTerreno().at(y)->setEdificios(mapa->getColonias().at(0)->getEdificios()->at(0)); mapa->getTerreno().at(x)->setEdificios(NULL); mapa->focoMapa(0, 0); d.limpaLinhaProntoAvisos(); cout << "Castelo "<< comObj.getArg2()<< " mudado com sucesso." << endl; return true; } } } } bool Interface::verificaComandoFase2(int controlo) { Desenho d; if (comObj.getArg1() == "MKPERFIL") { if (jogo.getPerfis().size() == 5) { d.limpaLinhaProntoAvisos(); cout << "ERRO!Ja estao 5 perfis criados" << endl; return false; } else { for (int i = 0; i < jogo.getPerfis().size(); i++) { if (jogo.getPerfis().at(i)->getID() == comObj.getArg2()) { d.limpaLinhaProntoAvisos(); cout << "ERRO!Ja existe perfil com o mesmo id" << endl; return false; } } Perfil *p = new Perfil(comObj.getArg2(), 10, 0, 0,0,0); jogo.setPerfis(p); return true; } } else if (comObj.getArg1() == "ADDPERFIL") { jogo.setPerfilNoVector(comObj.getArg2(), comObj.getArg3()); return false; } else if (comObj.getArg1() == "RMPERFIL") { jogo.removePerfil(comObj.getArg2()); return false; } else if (comObj.getArg1() == "SUBPERFIL") { jogo.removeCaracteristicaDoPerfil(comObj.getArg2(), comObj.getArg3()); return false; } return false; } bool Interface::verificaComandoInicioJogo() { Desenho d; bool flag = false; Mapa *mapa = jogo.getMapa(); if (comObj.getArg1() == "SER") { mapa->addSer(atoi(comObj.getArg2().c_str()), comObj.getArg3()); return false; }else if (comObj.getArg1() == "SETMOEDAS"){ mapa->setMoedasaUmaColonia(comObj.getArg2(), atoi(comObj.getArg3().c_str())); return false; } else if (comObj.getArg1() == "MKBUILD") { } else if (comObj.getArg1() == "LIST") { mapa->mostraColonia(comObj.getArg2()); d.limpaLinhaProntoAvisos(); cout << "Info da Colonia " << comObj.getArg2(); return false; }else if (comObj.getArg1() == "LISTP") { mapa->mostraPerfil(comObj.getArg2()); return false; }else if (comObj.getArg1() == "FOCO") { mapa->focoMapa(atoi(comObj.getArg2().c_str()), atoi(comObj.getArg3().c_str())); d.limpaLinhaProntoAvisos(); cout << "Foco Mudado"; return false; }else if (comObj.getArg1() == "BUILD") { mapa->constroiEdificio(comObj.getArg2(), atoi(comObj.getArg3().c_str()), atoi(comObj.getArg4().c_str())); return false; }else if (comObj.getArg1() == "SELL") { mapa->vendeEdificio(atoi(comObj.getArg2().c_str())); return false; }else if (comObj.getArg1() == "REPAIR") { mapa->reparaEdificio(atoi(comObj.getArg2().c_str())); return false; } else if (comObj.getArg1() == "UPGRADE") { mapa->upgradeEdificio(atoi(comObj.getArg2().c_str())); return false; } else if (comObj.getArg1() == "ATACA") { mapa->getColoniaActual()->setFlagAge(1); d.limpaLinhaProntoAvisos(); cout << "Ataca"; return false; }else if (comObj.getArg1() == "RECOLHE") { mapa->getColoniaActual()->setFlagAge(0); d.limpaLinhaProntoAvisos(); cout << "Recolhe"; return false; }else if (comObj.getArg1() == "NEXT") { flag =mapa->controlaCicloColonias(1); d.limpaLinhaProntoAvisos(); cout << "Proximo Turno"; if (flag == true) { return true; } return false; }else if (comObj.getArg1() == "NEXTN") { int turnos = atoi(comObj.getArg2().c_str()); flag = mapa->controlaCicloColonias(turnos); d.limpaLinhaProntoAvisos(); cout << "Proximos " << turnos << " Turnos"; if (flag == true) { return true; } return false; }else if (comObj.getArg1() == "FIM") { d.limpaLinhaProntoAvisos(); cout << "O jogador forcou a saida" << endl; return true; } else if (comObj.getArg1() == "LOAD") { string ficheiro = comObj.getArg2(); jogo.JogoFicheiro(ficheiro); d.limpaLinhaProntoAvisos(); cout << "Jogo Carregado"; return false; } else{ d.limpaLinhaProntoAvisos(); cout << "Comando invalido" << endl; return false; } return false; } void Interface::setComando(Comando comObj) { this->comObj = comObj; }
true
ab66fdb2625456e8db962929e6fac770ad91d4c2
C++
zoya-0509/Practice-codes
/Codechef GCD and LCM.cpp
UTF-8
360
2.828125
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; long long gcd(long long int a, long long int b) { if (b == 0) return a; return gcd(b, a % b); } long long lcm(int a, int b) { return (a / gcd(a, b)) * b; } int main() { int t; cin>>t; while(t--) {int a,b; cin>>a>>b; cout<<gcd(a,b)<<" "<<lcm(a, b)<<"\n"; }return 0; }
true
6faca2fa1e361270fe14c0d3c41b51a02c003407
C++
lazy3311/design_patterns
/decorator/main.cpp
UTF-8
996
3.25
3
[]
no_license
#include <iostream> #include "thincrust_pizza.hpp" #include "topping_mozzarella.hpp" #include "topping_sauce.hpp" int main(int argc, char** argv) { std::cout << "-------------------------------------------------------------------" << std::endl; std::cout << " DECORATOR PATTERN : Structural" << std::endl; std::cout << "-------------------------------------------------------------------" << std::endl; std::cout << "Decorator is a structural design pattern that lets you attach \\ \n\rnew behaviors to objects by placing these objects inside special wrapper \\ \n\robjects that contain the behaviors." << std::endl; std::cout << "-------------------------------------------------------------------\n" << std::endl; IPizza *pizza = new ToppingMozarella(new ToppingSauce(new ThinCrustPizza())); std::cout << "Ready: " << pizza->get_description() << std::endl; std::cout << "Cost: $" << pizza->get_cost() << std::endl; return 0; }
true
feefbf60ec6eb3551826270647d51f5889e522c2
C++
kaik25/silver-potato
/Source/Handle.cpp
UTF-8
520
2.6875
3
[]
no_license
#include "..\Include\Handle.h" using namespace std; Handle::Handle(HANDLE& rawHandle) : _handle(rawHandle) { }; void Handle::closeHandle(){ if (_handle != nullptr){ if (!(CloseHandle(_handle))){ throw CloseHandleException(GetLastError()); } } }; HandleCloser::~HandleCloser() { closeHandle(); }; void FindHandle::closeHandle(){ if (_handle != nullptr){ if (!(FindClose(_handle))){ throw CloseHandleException(GetLastError()); } } }; FindHandleCloser::~FindHandleCloser() { closeHandle(); };
true
bd228b4a25e4209d474cdad0402ad4aee1b53ef1
C++
prashantmarshal/ds-codes
/Array/smallernumbersleft.cpp
UTF-8
516
3.46875
3
[]
no_license
#include <iostream> #include <stack> using namespace std; void prevsmaller(int *arr, int size){ stack <int> mystack; for(int i = 0; i < size; ++i){ int temp = arr[i]; while(!mystack.empty() && mystack.top() >= arr[i]) mystack.pop(); if(!mystack.empty()) arr[i] = mystack.top(); else arr[i] = -1; mystack.push(temp); } } int main(){ int arr[] = {1, 3, 0, 2, 5}; int size = sizeof(arr)/sizeof(arr[0]); prevsmaller(arr, size); for (int i = 0; i < size; ++i) cout<<arr[i]<<" "; return 0; }
true
8ddeaaf9d0bc1a9b51bc55e37fa13c0cdc3144a1
C++
y42sora/soraSRM
/00001-00500/SRM496/Div2/AnagramFreeTest.cpp
UTF-8
1,989
3.390625
3
[]
no_license
#include "AnagramFree.h" #include <iostream> #include <vector> using std::cerr; using std::cout; using std::endl; using std::vector; class AnagramFreeTest { static void assertEquals(int testCase, const int& expected, const int& actual) { if (expected == actual) { cout << "Test case " << testCase << " PASSED!" << endl; } else { cout << "Test case " << testCase << " FAILED! Expected: <" << expected << "> but was: <" << actual << '>' << endl; } } AnagramFree solution; void testCase0() { string S_[] = {"abcd", "abdc", "dabc", "bacd"}; vector<string> S(S_, S_ + (sizeof(S_) / sizeof(S_[0]))); int expected_ = 1; assertEquals(0, expected_, solution.getMaximumSubset(S)); } void testCase1() { string S_[] = {"abcd", "abac", "aabc", "bacd"}; vector<string> S(S_, S_ + (sizeof(S_) / sizeof(S_[0]))); int expected_ = 2; assertEquals(1, expected_, solution.getMaximumSubset(S)); } void testCase2() { string S_[] = {"aa", "aaaaa", "aaa", "a", "bbaaaa", "aaababaa"}; vector<string> S(S_, S_ + (sizeof(S_) / sizeof(S_[0]))); int expected_ = 6; assertEquals(2, expected_, solution.getMaximumSubset(S)); } void testCase3() { string S_[] = {"creation", "sentence", "reaction", "sneak", "star", "rats", "snake"}; vector<string> S(S_, S_ + (sizeof(S_) / sizeof(S_[0]))); int expected_ = 4; assertEquals(3, expected_, solution.getMaximumSubset(S)); } public: void runTest(int testCase) { switch (testCase) { case (0): testCase0(); break; case (1): testCase1(); break; case (2): testCase2(); break; case (3): testCase3(); break; default: cerr << "No such test case: " << testCase << endl; break; } } }; int main() { for (int i = 0; i < 4; i++) { AnagramFreeTest test; test.runTest(i); } }
true
bab99a0964d76cd2bdf83898ba27aceb160d2c30
C++
contropist/CodeWorld
/Trashbin/Google Code Jam 2016/T4.cpp
UTF-8
1,344
2.671875
3
[]
no_license
//@ Including Header #include <csl_std.h> /** * Name : T4.cpp * Date : 2016年5月28日 下午11:38:08 * Copyright : fateud.com * Anti-Mage : The magic ends here. */ const int N = 30; int n, g[N][N], h[N], f[N]; int ans; bool check(int x) { if (x == n) return true; int cnt = 0; rep(i, 0, n) if (!h[i] && g[f[x]][i]) { ++cnt; h[i] = 1; if (!check(x + 1)) return false; h[i] = 0; } return cnt; } void dfs(int x, int y, int z) { if (z >= ans) return; if (y == n) ++x, y = 0; if (x == n) { memset(h, 0x00, sizeof h); bool flag = 1; rep(i, 0, n) f[i] = i; do { if (!check(0)) { flag = 0; break; } } while (next_permutation(f, f + n)); if (flag) { ans = z; // rep(i, 0, n) { // rep(j, 0, n) cout << g[i][j]; cout << endl; // } } return; } dfs(x, y + 1, z); if (!g[x][y]) { g[x][y] = 1; dfs(x, y + 1, z + 1); g[x][y] = 0; } } //@ Main Function int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int _, __ = 1; for(std::cin >> _; _; --_, ++__) { cin >> n; rep(i, 0, n) rep(j, 0, n) { char ch; cin >> ch; g[i][j] = (ch == '1'); } ans = n * n; dfs(0, 0, 0); std::cout << "Case #" << __ << ": "; cout << ans << endl; } return 0; }
true
f30f194dc5035f1250465ebf14fa6bc18dcb5ca5
C++
jasmeet13n/tinysql-db
/MemoryManager.cc
UTF-8
1,775
2.890625
3
[]
no_license
#ifndef __MEMORY_MANAGER_INCLUDED #define __MEMORY_MANAGER_INCLUDED #include <stack> #include "./StorageManager/Block.h" #include "./StorageManager/Config.h" #include "./StorageManager/Disk.h" #include "./StorageManager/Field.h" #include "./StorageManager/MainMemory.h" #include "./StorageManager/Relation.h" #include "./StorageManager/Schema.h" #include "./StorageManager/SchemaManager.h" class MemoryManager { private: MainMemory* mem; stack<int> freeBlocks; int memory_size; public: MemoryManager(MainMemory* m) { this->mem = m; memory_size = mem->getMemorySize(); for (int i = memory_size - 1; i >= 0; --i) { freeBlocks.push(i); } } int numFreeBlocks() { return freeBlocks.size(); } int getFreeBlockIndex() { if (!freeBlocks.empty()) { int top = freeBlocks.top(); freeBlocks.pop(); Block* top_block = mem->getBlock(top); top_block->clear(); return top; } return -1; } bool getNFreeBlockIndices(vector<int>& ans, int n) { if (freeBlocks.size() < n) { return false; } if (ans.size() != n) { ans.resize(n, -1); } for (int i = 0; i < ans.size(); ++i) { ans[i] = getFreeBlockIndex(); } return true; } bool getAllFreeBlockIndices(vector<int>& ans) { return getNFreeBlockIndices(ans, numFreeBlocks()); } void releaseBlock(int i) { if (i == -1) { return; } freeBlocks.push(i); } void releaseNBlocks(vector<int>& blocks) { for (int i = 0; i < blocks.size(); ++i) { releaseBlock(blocks[i]); } } void releaseAllBlocks() { while (!freeBlocks.empty()) { freeBlocks.pop(); } for (int i = memory_size - 1; i >= 0; --i) { freeBlocks.push(i); } } }; #endif
true
bdc70ad266d2dee791b0dfd8674a8f6792697ece
C++
rapyuta-robotics/alica
/supplementary/autodiff/src/Reification.cpp
UTF-8
1,326
2.703125
3
[ "MIT" ]
permissive
#include "Reification.h" #include "Tape.h" #include <sstream> namespace autodiff { Reification::Reification(TermPtr condition, TermHolder* owner) : BinaryFunction(condition, condition->negate(), owner) { } int Reification::accept(ITermVisitor* visitor) { return visitor->visit(this); } void Reification::acceptRecursive(ITermVisitor* visitor) { _left->acceptRecursive(visitor); _right->acceptRecursive(visitor); visitor->visit(this); } TermPtr Reification::aggregateConstants() { return this; } TermPtr Reification::derivative(VarPtr v) const { throw "Symbolic Derivation of Discretizer not supported."; return nullptr; } std::string Reification::toString() const { std::stringstream str; str << "Discretizer( " << _left->toString() << " )"; return str.str(); } void Reification::Eval(const Tape& tape, const Parameter* params, double* result, const double* vars, int dim) { const double* l = tape.getValues(params[0].asIdx); const double* r = tape.getValues(params[1].asIdx); if (l[0] > 0.75) { result[0] = 1.0; for (int i = 1; i <= dim; ++i) { result[i] = -r[i]; } } else { result[0] = 0.0; for (int i = 1; i <= dim; ++i) { result[i] = l[i]; } } } } /* namespace autodiff */
true
03eeebb14b5ea47511e07d94780d3c3c3b2655c3
C++
AdamTT1/bdScript
/ftObjs.h
UTF-8
3,788
2.59375
3
[]
no_license
#ifndef __FTOBJS_H__ #define __FTOBJS_H__ "$Id: ftObjs.h,v 1.8 2008-04-01 18:54:42 ericn Exp $" /* * ftObjs.h * * This header file declares some FreeType classes for * convenience. * * freeTypeLibrary_t - used to open/close the freetype library * freeTypeFont_t - used to represent an in-memory font file * freeTypeString_t - used to render a string in a particular font * * The primary interface for rendering is the freeTypeString_t * class, which is used to generate bytemap of the alpha of the * string (fraction of coverage in 1/255ths). * * Change History : * * $Log: ftObjs.h,v $ * Revision 1.8 2008-04-01 18:54:42 ericn * -prevent copies * * Revision 1.7 2004/07/25 22:33:59 ericn * -added support for rotation * * Revision 1.6 2004/07/04 21:30:32 ericn * -add monochrome(bitmap) support * * Revision 1.5 2003/02/10 01:17:00 ericn * -modified to allow truncation of text * * Revision 1.4 2003/02/09 02:58:52 ericn * -moved font dump to ftObjs * * Revision 1.3 2003/02/07 03:01:33 ericn * -made freeTypeLibrary_t internal and persistent * * Revision 1.2 2002/11/02 18:38:28 ericn * -added method getDataLength() * * Revision 1.1 2002/11/02 04:13:07 ericn * -Initial import * * * * Copyright Boundary Devices, Inc. 2002 */ #include <ft2build.h> #include FT_FREETYPE_H class freeTypeFont_t { public: freeTypeFont_t( void const *data, unsigned long size ); ~freeTypeFont_t( void ); bool worked( void ) const { return 0 != face_ ; } void dump( void ) const ; FT_Face face_ ; private: freeTypeFont_t( freeTypeFont_t const & ); // no copies }; class freeTypeString_t { public: freeTypeString_t( freeTypeFont_t &font, unsigned pointSize, char const *dataStr, unsigned strLen, unsigned maxWidth ); ~freeTypeString_t( void ); // bitmap dimensions unsigned getWidth( void ) const { return width_ ; } unsigned getHeight( void ) const { return height_ ; } // distance from top row of bitmap to baseline (may be negative) int getBaseline( void ) const { return baseline_ ; } // font height (for vertical spacing) unsigned getFontHeight( void ) const { return fontHeight_ ; } unsigned char getAlpha( unsigned x, unsigned y ) const { return data_[(y*width_)+x]; } unsigned char const *getRow( unsigned y ) const { return data_+(y*width_); } unsigned getDataLength( void ) const { return width_*height_ ; } unsigned width_ ; unsigned height_ ; int baseline_ ; unsigned fontHeight_ ; unsigned char *data_ ; }; // // draw a string into a // enum ftAlign_e { ftLeft = 0, ftCenterHorizontal = 1, ftRight = 2, ftTop = 0, ftBottom = 4, ftCenterVertical = 8 }; bool freeTypeToBitmapBox( freeTypeFont_t &font, unsigned pointSize, unsigned alignment, char const *dataStr, unsigned strLen, unsigned x, unsigned y, unsigned w, unsigned h, unsigned char *bmp, unsigned bmpStride, // bytes per row unsigned bmpRows, unsigned rotation = 0 ); // only 0, 90, 180, 270 supported #endif
true
5ec3704943deca8647d4b56fff132a4fb2d12bae
C++
kobe24o/LeetCode
/程序员面试金典/16.17.contiguous-sequence-lcci.cpp
UTF-8
1,176
3.046875
3
[]
no_license
class Solution { public: int maxSubArray(vector<int>& nums) { vector<int> dp(nums); for(int i = 1; i < nums.size(); ++i) { if(dp[i-1] > 0) dp[i] = max(dp[i], nums[i]+dp[i-1]); } return *max_element(dp.begin(),dp.end()); } }; class Solution { public: int maxSubArray(vector<int>& nums) { int maxSum = nums[0], dp_i_1 = nums[0], dp_i; for(int i = 1; i < nums.size(); ++i) { dp_i = max(nums[i], nums[i]+dp_i_1); maxSum = max(maxSum, dp_i); dp_i_1 = dp_i; } return maxSum; } }; class Solution { public: int maxSubArray(vector<int>& nums) { return divide(nums,0,nums.size()-1); } int divide(vector<int>& nums, int l, int r) { if(l == r) return nums[l]; int i, mid = l+((r-l)>>1); int Lsum = divide(nums,l,mid); int Rsum = divide(nums,mid+1,r); int Ls = 0, Rs = 0, maxL = INT_MIN, maxR = INT_MIN; for(i = l; i <= mid; ++i) { Ls += nums[i]; maxL = max(maxL, Ls); } for(i = mid+1; i <= r; ++i) { Rs += nums[i]; maxR = max(maxR, Rs); } return max(maxL+maxR, max(Lsum,Rsum)); } };
true
58b8ed9c072517c6c5bdc3d29aff63384517e55d
C++
JohnyEngine/CNC
/deprecated/heeksart/Point.h
UTF-8
1,622
3.4375
3
[ "Apache-2.0" ]
permissive
// Point.h // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #pragma once #include <cmath> // combines 3D vertex and vector class Point{ public: double x, y, z; Point():x(0.0), y(0.0){} Point(double X, double Y, double Z):x(X), y(Y), z(Z){} Point(const Point& p){operator=(p);} Point(const Point& p1, const Point& p2){operator=(p2 - p1);} Point(const double* p):x(p[0]), y(p[1]), z(p[2]){} const Point operator+(const Point& p)const{return Point(x + p.x, y + p.y, z + p.z);} const Point operator-(const Point& p)const{return Point(x - p.x, y - p.y, z - p.z);} const Point operator*(double d)const{return Point(x * d, y * d, z * d);} const Point operator/(double d)const{return Point(x / d, y / d, z / d);} const Point operator^(const Point &p)const{return Point(y * p.z - z * p.y, z * p.x - x * p.z, x * p.y - y * p.x);}// cross product const Point operator-()const{return Point(-x, -y, -z);} const double operator*(const Point &p)const{return (x * p.x + y * p.y + z * p.z);}// dot product const Point& operator=(const Point& p){x = p.x; y = p.y; z = p.z; return *this;} bool operator==(const Point& p)const{return dist(p)<0.001;} double dist(const Point &p)const{double dx = p.x - x; double dy = p.y - y; double dz = p.z - z; return sqrt(dx*dx + dy*dy + dz*dz);} void extract(double* e)const{e[0] = x; e[1] = y; e[2] = z;} const double* GetPtr()const{return &x;} double magn()const{return sqrt(x*x + y*y + z*z);} const Point norm()const{double m = magn(); if(m < 0.0000000000001)return Point(0, 0, 0); return Point(*this)/m;} };
true
c120659cd6c381938757be8a6d7b4540e378eff4
C++
juner417/data_structure
/day5/1_voidpointer.cpp
UTF-8
420
3.84375
4
[]
no_license
// 1_void pointer #include <stdio.h> // 핵심 : 포인터 변수 + 1 -> 포인터가 가르키는 대상체의 크기만큼 증가 // ex ) int* 라면 +1은 4바이트 증가 p3=400 -> p3+1 -> p3=404 int main() { // 포인터 연산 char c = 0; short s = 0; int n = 0; char* p1 = &c; short* p2 = &s; int* p3 = &n; printf("%p, %p\n", p1, p1+1); printf("%p, %p\n", p2, p2+1); printf("%p, %p\n", p3, p3+1); }
true
04387540c7be8c6a670e68682dc055ffbf4cc47e
C++
gerardpf2/SuperMonacoGP
/Super Monaco GP/Minimap.cpp
UTF-8
4,576
2.75
3
[ "MIT" ]
permissive
#include "Minimap.h" #include "Car.h" #include "Road.h" #include "Utils.h" #include "MinimapUI.h" #include "ModuleJson.h" #include "ModuleTexture.h" #include "ModuleRenderer.h" using namespace std; using namespace rapidjson; Minimap::Minimap(const Road* road) : road(road) { courseRect = COURSE_RECT; } Minimap::~Minimap() { } const Road* Minimap::getRoad() const { return road; } void Minimap::registerCar(const Car* car) { registeredCars.insert(car); } void Minimap::load(const char* jsonPath, const ModuleJson* moduleJson, ModuleTexture* moduleTexture) { assert(jsonPath); assert(moduleJson); assert(moduleTexture); Document jsonDocument; moduleJson->read(jsonPath, jsonDocument); const Value& courseJson = jsonDocument["course"]; const char* textureGroupPath = courseJson["textureGroupPath"].GetString(); uint textureId = courseJson["textureId"].GetUint(); uint texturePlayer = courseJson["texturePlayer"].GetUint(); uint textureEnemyCar = courseJson["textureEnemyCar"].GetUint(); const Value& pointsJson = jsonDocument["points"]; textureGroupId = moduleTexture->load(textureGroupPath); course = moduleTexture->get(textureGroupId, textureId); playerIcon = moduleTexture->get(textureGroupId, texturePlayer); enemyCarIcon = moduleTexture->get(textureGroupId, textureEnemyCar); addPoints(pointsJson); } void Minimap::unload(ModuleTexture* moduleTexture) { assert(moduleTexture); road = nullptr; points.clear(); registeredCars.clear(); moduleTexture->unload(textureGroupId); course = nullptr; playerIcon = nullptr; enemyCarIcon = nullptr; } void Minimap::render(const ModuleRenderer* moduleRenderer) const { assert(course); assert(moduleRenderer); moduleRenderer->renderTexture(course->t, course->r, &courseRect); renderCarIcons(moduleRenderer); } void Minimap::addPoints(const Value& pointsJson) { if(!pointsJson.Empty()) { // Compute minimapTotalLength based on all the defined points float minimapTotalLength = 0.0f; int initialX = pointsJson[0]["x"].GetInt(); int initialY = pointsJson[0]["y"].GetInt(); int previousX = initialX; int previousY = initialY; for(SizeType i = 1; i < pointsJson.Size(); ++i) { const Value& point = pointsJson[i]; int x = point["x"].GetInt(); int y = point["y"].GetInt(); minimapTotalLength += sqrtf(powf((float)(x - previousX), 2.0f) + powf((float)(y - previousY), 2.0f)); previousX = x; previousY = y; } // Compute all the needed ranges float accumulatedDistance = 0.0f; previousX = initialX; previousY = initialY; for(SizeType i = 0; i < pointsJson.Size(); ++i) { const Value& point = pointsJson[i]; int x = point["x"].GetInt(); int y = point["y"].GetInt(); float distance = sqrtf(powf((float)(x - previousX), 2.0f) + powf((float)(y - previousY), 2.0f)); accumulatedDistance += distance; points[accumulatedDistance / minimapTotalLength] = pair<int, int>(x, y); previousX = x; previousY = y; } } } void Minimap::findPoint(float lengthPercent, int& x, int& y) const { map<float, pair<int, int>>::const_iterator it = points.upper_bound(lengthPercent); map<float, pair<int, int>>::const_iterator it0 = it; map<float, pair<int, int>>::const_iterator it1 = --it; if(it0 == points.end()) it0 = it1; x = (int)interpolate(lengthPercent, it1->first, it0->first, (float)it1->second.first, (float)it0->second.first); y = (int)interpolate(lengthPercent, it1->first, it0->first, (float)it1->second.second, (float)it0->second.second); x = (int)(x * COURSE_RECT_SCALE); y = (int)(y * COURSE_RECT_SCALE); x += COURSE_RECT_X; y += COURSE_RECT_Y; } void Minimap::renderCarIcons(const ModuleRenderer* moduleRenderer) const { const Car* player = nullptr; for(const Car* car : registeredCars) { assert(car); if(car->getType() == GameObjectType::PLAYER) player = car; else renderCarIcon(car, moduleRenderer); } if(player) renderCarIcon(player, moduleRenderer); } void Minimap::renderCarIcon(const Car* car, const ModuleRenderer* moduleRenderer) const { assert(car); assert(road); assert(moduleRenderer); int w, h; const Texture* t; if(car->getType() == GameObjectType::CAR) { t = enemyCarIcon; w = ENEMY_CAR_ICON_W; h = ENEMY_CAR_ICON_H; } else { t = playerIcon; w = PLAYER_ICON_W; h = PLAYER_ICON_H; } float carPositionZPercent = car->getPosition()->z / road->getLength(); int x, y; findPoint(carPositionZPercent, x, y); SDL_Rect carRect{ (int)(x - w / 2), (int)(y - h / 2), w, h }; assert(t); moduleRenderer->renderTexture(t->t, t->r, &carRect); }
true