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
5390d525dcd34e1deccedd033d1a9b21325b3d67
C++
princejaydai/Rockit_project
/Rockit-project/项目源码/Rockit-master/src/rt_base/rt_dequeue.cpp
UTF-8
3,477
3.109375
3
[ "Apache-2.0" ]
permissive
#include "rt_dequeue.h" #include "rt_header.h" #include "rt_mem.h" RT_Deque* deque_create() { RT_Deque* list = (RT_Deque*)rt_mem_malloc(__FUNCTION__, sizeof(RT_Deque)); if(RT_NULL != list) { list->size = 0; list->head = RT_NULL; list->tail = RT_NULL; } list->entries = RT_NULL; list->max_size = 0; return list; } RT_Deque* deque_create(UINT8 max_size) { RT_Deque* list = deque_create(); RT_ASSERT(RT_NULL != list); list->max_size = max_size; list->entries = rt_malloc_array(RT_DequeEntry, max_size); RT_ASSERT(RT_NULL != list->entries); for(int idx = 0; idx < max_size; idx++) { RT_DequeEntry entry = list->entries[idx]; rt_memset(&entry, RT_NULL, sizeof(RT_DequeEntry)); } return list; } void deque_destory(RT_Deque *list) { RT_ASSERT(RT_NULL != list); RT_DequeEntry* entry = list->head; RT_DequeEntry* next; while(entry){ next = entry->next; rt_free(entry); entry = next; } rt_memset(list, 0, sizeof(RT_Deque)); } RT_DequeEntry* deque_entry_malloc(RT_Deque *list) { RT_ASSERT(RT_NULL != list); RT_DequeEntry *entry = RT_NULL; if( RT_NULL != list->entries ) { if(list->size < list->max_size) { for(int idx = 0; idx < list->max_size; idx++) { entry = &(list->entries[idx]); // found entry in unused pre-malloc entries if((RT_NULL == entry->data)||(ENTRY_FLAG_UNUSE == entry->flag)) { break; } } } else { entry = RT_NULL; } } else { entry = rt_malloc(RT_DequeEntry); } return entry; } RT_DequeEntry* deque_pop(RT_Deque *list) { RT_ASSERT(RT_NULL != list); RT_DequeEntry *entry = RT_NULL; if (deque_size(list) > 0) { entry = list->head; list->head = entry->next; list->size = (list->size>0)?(list->size-1):0; } return entry; } INT8 deque_push(RT_Deque *list, const void *data, RT_BOOL header/*=RT_FALSE*/) { RT_ASSERT(RT_NULL != list); RT_DequeEntry *entry = deque_entry_malloc(list); if (RT_NULL == entry) return RT_ERR_BAD; entry->data = (void *)data; entry->flag = ENTRY_FLAG_USE; entry->next = RT_NULL; if (deque_size(list) == 0) { // insert header, when list is RT_NULL entry->prev = RT_NULL; list->head = entry; list->tail = entry; } else { if(RT_TRUE==header){ RT_DequeEntry* head = list->head; head->prev = entry; entry->next = head; list->head = entry; }else{ RT_DequeEntry* tail = list->tail; tail->next = entry; entry->prev = tail; list->tail = entry; } } list->size++; return RT_OK; } INT8 deque_push_tail(RT_Deque *list, const void *data) { RT_BOOL header = RT_FALSE; return deque_push(list, data, header); } INT8 deque_push_head(RT_Deque *list, const void *data) { RT_BOOL header = RT_TRUE; return deque_push(list, data, header); } void* deque_get(RT_Deque *list, int index) { RT_DequeEntry* entry = list->head; while(RT_NULL != entry){ if(index==0) break; index--; entry = entry->next; } if(RT_NULL == entry) { return RT_NULL; } return entry->data; }
true
d86c259fc17e9381e3ba44496423957f17b9f09e
C++
makuto/horizon
/src/agent/needProcessor.hpp
UTF-8
1,324
2.59375
3
[ "MIT" ]
permissive
#ifndef NEEDPROCESSOR_HPP #define NEEDPROCESSOR_HPP #include <map> #include <base2.0/ept/eptParser.hpp> #include "agent.hpp" #include "need.hpp" #include "../world/time.hpp" #include "../object/objectManager.hpp" #include "../object/object.hpp" /* --NeedProcessor-- * NeedProcessors perform all the logic for a type of need. * For example, a simple Hunger NeedProcessor would subtract 10 from the need * every 30 seconds in updateNeed(), then when the need reaches its detriment * threshold, idk (TODO) * * This class is designed to be overloaded to do any custom need logic * */ class NeedProcessor { private: Need defaultNeed; public: int needID; NeedProcessor(); virtual ~NeedProcessor(); //Use this function to set defaults for this need (you must call this!) virtual bool initialize(eptFile* spec); //deltaTime should be the time since this need was last updated virtual int updateNeed(Agent* agent, Object* obj, ObjectManager* objectManager, Need* currentNeed, Time* deltaTime); //Sets the passed need's fields to defaults (specified by defaultNeed) virtual void initNeed(Need* currentNeed); }; //A map of needProcessors with needIDs meant to be their keys typedef std::map<int, NeedProcessor*> NeedProcessorDir; #endif
true
e6394dc020bcaa56b8c54832fb64683fe3ac136f
C++
pratham-0094/100DaysOfCode
/Day-41/BipartGraph.cpp
UTF-8
990
3.234375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; vector<vector<int>> adj; vector<int> col; vector<bool> vis; bool bipart; void color(int u, int curr) { if (col[u] != -1 && col[u] != curr) { bipart = false; return; } col[u] = curr; if (vis[u]) { return; } vis[u] = true; for (auto i : adj[u]) { color(i, curr ^ 1); } } int main() { int n, m; cin >> n >> m; adj = vector<vector<int>>(n); col = vector<int>(n, -1); vis = vector<bool>(n, false); int x, y; for (int i = 0; i < m; i++) { cin >> x >> y; adj[x].push_back(y); adj[y].push_back(x); } for (int i = 0; i < n; i++) { if (!vis[i]) { color(i, 0); } } if (bipart) cout << "graph is bipartite"; else cout << "graph is not bipartite"; return 0; }
true
49f70708cb8502ae8bd5174233dc7485cc71a0ab
C++
volzkzg/Tempus-Fugit-Code-Machine
/TeamTraining/7_24/J.cpp
UTF-8
1,124
2.578125
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int Maxn = 1100; char s[Maxn][600]; int len[Maxn]; const int p = 131; unsigned long long hash[Maxn]; unsigned long long rhash[Maxn]; unsigned long long pow[Maxn * 2]; void getHash(int pos, unsigned long long &h) { h = 0; for(int i = 0; i < len[pos]; ++i) h = h + s[pos][i] * pow[i]; } int check(int a, int b) { long long h1, h2; h1 = h2 = 0; h1 = hash[a] + hash[b] * pow[len[a]]; h2 = rhash[b] + rhash[a] * pow[len[b]]; return h1 == h2; } int main() { pow[0] = 1; for(int i = 1; i < Maxn * 2; ++i) pow[i] = pow[i - 1] * p; int T; scanf("%d", &T); for(int cas = 1; cas <= T; ++cas) { printf("Case #%d: ", cas); int n; scanf("%d", &n); for(int i = 1; i <= n; ++i) { scanf("%s", s[i]); len[i] = strlen(s[i]); getHash(i, hash[i]); reverse(s[i], s[i] + len[i]); getHash(i, rhash[i]); } int ans = 0; for(int i = 1; i <= n; ++i) { for(int j = 1; j <= n; ++j) { if(i == j) continue; if(check(i, j)) { ans++; } } } printf("%d\n", ans); } return 0; }
true
66189c5f6669d3fac2f8099a6cf6f414bb2edfe2
C++
findobj/HelloAndroid
/jni/findobj/train/Tile.cpp
UTF-8
393
3.359375
3
[]
no_license
#include "Tile.h" Tile::Tile(int index) { this->index = index; x = 0; y = 0; } Tile::Tile(int x, int y) { this->x = x; this->y = y; index = 0; } Tile::~Tile() { } bool Tile::equals(Object *obj) { if(obj != NULL) { Tile *tile = (Tile*)obj; if(index == tile->index && x == tile->x && y == tile->y) { return true; } } return false; }
true
7e89fc28e3a5dd20651815232fa835449528b607
C++
zn-ansari/domotics_iot
/finalCode/finalCode.ino
UTF-8
4,450
2.515625
3
[]
no_license
#include <Ethernet.h> #include <PubSubClient.h> byte mac[] = {0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02}; IPAddress server(192, 168, 1, 101); EthernetClient ethClient; PubSubClient client(ethClient); //ultrasonic int trig = 9; int echo = 8; int LED =7; float t = 0, h = 0, hp = 0; //energy float sample1=0; // for voltage float sample2=0; // for current float voltage=0.0; float val; // current callibration float actualval; // read the actual current from ACS 712 float amps=0.0; float totamps=0.0; float avgamps=0.0; float amphr=0.0; float watt=0.0; float enrgy=0.0; char j[5]; void setup() { Serial.begin(9600); client.setServer(server,1883); client.setCallback(callback); Ethernet.begin(mac); pinMode(5,OUTPUT); pinMode(4,OUTPUT); pinMode(3,OUTPUT); pinMode(2,OUTPUT); if(client.connect("catenzClient")) { Serial.println("connected"); } else { Serial.println("not connected"); Serial.println(client.state()); } client.subscribe("12"); client.subscribe("31"); client.subscribe("32"); client.subscribe("33"); pinMode(trig, OUTPUT); pinMode(echo, INPUT); pinMode(LED,OUTPUT); pinMode(9,OUTPUT); } void loop() { client.loop(); water(); energy(); parking(); } void callback(char* topic, byte* payload, unsigned int length) { int mytopic = tpc2int(topic); if(mytopic == 12) { int msg = pyld2int(payload, length); if(msg==121) { digitalWrite(5, HIGH); } else if(msg==120) digitalWrite(5, LOW); } else if(mytopic == 31) { int msg = pyld2int(payload, length); if(msg==311) { digitalWrite(4, HIGH); } else if(msg==310) digitalWrite(4, LOW); } else if(mytopic == 32) { int msg = pyld2int(payload, length); if(msg==321) { digitalWrite(3, HIGH); } else if(msg==320) digitalWrite(3, LOW); } else if(mytopic == 33) { int msg = pyld2int(payload, length); if(msg==331) { digitalWrite(2, HIGH); } else if(msg==330) digitalWrite(2, LOW); } } void water() { // Transmitting pulse digitalWrite(trig, LOW); delayMicroseconds(2); digitalWrite(trig, HIGH); delayMicroseconds(10); digitalWrite(trig, LOW); // Waiting for pulse t = pulseIn(echo, HIGH); // Calculating distance h = t/58; h = h -0; // offset correction h = 18- h; // water height, 0 - 50 cm hp = (h/18)*100; // distance in %, 0-100 % // Sending to computer char* w = data2char(hp); client.publish("11",w); } void energy() { for(int i=0;i<150;i++) { sample1+=analogRead(A2); //read the voltage from the sensor sample2+=analogRead(A3); //read the current from sensor delay(2); } sample1=sample1/150; sample2=sample2/150; voltage=4.669*2*sample1/1000; val =(5.0*sample2)/1024.0; actualval =val-2.5; // offset voltage is 2.5v long milisec = millis(); // calculate time in milliseconds long time=milisec/1000; // convert milliseconds to seconds amps =actualval*10; // 100mv/A from data sheet totamps=totamps+amps; // total amps avgamps=totamps/time; // average amps amphr=(avgamps*time)/3600; // amphour watt =voltage*amps; // power=voltage*current enrgy=(watt*time)/3600; //energy in watt hour char* e = data2char(enrgy); client.publish("21",e); } void parking() { int sensorValue1 = analogRead(A4); float voltage1 = sensorValue1 * (5.0 / 1023.0); Serial.println(voltage1); int sensorValue2 = analogRead(A5); float voltage2 = sensorValue2 * (5.0 / 1023.0); Serial.println(voltage2); if(voltage1>2&&voltage2>2) { client.publish("41","both the"); } else if(voltage1>2) { client.publish("41","A"); } else if(voltage2>2) { client.publish("41","B"); } else if(voltage1>2) { client.publish("41","null"); } } int tpc2int(char* topic) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); int mytopic = atoi (topic); Serial.print(mytopic); return(mytopic); } int pyld2int (byte* payload, unsigned int length) { payload[length] = '\0'; int msg = atoi( (const char *) payload); Serial.print(" = "); Serial.println(msg); return(msg); } char* data2char(float x) { String i = String(x); Serial.println(x); i.toCharArray(j,i.length()+1); return(j); }
true
9c30c69f5270b0a267ca354969d5a417c98337a0
C++
subuju/interview
/reverse_link.cpp
UTF-8
3,551
4.09375
4
[]
no_license
/* C++实现链表逆序打印,链表反转 *如何实现链表逆序,取决于题目的要求。如果面试官只要求打印,一般不改动链表结构为 *好,如果要求改变链表的方向,则需要改变结构,再顺序打印。 * *方法1:只逆序打印,不改变结构。采用递归,到达尾结点时打印输出,否则进入下一个 *结点的递归,当递归一层层退出的时候,便可以实现从尾到头的打印。 * *方法2:头插法:改变结构。从第二个结点开始往后,依次把每个结点移至链表头部,要注 *意最后链表不要是断裂的 * *方法3:改变指针方向。从头结点开始,依次把结点的next指针断开并指向该结点的前结点 *要注意保存好前结点,当前结点和下一个结点 * *方法4:只逆序打印,不改变结构。利用栈的后进先出来实现逆序 * *注意:链表为空,链表只有一个结点的情况 */ #include <iostream> #include <stack> using namespace std; struct ListNode { int value; ListNode *next; }; //递归实现逆序打印(不改变链表结构) void ReversePrint(ListNode *pHead) { if(pHead!=NULL) { if(pHead->next!=NULL) ReversePrint(pHead->next); cout<<pHead->value<<" "; } } //头插法(改变链表结构) ListNode* ReverseList1(ListNode *pHead) { if(pHead==NULL) return NULL; ListNode *p=pHead->next; ListNode *newHead=pHead; while(p!=NULL)//将p结点移到链表最前方 { pHead->next=p->next;//头结点指向p的下一个结点 p->next=newHead;//p插入链表最前方 newHead=p;//链表新头结点更新为p p=pHead->next;//处理下一个结点,该结点位于头结点后 } return newHead; } //依次改变指针方向(改变链表结构) ListNode *ReverseList2(ListNode *pHead) { ListNode *pre=NULL; ListNode *p=NULL; while(pHead!=NULL) { p=pHead->next;//保存剩余链表 pHead->next=pre;//断开剩余链表头结点pHead,指向pre pre=pHead;//pre更新 pHead=p;//head更新 } return pre; } //利用一个栈逆序输出单链表(不改变链表结构) void printListFromTailToHead(ListNode *pHead) { stack<ListNode*> nodes; ListNode *p=pHead; while(p!=NULL) { nodes.push(p); p=p->next; } while(!nodes.empty()) { p=nodes.top(); cout<<p->value<<" "; nodes.pop(); } } int main() { int n; cin>>n; ListNode* head=NULL; ListNode* p=NULL; ListNode* q=NULL; for(int i=0;i<n;i++) { q=new ListNode; cin>>q->value; if(head==NULL) { head=q; p=head; } else { p->next=q; p=p->next; } } if(head==NULL) return 0; p->next=NULL; cout<<"递归逆序打印:"<<endl; ReversePrint(head); cout<<endl<<"利用栈逆序打印:"<<endl; printListFromTailToHead(head); cout<<endl<<"头插法反转链表:"<<endl; ListNode* reverseHead; reverseHead=ReverseList1(head); p=reverseHead; while(p!=NULL) { cout<<p->value<<" "; p=p->next; } cout<<endl<<"改变指针方向反转链表(将链表再次反转):"<<endl; p=ReverseList2(reverseHead); while(p!=NULL) { cout<<p->value<<" "; q=p; p=p->next; delete q; } cout<<endl; return 0; }
true
dcc9bcd57f663c290a2552602970ef76b744e210
C++
LineageOS/android_frameworks_native
/libs/vr/libdvr/include/dvr/dvr_deleter.h
UTF-8
3,262
2.5625
3
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
#ifndef ANDROID_DVR_DELETER_H_ #define ANDROID_DVR_DELETER_H_ #include <sys/cdefs.h> #include <memory> // Header-only C++ helper to delete opaque DVR objects. __BEGIN_DECLS // Use forward declarations to avoid dependency on other headers. typedef struct DvrBuffer DvrBuffer; typedef struct DvrReadBuffer DvrReadBuffer; typedef struct DvrWriteBuffer DvrWriteBuffer; typedef struct DvrReadBufferQueue DvrReadBufferQueue; typedef struct DvrWriteBufferQueue DvrWriteBufferQueue; typedef struct DvrDisplayManager DvrDisplayManager; typedef struct DvrSurfaceState DvrSurfaceState; typedef struct DvrSurface DvrSurface; typedef struct DvrHwcClient DvrHwcClient; typedef struct DvrHwcFrame DvrHwcFrame; void dvrBufferDestroy(DvrBuffer* buffer); void dvrReadBufferDestroy(DvrReadBuffer* read_buffer); void dvrWriteBufferDestroy(DvrWriteBuffer* write_buffer); void dvrReadBufferQueueDestroy(DvrReadBufferQueue* read_queue); void dvrWriteBufferQueueDestroy(DvrWriteBufferQueue* write_queue); void dvrDisplayManagerDestroy(DvrDisplayManager* client); void dvrSurfaceStateDestroy(DvrSurfaceState* surface_state); void dvrSurfaceDestroy(DvrSurface* surface); void dvrHwcClientDestroy(DvrHwcClient* client); void dvrHwcFrameDestroy(DvrHwcFrame* frame); __END_DECLS // Avoid errors if this header is included in C code. #if defined(__cplusplus) namespace android { namespace dvr { // Universal DVR object deleter. May be passed to smart pointer types to handle // deletion of DVR API objects. struct DvrObjectDeleter { void operator()(DvrBuffer* p) { dvrBufferDestroy(p); } void operator()(DvrReadBuffer* p) { dvrReadBufferDestroy(p); } void operator()(DvrWriteBuffer* p) { dvrWriteBufferDestroy(p); } void operator()(DvrReadBufferQueue* p) { dvrReadBufferQueueDestroy(p); } void operator()(DvrWriteBufferQueue* p) { dvrWriteBufferQueueDestroy(p); } void operator()(DvrDisplayManager* p) { dvrDisplayManagerDestroy(p); } void operator()(DvrSurfaceState* p) { dvrSurfaceStateDestroy(p); } void operator()(DvrSurface* p) { dvrSurfaceDestroy(p); } void operator()(DvrHwcClient* p) { dvrHwcClientDestroy(p); } void operator()(DvrHwcFrame* p) { dvrHwcFrameDestroy(p); } }; // Helper to define unique pointers for DVR object types. template <typename T> using MakeUniqueDvrPointer = std::unique_ptr<T, DvrObjectDeleter>; // Unique pointer types for DVR objects. using UniqueDvrBuffer = MakeUniqueDvrPointer<DvrBuffer>; using UniqueDvrReadBuffer = MakeUniqueDvrPointer<DvrReadBuffer>; using UniqueDvrWriteBuffer = MakeUniqueDvrPointer<DvrWriteBuffer>; using UniqueDvrReadBufferQueue = MakeUniqueDvrPointer<DvrReadBufferQueue>; using UniqueDvrWriteBufferQueue = MakeUniqueDvrPointer<DvrWriteBufferQueue>; using UniqueDvrDisplayManager = MakeUniqueDvrPointer<DvrDisplayManager>; using UniqueDvrSurfaceState = MakeUniqueDvrPointer<DvrSurfaceState>; using UniqueDvrSurface = MakeUniqueDvrPointer<DvrSurface>; using UniqueDvrHwcClient = MakeUniqueDvrPointer<DvrHwcClient>; using UniqueDvrHwcFrame = MakeUniqueDvrPointer<DvrHwcFrame>; // TODO(eieio): Add an adapter for std::shared_ptr that injects the deleter into // the relevant constructors. } // namespace dvr } // namespace android #endif // defined(__cplusplus) #endif // ANDROID_DVR_DELETER_H_
true
5ca52900430ff9ca13102495fccaa389cb6fd2ac
C++
sankalpjain99/LeetCode-July-Challenge
/Week2/Day3-FlattenAMultiLevelDLL.cpp
UTF-8
737
2.96875
3
[]
no_license
/* // Definition for a Node. class Node { public: int val; Node* prev; Node* next; Node* child; }; */ class Solution { public: Node* flatten(Node* head) { if(!head) return NULL; Node* curr=head; while(curr){ if(curr->child){ Node* nt = curr->next; Node* c = curr->child; curr->next = c; c->prev = curr; curr->child =NULL; while(c->next) c=c->next; c->next = nt; if(nt) nt->prev = c; } curr=curr->next; } return head; } };
true
5882b9b7239519fed87cfaa32333b729eae31b22
C++
dipta-dhar/Algorithm-and-DataStructure
/Algorithms/dpAlgorithms/O1_Knapsack.cpp
UTF-8
687
2.984375
3
[ "MIT" ]
permissive
#include<cstdio> #define max(a,b) ((a)>(b) ? (a):(b)) using namespace std; int knapSack(int MW, int weight[], int price[], int N) { int i,w; int K[N+1][MW+1]; for(i=0; i<=N; i++) { for(w=0; w<=MW; w++) { if (i==0 || w==0) K[i][w] = 0; else if (weight[i-1] <= w) K[i][w] = max(price[i-1]+K[i-1][w-weight[i-1]], K[i-1][w]); else K[i][w] = K[i-1][w]; } } return K[N][MW]; } int main() { int price[] = {60, 100, 120}; int weight[] = {2, 1, 4}; int MW = 6; int N = sizeof(price)/sizeof(price[0]); printf("%d", knapSack(MW, weight, price, N)); return 0; }
true
0f6eca895eedec18ae215677861fba98fbcaeba7
C++
MasterJH5574/CS158-DS-Project
/vector/data/two.memcheck/code.cpp
UTF-8
451
2.515625
3
[]
no_license
#include "vector.hpp" #include <iostream> #include <vector> int main() { sjtu::vector<long long> v; for (long long i = 0; i < 1LL << 10; ++i) { v.push_back(i); } std::cout << v.back() << std::endl; for (long long i = 0; i < 1LL << 10; ++i) { v.insert(v.begin(), i); } for (size_t i = 0; i < 1LL << 10; ++i) { std::cout << v.front() << std::endl; v.erase(v.begin()); } return 0; }
true
86fad4ad8b5c0056cbdb00097258fcf26e4dccac
C++
treejames/arrayfire
/include/af/blas.h
UTF-8
5,347
2.90625
3
[ "BSD-3-Clause" ]
permissive
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ /** \file blas.h * * Contains BLAS related functions * * Contains functions for basic BLAS functionallity */ #pragma once #include "af/defines.h" #ifdef __cplusplus extern "C" { #endif /** \ingroup blas_func_matmul */ typedef enum af_transpose_enum { AF_NO_TRANSPOSE, AF_TRANSPOSE, AF_CONJUGATE_TRANSPOSE } af_blas_transpose; #ifdef __cplusplus } #endif #ifdef __cplusplus namespace af { class array; /** \brief Matrix multiply on two arrays \copydetails blas_func_matmul \param[in] lhs The array object on the left hand side \param[in] rhs The array object on the right hand side \param[in] optLhs Transpose operation before the function is performed \param[in] optRhs Transpose operation before the function is performed \return The result of the matrix multiplication of lhs, rhs \ingroup blas_func_matmul */ AFAPI array matmul(const array &lhs, const array &rhs, af_blas_transpose optLhs = AF_NO_TRANSPOSE, af_blas_transpose optRhs = AF_NO_TRANSPOSE); /** \brief Matrix multiply on two arrays \copydetails blas_func_matmul \param[in] lhs The array object on the left hand side \param[in] rhs The array object on the right hand side \return The result of the matrix multiplication of \p lhs, transpose(\p rhs) \ingroup blas_func_matmul */ AFAPI array matmulNT(const array &lhs, const array &rhs); /** \brief Matrix multiply on two arrays \copydetails blas_func_matmul \param[in] lhs The array object on the left hand side \param[in] rhs The array object on the right hand side \return The result of the matrix multiplication of transpose(\p lhs), \p rhs \ingroup blas_func_matmul */ AFAPI array matmulTN(const array &lhs, const array &rhs); /** \brief Matrix multiply on two arrays \copydetails blas_func_matmul \param[in] lhs The array object on the left hand side \param[in] rhs The array object on the right hand side \return The result of the matrix multiplication of transpose(\p lhs), transpose(\p rhs) \ingroup blas_func_matmul */ AFAPI array matmulTT(const array &lhs, const array &rhs); /** \brief Dot Product Scalar dot product between two vectors. Also referred to as the inner product. \democode{ // compute scalar dot product array x = randu(100), y = randu(100); af_print(dot(x,y)); } \ingroup blas_func_dot */ AFAPI array dot (const array &lhs, const array &rhs, af_blas_transpose optLhs = AF_NO_TRANSPOSE, af_blas_transpose optRhs = AF_NO_TRANSPOSE); /** \brief Transposes a matrix \copydetails blas_func_transpose \param[in] in Input Matrix \param[in] conjugate If true a congugate transposition is performed \return Transposed matrix \ingroup blas_func_transpose */ AFAPI array transpose(const array& in, const bool conjugate = false); /** }@ */ } #endif #ifdef __cplusplus extern "C" { #endif /** \brief Matrix multiply on two \ref af_array \details Performs a matrix multiplication on two arrays (lhs, rhs). \param[out] out Pointer to the output \ref af_array \param[in] lhs A 2D matrix \ref af_array object \param[in] rhs A 2D matrix \ref af_array object \param[in] optLhs Transpose operation before the function is performed \param[in] optRhs Transpose operation before the function is performed \return AF_SUCCESS if the process is successful. \ingroup blas_func_matmul */ AFAPI af_err af_matmul( af_array *out , const af_array lhs, const af_array rhs, af_blas_transpose optLhs, af_blas_transpose optRhs); /** Scalar dot product between two vectors. Also referred to as the inner product. \democode{ // compute scalar dot product array x = randu(100), y = randu(100); print(dot<float>(x,y)); } \ingroup blas_func_dot */ AFAPI af_err af_dot( af_array *out, const af_array lhs, const af_array rhs, af_blas_transpose optLhs, af_blas_transpose optRhs); /** \brief Transposes a matrix This funciton will tranpose the matrix in. \param[out] out The transposed matrix \param[in] in Input matrix which will be transposed \param[in] conjugate Perform a congugate transposition \return AF_SUCCESS if the process is successful. \ingroup blas_func_transpose */ AFAPI af_err af_transpose(af_array *out, af_array in, const bool conjugate); #ifdef __cplusplus } #endif
true
e7754e4cb13844d5a3bdd646d68252afdc071ef6
C++
johnbower2012/devel
/scripts/calculations/emulator/observables_class.cpp
UTF-8
10,718
2.859375
3
[]
no_license
#include<iostream> #include<fstream> #include<cmath> #include "armadillo" void tilde_function(const arma::mat &matrix, const arma::vec &error, arma::vec &mean, arma::mat &tilde); void tilde_function(const arma::mat &matrix, arma::mat &covariance, arma::vec &mean, arma::mat &tilde); void covariance_function(const arma::mat &matrix, arma::mat &covariance); void sort_eigen_function(arma::vec &eigval, arma::mat &eigvec); double zeroth_moment(const arma::mat &function); double first_moment(const arma::mat &function); double second_moment(const arma::mat &function); void obs_matrix_moments(int files, int obs_file, arma::mat *&val_matrix, const arma::vec &delY_vec, arma::mat &obs_matrix); double zeroth_moment_fabs(const arma::mat &function); double first_moment_fabs(const arma::mat &function); double second_moment_fabs(const arma::mat &function); void obs_matrix_moments_fabs(int files, int obs_file, arma::mat *&val_matrix, const arma::vec &delY_vec, arma::mat &obs_matrix); arma::vec average_columns(arma::mat input); void load_file(int files, int lines, int runs, std::string *&infilename, arma::vec &delY_vec, arma::mat *&val_matrix); void print_file(std::string outfilename, std::string title, arma::vec vector); void print_file(std::string outfilename, arma::vec vector); void print_file(std::string outfilename, std::string title, arma::mat matrix); void print_file(std::string outfilename, arma::mat matrix); void print_fractional_sum(arma::vec vector); /****** Functions to create the y~ matrix and conduct PCA ******/ //calculate y_tilde, with zero mean and std divided by error, i.e. [z = (y-ybar)/error] void tilde_function(const arma::mat &matrix, const arma::vec &error, arma::vec &mean, arma::mat &tilde){ int repetitions = matrix.n_rows; int observables = matrix.n_cols; mean = arma::zeros<arma::vec>(observables); tilde = arma::zeros<arma::mat>(repetitions,observables); for(int i=0;i<observables;i++){ for(int j=0;j<repetitions;j++){ mean(i) += matrix(j,i); } mean(i) /= (double) repetitions; } for(int i=0;i<repetitions;i++){ for(int j=0;j<observables;j++){ tilde(i,j) = (matrix(i,j) - mean(j))/error(j); } } } void tilde_function_input(const arma::mat &matrix, const arma::vec &error, arma::vec &mean, arma::mat &tilde){ int repetitions = matrix.n_rows; int observables = matrix.n_cols; tilde = arma::zeros<arma::mat>(repetitions,observables); for(int i=0;i<repetitions;i++){ for(int j=0;j<observables;j++){ tilde(i,j) = (matrix(i,j) - mean(j))/error(j); } } } void covariance_function(const arma::mat &matrix, arma::mat &covariance){ int repetitions = matrix.n_rows; int observables = matrix.n_cols; covariance = arma::zeros<arma::mat>(observables,observables); for(int i=0;i<observables;i++){ for(int j=0;j<observables;j++){ for(int k=0;k<repetitions;k++){ covariance(i,j) += matrix(k,i)*matrix(k,j); } covariance(i,j) /= (double) repetitions; } } } void sort_eigen_function(arma::vec &eigval, arma::mat &eigvec){ int i, j, sort, observables = eigval.n_elem; arma::mat eigsort = arma::zeros<arma::mat>(observables,observables); arma::mat eigval_matrix = arma::zeros<arma::mat>(observables,2); for(i=0;i<observables;i++){ eigval_matrix(i,0) = eigval(i); eigval_matrix(i,1) = i; } eigval_matrix = arma::sort(eigval_matrix, "descending", 0); for(i=0;i<observables;i++){ sort = eigval_matrix(i,1); for(j=0;j<observables;j++){ eigsort(j,i) = eigvec(j,sort); } eigval(i) = eigval_matrix(i,0); } for(i=0;i<observables;i++){ for(j=0;j<observables;j++){ eigvec(i,j) = eigsort(i,j); } } } // END: Functions to create the y~ matrix and conduct PCA /****** Functions for statistics ******/ double zeroth_moment(const arma::mat &function){ int points = function.n_rows - 1; double zero = 0.0, f, dx; for(int i=0;i<points;i++){ f = (function(i+1,1) + function(i,1))/2.0; dx = function(i+1,0) - function(i,0); zero += f*dx; } return zero; } double first_moment(const arma::mat &function){ int points = function.n_rows - 1; double zero = 0.0, first = 0.0, f, x, dx; for(int i=0;i<points;i++){ f = (function(i+1,1) + function(i,1))/2.0; dx = function(i+1,0) - function(i,0); zero += f*dx; } for(int i=0;i<points;i++){ f = (function(i+1,1) + function(i,1))/2.0; x = (function(i+1,0) + function(i,0))/2.0; dx = function(i+1,0) - function(i,0); first += f*x*dx; } first /= zero; return first; } double second_moment(const arma::mat &function){ int points = function.n_rows - 1; double zero = 0.0, first = 0.0, second = 0.0; double f, x, dx; for(int i=0;i<points;i++){ f = (function(i+1,1) + function(i,1))/2.0; dx = function(i+1,0) - function(i,0); zero += f*dx; } for(int i=0;i<points;i++){ f = (function(i+1,1) + function(i,1))/2.0; x = (function(i+1,0) + function(i,0))/2.0; dx = function(i+1,0) - function(i,0); first += f*x*dx; } first /= zero; for(int i=0;i<points;i++){ f = (function(i+1,1) + function(i,1))/2.0; x = (function(i+1,0) + function(i,0))/2.0; dx = function(i+1,0) - function(i,0); second += (x - first)*(x - first)*f*dx; } second /= zero; return second; } void obs_matrix_moments(int files, int obs_file, arma::mat *&val_matrix, const arma::vec &delY_vec, arma::mat &obs_matrix){ int i,j,k; int runs = val_matrix[0].n_rows; int lines = delY_vec.n_elem; arma::mat function = arma::zeros<arma::mat>(lines,2); obs_matrix = arma::zeros<arma::mat>(runs,obs_file*files); for(i=0;i<files;i++){ for(j=0;j<runs;j++){ for(k=0;k<lines;k++){ function(k,0) = delY_vec(k); function(k,1) = val_matrix[i](j,k); } obs_matrix(j,i*obs_file) = zeroth_moment(function); obs_matrix(j,i*obs_file+1) = first_moment(function); obs_matrix(j,i*obs_file+2) = second_moment(function); } } } //ABS VERSIONS double zeroth_moment_fabs(const arma::mat &function){ int points = function.n_rows - 1; double zero = 0.0, f, dx; for(int i=0;i<points;i++){ f = fabs(function(i+1,1) + function(i,1))/2.0; dx = function(i+1,0) - function(i,0); zero += f*dx; } return zero; } double first_moment_fabs(const arma::mat &function){ int points = function.n_rows - 1; double zero = 0.0, first = 0.0, f, x, dx; for(int i=0;i<points;i++){ f = fabs(function(i+1,1) + function(i,1))/2.0; dx = function(i+1,0) - function(i,0); zero += f*dx; } for(int i=0;i<points;i++){ f = (function(i+1,1) + function(i,1))/2.0; x = (function(i+1,0) + function(i,0))/2.0; dx = function(i+1,0) - function(i,0); first += f*x*dx; } // first /= zero; return first; } double second_moment_fabs(const arma::mat &function){ int points = function.n_rows - 1; double zero = 0.0, first = 0.0, second = 0.0; double f, x, dx; for(int i=0;i<points;i++){ f = fabs(function(i+1,1) + function(i,1))/2.0; dx = function(i+1,0) - function(i,0); zero += f*dx; } for(int i=0;i<points;i++){ f = (function(i+1,1) + function(i,1))/2.0; x = (function(i+1,0) + function(i,0))/2.0; dx = function(i+1,0) - function(i,0); first += f*x*dx; } // first /= zero; for(int i=0;i<points;i++){ f = (function(i+1,1) + function(i,1))/2.0; x = (function(i+1,0) + function(i,0))/2.0; dx = function(i+1,0) - function(i,0); second += (x - first)*(x - first)*f*dx; } // second /= zero; return second; } void obs_matrix_moments_fabs(int files, int obs_file, arma::mat *&val_matrix, const arma::vec &delY_vec, arma::mat &obs_matrix){ int i,j,k; int runs = val_matrix[0].n_rows; int lines = delY_vec.n_elem; arma::mat function = arma::zeros<arma::mat>(lines,2); obs_matrix = arma::zeros<arma::mat>(runs,obs_file*files); for(i=0;i<files;i++){ for(j=0;j<runs;j++){ for(k=0;k<lines;k++){ function(k,0) = delY_vec(k); function(k,1) = val_matrix[i](j,k); } obs_matrix(j,i*obs_file) = zeroth_moment_fabs(function); obs_matrix(j,i*obs_file+1) = first_moment_fabs(function); obs_matrix(j,i*obs_file+2) = second_moment_fabs(function); } } } // END: Functions for statistics arma::vec average_columns(arma::mat input){ int rows = input.n_rows; int columns = input.n_cols; arma::vec avg = arma::zeros<arma::vec>(columns); for(int i=0;i<columns;i++){ for(int j=0;j<rows;j++){ avg(i) += input(j,i); } avg(i) /= (double) rows; } return avg; } void load_file(int files, int lines, int runs, std::string *&infilename, arma::vec &delY_vec, arma::mat *&val_matrix){ std::ifstream ifile; if(val_matrix!=nullptr){ delete[] val_matrix; } val_matrix = new arma::mat[files]; int i, j, k; for(i=0;i<files;i++){ val_matrix[i] = arma::zeros<arma::mat>(runs,lines); ifile.open(infilename[i]); printf("+++++ %s LOADED +++++\n", infilename[i].c_str()); for(j=0;j<lines;j++){ for(k=0;k<runs+1;k++){ if(k==0){ ifile >> delY_vec(j); } else{ ifile >> val_matrix[i](k-1,j); } } } ifile.close(); } } void print_file(std::string outfilename, std::string title, arma::vec vector){ int elem = vector.n_elem; std::ofstream ofile; ofile.open(outfilename); ofile << title.c_str() << '\n'; for(int i=0;i<elem;i++){ ofile << ' ' << vector(i) << '\n'; } ofile.close(); } void print_file(std::string outfilename, arma::vec vector){ int elem = vector.n_elem; std::ofstream ofile; ofile.open(outfilename); for(int i=0;i<elem;i++){ ofile << ' ' << vector(i) << '\n'; } ofile.close(); } void print_file(std::string outfilename, std::string title, arma::mat matrix){ int rows = matrix.n_rows; int cols = matrix.n_cols; std::ofstream ofile; ofile.open(outfilename); ofile << title.c_str() << '\n'; for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ ofile << ' ' << matrix(i,j); } ofile << '\n'; } ofile.close(); } void print_file(std::string outfilename, arma::mat matrix){ int rows = matrix.n_rows; int cols = matrix.n_cols; std::ofstream ofile; ofile.open(outfilename); for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ ofile << ' ' << matrix(i,j); } ofile << '\n'; } ofile.close(); } //print running fractional total of vector void print_fractional_sum(arma::vec vector){ int length = vector.n_elem; arma::vec sum = arma::zeros<arma::vec>(length); for(int i=0;i<length;i++){ sum(i) = vector(i); sum(i) += sum(abs(i-1)); } for(int i=0;i<length;i++){ sum(i) /= sum(length-1); } sum.print("+++++ eigval fractional sum +++++"); }
true
c1fe2d1cb6dc2114180b7eac59e1c942cbc14dfd
C++
zoyanhui/leetcode
/2013/Reverse Integer.cpp
UTF-8
498
2.90625
3
[]
no_license
class Solution { public: int reverse(int x) { // Start typing your C/C++ solution below // DO NOT write int main() function if(x == 0) return x; bool isPos = true; if(x<0) { isPos = false; x = -x;} int ans = 0; while(x) { ans *= 10; ans += x%10; x /= 10; } if(isPos) return ans; else return -ans; } };
true
ce85d5d7fa0ae26f87e0aee9b4a4eaedd73051e2
C++
mahongquan/java-jni
/src2/DownloadModule.h
GB18030
766
2.53125
3
[]
no_license
#ifndef DOWNLOAD_MODULE_H #define DOWNLOAD_MODULE_H #include <string> #include "curl/curl.h" using namespace std; class DownLoadModule { public: DownLoadModule(); virtual ~DownLoadModule(); static void Init(); static void Cleanup(); public: static size_t DownLoadPackage(void *ptr, size_t size, size_t nmemb, void *userdata); private: long GetLocalFileLenth(const string& strFileName); public: /* * param1 string ļurlַ * param2 string ص· עҪ/β * param3 string غļ * return 0 سɹ/-1ʼʧ/Ϊcurlش * */ int DownLoad(std::string strUrl, std::string strStoragePath, std::string strFileName); private: CURL *m_pCurl; }; #endif
true
e1cdb492926330354a38ea895aa5391171cd0caa
C++
himanshudangre/CPP-Codes
/remove_duplicates_in_link_list.cpp
UTF-8
936
3.546875
4
[]
no_license
#include<stdio.h> #include<stdlib.h> struct node { int daa; struct node *next; }*first = NULL; //fun for creating a lik=nked list void create ( int A[],int n) { int i; struct node *t,*last; first = (struct node*)malloc(sizeof(struct node)); first->data=A[0]; first ->next=NULL; last =first; for(i=1;i<n;i++) { t=(struct node*)malloc(sizeof(struct node)); t->data=A[i]; t->next = NULL; last->next=t; last=t; } } void rdisplay(struct node *p) { if(p!=NULL) { printf("%d ",p->data); rdisplay(p->next); } } void removeduplicate(struct node *p) { struct node *q=p->next; while (q!=NULL) { if(p->data!=q->data) { p=q; q=q->next; } else { p->next=q->next; free(q); q=p->next; } } } int main() { int A[]={1,2,3,4,5,6,6}; create(A,7); removeduplicate(first); rdisplay(first); return 0; }
true
2ea32cce43f4f23ba480961292577eacfe67ef69
C++
alex-tifrea/Review_summarizer
/IO.h
UTF-8
1,141
2.859375
3
[]
no_license
#ifndef __IO_H__ #define __IO_H__ #include <iostream> #include <fstream> #include <string> #include <vector> #include <unordered_map> struct WordInfo_t { unsigned int frequency; std::string partOfSpeech; }; typedef struct WordInfo_t WordInfo; struct WordPosition{ int review_nr, word_nr; WordPosition(int a, int b) { review_nr = a; word_nr = b; } }; class IO { private: std::string in_name, out_name; std::fstream in; std::fstream out; int total_sentences_nr; public: IO(std::string _in_name, std::string _out_name); IO(IO*); ~IO(); /* * Read reviews from file. */ void readReviews(std::unordered_map<std::string, WordInfo> &wordInfo, std::vector<std::vector<std::string> > &reviews); void readReviews(std::unordered_map<std::string, WordInfo> &wordInfo, std::vector<std::vector<std::string> > &reviews, std::unordered_map<std::string, std::vector<WordPosition> > &word_positions); int get_sentences_nr() { return total_sentences_nr; } }; #endif // __IO_H__
true
54aa8f381b9962c7432a4b407af72967a75c146b
C++
amitchhajer/interviewstreet
/cs3/ncr.cc
UTF-8
675
2.5625
3
[]
no_license
#include<stdio.h> #include<math.h> #include <iostream> using namespace std; int main() { unsigned long long int t,i,n,r,c,num = 1,den = 1,temp; cin>>t; for(i=0;i<t;i++) { cin>>n; cin>>r; if(r > n) cout<<"\n0"; if(n == 0) cout<<"\n0"; c = n-r; if(c > r) { temp = r; r = c; c = temp; } for(i=r+1;i<=n; i++) { num = (num * i)%142857; } cout<<num<<"\n"; for(i=2;i<=c;i++) { den = (den * i)%142857; } cout<<den; cout<<"\n"; cout<<num/den; } return 0; }
true
640372889421207db0d541dfc24797e0c549470f
C++
myrealMVP/Compilers
/Token.cpp
GB18030
35,369
3.1875
3
[]
no_license
#include <iostream> #include <string.h> #include <deque> #include <cmath> #include <string> #include <vector> #include <fstream> #include <iomanip> #define INPUT_PATH "testfile.txt" #define OUTPUT_PATH "output.txt" using namespace std; /* Ķǹؼֺͽ ӹؼֺͽ 1.K / P ӦĹؼֺͽ 2. KEY_NUM / PRA_NUM */ #define KEY_NUM 20 #define PRA_NUM 36 class Token { public: string classification; int index; }; class scanner { public: int identifier_num = 1; int count1_num = 1; // ĸ int count2_num = 1; // ʵĸ int char_num = 1; // ַĸ int string_num = 1; // ַĸ bool FLAG = true; // жϴʷǷϷ vector<string> v; // ȡTOKEN string all_ch; //********************ȫҪָ********************************** //string Ҫ'\0'жϽ // ĴתΪchar* const char* scanner_ptr; bool read_program(); int val(const char ch); bool nextw(Token& token); // ***************************************ؼֱ************************************** string K[KEY_NUM + 1] = { "", // "const", "int", "short", "float", "double", "char", "string", "bool", // "void", "main", "return", // ж "if", "else", // ѭ "do", "while", "for", "break", // "cin", "cout", // ṹ "struct", }; // ***************************************************************************** string P[PRA_NUM + 1] = { "", // ӡˡģ "+", "-", "*", "/", "%", "!", // СڡСڵڡڡڵڡڡ "<", "<=", ">", ">=", "==", "!=", // ֵֺš "=", ";", ",", // ˫Ŀ "++", "--", "+=", "-=", "*=", "/=", "%=", // Բšš "(", ")", "[", "]", "{", "}", // ע "//", // ߼ "&&", "||", // ">>", "<<", // ʶ "#", // š˫ "'", "\"", }; // ***************************************ʶ************************************** string I[50] { "" }; // ***************************************ʵ(int)************************************** int CI[50] { 0 }; // ***************************************ʵ(double)************************************** double CR[50] { 0 }; // ***************************************ַ************************************** char CH[50] { ' ' }; // ***************************************ַ(double)************************************** string ST[50] { "" }; }; bool scanner::read_program() { // testfile.txt ȡ string buf; ifstream in; in.open(INPUT_PATH, ios::in); if (!in.is_open()) { cout << "file not open" << endl; exit(1); } while (getline(in, buf)) { // еĴΪһУȥո all_ch = all_ch + buf; // ӿոΪʹ ؼֺͱʶ뿪 // Ļ ؼֻֻʶ all_ch += '\n'; } in.close(); all_ch += "#"; //string Ҫ'\0'жϽ scanner_ptr = all_ch.c_str(); // ļ ofstream out; out.open(OUTPUT_PATH, ios::out); out.close(); } // ASCIIתΪ int scanner::val(const char ch) { return ch - 48; } // ﷨ĶȡһToken bool scanner::nextw(Token& token) { // ıжǷѾToken(Ϊfalse˳ȡ) bool if_continue = true; while (*scanner_ptr && if_continue) { if (*scanner_ptr == ' ' || *scanner_ptr == '\n' || *scanner_ptr == '\r' || *scanner_ptr == '\t' || *scanner_ptr == '\v' || *scanner_ptr == '\f') { // ոĻֱѡ scanner_ptr++; // ЩתַûTokenҪ if_continue = true; } else if (*scanner_ptr >= 48 && *scanner_ptr <= 57) { // & ʵ // q1 ״̬ɳʼ int n = 0; // ƴβֵ int p = 0; // ƴֵָ int m = 0; // Сλ int t = 0; // ָķ // 1 Ϊ -1 Ϊ int e = 1; // ͱ // 0 Ϊͣ 1 Ϊʵ // q2 ״̬һַ n = n * 10 + val(*scanner_ptr); scanner_ptr++; // жǷΪս while (*scanner_ptr >= '0' && *scanner_ptr <= '9') { // ֱַֹͣ n = n * 10 + val(*scanner_ptr); scanner_ptr++; } // ʱ򣬷Ϊ // 1.һַ'e''.ֱ˳ // 2.ǣôͼ // q3 ״̬ if (*scanner_ptr == '.') { t = 1; // ڳʵ scanner_ptr++; if (*scanner_ptr >= '0' && *scanner_ptr <= '9') { // С󣬺һλҪ֣ʷ n = n * 10 + val(*scanner_ptr); m++; // Сλһλ scanner_ptr++; } else { FLAG = false; break; } while (*scanner_ptr >= '0' && *scanner_ptr <= '9') { // ֱַֹͣ // q4 ״̬ n = n * 10 + val(*scanner_ptr); m++; // Сλһλ scanner_ptr++; } } // q5 ״̬ if (*scanner_ptr == 'e') { t = 1; scanner_ptr++; // +1 -1һǶ'e'жϵģҲû if (*scanner_ptr == '+' || *scanner_ptr == '-') { // q6 ״̬ if (*scanner_ptr == '-') { e = -1; // ָϵΪ-1 } scanner_ptr++; } while (*scanner_ptr >= '0' && *scanner_ptr <= '9') { // ֱַֹͣ // q7 ״̬ p = p * 10 + val(*scanner_ptr); scanner_ptr++; } } // ֵĽ // num ȡֵĽ double num = n * pow(10, e * p - m); if (t == 0) { // Ϊ int i = 1; for (; i < count1_num; i++) { if (num == CI[i]) { // ظĻֱԭе //string tmp = "INTCON " + std::to_string(C1[i]); //v.push_back(tmp); ////printf("(C1 %d)", i); token.classification = "CI"; token.index = i; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "CI" << "," << i << ")" << endl; out.close(); break; } } if (i == count1_num) { //ظĻ벢ӡ CI[count1_num] = num; //string tmp = "INTCON " + std::to_string(C1[count1_num]); //v.push_back(tmp); ////printf("(C1 %d)", count1_num); token.classification = "CI"; token.index = count1_num; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "CI" << "," << count1_num << ")" << endl; out.close(); count1_num++; } } else { // Ϊʵ int i = 1; for (; i < count2_num; i++) { if (num == CR[i]) { // ظĻֱԭе //string tmp = "(C2 " + std::to_string(i) + ")"; //v.push_back(tmp); ////printf("(C2 %d)", i); token.classification = "CR"; token.index = i; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "CR" << "," << i << ")" << endl; out.close(); break; } } if (i == count2_num) { //ظĻ벢ӡ CR[count2_num] = num; //string tmp = "(C2 " + std::to_string(count2_num) + ")"; //v.push_back(tmp); ////printf("(C2 %d)", count2_num); token.classification = "CR"; token.index = count2_num; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "CR" << "," << count2_num << ")" << endl; out.close(); count2_num++; } } } else if (*scanner_ptr == '_' || (*scanner_ptr >= 'a' && *scanner_ptr <= 'z') || (*scanner_ptr >= 'A' && *scanner_ptr <= 'Z')) { char* mystring = new char[20]; // ҪÿοÿͷţϴĻһεĽӰ int length = 0; mystring[length++] = *scanner_ptr; int flag = 1; // ʾǷֻ»ߣһDZʶ // flag = 0 ֱʶ 1ʱҪ ʶ͹ؼ scanner_ptr++; while (*scanner_ptr == '_' || (*scanner_ptr >= 'a' && *scanner_ptr <= 'z') || (*scanner_ptr >= 'A' && *scanner_ptr <= 'Z') || (*scanner_ptr >= '0' && *scanner_ptr <= '9')) { if (*scanner_ptr == '_' || (*scanner_ptr >= '0' && *scanner_ptr <= '9')) { flag = 0; } mystring[length++] = *scanner_ptr; scanner_ptr++; } // һҪһ䣬ܹһַ mystring[length++] = '\0'; // if (flag) { // ؼ bool isfind = false; for (int i = 1; i <= KEY_NUM; i++) { if (mystring == K[i]) { isfind = true; //string tmp = K_name[i] + " " + K[i]; //v.push_back(tmp); ////printf("(K %d)", i); token.classification = "K"; token.index = i; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "K" << "," << i << ")" << endl; //out.close(); break; } } if (!isfind) { // ؼûҵDZʶ int i = 1; for (; i < identifier_num; i++) { if (mystring == I[i] && strlen(mystring) == I[i].length()) { // ظĻֱԭе //string tmp = "IDENFR " + I[i]; //v.push_back(tmp); ////printf("(I %d)", i); token.classification = "I"; token.index = i; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "I" << "," << i << ")" << endl; out.close(); break; } } if (i == identifier_num) { //ظĻ벢ӡ I[identifier_num] = mystring; //string tmp = "IDENFR " + I[identifier_num]; //v.push_back(tmp); ////printf("(I %d)", identifier_num); token.classification = "I"; token.index = identifier_num; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "I" << "," << identifier_num << ")" << endl; out.close(); identifier_num++; } } } else { int i = 1; for (; i < identifier_num; i++) { if (mystring == I[i] && strlen(mystring) == I[i].length()) { // ظĻֱԭе //string tmp = "IDENFR " + I[i]; //v.push_back(tmp); ////printf("(I %d)", i); token.classification = "I"; token.index = i; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "I" << "," << i << ")" << endl; out.close(); break; } } if (i == identifier_num) { //ظĻ벢ӡ I[identifier_num] = mystring; //string tmp = "IDENFR " + I[identifier_num]; //v.push_back(tmp); ////printf("(I %d)", identifier_num); token.classification = "I"; token.index = identifier_num; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "I" << "," << identifier_num << ")" << endl; out.close(); identifier_num++; } } delete[]mystring; mystring = nullptr; } else if ((*scanner_ptr >= 40 && *scanner_ptr <= 45) || *scanner_ptr == 47 || (*scanner_ptr >= 59 && *scanner_ptr <= 62) || (*scanner_ptr >= 123 && *scanner_ptr <= 125) || *scanner_ptr == 33 || *scanner_ptr == 35 || (*scanner_ptr >= 37 && *scanner_ptr <= 38) || *scanner_ptr == 91 || *scanner_ptr == 93) { // жַ if (*scanner_ptr == '=' || *scanner_ptr == '>' || *scanner_ptr == '<' || *scanner_ptr == '!' || *scanner_ptr == '/' || *scanner_ptr == '+' || *scanner_ptr == '-' || *scanner_ptr == '*' || *scanner_ptr == '%') { switch (*scanner_ptr) { case '=': { scanner_ptr++; if (*scanner_ptr == '=') { //string tmp = P_name[9] + " " + P[9]; //v.push_back(tmp); ////printf("(P %d)", 5); token.classification = "P"; token.index = 11; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 11 << ")" << endl; out.close(); scanner_ptr++; } else { //string tmp = P_name[11] + " " + P[11]; //v.push_back(tmp); ////printf("(P %d)", 11); token.classification = "P"; token.index = 13; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 13 << ")" << endl; out.close(); } break; } case '>': { scanner_ptr++; if (*scanner_ptr == '=') { //string tmp = P_name[8] + " " + P[8]; //v.push_back(tmp); ////printf("(P %d)", 14); token.classification = "P"; token.index = 10; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 10 << ")" << endl; out.close(); scanner_ptr++; } else if (*scanner_ptr == '>') { //string tmp = P_name[8] + " " + P[8]; //v.push_back(tmp); ////printf("(P %d)", 14); token.classification = "P"; token.index = 32; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 32 << ")" << endl; out.close(); scanner_ptr++; } else { //string tmp = P_name[7] + " " + P[7]; //v.push_back(tmp); ////printf("(P %d)", 8); token.classification = "P"; token.index = 9; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 9 << ")" << endl; out.close(); } break; } case '<': { scanner_ptr++; if (*scanner_ptr == '=') { //string tmp = P_name[6] + " " + P[6]; //v.push_back(tmp); ////printf("(P %d)", 16); token.classification = "P"; token.index = 8; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 8 << ")" << endl; out.close(); scanner_ptr++; } else if (*scanner_ptr == '<') { //string tmp = P_name[6] + " " + P[6]; //v.push_back(tmp); ////printf("(P %d)", 16); token.classification = "P"; token.index = 33; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 33 << ")" << endl; out.close(); scanner_ptr++; } else { //string tmp = P_name[5] + " " + P[5]; //v.push_back(tmp); ////printf("(P %d)", 7); token.classification = "P"; token.index = 7; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 7 << ")" << endl; out.close(); } break; } case '!': { scanner_ptr++; if (*scanner_ptr == '=') { //string tmp = P_name[10] + " " + P[10]; //v.push_back(tmp); ////printf("(P %d)", 16); token.classification = "P"; token.index = 12; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 12 << ")" << endl; out.close(); scanner_ptr++; } else { /*string tmp = "(P " + std::to_string(7) + ")"; v.push_back(tmp);*/ //printf("(P %d)", 7); token.classification = "P"; token.index = 6; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 6 << ")" << endl; out.close(); } break; } case '/': { scanner_ptr++; if (*scanner_ptr == '/') { // ĵط԰һȫӰToken while (*scanner_ptr != '\n') { scanner_ptr++; } scanner_ptr++; } else if (*scanner_ptr == '=') { //string tmp = P_name[6] + " " + P[6]; //v.push_back(tmp); ////printf("(P %d)", 16); token.classification = "P"; token.index = 21; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 21 << ")" << endl; out.close(); scanner_ptr++; } else { //string tmp = P_name[4] + " " + P[4]; //v.push_back(tmp); ///*printf("(P %d)", 7);*/ token.classification = "P"; token.index = 4; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 4 << ")" << endl; out.close(); } break; } case '%': { scanner_ptr++; if (*scanner_ptr == '=') { //string tmp = P_name[9] + " " + P[9]; //v.push_back(tmp); ////printf("(P %d)", 5); token.classification = "P"; token.index = 22; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 22 << ")" << endl; out.close(); scanner_ptr++; } else { //string tmp = P_name[11] + " " + P[11]; //v.push_back(tmp); ////printf("(P %d)", 11); token.classification = "P"; token.index = 5; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 5 << ")" << endl; out.close(); } break; } case '*': { scanner_ptr++; if (*scanner_ptr == '=') { //string tmp = P_name[9] + " " + P[9]; //v.push_back(tmp); ////printf("(P %d)", 5); token.classification = "P"; token.index = 20; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 20 << ")" << endl; out.close(); scanner_ptr++; } else { //string tmp = P_name[11] + " " + P[11]; //v.push_back(tmp); ////printf("(P %d)", 11); token.classification = "P"; token.index = 3; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 3 << ")" << endl; out.close(); } break; } case '+': { scanner_ptr++; if (*scanner_ptr == '+') { token.classification = "P"; token.index = 16; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 16 << ")" << endl; out.close(); scanner_ptr++; } else if (*scanner_ptr == '=') { //string tmp = P_name[6] + " " + P[6]; //v.push_back(tmp); ////printf("(P %d)", 16); token.classification = "P"; token.index = 18; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 18 << ")" << endl; out.close(); scanner_ptr++; } else { //string tmp = P_name[4] + " " + P[4]; //v.push_back(tmp); ///*printf("(P %d)", 7);*/ token.classification = "P"; token.index = 1; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 1 << ")" << endl; out.close(); } break; } case '-': { scanner_ptr++; if (*scanner_ptr == '-') { token.classification = "P"; token.index = 17; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 17 << ")" << endl; out.close(); scanner_ptr++; } else if (*scanner_ptr == '=') { //string tmp = P_name[6] + " " + P[6]; //v.push_back(tmp); ////printf("(P %d)", 16); token.classification = "P"; token.index = 19; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 19 << ")" << endl; out.close(); scanner_ptr++; } else { //string tmp = P_name[4] + " " + P[4]; //v.push_back(tmp); ///*printf("(P %d)", 7);*/ token.classification = "P"; token.index = 2; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << 2 << ")" << endl; out.close(); } break; } default: break; } } else { // һַ int i = 1; for (; i <= PRA_NUM; i++) { if (*scanner_ptr == P[i][0]) { //string tmp = P_name[i] + " " + P[i]; //v.push_back(tmp); ////printf("(P %d)", i); token.classification = "P"; token.index = i; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "P" << "," << i << ")" << endl; out.close(); break; } } scanner_ptr++; } } else if (*scanner_ptr == 39) { // ַĿʼ' scanner_ptr++; int i = 1; for (; i < char_num; i++) { if (*scanner_ptr == CH[i]) { // ظĻֱԭе //string tmp = "(CT " + std::to_string(i) + ")"; //v.push_back(tmp); ////printf("(CT %d)", i); token.classification = "CH"; token.index = i; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "CH" << "," << i << ")" << endl; out.close(); break; } } if (i == char_num) { //ظĻ벢ӡ CH[char_num] = *scanner_ptr; //string tmp = "(CT " + std::to_string(char_num) + ")"; //v.push_back(tmp); ////printf("(CT %d)", char_num); token.classification = "CH"; token.index = char_num; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "CH" << "," << char_num << ")" << endl; out.close(); char_num++; } scanner_ptr++; // жһַǷΪ if (*scanner_ptr == 39) { // ǵĻٶһ scanner_ptr++; } else { FLAG = false; // ʷ return false; break; } } else if (*scanner_ptr == 34) { // ַĿʼ" string tmp = ""; scanner_ptr++; while (*scanner_ptr != 34) { // " ,һֱȡ tmp += *scanner_ptr; // ָǵú scanner_ptr++; } // Ҫtmp int i = 1; for (; i < string_num; i++) { if (tmp == ST[i]) { // ظĻֱԭе //string tmp = "(ST " + std::to_string(i) + ")"; //v.push_back(tmp); ////printf("(ST %d)", i); token.classification = "ST"; token.index = i; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "ST" << "," << i << ")" << endl; out.close(); break; } } if (i == string_num) { //ظĻ벢ӡ ST[string_num] = tmp; //string tmp = "(ST " + std::to_string(string_num) + ")"; //v.push_back(tmp); ////printf("(ST %d)", string_num); token.classification = "ST"; token.index = string_num; if_continue = false; ofstream out; out.open(OUTPUT_PATH, ios::app); out << "(" << "ST" << "," << string_num << ")" << endl; out.close(); string_num++; } scanner_ptr++; } else { // ڲλö˷Ƿַ FLAG = false; // ǷֵַΪ return false; } } // ⣬Tokenȷ if (*scanner_ptr) { return true; } else { return false; } }
true
f9519e4432390e0561f7a7db8efb543114a424a1
C++
fchurca/fiuba-7542-20152
/src/main/socket/winSocket/winSocket.cpp
ISO-8859-1
3,432
2.75
3
[]
no_license
//----------------------------------------------------------------------------- #include "winSocket.h" //----------------------------------------------------------------------------- using namespace std; shared_ptr<Socket> Socket::create() { //return make_shared<WinSocket>(); return nullptr; } WinSocket::WinSocket() { } //----------------------------------------------------------------------------- WinSocket::~WinSocket() { //if(close(sockfd) == -1) // std::cerr << "ERROR: No se ha podido cerrar el socket." << std::endl } bool WinSocket::Connect(std::string hostIp, int hostPort) { //cerr << "connect()" << endl; // Usamos connect cuando tenemos que conectarnos a un server // Obtenemos host //struct hostent *he = gethostbyname(hostIp.c_str()); //if (!he) { // return false; //} // //// Obtenemos socket //if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { // return false; //} // //// Cargamos datos de la conexin a realizar //memset(&sockaddr, '\0', sizeof(sockaddr)); //sockaddr.sin_family = AF_INET; //sockaddr.sin_port = htons(hostPort); //memcpy(&sockaddr.sin_addr, he->h_addr, he->h_length); // //// Conectamos //if (connect(sockfd, (struct sockaddr *)&sockaddr, sizeof(struct sockaddr)) == -1) { // return false; //} return true; } //----------------------------------------------------------------------------- bool WinSocket::Listen(unsigned int port, int maxConnections) { //sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //if (sockfd < 0) // return false; // //status = true; // //sockaddr.sin_family = AF_INET; //sockaddr.sin_port = htons(port); // //sockaddr.sin_addr.s_addr = htonl(INADDR_ANY); // //if (bind(sockfd, // (struct sockaddr *)&sockaddr, // sizeof(sockaddr)) < 0) //{ // return false; //} // //// Comenzamos la escucha //if (listen(sockfd, maxConnections) < 0) //{ // return false; //} return true; } std::shared_ptr<Socket> WinSocket::Accept() { //cerr << "accept()" << endl; //int sin_size = sizeof(struct sockaddr_in); ////Revisar //auto socket_client = make_shared<WinSocket>(); // //int sockfd_client = accept(sockfd, (struct sockaddr *)&(socket_client->sockaddr), &sin_size); // //socket_client->sockfd = sockfd_client; //// Corroboramos si no se cerr el socket //if (status != 1) return nullptr; // //return socket_client; return nullptr; } //----------------------------------------------------------------------------- void WinSocket::deinit() { this->status = false; } //----------------------------------------------------------------------------- void WinSocket::Activate() { this->status = true; } bool WinSocket::IsActive() { return status; } long WinSocket::Recv(void* data, int dataLenght) { //cerr << "receive()" << endl; //REVISAR //memset(data, '\0', dataLenght); // Recibimos datos en buffer //return recv(sockfd,(char*)data, dataLenght, 0); return 0; } long WinSocket::Send(const void* data, int dataLenght) { ////cerr << "send()" << endl; //// Cantidad de bytes que han sido enviados //int total_bytes = 0; //// Cantidad de bytes que faltan enviar //int residuary_bytes = dataLenght; //// Variable auxiliar //int n; // //while (residuary_bytes > 0) //{ // // Realizamos envo de bytes // n = send(sockfd, (char *)data + total_bytes, residuary_bytes, 0); // // if (n == -1) return -1; // // total_bytes += n; // residuary_bytes -= n; //} // return 0; }
true
4db485319313e4e5da43a634770df6768ac6d814
C++
ToonLunk/ArithmeticTrainer
/main.cpp
UTF-8
7,862
3.875
4
[]
no_license
/* This game was finished by Chase Brock on May 4th, 2021. This program will generate two random numbers, and either mutliply, divide, subtract, or add them together. It will prompt the user with the two numbers, and the user must enter the correct answer. If a correct answer is entered, points are added to the score, and the game continues. If not, the game ends, and a function will check to see if the current score is the highest recorded and if so, replace the current number in highscores.txt with the new, highest score. The player can choose to play the game, view the current high score, or quit the game from the main menu.*/ #include <iostream> #include <ctime> // to make a 'seed' to make random numbers different on each execution #include <cstdlib> // to use rand(); #include <string> // to use strings #include <fstream> // to read/write files using namespace std; void mainMenu(); // the main menu the player will interact with void playGame(int difficulty); // holds the main game function, calls all functions int numGen(int diff); // generates 2 numbers and operates them together void addHighScore(int score); // adds a new high score, if necassary void seeHighScore(); // allows the player to view the current highest score void mainMenu() // main menu for game; wll present user with options for the game { int choice; // holds the user's choice int difficulty; // holds how hard the game should start out cout << "\nPlease select an option: \n1. Play Game. \n2. View High Score. \n3. Quit Game" << endl; cin >> choice; if(choice == 1) { // play game //cout << "\nStarting Game..." << endl; cout << "\nPlease select your difficulty:\n1. Normal. \n2. Hard.\n3. Impossible." << endl; cout << "\nEnter anything else to quit the game." << endl; cin >> difficulty; // get difficulty from user if (cin.fail() || (difficulty != 1 && difficulty != 2 && difficulty !=3)) // input validation { cout << "Thanks for playing!" << endl; exit(2); // 2 = user entered wrong number in difficulty selection } cin.clear(); // clears input log cin.ignore(); // ignores dead space in input log playGame(difficulty); // launch game } else if (choice == 2) { // show high score cin.clear(); cin.ignore(); seeHighScore(); mainMenu(); // go back to menu } else if (choice == 3) { // quit game cout << "Thanks for Playing!" << endl; cin.clear(); // these clear the choice cin.ignore(); } else { cout << "Invalid Option."; cin.clear(); // these two clear the input logs cin.ignore(); mainMenu(); } } void playGame(int uDifficulty) // this is where the game is played, score is kept, and difficulty set { int answer; // holds the correct answer int userAnswer; // holds the user's answer int score = 1; // initialize the player's score int difficulty = (100 * uDifficulty) - 90; // calculates difficluty; gets harder as game progresses- // Starts based on user's selected difficulty. bool isCorrect = true; // a flag to check if answer was correct while(isCorrect) { answer = numGen(difficulty); // get a new question cin >> userAnswer; // get a new answer if (answer == userAnswer) { score += 193 * uDifficulty; // add points based on difficulty difficulty += (5 * uDifficulty); // increase difficulty based on user preference cout << "\nCorrect! Score = " << score << ", difficulty = " << difficulty << endl << endl; } else { cout << "Incorrect! Correct answer was: " << answer << endl; cout << "******************************************************" << endl; cout << "* Your Score: " << score << " point(s). Thanks for Playing! *" << endl; cout << "******************************************************" << endl; seeHighScore(); addHighScore(score); isCorrect = false; } } mainMenu(); // go back to main menu } int numGen(int diff) { int difficulty = diff; srand((unsigned) time(0)); // set a 'seed' to make numbers always random int randomNum1 = rand() % difficulty; // make a random number int randomNum2 = rand() % difficulty; // make another random number int finalNum; // holds the answer that the user must guess int choice = (rand() % 4) + 1; // choose a random num from 1-4 to decide what operator to use if (choice == 1) // multiply { finalNum = randomNum1 * (randomNum2 / 2); cout << "What is " << randomNum1 << " times " << (randomNum2 / 2) << "?" << endl; } else if (choice == 2) // divide { finalNum = randomNum1 / (randomNum2 / 2); cout << "What is " << randomNum1 << " divided by " << (randomNum2 / 2) << "?" << endl; } else if (choice == 3) // add { finalNum = randomNum1 + randomNum2; cout << "What is " << randomNum1 << " plus " << randomNum2 << "?" << endl; } else if (choice ==4) // subtract { finalNum = randomNum1 - randomNum2; cout << "What is " << randomNum1 << " minus " << randomNum2 << "?" << endl; } return finalNum; // return the asnwer } void addHighScore(int score) { int line; // holds the 'current' number in the while loop int highScore = score; // holds the last score of the player /* Create/Read file to hold high scores */ ifstream inFile; // create file object inFile.open("highscores.txt"); // open highscores.txt int temp = 0; // make a temporary variable to find if the current // score was higher than any score in highscores.txt if (inFile.fail()) // if the file doesn't exist, give a proper error { inFile.close(); } else { while(!inFile.eof()) // while there are still things left to read in file { inFile >> line; // go to next line if (line > temp) // if the current line is greater than the temp variable { temp = line; // it becomes the new temp } } inFile.close(); // close the file object } if (highScore > temp) // if the highscore is greater than the biggest score in the file { cout << "New Record! High Score Saved!" << endl; ofstream outFile; // create new file object outFile.open("highscores.txt"); // open the highscores.txt outFile << highScore; // write the highscore to the file outFile.close(); // close the file object } } void seeHighScore() // view high score from highscores.txt { int line; // to hold the current number and display it. ifstream inFile; // create file object inFile.open("highscores.txt"); // open highscores.txt if (inFile.fail()) // if the file doesn't exist, give a proper error { cerr << "highscores.exe does not exist." << endl; exit(1); } while(!inFile.eof()) // while there are still things left to read in file { inFile >> line; // go to next line cout << "The current High Score is: " << line << " Points." << endl; } inFile.close(); // close the file object } int main() { cout << "\nWelcome to the Math Game by Chase Brock! The rules are simple: " << endl; cout << "Enter your answer and press Enter. Helpful tip: In the division section, only enter " << endl; cout << "How many times the number is wholly divisible. For example, the answer to 20 / 8 is '2', and " << endl; cout << "10 / 15 is '0'." << endl; mainMenu(); return 0; }
true
c1684d53d91130001cad1167999702aa6fddbedf
C++
molvin/Planets-OpenGL
/ShaderMathAssignment/src/Graphics/Texture.cpp
UTF-8
1,863
3.046875
3
[]
no_license
#include "Texture.h" #include <SOIL.h> Texture::Texture(const float* pixels, const int width, const int height) : _width(width), _height(height) { glCreateTextures(GL_TEXTURE_2D, 1, &TextureId); glBindTexture(GL_TEXTURE_2D, TextureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _width, _height, 0, GL_RGBA, GL_FLOAT, pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); } Texture::Texture(const std::string& path) { unsigned char* pixels = SOIL_load_image(path.c_str(), &_width, &_height, &_channels, SOIL_LOAD_RGBA); SwizzleRows(pixels); glCreateTextures(GL_TEXTURE_2D, 1, &TextureId); glBindTexture(GL_TEXTURE_2D, TextureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _width, _height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); SOIL_free_image_data(pixels); } Texture::~Texture() { glDeleteTextures(1, &TextureId); } void Texture::Bind(const int slot) const { glBindTextureUnit(slot, TextureId); } void Texture::SwizzleRows(unsigned char* data) const { const int rowSize = _width * 4; auto* temp = new unsigned char[rowSize]; const int iterations = _height / 2; for(int i = 0; i < iterations; i++) { unsigned char* source = data + rowSize * i; unsigned char* target = data + rowSize * (_height - i - 1); memcpy(temp, source, rowSize); memcpy(source, target, rowSize); memcpy(target, temp, rowSize); } delete[] temp; }
true
13b459e7e6bd888dfc89a7b9a1977bcfe9dc39d6
C++
hoang-khoi/tksort
/TaskNode.cpp
UTF-8
645
3.21875
3
[]
no_license
#include "TaskNode.h" #include <ostream> #include <utility> TaskNode::TaskNode(std::string name) : name(std::move(name)) {} void TaskNode::depends(TaskNode &other) { other.dependant.push_back(this); } std::ostream &operator<<(std::ostream &out, const TaskNode &taskNode) { out << "Task: " << taskNode.name << ". Dependants: " << taskNode.dependant.size(); for (TaskNode *dependant : taskNode.dependant) { out << '\n' << dependant->getName(); } return out; } const std::string &TaskNode::getName() const { return name; } const std::list<TaskNode *> &TaskNode::getDependant() const { return dependant; }
true
b82b20f3e29249eb9c7dc40d78d25bc39f089dd9
C++
CJHMPower/Fetch_Leetcode
/data/Submission/651 4 Keys Keyboard/4 Keys Keyboard_1.cpp
UTF-8
1,478
2.875
3
[]
no_license
//-*- coding:utf-8 -*- // Generated by the Fetch-Leetcode project on the Github // https://github.com/CJHMPower/Fetch-Leetcode/ // 651 4 Keys Keyboard // https://leetcode.com//problems/4-keys-keyboard/description/ // Fetched at 2018-07-24 // Submitted 5 months, 1 week ago // Runtime: 3 ms // This solution defeats 9.69% cpp solutions class Solution { public: int maxA(int N) { vector<int> dp; vector<int> ctrl; dp.push_back(0); ctrl.push_back(0); if (N <= 6) { return N; } for (int i = 1; i <= 5; i++) { dp.push_back(i); ctrl.push_back(0); } for (int i = 6; i <= N; i++) { int cmp = 0; int ctrl_cmp = 0; if (dp[i - 1] + ctrl[i - 1] > cmp || (dp[i - 1] + ctrl[i - 1] == cmp && ctrl[i - 1] > ctrl_cmp)) { cmp = dp[i - 1] + ctrl[i - 1]; ctrl_cmp = ctrl[i - 1]; } if (dp[i - 2] + 2 * ctrl[i - 2] > cmp || (dp[i - 2] + 2 * ctrl[i - 2] == cmp && ctrl[i - 2] > ctrl_cmp)) { cmp = dp[i - 2] + 2 * ctrl[i - 2]; ctrl_cmp = ctrl[i - 2]; } int value = dp[i - 3] * 2; if (value > cmp || (value == cmp && dp[i - 3] > ctrl_cmp)) { cmp = value; ctrl_cmp = dp[i - 3]; } value = dp[i - 4] * 3; if (value > cmp || (value == cmp && dp[i - 4] > ctrl_cmp)) { cmp = value; ctrl_cmp = dp[i - 4]; } dp.push_back(cmp); ctrl.push_back(ctrl_cmp); } return dp[N]; } };
true
124898b6d59ec586e66968fa949945d4858b8ab1
C++
pabloarizaluna/unreal-course
/Section_2/TripleX.cxx
UTF-8
1,900
3.296875
3
[ "MIT" ]
permissive
#include <iostream> #include <random> void PrintIntroduction(const int&); bool PlayGame(const int&); int main() { bool bLevelComplete; int LevelDifficulty = 1; const int MaxDifficulty = 5; while (LevelDifficulty <= MaxDifficulty) // Loop game until all levels completed { bLevelComplete = PlayGame(LevelDifficulty); std::cin.clear(); // Clears any errors std::cin.ignore(); // Discards the buffer if (bLevelComplete) ++LevelDifficulty; else LevelDifficulty = 1; } std::cout << "***you've decode all message, now you know everything***"; std::cout << std::endl; return 0; } bool PlayGame(const int& Difficulty) { PrintIntroduction(Difficulty); int Mask = 0; for(int i = 1; i <= Difficulty; i++) { Mask = Mask << 4; Mask += 0xf; } //Prepare the random number generator std::random_device RandomDevice; std::mt19937 MersenneTwister(RandomDevice()); std::uniform_int_distribution<> IntDist(0, Mask); const int Message = IntDist(MersenneTwister); int Complement = Message ^ Mask; std::cout << "+ The message is: " << Message << std::endl; std::cout << "+ The disguise is: " << Mask << std::endl << std::endl; int PlayerGuess; std::cin >> PlayerGuess; bool result = false; if (Complement == PlayerGuess) { result = true; std::cout << "You decode The message, for now you still alive" << std::endl; } else { std::cout << std::endl; std::cout << "++You died cause you didn't know the message++" << std::endl; std::cout << "++Try Again++" << std::endl; } std::cout << std::endl; return result; } void PrintIntroduction(const int& Difficulty) { std::cout << "You are a secret agent decoding a level " << Difficulty; std::cout << " secrect message..." << std::endl; std::cout << "Enter the correct code to continue..."; std::cout << std::endl << std::endl; }
true
6c55b4172a70299b00c67e1df75ad872ee3e8e31
C++
YernurSFU/libflow
/include/flow/op/reverse.hpp
UTF-8
1,491
3.125
3
[]
no_license
#ifndef FLOW_OP_REVERSE_HPP_INCLUDED #define FLOW_OP_REVERSE_HPP_INCLUDED #include <flow/core/flow_base.hpp> namespace flow { namespace detail { template <typename Flow> struct reverse_adaptor : flow_base<reverse_adaptor<Flow>> { constexpr explicit reverse_adaptor(Flow&& flow) : flow_(std::move(flow)) {} constexpr auto next() -> next_t<Flow> { return flow_.next_back(); } constexpr auto next_back() -> next_t<Flow> { return flow_.next(); } template <bool B = is_sized_flow<Flow>> constexpr auto size() const -> std::enable_if_t<B, dist_t> { return flow_.size(); } template <typename F = Flow, typename = std::enable_if_t<is_multipass_flow<F>>> constexpr auto subflow() const -> reverse_adaptor<subflow_t<F>> { return reverse_adaptor<Flow>{flow_.subflow()}; } constexpr auto reverse() && -> Flow { return std::move(*this).flow_; } private: Flow flow_; }; } inline constexpr auto reverse = [](auto&& flowable) { static_assert(is_flowable<decltype(flowable)>, "Argument to flows::reverse() must be a Flowable type"); return FLOW_COPY(flow::from(FLOW_FWD(flowable))).reverse(); }; template <typename D> constexpr auto flow_base<D>::reverse() && { static_assert(is_reversible_flow<D>, "reverse() requires a reversible flow"); return detail::reverse_adaptor<D>{consume()}; } } #endif
true
45561e3e105be1fbe1cbbfe24d7bf783f548e64a
C++
liuxinyu123/socket
/socket7/server_client/client.cpp
UTF-8
1,019
2.578125
3
[]
no_license
#include <iostream> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <cstring> #include <unistd.h> #include <cstdio> using std::cout; using std::endl; using std::cerr; int main (int argc, char *argv[]) { int sock = socket (PF_INET, SOCK_STREAM, 0); if (-1 == sock) cerr << "create socket fail" << endl; struct sockaddr_in connaddr; connaddr.sin_family = AF_INET; connaddr.sin_port = htons (5555); connaddr.sin_addr.s_addr = inet_addr ("127.0.0.1"); if (-1 == connect (sock, (sockaddr*)&connaddr, sizeof (connaddr))) cerr << "connect error" << endl; char send_buf[1024] = {0}; char receive_buf[1024] = {0}; while (fgets (send_buf, sizeof (receive_buf), stdin) != nullptr) { write (sock, send_buf, strlen (send_buf)); int ret = read (sock, receive_buf, sizeof (receive_buf)); fputs (receive_buf, stdout); std::memset (send_buf, 0, sizeof (send_buf)); std::memset (receive_buf, 0, sizeof (receive_buf)); } close (sock); return 0; }
true
ed0b8191f1ec0f85dd6e61f5c165ac582af76623
C++
objective-audio/audio_engine
/audio/graph/yas_audio_graph_connection.cpp
UTF-8
2,219
2.640625
3
[ "MIT" ]
permissive
// // yas_audio_connection.cpp // #include "yas_audio_graph_connection.h" #include <cpp_utils/yas_stl_utils.h> #include "yas_audio_graph_node.h" using namespace yas; using namespace yas::audio; graph_connection::graph_connection(graph_node_ptr const &src_node, uint32_t const src_bus, graph_node_ptr const &dst_node, uint32_t const dst_bus, audio::format const &format) : _source_bus(src_bus), _destination_bus(dst_bus), _format(format), _source_node(to_weak(src_node)), _destination_node(to_weak(dst_node)) { } graph_connection::~graph_connection() { if (auto node = this->_destination_node.lock()) { connectable_graph_node::cast(node)->remove_input_connection(this->_destination_bus); } if (auto node = this->_source_node.lock()) { connectable_graph_node::cast(node)->remove_output_connection(this->_source_bus); } } uint32_t graph_connection::source_bus() const { return this->_source_bus; } uint32_t graph_connection::destination_bus() const { return this->_destination_bus; } graph_node_ptr graph_connection::source_node() const { return this->_source_node.lock(); } graph_node_ptr graph_connection::destination_node() const { return this->_destination_node.lock(); } format const &graph_connection::format() const { return this->_format; } void graph_connection::remove_nodes() { this->_source_node.reset(); this->_destination_node.reset(); } void graph_connection::remove_source_node() { this->_source_node.reset(); } void graph_connection::remove_destination_node() { this->_destination_node.reset(); } graph_connection_ptr graph_connection::make_shared(graph_node_ptr const &src_node, uint32_t const src_bus, graph_node_ptr const &dst_node, uint32_t const dst_bus, audio::format const &format) { auto shared = graph_connection_ptr(new graph_connection{src_node, src_bus, dst_node, dst_bus, format}); connectable_graph_node::cast(src_node)->add_connection(shared); connectable_graph_node::cast(dst_node)->add_connection(shared); return shared; }
true
388bcfc2da9f5c16bfe198af7a95d37294e26105
C++
soulaim/worldofapo
/src/graphics/camera.cpp
UTF-8
5,544
2.71875
3
[]
no_license
#include "graphics/frustum/matrix4.h" #include "graphics/camera.h" #include "world/objects/unit.h" #include "misc/apomath.h" #include "algorithms.h" Camera::Camera(): BasicCamera(), default_direction(-30.0f, 0.0f, 0.0f), unit(0), mode_(THIRD_PERSON) { cur_sin = 0.0f; cur_cos = 0.0f; cur_upsin = 0.0f; cur_upcos = 0.0f; unit_id = -2; } Unit* Camera::getUnitPointer() const { return unit; } vec3<float> Camera::getTarget() const { if(mode_ == STATIC) { return BasicCamera::getTarget(); } else if(mode_ == FIRST_PERSON) { return fps_direction; } return currentTarget; } void Camera::setAboveGround(float min_cam_y) { if(mode_ == THIRD_PERSON) { if(currentPosition.y + currentRelative.y < min_cam_y) { currentRelative.y = min_cam_y - currentPosition.y; } } } bool Camera::unitDie(int id) { if(id == unit_id) { unit = 0; return true; } return false; } const Location& Camera::getUnitLocation() const { static Location lastPos; if(unit) lastPos = unit->getPosition(); return lastPos; } vec3<float> Camera::getPosition() const { if(mode_ == THIRD_PERSON) { return currentPosition + currentRelative; } else if(mode_ == FIRST_PERSON) { return currentPosition; } return BasicCamera::getPosition(); } void Camera::setPosition(const vec3<float>& position) { if(mode_ == THIRD_PERSON) { currentRelative = position; } else { BasicCamera::setPosition(position); } } void Camera::tick() { if(unit) { if(mode_ == THIRD_PERSON) { relativeTick(); } else if(mode_ == FIRST_PERSON) { fpsTick(); } } } void Camera::bind(Unit* unit, FollowMode mode) { this->mode_ = mode; this->unit = unit; this->unit_id = unit->id; } void Camera::setMode(FollowMode mode) { this->mode_ = mode; } Camera::FollowMode Camera::mode() const { return mode_; } void Camera::updateInput(int keystate, int x, int y) { if(mode_ == STATIC) { vec3<float> delta = (getTarget() - currentPosition); delta.normalize(); vec3<float> delta_sides = delta * vec3<float>(0.0f, 1.0f, 0.0f); delta_sides.normalize(); float speed = default_direction.length() / 30.0f; delta *= speed; delta_sides *= speed; if(keystate & 2) { currentPosition += delta_sides; } if(keystate & 1) { currentPosition -= delta_sides; } if(keystate & 4) { currentPosition += delta; } if(keystate & 8) { currentPosition -= delta; } change_yaw(-x / 10.0f); change_pitch(y / 10.0f); } } void Camera::fpsTick() { ApoMath math; double cos = math.getCos(unit->angle).getFloat(); double sin = math.getSin(unit->angle).getFloat(); double upsin = math.getSin(unit->upangle).getFloat(); double upcos = math.getCos(unit->upangle).getFloat(); cur_sin += (sin - cur_sin) * 0.2f; cur_cos += (cos - cur_cos) * 0.2f; cur_upsin += (upsin - cur_upsin) * 0.2f;; cur_upcos += (upcos - cur_upcos) * 0.2f; vec3<float> relative_position; getRelativePos(relative_position); vec3<float> camTarget; const Location& unitPos = unit->getEyePosition(); camTarget.x = unitPos.x.getFloat(); camTarget.y = unitPos.y.getFloat(); camTarget.z = unitPos.z.getFloat(); currentPosition += (camTarget - currentPosition) * 0.2f; fps_direction = currentPosition; fps_direction.x -= relative_position.x; fps_direction.y -= relative_position.y; fps_direction.z -= relative_position.z; } void Camera::getRelativePos(vec3<float>& result) const { float x = default_direction.x; float y = default_direction.y; float z = default_direction.z; result.x = cur_cos * cur_upcos * x - cur_sin * z + cur_cos * cur_upsin * y; result.z = cur_sin * cur_upcos * x + cur_cos * z + cur_sin * cur_upsin * y; result.y = -cur_upsin * x + 0.0 * z + cur_upcos * y; } void Camera::relativeTick() { ApoMath math; double cos = math.getCos(unit->angle).getFloat(); double sin = math.getSin(unit->angle).getFloat(); double upsin = math.getSin(unit->upangle).getFloat(); double upcos = math.getCos(unit->upangle).getFloat(); cur_sin += (sin - cur_sin) * 0.2f; cur_cos += (cos - cur_cos) * 0.2f; cur_upsin += (upsin - cur_upsin) * 0.2f;; cur_upcos += (upcos - cur_upcos) * 0.2f; vec3<float> relative_position; getRelativePos(relative_position); vec3<float> camTarget; const Location& unitPos = unit->getEyePosition(); camTarget.x = unitPos.x.getFloat(); camTarget.y = unitPos.y.getFloat(); camTarget.z = unitPos.z.getFloat(); float multiplier = 0.04f; currentRelative += (relative_position - currentRelative) * multiplier; currentPosition += (camTarget - currentPosition) * multiplier; currentTarget += (camTarget - currentTarget) * multiplier; } void Camera::zoomIn() { if(mode_ == THIRD_PERSON || mode_ == STATIC) { if(default_direction.length() > 1.0f) { default_direction *= 2.0f/3.0f; } } else if(mode_ == FIRST_PERSON) { BasicCamera::zoomIn(); } } void Camera::zoomOut() { if(mode_ == THIRD_PERSON || mode_ == STATIC) { if(default_direction.length() < 100.0f) { default_direction *= 3.0f/2.0f; } } else if(mode_ == FIRST_PERSON) { BasicCamera::zoomOut(); } } float Camera::getXrot() const { if(mode_ == STATIC) { return getXangle(currentPosition - currentTarget); } static float x_rot = 0.f; if(unit) { x_rot = ApoMath().getDegrees(unit->angle); } return x_rot; } float Camera::getYrot() const { if(mode_ == STATIC) { return getYangle(currentTarget - currentPosition); } static float y_rot = 0.f; if(unit) { y_rot = ApoMath().getDegrees(unit->upangle); } return y_rot; }
true
742d5a8dc3da5d10c229499c8aeb3c41d8481d07
C++
perichere/c-_kurs_od_60_epizoda
/kalkulator.cpp
UTF-8
337
2.625
3
[ "CC0-1.0" ]
permissive
#include <iostream> using namespace std; int main() { int prvi_broj = 5; int drugi_broj = 20; int zbir = prvi_broj + drugi_broj; cout << zbir << endl; return 0; } drugi nacin je #include <iostream> using namespace std; int main() { int zbir = 5 + 3 + 4 + 6 + 9; cout << zbir << endl; return 0; }
true
c483331cf10a8e6d2461fc96f48ee84ad91eaff3
C++
boingboomtschak/cpsc-projects
/cpsc1430/player.h
UTF-8
631
2.84375
3
[]
no_license
// Devon McKee // player.h // Header file for player class for Chutes & Ladders Redux (p1) // 2019-1-17 #include <iostream> #ifndef PLAYER_H #define PLAYER_H class Player { public: Player(); Player(std::string str); std::string getName() const; int getSpace() const; bool incrementChutes(); bool incrementLadders(); void setSpace(int num); void setName(std::string str); void reportChutesLadders(); // post: reports number of chutes and ladders player has landed on void reset(); private: static const int START_SPACE = 0; std::string name; int space; int chutes; int ladders; }; #endif // player_h
true
bcbfce1dbf5f9ee717916fb4641008e6fc9a45a7
C++
saulpower/CodaTime
/CodaTime/chrono/ISOChronology.cpp
UTF-8
4,742
2.953125
3
[]
no_license
// // ISOChronology.cpp // CodaTime // // Created by Saul Howard on 12/16/13. // Copyright (c) 2013 Saul Howard. All rights reserved. // #include "ISOChronology.h" CODATIME_BEGIN /** * Gets an instance of the ISOChronology. * The time zone of the returned instance is UTC. * * @return a singleton UTC instance of the chronology */ ISOChronology *ISOChronology::getInstanceUTC() { return INSTANCE_UTC; } /** * Gets an instance of the ISOChronology in the default time zone-> * * @return a chronology in the default time zone */ ISOChronology *ISOChronology::getInstance() { return getInstance(DateTimeZone::getDefault()); } /** * Gets an instance of the ISOChronology in the given time zone-> * * @param zone the time zone to get the chronology in, NULL is default * @return a chronology in the specified time zone */ ISOChronology *ISOChronology::getInstance(DateTimeZone *zone) { if (zone == NULL) { zone = DateTimeZone::getDefault(); } int index = 0;//System.identityHashCode(zone) & (FAST_CACHE_SIZE - 1); ISOChronology *chrono = cFastCache[index]; if (chrono != NULL && chrono->getZone() == zone) { return chrono; } // TODO: synchronized // synchronized (cCache) { chrono = cCache[zone]; if (chrono == NULL) { chrono = new ISOChronology(ZonedChronology::getInstance(INSTANCE_UTC, zone)); cCache[zone] = chrono; } // } cFastCache[index] = chrono; return chrono; } // Conversion //----------------------------------------------------------------------- /** * Gets the Chronology in a specific time zone-> * * @param zone the zone to get the chronology in, NULL is default * @return the chronology */ Chronology *ISOChronology::withZone(DateTimeZone *zone) { if (zone == NULL) { zone = DateTimeZone::getDefault(); } if (zone == getZone()) { return this; } return getInstance(zone); } // Output //----------------------------------------------------------------------- /** * Gets a debugging toString. * * @return a debugging string */ string ISOChronology::toString() { string str("ISOChronology"); DateTimeZone *zone = getZone(); if (zone != NULL) { str.append(1, '['); str.append(zone->getID()); str.append(1, ']'); } return str; } void ISOChronology::assemble(Fields *fields) { if (getBase()->getZone() == DateTimeZone::UTC) { // Use zero based century and year of century. fields->centuryOfEra = new DividedDateTimeField(ISOYearOfEraDateTimeField::INSTANCE, DateTimeFieldType::centuryOfEra(), 100); fields->centuries = fields->centuryOfEra->getDurationField(); fields->yearOfCentury = new RemainderDateTimeField((DividedDateTimeField*) fields->centuryOfEra, DateTimeFieldType::yearOfCentury()); fields->weekyearOfCentury = new RemainderDateTimeField((DividedDateTimeField*) fields->centuryOfEra, fields->weekyears, DateTimeFieldType::weekyearOfCentury()); } } //----------------------------------------------------------------------- /** * Checks if this chronology instance equals another. * * @param obj the object to compare to * @return true if equal * @since 1.6 */ bool ISOChronology::equals(const Object *obj) const { if (this == obj) { return true; } const ISOChronology *chrono = dynamic_cast<const ISOChronology*>(obj); if (chrono != 0) { return getZone()->equals(chrono->getZone()); } return false; } /** * A suitable hash code for the chronology. * * @return the hash code * @since 1.6 */ int ISOChronology::hashCode() { string iso("ISO"); hash<string> hash; return hash(iso) * 11 + getZone()->hashCode(); } //----------------------------------------------------------------------- /** * Serialize ISOChronology instances using a small stub. This reduces the * serialized size, and deserialized instances come from the cache. */ //private void writeReplace() { // return new Stub(getZone()); //} // //private static final class Stub implements Serializable { // private static final long serialVersionUID = -6212696554273812441L; // // private transient DateTimeZone iZone; // // Stub(DateTimeZone zone) { // iZone = zone; // } // // private Object readResolve() { // return ISOChronology.getInstance(iZone); // } // // private void writeObject(ObjectOutputStream out) throws IOException { // out.writeObject(iZone); // } // // private void readObject(ObjectInputStream in) // throws IOException, ClassNotFoundException // { // iZone = (DateTimeZone)in.readObject(); // } //} CODATIME_END
true
dd35755ccb1f51881adbba121ef8187b0db7008b
C++
aakashvarshney23/Singly-Linked-List-Main-
/main.cpp
UTF-8
5,346
4.15625
4
[]
no_license
#include <iostream> using namespace std; struct node { int val; node *next; node(int x) : val(x), next(nullptr) {} }; class MyLinkedList { private: node *head; public: /** Initialize your data structure here. */ MyLinkedList() { head = nullptr; } /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ int get(int index) { node *temp = head; if (temp != nullptr) { for (int i = 0; i < index; i++) { temp = temp->next; } } return temp->val; } /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ void addAtHead(int val) { node *temp = new node(val); temp->next = head; head = temp; } /** Append a node of value val to the last element of the linked list. */ void addAtTail(int val) { if (head == nullptr) addAtHead(val); else if (head != nullptr) { node *temp = new node(val); node *track = head; while (track->next != nullptr) { track = track->next; } track->next = temp; } } /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, * the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ void addAtIndex(int index, int val) { node *temp = new node(val); node *prev = head; node *next_node = head; if (index == 1) addAtHead(val); else if ((index == size())) addAtTail(val); else if (index > size() || (index == 0)) cout << "The node cannot be inserted because the index is too large" << endl; else { for (int i = 2; i < index; i++) { prev = prev->next; } next_node = prev->next; prev->next = temp; temp->next = next_node; } } /** Delete the index-th node in the linked list, if the index is valid. */ void deleteAtIndex(int index) { node *prev = head; node *next_node = head; if (index > size()) cout << "Invalid"; else if (index == 1) head = head->next; else if (index <= size()) { for (int i = 2; i < index; i++) { prev = prev->next; } next_node = prev->next; prev->next = next_node->next; } } // Shows the updated size of the linked list int size() { int count = 0; node *temp = head; if (temp == nullptr) return count; else { do { count++; temp = temp->next; } while (temp != nullptr); } return count; } // Prints the linked list with the arrows. void print() { node *temp = head; if (temp == nullptr) cout << "Empty list"; else { do { cout << temp->val << "->"; temp = temp->next; } while (temp != nullptr); } cout << "\n"; } // Reverse a given singly linked list void reverse_linked_list() { node *temp = head; node *next = nullptr; node *prev = nullptr; while (temp != nullptr) { next = temp->next; temp->next = prev; prev = temp; temp = next; } head = prev; } // merge two sorted linked lists // The error here is that it terminates before reaching the null pointer. One of the element is left out. MyLinkedList mergeTwoLinkedList(MyLinkedList b) { MyLinkedList c; node *tempa = this->head; node *tempb = b.head; if (b.head == nullptr) return *this; if (this->head == nullptr) return b; if (tempa && tempb) { while (tempa && tempb) if ((tempa->val) <= (tempb->val)) { c.addAtTail(tempa->val); tempa = tempa->next; } else if ((tempa->val) >= (tempb->val)) { c.addAtTail(tempb->val); tempb = tempb->next; } while (tempa != nullptr) { c.addAtTail(tempa->val); tempa = tempa->next; } while (tempb != nullptr){ c.addAtTail(tempb->val); tempb = tempb->next; } return c; } } }; int main() { MyLinkedList a; MyLinkedList b; MyLinkedList c; a.addAtTail(1); a.addAtTail(21); a.addAtTail(31); a.addAtTail(40); a.addAtTail(50); a.addAtTail(61); b.addAtTail(17); b.addAtTail(81); b.addAtTail(82); b.addAtTail(83); b.addAtTail(84); a.print(); b.print(); cout << "A Size :" << a.size() << endl; cout << "B Size :" << b.size() << endl; c = b.mergeTwoLinkedList(a); c.print(); cout << "C Size: " << c.size() << endl; }
true
974dd121db50779a37a45eaf5a7b0c69c87b76b8
C++
dynamiquel/The-Game
/TheGame/TheGame.cpp
UTF-8
2,230
2.984375
3
[ "MIT" ]
permissive
// TheGame.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "Game.h" #include <iostream> int main() { std::cout << "Welcome to a C++ implementation of 'The Game' by Liam HALL.\n"; std::cout << "\nGuide\n" << "============================================================\n" << "\n 1-5 Players\n" << "\n 1) Each player starts with 6-8 cards in their hand;\n" << "\n 2) There are four play piles." << "\n The first two play piles start at 1 and only cards greater than the top card can be placed." << "\n The other two play piles start at 100 and only card smaller than the top cards can be placed;\n" << "\n 3) The goal is to discard all 98 cards into the four piles;\n" << "\n 4) In any play pile, you can place a card that has a difference of exactly 10 from the top card;\n" << "\n 5) The player must play two cards each turn, or one card if the draw pile is empty;\n" << "\n 6) When a player finishes their turn, they refill their hand from the draw pile;\n" << "\n 7) Players are not allowed to reveal the numbers in their hands." << "\n However, they are allowed to tell others not to play on certain play piles amongst other suggestions;\n" << "\n 8) If one player is unable to play the required number of cards. It's game over for everyone;\n" << "\n 9) The lower the score, the better.\n" << "\n============================================================\n"; Game* game = new Game; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
true
dbe3e7c77c50862b47b3557ea348a8f564f46639
C++
stevenj/ControLeo2
/ReflowWizard/ControLeo2_LCD.h
UTF-8
2,984
2.953125
3
[]
no_license
// Written by Peter Easton // Released under WTFPL license // // Change History: // 14 August 2014 Initial Version // 1 August 2017 Steven Johnson // Rewritten to act like a refreshed frame buffer. // Provide an ability to show scrolling long messages on one line at a time. // Need to call "refresh" at an appropriate interval to allow the screen to redraw // 20 times a second is more than fast enough. // #ifndef CONTROLEO2_LCD_h #define CONTROLEO2_LCD_h class ControLeo2_LCD { public: ControLeo2_LCD(void); void clear(void); void PrintStr(uint8_t x, uint8_t y, const char* str); void PrintStr(uint8_t x, uint8_t y, const __FlashStringHelper* str); void PrintInt(uint8_t x, uint8_t y, uint8_t width, uint16_t value, char fill); void PrintInt(uint8_t x, uint8_t y, uint8_t width, uint16_t value); void ScrollLine(uint8_t y, uint8_t rpt, const __FlashStringHelper* str); bool LineScrolling(void); void CursorOff(void); void CursorOn(uint8_t x, uint8_t y, bool blink, bool underline); void CursorOn(uint8_t x, uint8_t y, bool blink); void CursorOn(uint8_t x, uint8_t y); void ScreenOff(void); void ScreenOn(void); void setChar(uint8_t x, uint8_t y, uint8_t character); void defineCustomChars(const uint8_t *charmap); void refresh(void); void send(uint8_t, uint8_t); private: void upload_charset(const uint8_t *charmap); void write4bits(uint8_t); uint8_t _displaycontrol; const uint8_t *_custom_chars; // Address of Standard mode Custom Characters in Flash. union { uint8_t _cursor_xy; struct { uint8_t _cursor_x:4; // X Position of Cursor on a Line (0-15) uint8_t _cursor_y:1; // Y Position of Cursor (Line) (0 or 1) bool _cursor_blink:1; // Blink character at Cursor, or not. bool _cursor_on:1; // Is the Cursor Displayed or Not. bool _screen_on:1; // Is the Screen Displayed or Not. }; }; uint8_t _frame_buffer[2][16+1]; // Virtual Screen Buffer, (one character wider than needed to accomodate null if std string functions are used on it.) uint8_t *_scroll_msg; // Scrolling message union { uint8_t _scroll_line_rpt; // Bit 7 = Line, Bit 0-6 = Number of times to show it. (0 = Off, 127 = Forever) struct { uint8_t _scroll_rpt:7; // Repeat Counter uint8_t _scroll_line:1; // Scroll Line }; }; int8_t _scroll_x; // Position of Scroll. -16 -> -1 = Spaces, 0 -> _scroll_size = Characters from the buffer // Because its signed, maximum practical line size is 126 Characters. }; #endif //CONTROLEO2_LCD_h
true
ece348a9447d6170d3e880592b554f3223687270
C++
voladoddi/ctci
/ch4_Graphs/leetcode133_cloneGraph.cc
UTF-8
1,327
3.5625
4
[]
no_license
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */ class Solution { public: // typedef for easier typedef UndirectedGraphNode udgNode; UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { // if empty graph if (!node) return nullptr; // map for visited. unordered_set<udgNode*> visited; // recur - DFS udgNode* result = cloneGraphHelper(node, visited); return result; } udgNode* cloneGraphHelper(udgNode* node, unordered_set<udgNode*> &visited) { if(visited.find(node)!=visited.end()) //found node in visited set. return node; else { udgNode* clone = new udgNode(node->label); //visit / process/ clone the node. visited.insert(clone); //mark the node as visited. vector<udgNode*>::iterator it; // process the neighbours. for(it=node->neighbors.begin(); it!=node->neighbors.end(); ++it) clone->neighbors.push_back(cloneGraphHelper(*it,visited)); return clone; } } };
true
89feb58a17fe649e95ef615dae4e9c92e7e5c8f4
C++
Sabila-Nawshin/CodeForces
/96A. Football.cpp
UTF-8
454
3.046875
3
[]
no_license
#include <iostream> using namespace std; int main(){ string s; cin >> s; int maxm = 0, count = 1; for (int i = 0; i < s.size() - 1; i++){ if(s.at(i) == s.at(i + 1)) ++count; else { maxm = max(count, maxm); count = 1; } } maxm = max(count, maxm); //cout << max; if (maxm >= 7) cout << "YES" << endl; else cout << "NO" << endl; return 0; }
true
6eedab787ebcbe8de0abaf6de040709c16e30d09
C++
edisondev/Energia-Libraries
/MatrixMath.h
UTF-8
2,600
2.765625
3
[]
no_license
/// /// @file MatrixMath.h /// @brief Library header /// @details Matrix library /// @n /// * Modified by Edison Developers on 16/02/2015 by adding the following functions: /// * void normalizeVec(float* vector) /// * float dotProduct(float* vector_one, float* vector_two) /// * void scalar_product(float* matrixIn, double scalar) /// * (Original downloaded from: http://forum.43oh.com/topic/3321-energia-library-matrix-for-launchpad-fraunchpad-and-stellarpad/) /// * Created by Charlie Matlack on 12/18/10. Changed name. /// * Original code by RobH45345 on Arduino Forums, taken from unknown source. /// * Rei Vilo - Apr 15, 2011 - Added void MatrixMath::MatrixRowPrint(float* matrixA, uint8_t m, uint8_t n, String label){ /// * Rei Vilo - Jan 26, 2013 - Initial port to Energia /// * Rick - Jan 27, 2013 - http://forum.43oh.com/topic/3275-is-there-an-energia-matrix-math-library-for-the-msp430-and-stellaris/?p=28604 /// * Rei Vilo - Feb 04, 2013 - Revised library with examples /// * Edison Developers - Feb 16, 2015 - Addition of the following functions: /// * void normalizeVec(float* vector) /// * float dotProduct(float* vector_one, float* vector_two) /// * void scalar_product(float* matrixIn, double scalar /// /// @n /// @n @a Developed with [embedXcode](http://embedXcode.weebly.com) /// @n /// @author Rei VILO /// @author embedXcode.weebly.com /// @date Feb 03, 2013 /// @version 103 /// /// @copyright © Rei VILO, 2013 /// @copyright CC = BY NC SA /// /// @see ReadMe.txt for references #ifndef MatrixMath_h #define MatrixMath_h #include "Energia.h" class MatrixMath { public: MatrixMath(); void MatrixPrint(float* matrixA, uint8_t m, uint8_t n, String label); // vilo.rei - Apr 15, 2011 void MatrixRowPrint(float* matrixA, uint8_t m, uint8_t n, String label); void MatrixCopy(float* matrixA, uint8_t n, uint8_t m, float* B); void MatrixMult(float* matrixA, float* matrixB, uint8_t m, uint8_t p, uint8_t n, float* matrixC); void MatrixAdd(float* matrixA, float* matrixB, uint8_t m, uint8_t n, float* matrixC); void MatrixSubtract(float* matrixA, float* matrixB, uint8_t m, uint8_t n, float* matrixC); void MatrixTranspose(float* matrixA, uint8_t m, uint8_t n, float* matrixC); uint8_t MatrixInvert(float* matrixA, uint8_t n); float DotProduct(float* vector_one, int length , float* vector_two); //EdisonDev - Feb 16, 2015 void NormalizeVector(float* MatIn, int n, int m, float* MatOut); //EdisonDev - Feb 16, 2015 void ScalarProduct(float* MatIn, int n, int m, double scalar,float* MatOut); //EdisonDev - Feb 16, 2015 }; #endif
true
64da37a1f8aa878df42d92abbdea7d58ee6bff93
C++
lollor/orologio-sveglia
/Arduino/Versione_1.0/Versione_1.0.ino
UTF-8
536
2.875
3
[]
no_license
void setup(){ Serial.begin(9600); pinMode(LED_BUILTIN, OUTPUT); } void loop(){ String parola = leggiParola(); //Serial.println(parola); //Serial.write("picio"); if (parola == "Suona"){ digitalWrite(LED_BUILTIN, HIGH); Serial.println("Sto illuminando"); delay(5000); digitalWrite(LED_BUILTIN, LOW); } delay(50); } String leggiParola(){ String finale; while(Serial.available()){ char c = Serial.read(); if (c == ';') return finale; else{ finale+=c; } delay(10); } }
true
16952a43ed4d70679c9f866470dc0593957ff729
C++
ggilbert108/algorithms-for-runekir
/Letter Cubes/Letter Cubes/cubes.cpp
UTF-8
2,754
2.828125
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <assert.h> #include <map> #include <set> #include <vector> #include <algorithm> using namespace std; typedef map<char, set<char>> CharMap; void findIncompatibles(CharMap& incompatible, char a, char b) { if (incompatible.find(a) == incompatible.end()) { set<char> charSet; incompatible.insert(pair < char, set<char>>(a, charSet)); } if (incompatible.find(b) == incompatible.end()) { set<char> charSet; incompatible.insert(pair < char, set<char>>(b, charSet)); } incompatible[a].insert(b); incompatible[b].insert(a); } void findIncompatibles(CharMap& incompatible, string word) { for (int i = 0; i < word.length(); i++) { for (int j = 0; j < i; j++) { findIncompatibles(incompatible, word[i], word[j]); } } } bool areCompatible(CharMap& incompatible, char a, char b) { if (a == b) return true; return incompatible[a].find(b) == incompatible[a].end(); } bool areCompatible(CharMap& incompatible, string str, char ch) { for (int i = 0; i < str.length(); i++) { char strCh = str[i]; if (!areCompatible(incompatible, strCh, ch)) { return false; } } return true; } vector<string> getCubes(CharMap& incompatible, vector<string> cubes, string allChars, int pos) { if (pos >= allChars.length()) { return cubes; } char ch = allChars[pos]; for (int i = 0; i < cubes.size(); i++) { if (cubes[i].length() < 6 && areCompatible(incompatible, cubes[i], ch)) { cubes[i] += ch; vector<string> result = getCubes(incompatible, cubes, allChars, pos + 1); if (result.size() > 0) { return result; } cubes[i] = cubes[i].substr(0, cubes[i].length() - 1); } } vector<string> empty; return empty; } void main() { ifstream fin("cubes.in"); assert(fin); ofstream fout("cubes.out"); int numWords; char extra; fin >> numWords >> extra; while (numWords > 0) { int numCubes = -1; CharMap incompatible; for (int i = 0; i < numWords; i++) { string word; fin >> word; if (numCubes == -1) numCubes = word.length(); findIncompatibles(incompatible, word); } string allChars = ""; for each(pair <char, set<char>> pair in incompatible) { allChars += pair.first; } vector<string> cubes(numCubes); vector<string> result = getCubes(incompatible, cubes, allChars, 0); for (int i = 0; i < result.size(); i++) { if (result[i].length() < 6) result[i] += extra; sort(result[i].begin(), result[i].end()); } sort(result.begin(), result.end()); string resLine = ""; for each(string str in result) { resLine += str + " "; } resLine = resLine.substr(0, resLine.length() - 1); fout << resLine << endl; fin >> numWords >> extra; } fin.close(); fout.close(); }
true
f3a14dc8e8385acb122e1707f0fabc8bc021c74f
C++
JonnyKong/LeetCode
/7_Reverse_Integer.cpp
UTF-8
539
3.125
3
[]
no_license
// // 7.Reverse Integer.h // Project 1 // // Created by Jonny Kong on 2/22/16. // Copyright © 2016 Jonny Kong. All rights reserved. // int reverse(int x) { int sign = 1; int i = 0; if (x < 0) { sign = -1; i++; } else if (!x) return 0; char number[20] = {0}; sprintf(number, "%d", x); long result = 0; int time = 0; while (number[i]) { result += (number[i++] - 48) * pow(10, time++); } if (result >= 2147483647) return 0; if (sign == 1) return ((int)result); else return -1 * ((int)result); }
true
769ac389c7cc113befbe65a2d32087439adc8b8d
C++
angieshu/Space_Shooter
/src/Enemy.class.cpp
UTF-8
397
2.59375
3
[]
no_license
/** * @Author: Anhelina Shulha <angieshu> * @Date: Jul-25-2017 * @Email: anhelina.shulha@gmail.com * @Filename: Enemy.class.cpp * @Last modified by: angieshu * @Last modified time: Jul-26-2017 */ #include "Enemy.class.hpp" Enemy::Enemy(int x) { setWidth(ENEMY_WIDTH); setHeight(ENEMY_HEIGHT); setX(x); setY(-ENEMY_HEIGHT - 1); } Enemy::~Enemy(void) { } void Enemy::moveDown(void) { setY(getY() + 3); }
true
94d431eb04fe58c1fd2b80e9c20ffc025a9805d1
C++
Ashray11/InterviewBit
/Tree/Vertical Order Traversal.cpp
UTF-8
915
2.984375
3
[]
no_license
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ vector<vector<int> > Solution::verticalOrderTraversal(TreeNode* A) { vector <vector <int>> v; if(A==NULL){ return v; } queue <pair <TreeNode* , int>> q; q.push({A,0}); map < int, vector <int>> mp; while(!q.empty()){ pair <TreeNode* , int> temp = q.front(); q.pop(); if(temp.first->left){ q.push({temp.first->left,temp.second-1}); } if(temp.first->right){ q.push({temp.first->right,temp.second+1}); } mp[temp.second].push_back(temp.first->val); } for(auto it = mp.begin();it!=mp.end();it++){ v.push_back(it->second); } return v; }
true
e81b6af4b00e3b33a4654d164903f03c56287ec0
C++
matthhan/statnlp
/exercise3/exercise03.1/class_counter.hh
UTF-8
453
2.765625
3
[]
no_license
#ifndef CLASS_COUNTER_HH #define CLASS_COUNTER_HH #include <map> #include <vector> #include <string> class ClassCounter { public: void addToCount(std::string className); ClassCounter(); double relativeFrequency(std::string className); std::vector<std::string> getVectorOfClasses(); private: int getCount(std::string className); std::map<std::string,int> counts; int totalCount; }; #endif
true
29645986642207d9efb460f724dda3b4bff4b8d9
C++
braham517/DSA
/Algorithm/Sorting/4. MergeSort.cpp
UTF-8
713
3.15625
3
[]
no_license
#include <iostream> using namespace std; void mergesort(int arr[],int l,int m,int r) { int n1=m-l+1; int n2=r-m; int left[n1]; int right[n2]; for(int i=0;i<n1;i++) left[i]=arr[l+i]; for(int i=0;i<n1;i++) right[i]=arr[m+1+i]; int i=0,j=0,k=l; while(i<n1&&j<n2) { if(left[i]<right[j]) arr[k++]=left[i++]; else arr[k++]=right[j++]; } while(i<n1) arr[k++]=left[i++]; while(j<n2) arr[k++]=right[j++]; } void merge(int arr[],int l,int r) { if(r>l) { int m=(l+r)/2; merge(arr,l,m); merge(arr,m+1,r); mergesort(arr,l,m,r); } } int main() { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) cin>>arr[i]; merge(arr,0,n-1); for(int i=0;i<n;i++) cout<<arr[i]<<" "; return 0; }
true
4afe7ed751f00fa2bacfe854cd31b9f5ebbf60b0
C++
719400737/LeetCode
/剑指offer/39.cpp
UTF-8
534
2.578125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; class Solution { public: int majorityElement(vector<int>& nums) { pair<int,int> res; res=make_pair(nums[0],0); for(auto i:nums){ if(i==res.first){ res.second++; continue; } if(res.second==0){ res.first=i; res.second=1; continue; } res.second--; } return res.first; } }; int main(){ return 1; }
true
dfb2cc18f6e45a3fa23545a5b9651a90fb7eeacb
C++
kremena1993/Yanev--Kremena--Assignments--48969
/assignment 4/exmpl 13.4.cpp
UTF-8
2,014
3.78125
4
[]
no_license
/* Kremena Yanev Chapter 13, Problem 4 */ #include <iostream> #include<string> using namespace std; class Info{ private: std::string name, address; long long int age, number; //Reason for long long int is to be able to hold 10 digits public: void getinfo(); std::string getname(){ return name; }; std::string getaddress(){ return address; }; int getage(){ return age; }; int getnumber(){ return number; }; }; int main(int argc, char** argv) { Info mystuff, friend1, friend2; int choice = 1; cout << "Hello!" << endl; cout << "Who's info do you want to store?" << endl; while (choice>0 && choice<4){ cout << "1. You\n2. Friend 1\n3. Friend 2" << endl; cin >> choice; cin.ignore(); switch (choice){ case 1: mystuff.getinfo(); break; case 2: friend1.getinfo(); break; case 3: friend2.getinfo(); break; default: choice = 4; break; } cout << "Who's information do you want to enter next?" << endl; cout << "If done, enter anything other than 1,2, or 3." << endl; } cout << endl << "Here you are:" << endl; cout << "\tName: " << mystuff.getname() << endl << "\tAddress: " << mystuff.getaddress() << endl; cout << "\tAge: " << mystuff.getage() << endl << "\tPhone Number: " << mystuff.getnumber() << endl; cout << endl << "Here is Friend 1:" << endl; cout << "\tName: " << friend1.getname() << endl << "\tAddress: " << friend1.getaddress() << endl; cout << "\tAge: " << friend1.getage() << endl << "\tPhone Number: " << friend1.getnumber() << endl; cout << endl << "Here is Friend 2:" << endl; cout << "\tName: " << friend2.getname() << endl << "\tAddress: " << friend2.getaddress() << endl; cout << "\tAge: " << friend2.getage() << endl << "\tPhone Number: " << friend2.getnumber() << endl; return 0; } void Info::getinfo(){ cout << "Enter name." << endl; getline(cin, name); cout << "Enter age." << endl; cin >> age; cin.ignore(); cout << "Enter address." << endl; getline(cin, address); cout << "Enter phone number." << endl; cin >> number; }
true
5de34448b989b2fc7c3407116a9dc3b3ffff387c
C++
OliveOld/PetTrack
/Bean/Filter.ino
UTF-8
3,117
3.171875
3
[]
no_license
// ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== // // Author // - Park Dong Ha (luncliff@gmail.com) // // Note // 가속도 센서의 값을 읽고, Low Pass Filter를 적용하여 // 측정값(MA), 중력 가속(G), 신체 가속(LA)를 분리한다. // MA = LA + G // // Note // Low Pass Filter // 낮은 주파수(Low Frequency)만 통과시킨다. 이는 긴 주기의 파동과 같다. // 실제환경에서 이는 지속적으로 작용하는(따라서 주기가 긴) 중력을 // 의미하며, 따라서 LPF는 중력 성분만을 필터링하게 된다. // // G = filter(MA) // // 이론상으로는 필터링을 통해 중력성분 만 획득하는 것이 가능하지만, // 실제로는 중력 이외의 성분, 즉 High Frequency 성분을 희석(Attenuate) // 시키는 것이다. // 그 수준을 결정하기 위해 alpha값이 적절히 결정되어야 하며, 이 코드는 // 0.8을 사용한다. 따라서... // // G_new = (0.8 * G_old) + (0.2 * MA) // = (0.8 * G_old) + (0.2 * (LA + G)) // = 1.0 * G + 0.2 * LA // // 결과적으로 새로 유도한 G 에는 (1-alpha) 만큼의 LA가 포함된다. // 이렇게 유도한 G를 MA에서 제외시킴으로써 LA역시 유도가 가능하다. // // LA_new = MA - G_new // // Caution // 출력 형태: { MA.x, MA.y, MA.z } // // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- void Println(int x, int y, int z) { Serial.print(x); Serial.print(','); Serial.print(y); Serial.print(','); Serial.print(z); Serial.print('\n'); delay(5); } struct Unit { int x, y, z; Unit() { x = y = z = 0; } }; // - Note // 3-Axis Low Pass Filter class LPF3A { public: int alpha; Unit la; // Linear Acceleration Unit g; // Gravity Acceleration public: LPF3A() { alpha = 0; // Caution : 0 by default la.x = la.y = la.z = 0; g.x = g.y = g.z = 0; } int factor(int x) { return (x * alpha) / 1000; } // - Note // Receive Measured accceleration, // then update Linear/Gravity acceleration. void separate(int mx, int my, int mz) { // G = a*G + (1-a)* MA g.x = mx + factor(g.x - mx); g.y = my + factor(g.y - my); g.z = mz + factor(g.z - mz); // LA = MA - G la.x = mx - g.x; la.y = my - g.y; la.z = mz - g.z; } }; // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- LPF3A filter; void setup() { // Attenuation Ratio filter.alpha = 759; // 0.759 } void loop() { // Measure acceleration Unit ma; ma.x = Bean.getAccelerationX(); ma.y = Bean.getAccelerationY(); ma.z = Bean.getAccelerationZ(); // Filtering filter.separate(ma.x, ma.y, ma.z); Unit g = filter.g; // Gravity Acceleration Unit la = filter.la; // Linear Acceleration // Report Println(ma.x, ma.y, ma.z); // Bean.sleep(200); // ~5 Hz }
true
c5d95fc9f09e787b2815e7424db3d075aaa44de7
C++
BYOUINZAKA/LeetCodeNotes
/354.cpp
UTF-8
1,170
3.03125
3
[ "MIT" ]
permissive
/* * @Author: Hata * @Date: 2020-07-10 13:03:05 * @LastEditors: Hata * @LastEditTime: 2020-07-10 13:47:40 * @FilePath: \LeetCode\354.cpp * @Description: https://leetcode-cn.com/problems/russian-doll-envelopes/ */ #include <bits/stdc++.h> class Solution { template <class T> constexpr bool fitInto(T &&base, T &&into) const { return base[0] < into[0] && base[1] < into[1]; } public: int maxEnvelopes(std::vector<std::vector<int>> &envelopes) { const int N = envelopes.size(); if (N == 0) return 0; std::sort(envelopes.begin(), envelopes.end(), [](auto &&lhs, auto &&rhs) { return lhs.front() != rhs.front() ? lhs.front() < rhs.front() : lhs.back() > rhs.back(); }); std::vector<int> dp(N, 1); for (int i = 1; i < N; ++i) { int raise = 0; for (int j = i - 1; j >= 0; --j) { if (fitInto(envelopes[j], envelopes[i])) raise = std::max(dp[j], raise); } dp[i] += raise; } return *std::max_element(dp.cbegin(), dp.cend()); } };
true
8804d1d5c61d05f7f991d442cf2dbd40692bbc80
C++
angelicaalemanc/ProyectoIntegradorTC1030_E3
/Pelicula.cpp
UTF-8
962
3.4375
3
[]
no_license
#include "Pelicula.h" // Constructor default Pelicula::Pelicula(){ id = 0; nombre = ""; duracionH = 0; genero = ""; calificacionPelicula = 0.0; } // Constructor Pelicula::Pelicula(int Id, string Nombre,float DuracionH, string Genero, float CalificacionPelicula){ id = Id; nombre = Nombre; duracionH = DuracionH; genero = Genero; calificacionPelicula = evaluar(CalificacionPelicula); } // Método set de la clase Pelicula float Pelicula::getCalificacionPelicula(){return calificacionPelicula;} // Otros métodos void Pelicula::print(){ cout << "Id: " << getId() <<endl; cout << "Película: " << getNombre() <<endl; cout << "Duración (h): " << getDuracionH() <<endl; cout << "Género: " << getGenero() <<endl; cout << "Calificación: " << getCalificacionPelicula() <<endl; cout << "\n" << endl; } float Pelicula::evaluar(float CalificacionPelicula){ calificacionPelicula = CalificacionPelicula; return calificacionPelicula; }
true
06105402f9199ac373e2b7078bc5d4b52ca0eab8
C++
Bpara001/CS_UCR
/cs100/assn2/main2.cpp
UTF-8
2,907
3.5
4
[]
no_license
//================================================= // // Name: wong, christopher // Login id: wongc // Email: cwong030@student.ucr.edu // // Assignment name: assn1 // Lab section: 022 // TA: Busra Celikkaya // // I hereby certify that the contents of this file // re ENTIRELY my own original work. // //================================================= #include <iostream> #include <vector> inline std::vector<std::string> split( const std::string s, const std::string pat ) // Returns the vector of fragments (substrings) obtained by // splitting s at occurrences of pat. Use C++’s string::find. // If s begins with an occurrence of pat, it has an empty-string // fragment. Similarly for trailing occurrences of pat. After each // occurrence of pat, scanning resumes at the following character, // if any. { //declare vectors and variables std::vector<std::string> stringvec; std::vector<int> posvec; int pos = 0; int postemp = 0; //get the position of each instance of the pat posvec.push_back((0)); while(s.find(pat,pos) != -1) { posvec.push_back(s.find(pat,pos) + pat.size()); postemp = s.find(pat,pos); pos = postemp + pat.size(); } //calculate the string and add to vector for(int i = 0; i < posvec.size(); i++) { pos = posvec[i+1] - posvec[i] - pat.size(); stringvec.push_back(s.substr(posvec[i],pos)); } //return newly created vector return stringvec; } inline std::string join(const std::vector<std::string> v, const std::string pat, int start=0, int n=-1) // Joins members of v separated by occurrences of pat into a single // string and returns it. The value of start is the index of the // first member to be joined, and n bounds the number of members to // be joined; a value of -1 indicates that all members from start to // the end of v should be joined { //Error check: make sure n is not more then vector size if(n > v.size() && n != -1) { std::cout <<"\nERROR:inline join: n is greater then vector size\n"; return 0; } //Error check: make sure n is not less then -1 if(n < -1) { std::cout <<"\nERROR:inline join: n is less then -1\n"; return 0; } //Error: make sure start is not more then vector size if(start > v.size()) { std::cout <<"\nERROR:inline join: start is greater then vec size\n"; return 0; } //Error: make sure start is not less then 0 if(start < 0) { std::cout <<"\nERROR:inline join: start is less then 0\n"; return 0; } //check: if n is -1, transfers through entire vector if(n == -1) n = v.size(); //create a string adding vector and pat information std::string s = ""; for(int i = start; i < n; i++) { s += v[i]; if((i+1) < n) s += pat; } //return newly created string return s; } using namespace std; int main() { }
true
c0488d18bb6f524081b0fb4c74156d248677e025
C++
ArmanTapayev/Urok5_Module5_LR
/Urok5_Module5_LR/Urok5_Module5_LR/Source.cpp
UTF-8
3,714
3.0625
3
[]
no_license
#include<stdio.h> #include<iostream> #include<locale.h> #include<math.h> #include<time.h> using namespace std; void main() { setlocale(LC_ALL, "Rus"); srand(time(NULL)); int i, j, n, m; /* Разработать программу, реализующую обработку числового двухмерного произвольного массива тремя методами сортировки (пузырьком, вставкой, выбором).*/ int A[5][5]; n = 5; m = 5; cout << "Исходный массив: " << endl; cout << endl; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { A[i][j] = 10 + rand() % 50; cout << A[i][j] << "\t"; } cout << endl; } cout << endl; cout << "Метод вставками:" << endl; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int value = A[i][j]; // запоминаем значение элемента int index = j; // и его индекс while ((index > 0) && (A[i][index - 1] > value)) { // смещаем другие элементы к концу массива пока они меньше index A[i][index] = A[i][index - 1]; index--; // смещаем просмотр к началу массива } A[i][index] = value; // рассматриваемый элемент помещаем на освободившееся место } } cout << endl; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { cout << A[i][j] << "\t"; } cout << endl; } cout << endl; cout << "Метод пузырьком:" << endl; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int k = m-1; k > j; k--) // для всех элементов после i-ого { if (A[i][k - 1] > A[i][k]) // если текущий элемент меньше предыдущего { int temp = A[i][k - 1]; // меняем их местами A[i][k - 1] = A[i][k]; A[i][k] = temp; } } } } cout << endl; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { cout << A[i][j] << "\t"; } cout << endl; } cout << endl; cout << "Метод выбором:" << endl; //Организуем цикл для всех элементов кроме последнего int min, temp; // для поиска минимального элемента и для обмена for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int k = 0; k < m; k++) { min = j; // запоминаем индекс текущего элемента // ищем минимальный элемент чтобы поместить на место i-ого for (int k = j + 1; k < m; k++) // для остальных элементов после i-ого { if (A[i][j] < A[i][min]) // если элемент меньше минимального, min = k; // запоминаем его индекс в min } temp = A[i][j]; // меняем местами i-ый и минимальный элементы A[i][j] = A[i][min]; A[i][min] = temp; } } } cout << endl; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { cout << A[i][j] << "\t"; } cout << endl; } system("pause"); }
true
f5a36013f0ad666232326be7f309e9728c5f4bd1
C++
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/C++/long-multiplication-1.cpp
UTF-8
2,912
3.234375
3
[]
no_license
#include <iostream> #include <sstream> //-------------------------------------------------------------------------------------------------- typedef long long bigInt; //-------------------------------------------------------------------------------------------------- using namespace std; //-------------------------------------------------------------------------------------------------- class number { public: number() { s = "0"; neg = false; } number( bigInt a ) { set( a ); } number( string a ) { set( a ); } void set( bigInt a ) { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); } void set( string a ) { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); } number operator * ( const number& b ) { return this->mul( b ); } number& operator *= ( const number& b ) { *this = *this * b; return *this; } number& operator = ( const number& b ) { s = b.s; return *this; } friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << "-"; out << a.s; return out; } friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; } private: number mul( const number& b ) { number a; bool neg = false; string r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' ); int xx, ss, rr, t, c, stp = 0; string::reverse_iterator xi = bs.rbegin(), si, ri; for( ; xi != bs.rend(); xi++ ) { c = 0; ri = r.rbegin() + stp; for( si = s.rbegin(); si != s.rend(); si++ ) { xx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48; ss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10; ( *ri++ ) = t + 48; } if( c > 0 ) ( *ri ) = c + 48; stp++; } trimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0; if( t & 1 ) a.s = "-" + r; else a.s = r; return a; } void trimLeft( string& r ) { if( r.length() < 2 ) return; for( string::iterator x = r.begin(); x != ( r.end() - 1 ); ) { if( ( *x ) != '0' ) return; x = r.erase( x ); } } void clearStr() { for( string::iterator x = s.begin(); x != s.end(); ) { if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x ); else x++; } } string s; bool neg; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { number a, b; a.set( "18446744073709551616" ); b.set( "18446744073709551616" ); cout << a * b << endl << endl; cout << "Factor 1 = "; cin >> a; cout << "Factor 2 = "; cin >> b; cout << "Product: = " << a * b << endl << endl; return system( "pause" ); } //--------------------------------------------------------------------------------------------------
true
958d819011915ddb1dd81a32ebd259ee29d111f3
C++
morganstanley/binlog
/include/mserialize/visit.hpp
UTF-8
1,013
2.78125
3
[ "Apache-2.0" ]
permissive
#ifndef MSERIALIZE_VISIT_HPP #define MSERIALIZE_VISIT_HPP #include <mserialize/detail/Visit.hpp> #include <mserialize/cx_string.hpp> #include <mserialize/string_view.hpp> namespace mserialize { /** * Visit the serialized objects in `istream`. * * @requires `visitor` to model the Visitor concept, see Vistor.hpp * @requires `istream` must model the mserialize::InputStream concept. * @pre `tag` must be a valid type tag, e.g: * a tag returned by mserialize::tag<T>(). * @pre `istream` must contain a serialized object, * whose type tag is `tag`. * @throws std::exception if reading of `istream` fails. * @throws std::runtime_error if tag is too deeply nested, * to prevent stack overflow. * @throws std::runtime_error if tag is syntactically invalid */ template <typename Visitor, typename InputStream> void visit(string_view tag, Visitor& visitor, InputStream& istream) { detail::visit_impl(tag, tag, visitor, istream, 2048); } } // namespace mserialize #endif // MSERIALIZE_VISIT_HPP
true
6b5d4606939a75afe29ed602b27d13236ae24428
C++
beaupletga/Tetrahedra_Into_Diamonds
/Tetraedres_en_diamants/src/step4.cpp
UTF-8
6,048
2.8125
3
[]
no_license
#include "../include/step4.h" int id_to_index(vector<Diamond> &diamond_list,Diamond* ref) { for(int i=0;i<diamond_list.size();i++) { if (&diamond_list[i]==ref) return i; } assert(true==false); return -1; } // this function reads all diamond and create the adjacency array // this is an array containing the index of the neighbour for each face of each diamond // ex : at index 2, there is the index of the neighbour (this index is more precise as it's // the index of the face of the neighboring diamond) sharing the third face of the first diamond map<int,int> step_4(vector<Tetrahedron> &tetra_list,vector<Diamond> &diamond_list,int (diamond_array)[], bool (diamond_extra_bytes_array)[],int diamond_array_size,map<int,Diamond*> &anchor_dict ,vector<tuple<int,int,int>> &permutation_array,vector<tuple<int,int,int>> &face_array) { // cout<<1<<endl; // cout<<anchor_dict[12560]<<endl; vector<int> tetra_order; map<int,int> diamond_id_to_index; map<int,int> index_to_diamond_id; int index=0; for(int i=0;i<anchor_dict.size();i++) { // cout<<i<<" "<<anchor_dict[i]<<endl; // cout<<"id "<<i<<" "<<anchor_dict[i]->get_id()<<endl; diamond_id_to_index[anchor_dict[i]->get_id()]=index; // cout<<1.5<<endl; index+=anchor_dict[i]->get_neighbours().size(); // cout<<1.75<<endl; tetra_order.push_back(id_to_index(diamond_list,anchor_dict[i])); // cout<<1.85<<endl; } // cout<<2<<endl; // each diamond is represented by an id and the index of the first face in the diamond array for(int i=0;i<diamond_list.size();i++) { if(diamond_id_to_index.count(diamond_list[i].get_id())==0) { diamond_id_to_index[diamond_list[i].get_id()]=index; index+=diamond_list[i].get_neighbours().size(); tetra_order.push_back(i); } } // cout<<3<<endl; index=0; // for each diamond for(int i=0;i<tetra_order.size();i++) { // cout<<30<<endl; diamond_extra_bytes_array[index]=1; int j=0; // we iterate over the external faces (neighbours) // cout<<31<<endl; for(Diamond* diamond : diamond_list[tetra_order[i]].get_neighbours()) { // if (get<0>(face_array[index])==0 && get<1>(face_array[index])==0 && get<2>(face_array[index])==1) // { // cout<<"PROBLEM3"<<endl; // assert(true==false); // } // if the neigbour doesn'texist (the diamond is on the boundary) // cout<<4<<endl; if (diamond==NULL) { diamond_array[index]=-1; tuple<int,int,int> tmp = {0,0,0}; permutation_array.push_back(tmp); } // ow, we check what is the else { // cout<<5<<endl; // offset=0 => first face of the tetra... // int offset = diamond->get_neighbour_index(&diamond_list[tetra_order[i]]); int offset = -1; for (int k=0;k<diamond->neighbours_faces.size();k++) { if (diamond->neighbours_faces[k]==diamond_list[tetra_order[i]].neighbours_faces[j]) { offset=k; } } if (offset==-1) { cout<<"unknown face"<<endl; assert(true==false); } diamond_array[index]=diamond_id_to_index[diamond->get_id()]+offset; diamond_array[diamond_id_to_index[diamond->get_id()]+offset]=index; tuple<int,int,int> permut = {diamond_list[tetra_order[i]].get_permutation(j)[0], diamond_list[tetra_order[i]].get_permutation(j)[1], diamond_list[tetra_order[i]].get_permutation(j)[2]}; // if (index==4) // { // cout<<get<0>(face_array[index])<<" "<<get<1>(face_array[index])<<" "<<get<2>(face_array[index])<<endl; // } permutation_array.push_back(permut); // permutation_array[index] = permut; // if (index==4) // { // cout<<get<0>(face_array[index])<<" "<<get<1>(face_array[index])<<" "<<get<2>(face_array[index])<<endl; // } // cout<<6<<endl; } face_array.push_back(diamond_list[tetra_order[i]].neighbours_faces[j]); // face_array[index] = diamond_list[tetra_order[i]].neighbours_faces[j]; // if () // cout<<index<<" "<<get<0>(face_array[index])<<" "<<get<1>(face_array[index])<<" "<<get<2>(face_array[index])<<endl; // if (index==4) // { // cout<<get<0>(face_array[index])<<" "<<get<1>(face_array[index])<<" "<<get<2>(face_array[index])<<endl; // cout<<"because i=4"<<endl; // // assert(true==false); // } // cout<<7<<endl; index_to_diamond_id[index]=diamond_list[tetra_order[i]].get_id(); index++; j++; // cout<<8<<endl; } // cout<<9<<endl; } // for (int i=0;i<face_array.size();i++) // { // if ((get<0>(face_array[i])==0) && (get<1>(face_array[i])==0) && (get<2>(face_array[i])==1)) // { // cout<<i<<endl; // cout<<get<0>(face_array[i])<<" "<<get<1>(face_array[i])<<" "<<get<2>(face_array[i])<<endl; // cout<<"PROBLEM4"<<endl; // assert(true==false); // } // } // cout<<"index : "<<index<<endl; // for(int i=0;i<tetra_list.size();i+=2) // { // tetra_array[i]=diamond_id_to_index[tetra_list[i].get_diamond_ref()->get_id()]+tetra_list[i].get_position_in_diamond(); // } // cout<<91<<endl; return index_to_diamond_id; }
true
3eb834d20c645cc286d5a90e3ec5688cf58d1bdf
C++
jackdongrepo/3081W-Bus-Simulation
/project/src/data_structs.h
UTF-8
2,070
3.078125
3
[]
no_license
/** * @file data_structs.h * * @Copyright 2019 3081 Staff, All rights reserved. */ #ifndef SRC_DATA_STRUCTS_H_ #define SRC_DATA_STRUCTS_H_ /******************************************************************************* * Includes ******************************************************************************/ #include <string> #include <vector> /** * @brief Position struct. Contains longtitude and latitude coordinates * * @param[in] x, longtitude * @param[in] y, latittude */ struct Position { Position() : x(0), y(0) {} float x; float y; }; /** * @brief Bus struct. Contains bus metrics at a given point. Contains the * geo location coordinates that get updated constantly. * * @param[in] string::id, name of the bus * @param[in] int num_passengers, current number of passengers * @param[in] int capacity, maximum capacity of bus */ struct BusData { BusData() : id(""), position(Position()), num_passengers(0), capacity(0) {} std::string id; // some unique identifier for the bus Position position; // long lat position of bus int num_passengers; int capacity; }; /** * @brief Stop struct. Contains stop metrics at a given point. Contains the * geo location coordinate and number of people. * * @param[in] string::id, name of the stop * @param[in] Position position, location of the stop * @param[in] int num_people, number of people at the stop */ struct StopData { StopData() : id(""), position(Position()), num_people(0) {} std::string id; // some unique identifier for the stop Position position; // long lat position of bus int num_people; }; /** * @brief Route struct. Contains route metrics at a given point. Contains the * vector of stops structs. * * @param[in] string::id, name of the route * @param[in] std::vector<StopData> stops, vector of stop structs */ struct RouteData { RouteData() : id(""), stops(std::vector<StopData>(0)) {} std::string id; // some unique identifier for the route std::vector<StopData> stops; }; #endif // SRC_DATA_STRUCTS_H_
true
3d80f0ded22005ed3161bc0531a4cff48f313e15
C++
JeffersonCarvalh0/uri-problems
/maratonas/icpc-sa-2016/back-to-the-future/main.cpp
UTF-8
1,748
2.578125
3
[]
no_license
# include <iostream> # include <vector> # include <list> # include <set> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, m, a, b, v1, v2, ans; set<pair<int, int>> s; cin >> n >> m >> a >> b; vector<list<int>> adj_list(n); vector<int> deg(n); vector<bool> inset(n, true); while (m--) { cin >> v1 >> v2; --v1; --v2; adj_list[v1].push_back(v2); adj_list[v2].push_back(v1); ++deg[v1]; ++deg[v2]; } for (int i = 0; i < n; ++i) s.insert({ deg[i], i }); bool erased_first, erased_second; erased_first = erased_second = true; int cur; ans = n; while ((erased_first || erased_second) && !s.empty()) { erased_first = false; erased_second = false; cur = s.begin()->second; if (deg[cur] < a || ans - (deg[cur] + 1) < b) { s.erase(s.begin()); --ans; inset[cur] = false; for (auto adj : adj_list[cur]) if (inset[adj]) { s.erase({ deg[adj], adj }); --deg[adj]; s.insert({ deg[adj], adj }); } erased_first = true; } if (!s.empty()) { cur = prev(s.end())->second; if (deg[cur] < a || ans - (deg[cur] + 1) < b) { s.erase(prev(s.end())); --ans; inset[cur] = false; for (auto adj : adj_list[cur]) if (inset[adj]) { s.erase({ deg[adj], adj }); --deg[adj]; s.insert({ deg[adj], adj }); } erased_second = true; } } } cout << ans << '\n'; return 0; }
true
143eb789e80c7a05efd8eb67b9ecef6115eb3cc0
C++
sungbin-kang/CPlusPlus_Data-Structure
/Stacks/StackL.cpp
UTF-8
1,123
3.359375
3
[]
no_license
// ********************************************************* // Implementation file StackL.cpp for the ADT stack. // ADT list implementation. // ********************************************************* #include "StackL.h" // header file template <typename StackItem> Stack<StackItem> :: Stack() { } template <typename StackItem> bool Stack<StackItem> ::isEmpty() const { return aList.isEmpty(); } template <typename StackItem> bool Stack<StackItem> ::push(const StackItem &newItem) { return aList.insert(1, newItem); // It inserts the new item in the position 1, // and pushes back the item that was originally at position 1. } template <typename StackItem> bool Stack<StackItem> ::pop(StackItem &stackTop) { bool success = aList.retrieve(1, stackTop); if (success == false) return false; aList.remove(1); return true; } template <typename StackItem> bool Stack<StackItem> ::pop() { return aList.remove(1); } template <typename StackItem> bool Stack<StackItem> ::getTop(StackItem &stackTop) const { return aList.retrieve(1, stackTop); }
true
e8f7aa55f08fe1e14ec6d2dceaa96ca7efb1a424
C++
BogdanJWK/Assignments_UBB
/1st Year/Semester 2/SDA/Lab5/MultiMap.cpp
UTF-8
3,480
3.453125
3
[]
no_license
#include "MultiMap.h" #include "MultiMapIterator.h" #include <exception> #include <iostream> using namespace std; //O(1) int MultiMap::hash(TElem tuple, int m) const { int rez = tuple.key; while (rez < 0) rez += m; return rez % m; } void MultiMap::freeNode(node* x) { if (x->next != NULL) freeNode(x->next); delete x; return; } //O(n) void MultiMap::resize() { node* x; node** newhash; int m = this->capacity; this->capacity *= 2; this->nrPairs = 0; newhash = new node * [this->capacity * sizeof(node*)]; for (int i = 0; i < this->capacity; ++i) { node* startNode; startNode = new node; newhash[i] = startNode; newhash[i]->next = NULL; newhash[i]->tuple = NULL_TELEM; } swap(newhash, this->hashtable); for (int i = 0; i < m; ++i) { x = newhash[i]; while (x->next != NULL) { x = x->next; this->add(x->tuple.key, x->tuple.tvalue); } } for (int i = 0; i < m; ++i) freeNode(newhash[i]); delete newhash; } MultiMap::MultiMap() { this->capacity = 8; this->nrPairs = 0; this->hashtable = new node * [this->capacity * sizeof(node*)]; for (int i = 0; i < this->capacity; ++i) { node* startNode; startNode = new node; this->hashtable[i] = startNode; this->hashtable[i]->next = NULL; this->hashtable[i]->tuple = NULL_TELEM; } this->maxAlpha = 0.7; } //O(n) void MultiMap::add(TKey c, TValue v) { node* newNode; newNode = new node; TElem tup; tup.key = c; tup.tvalue = v; newNode->tuple = tup; newNode->next = NULL; if (this->nrPairs / this->capacity > this->maxAlpha) this->resize(); int k = hash(newNode->tuple, this->capacity); node* x = this->hashtable[k]; while (x->next != NULL) x = x->next; x->next = newNode; this->nrPairs++; } //O(n) bool MultiMap::remove(TKey c, TValue v) { TElem tup; tup.key = c; tup.tvalue = v; int k = hash(tup, this->capacity); node* currNode = this->hashtable[k]; node* nextNode; while (currNode->next != NULL) { nextNode = currNode->next; if (nextNode->tuple.key == c && nextNode->tuple.tvalue == v) { currNode->next = nextNode->next; this->nrPairs--; delete nextNode; return true; } currNode = nextNode; } return false; } //O(n) vector<TValue> MultiMap::search(TKey c) const { TElem tup; tup.key = c; int k = this->hash(tup, this->capacity); vector<TValue> a; node* x = this->hashtable[k]; while (x->next != NULL) { x = x->next; if (x->tuple.key == c) a.push_back(x->tuple.tvalue); } return a; } //O(1) int MultiMap::size() const { return this->nrPairs; } //O(1) bool MultiMap::isEmpty() const { return this->nrPairs == 0; } MultiMapIterator MultiMap::iterator() const { return MultiMapIterator(*this); } MultiMap::~MultiMap() { for (int i = 0; i < this->capacity; ++i) freeNode(this->hashtable[i]); delete this->hashtable; } void MultiMap::filter(Condition cond) { node* x; for (int i = 0; i < this->size(); ++i) { x = this->hashtable[i]; if(cond(x->tuple.key) == 0) while (x->next != NULL) { x = x->next; remove(x->tuple.key, x->tuple.tvalue); } } } /* O(n) function filter(condition): x: ^node for i = 0, size() execute x <- hashtable[i] if condition([x].tuple.key) = false then while not [x].next = NIL execute x <- [x].next remove([x].tuple.key, [x].tuple.tvalue) end-while end-fi end-for end-function */
true
3c1f30edebcb7857dddd048944c202655df5ad65
C++
bijooos/QtDesktop
/Day1/valueWidgets/main.cpp
UTF-8
1,350
2.828125
3
[]
no_license
#include <QtWidgets> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget *window = new QWidget; QVBoxLayout *layout = new QVBoxLayout; /* Sliders */ QSlider *slider = new QSlider(Qt::Horizontal, window); /* Setting range for slider */ slider->setRange(0,99); /* Setting initial calue for slider */ slider->setValue(0); /* Progress bar */ QProgressBar *progress = new QProgressBar(window); progress->setRange(0,150); progress->setValue(0); progress->setFormat("%v - %p"); /* Spin box */ QSpinBox *spin = new QSpinBox(window); spin->setRange(0,99); spin->setValue(0); spin->setSuffix(" INR"); /* Adding to layout */ layout->addWidget(slider); layout->addStretch(1); layout->addWidget(progress); layout->addStretch(1); layout->addWidget(spin); window->setLayout(layout); window->show(); /* TODO * 1. Try to implement this in seperate class. * 2. Using signals and slots connect slider and progress bar (When slider value changes, change progressbar) * 3. Connect slider and spin box (When slider value changes, change spin box also). * 4. connect spin box and slider (When spinr value changes, change slider also). */ return app.exec(); }
true
ac1e1fce980a74de18674fb9cca4a5b83a181ce0
C++
myhhx/nfw
/src.2262/nfw_head.h
UTF-8
3,452
2.796875
3
[]
no_license
#ifndef nfw_head_h #define nfw_head_h #include <string.h> #include <array> #include <string> #include <boost/asio.hpp> #include <boost/utility.hpp> #include <nfw_assert.h> #include <nfw_socket.h> #include <nfw_timeout.h> namespace nfw { namespace head { template <typename raw_t> struct socket_t : boost::noncopyable { raw_t * raw; socket_t(raw_t * raw) : raw(raw) { } ~socket_t() { delete raw; } std::string head; }; template <typename raw_t> void cancel(socket_t<raw_t> & socket) { nfw::socket::cancel(*(socket.raw)); } template <typename raw_t> void close(socket_t<raw_t> & socket) { nfw::socket::close(*(socket.raw)); } template <typename raw_t> boost::asio::io_service & get_io_service( socket_t<raw_t> & socket) { return nfw::socket::get_io_service(*(socket.raw)); } template <typename raw_t, typename buf_t, typename handler_t> void async_read_some(socket_t<raw_t> & socket, const buf_t & buf, handler_t && handler) { nfw::socket::async_read_some(*(socket.raw), buf, handler); } template <typename raw_t, typename buf_t, typename handler_t> void async_read(socket_t<raw_t> & socket, const buf_t & buf, handler_t && handler) { boost::asio::async_read(*(socket.raw), buf, handler); } template <typename raw_t, typename buf_t, typename handler_t> void async_write(socket_t<raw_t> & socket, const buf_t & buf, handler_t && handler) { boost::asio::async_write(*(socket.raw), buf, handler); } template <typename raw_t> const std::string & get_head(socket_t<raw_t> & socket) { return socket.head; } typedef std::array<char, 64> head_t; template <typename raw_t, typename handler_t> void head_a(raw_t * raw, const std::string & head, handler_t && handler) { head_t * h = new head_t(); nfw_assert(strlen(head.c_str()) < h->size()); strcpy(h->data(), head.c_str()); boost::asio::async_write(*raw, boost::asio::buffer(*h), [h, raw, handler] ( const boost::system::error_code & error, std::size_t) { if (!error) { socket_t<raw_t> * socket = new socket_t<raw_t>(raw); socket->head = h->data(); handler(socket); } else { handler(NULL); delete raw; } delete h; }); } template <typename raw_t, typename handler_t> void head_b(raw_t * raw, handler_t && handler) { head_t * head = new head_t(); boost::asio::async_read(*raw, boost::asio::buffer(*head), nfw::timeout::wrap(*raw, 2, [head, raw, handler] ( const boost::system::error_code & error, std::size_t) { if (!error) { head->back() = 0; socket_t<raw_t> * socket = new socket_t<raw_t>(raw); socket->head = head->data(); handler(socket); } else { handler(NULL); delete raw; } delete head; })); } }} #endif
true
3065114365face5709d8d6dc05db904a85d9ea71
C++
cdeln/cpp_enum_set
/test/test_common.cpp
UTF-8
4,298
3.3125
3
[ "MIT" ]
permissive
#include "testing.hpp" #include <enum_set/common.hpp> using namespace ::enum_set; TEST_CASE("all returns true only if all arguments are true") { STATIC_CHECK(detail::all(), "All with no arguments is always true"); STATIC_CHECK(detail::all(true), "All of one true is true"); STATIC_CHECK(!detail::all(false), "All of false is false"); STATIC_CHECK(detail::all(true, true), "All of multiple true is true"); STATIC_CHECK(!detail::all(false, true), "All of multiple booleans with one false is false"); STATIC_CHECK(!detail::all(true, false), "All of multiple booleans with one false is false"); STATIC_CHECK(!detail::all(false, false), "All of multiple false is false"); } TEST_CASE("any returns true if atleast one argument is true") { STATIC_CHECK(!detail::any(), "Any with no arguments is always false"); STATIC_CHECK(detail::any(true), "Any of one true is true"); STATIC_CHECK(!detail::any(false), "Any of false is false"); STATIC_CHECK(detail::any(true, true), "Any of multiple true is true"); STATIC_CHECK(detail::any(false, true), "Any of multiple booleans with one true is true"); STATIC_CHECK(detail::any(true, false), "Any of multiple booleans with one true is true"); STATIC_CHECK(!detail::any(false, false), "Any of all false is false"); } TEST_CASE("count returns the number of trues in a set of bools") { STATIC_CHECK(detail::count() == 0, "Count of nothing is 0"); STATIC_CHECK(detail::count(false) == 0, "Count of one false is 0"); STATIC_CHECK(detail::count(true) == 1, "Count of one true is 1"); STATIC_CHECK(detail::count(false, false) == 0, "Count of all false is 0"); STATIC_CHECK(detail::count(false, true) == 1, "Count of bools with one true is 1"); STATIC_CHECK(detail::count(true, false) == 1, "Count of bools with one true is 1"); STATIC_CHECK(detail::count(true, true) == 2, "Count of multiple true is the number of true"); } TEST_CASE("index_of gives the expected index for a singleton type list") { STATIC_CHECK((detail::index_of<int, int>::value == 0), "Index of present type is the index in the type list"); STATIC_CHECK((detail::index_of<bool, int>::value == 1), "Index of non-present type is the size of the type list"); } TEST_CASE("index_of gives the expected index for a general type list") { STATIC_CHECK((detail::index_of<int, int, bool, int>::value == 0), "Index of present type is the index of its first occurence in the type list"); STATIC_CHECK((detail::index_of<bool, int, bool, int>::value == 1), "Index of present type is the index of its first occurence in the type list"); STATIC_CHECK((detail::index_of<float, int, bool, int>::value == 3), "Index of non-present type is the size of the type list"); } TEST_CASE("index_of_value gives the expected index for a singleton value list") { STATIC_CHECK((detail::index_of_value<int, 1>(1) == 0), "Index of present value is the index in the value list"); STATIC_CHECK((detail::index_of_value<int, 1>(0) == 1), "Index of non-present value is the size of the value list"); } TEST_CASE("index_of_value gives the expected index for a general value list") { STATIC_CHECK((detail::index_of_value<int, 1, 2, 1>(1) == 0), "Index of present value is the index of its first occurence in the value list"); STATIC_CHECK((detail::index_of_value<int, 1, 2, 1>(2) == 1), "Index of present value is the index of its first occurence in the value list"); STATIC_CHECK((detail::index_of_value<int, 1, 2, 1>(3) == 3), "Index of non-present value is the size of the value list"); } TEST_CASE("get_value returns the correct value for valid index") { STATIC_CHECK((detail::get_value<int, 1, 2, 1>(0) == 1), "Value at valid index is correct"); STATIC_CHECK((detail::get_value<int, 1, 2, 1>(1) == 2), "Value at valid index is correct"); STATIC_CHECK((detail::get_value<int, 1, 2, 1>(2) == 1), "Value at valid index is correct"); } TEST_CASE("get_value throws an exception on out of range access") { CHECK_THROWS((detail::get_value<int, 1, 2, 1>(3))); CHECK_THROWS((detail::get_value<size_t, 1, 2, 1>(3))); }
true
331790f1bf40319d545e0e2d707cd8844e8a5c80
C++
Layty/CppPrimer
/9th/9.34.cpp
UTF-8
553
3.171875
3
[]
no_license
/*假定vi是一个保存int的容器,其中有偶数值也要奇数值,分析下面循环的行为,然后编写程序验证你的分析是否正确。*/ #include "include.h" int main(int argc, const char** argv) { vector<int> v1={1,2,3,4,5,6,7,8,9}; auto iter=v1.begin(); while(iter!=v1.end()) { if(*iter%2) { iter=v1.insert(iter,*iter); // ++iter; ///-----if里面也需要++一次 } ++iter; } print(v1); while(1); return 0; }
true
b28fbf71be17463dbd6994b2655b6158ed76ba24
C++
pozharus/cpp_yellow_belt
/VectorPart/main.cpp
UTF-8
2,892
3.484375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> //#include "test_framework.h" using namespace std; void PrintVectorPart(const vector<int>& numbers) { vector<int> result; //get it on first negative num from vector or it on last elem auto negative_num = find_if(begin(numbers), end(numbers), [](const int num) { return num < 0; }); if (!numbers.empty()) { if (negative_num != begin(numbers) && negative_num != end(numbers)) { //if neg num was searched, but not first elem auto exclude_r_border = negative_num; while (exclude_r_border != begin(numbers)) { exclude_r_border--; //step right <- left result.push_back(*exclude_r_border); } for (auto& item : result) { cout << item << " "; } } else if (negative_num == end(numbers)) { //have no neg nums in vec result = numbers; reverse(begin(result), end(result)); for (auto& item : result) { cout << item << " "; } } } } /* vector<int> GetVectorPart(const vector<int>& numbers) { vector<int> result; //get it on first negative num from vector or it on last elem auto negative_num = find_if(begin(numbers), end(numbers), [](const int num) { return num < 0; }); if (!numbers.empty()) { if (negative_num == end(numbers)) { //have no neg nums in vec result = numbers; reverse(begin(result), end(result)); } else if(negative_num == begin(numbers)) { //return empty vector if in vec 'numbers' first elem neg num return result; } else { //if neg num was searched auto exclude_r_border = negative_num; while (exclude_r_border != begin(numbers)) { exclude_r_border--; //step right <- left result.push_back(*exclude_r_border); } } } return result; } void TestPrintVectorPart() { vector<int> in_1 = { 6, 1, 8, -5, 4 }; vector<int> out_1 = { 8, 1, 6 }; AssertEqual(GetVectorPart(in_1), out_1, "Case 1"); vector<int> in_2 = { -6, 1, 8, -5, 4 }; vector<int> out_2 = { }; AssertEqual(GetVectorPart(in_2), out_2, "Case 2. First element are already negative"); vector<int> in_3 = { 6, 1, 8, 5, 4 }; vector<int> out_3 = { 4, 5, 8, 1, 6 }; AssertEqual(GetVectorPart(in_3), out_3, "Case 3. Reverse vector if not have negative num"); vector<int> in_4 = { }; vector<int> out_4 = { }; AssertEqual(GetVectorPart(in_4), out_4, "Case 4. Empty vec"); } */ int main() { //TestRunner tr; //tr.RunTest(TestPrintVectorPart, "TestPrintVectorPart"); return 0; }
true
d0ecc1baff679f6658c5bce550845832f82dae29
C++
kkoala0864/LeetCode
/0394_Decode_String/Solution.cpp
UTF-8
1,011
3.140625
3
[]
no_license
#include <Solution.h> #include <iostream> #include <stack> using namespace std; string Solution::decodeString(string s) { if (s.empty()) return s; stack<int> times; string ret; for (int i = 0 ; i < s.size() ;) { if (s.at(i) >= '0' && s.at(i) <= '9') { string time; while (s.at(i) >= '0' && s.at(i) <= '9') { time.push_back(s.at(i++)); } times.push(stoi(time)); } else if (s.at(i) == '[') { string repeat; int count(1); ++i; while (count > 0) { if (s.at(i) == '[') ++count; else if (s.at(i) == ']') --count; if (count > 0) repeat.push_back(s.at(i)); ++i; } repeat = decodeString(repeat); int repTime = times.top(); times.pop(); while (repTime-- > 0) { ret.append(repeat); } } else { ret.push_back(s.at(i)); ++i; } } if (!times.empty()) { string repStr = ret; int repTime = times.top(); while (repTime-- > 1) ret.append(repStr); } return ret; }
true
e834bb2e9b9ad808600587e7ebe2ab78dca3a92a
C++
LionsWrath/maratona-treino
/URI1253/1253.cpp
UTF-8
1,045
2.96875
3
[]
no_license
#include <iostream> #include <string> #include <map> using namespace std; string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; map<char, int> charToInt = { {'A', 0}, {'B', 1}, {'C', 2}, {'D', 3}, {'E', 4}, {'F', 5}, {'G', 6}, {'H', 7}, {'I', 8}, {'J', 9}, {'K', 10}, {'L', 11}, {'M', 12}, {'N', 13}, {'O', 14}, {'P', 15}, {'Q', 16}, {'R', 17}, {'S', 18}, {'T', 19}, {'U', 20}, {'V', 21}, {'W', 22}, {'X', 23}, {'Y', 24}, {'Z', 25}}; int main() { int N; int M; string letter; cin >> N; for (int i=0; i<N; i++) { cin >> letter >> M; for (int j=0; j<letter.size(); j++) { int index = (charToInt[letter[j]] - M); if (index < 0) index += 26; else index %= 26; letter[j] = alphabet[index]; } cout << letter << endl; } return 0; }
true
5da5f2e02aaedb2c2e493295954cd18986f2e7fb
C++
brychrwolf/Cuda-One-Ring
/sandbox/readPLY.cpp
UTF-8
3,120
2.75
3
[]
no_license
#include <iostream> #include <string> #include <sstream> #include <fstream> #include <vector> #include <iterator> template<typename T> std::vector<T> split(std::string line){ std::istringstream iss(line); std::vector<T> results(std::istream_iterator<T>{iss}, std::istream_iterator<T>()); return results; } template std::vector<std::string> split<std::string>(std::string); template std::vector<int> split<int>(std::string); template std::vector<float> split<float>(std::string); int main(){ //std::ifstream infile("test.ply"); std::ifstream infile("../../example_meshes/h.ply"); //std::ifstream infile("../../example_meshes/Unisiegel_UAH_Ebay-Siegel_Uniarchiv_HE2066-60_010614_partial_ASCII.ply"); bool inHeaderSection = true; int faceSectionBegin; int vi = 0; int fi = 0; int numVertices; int numFaces; int* flat_vertices; int* flat_faces; int v_idx = 0; int x_idx; int y_idx; int z_idx; std::string line; int lineNumber = 0; // read every line in the file while(std::getline(infile, line)){ // 3 sections: header, vertices, faces if(inHeaderSection){ // parse for numVertices and numFaces if(line.substr(0, 7) == "element"){ if(line.substr(8, 6) == "vertex"){ std::vector<std::string> words = split<std::string>(line); std::istringstream convert(words[2]); convert >> numVertices; }else if(line.substr(8, 4) == "face"){ std::vector<std::string> words = split<std::string>(line); std::istringstream convert(words[2]); convert >> numFaces; }else{ std::cerr << "ERR (" << lineNumber << "): Bad Element:: " << line << std::endl; } // parse for coord indexes }else if(line.substr(0, 8) == "property"){ std::vector<std::string> words = split<std::string>(line); if(words[2] == "x") x_idx = v_idx; else if(words[2] == "y") y_idx = v_idx; else if(words[2] == "z") z_idx = v_idx; v_idx++; }else if(line.substr(0, 10) == "end_header"){ inHeaderSection = false; faceSectionBegin = lineNumber + 1 + numVertices; flat_vertices = (int*) malloc(3 * numVertices * sizeof(int)); flat_faces = (int*) malloc(3 * numFaces * sizeof(int)); } }else if(lineNumber < faceSectionBegin){ std::vector<int> coords = split<int>(line); flat_vertices[vi*3 + 0] = coords[x_idx]; flat_vertices[vi*3 + 1] = coords[y_idx]; flat_vertices[vi*3 + 2] = coords[z_idx]; vi++; }else{ std::vector<int> coords = split<int>(line); flat_faces[fi*3 + 0] = coords[1]; //coords[0] is list size flat_faces[fi*3 + 1] = coords[2]; flat_faces[fi*3 + 2] = coords[3]; fi++; } lineNumber++; } for(vi = 0; vi < numVertices; vi++) std::cerr << "v[" << vi << "] " << flat_vertices[vi*3 + 0] << " " << flat_vertices[vi*3 + 1] << " " << flat_vertices[vi*3 + 2] << std::endl; std::cerr << std::endl; for(fi = 0; fi < numFaces; fi++) std::cerr << "f[" << fi << "] " << flat_faces[fi*3 + 0] << " " << flat_faces[fi*3 + 1] << " " << flat_faces[fi*3 + 2] << std::endl; std::cerr << std::endl << "numVertices " << numVertices << " numFaces " << numFaces << std::endl; }
true
f05e6a48568c8a856a1167084938546bbfb3f1ba
C++
perryleung/leetcode
/code/222.完全二叉树的节点个数.cpp
UTF-8
1,614
3.515625
4
[]
no_license
/* * @lc app=leetcode.cn id=222 lang=cpp * * [222] 完全二叉树的节点个数 * * https://leetcode-cn.com/problems/count-complete-tree-nodes/description/ * * algorithms * Medium (76.49%) * Likes: 413 * Dislikes: 0 * Total Accepted: 73.9K * Total Submissions: 96.6K * Testcase Example: '[1,2,3,4,5,6]' * * 给出一个完全二叉树,求出该树的节点个数。 * * 说明: * * * 完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 * h 层,则该层包含 1~ 2^h 个节点。 * * 示例: * * 输入: * ⁠ 1 * ⁠ / \ * ⁠ 2 3 * ⁠/ \ / * 4 5 6 * * 输出: 6 * */ // @lc code=start /** * 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 countNodes(TreeNode* root) { if(!root) return 0; TreeNode *left = root; TreeNode* right = root; int left_hight = 0; int right_hight = 0; while(left){ left_hight++; left = left->left; } while(right){ right_hight++; right = right->right; } if (left_hight == right_hight) return pow(2, left_hight) - 1; return 1 + countNodes(root->left) + countNodes(root->right); } }; // @lc code=end
true
79dd4d1a713ed270ccfabc0a6f70e169635e926b
C++
franceschi/CECS2222
/Exam_II/Exam_II/Student.cpp
UTF-8
3,170
3.328125
3
[]
no_license
#include "Student.h" Student::Student():firstName("Jesus"),lastName("Christ"),id("777"),birthDate(),phone(),tests(){} Student::Student(const MyString & tempFirstName, const MyString & tempLastName, const MyString & tempID, const StudentDate & tempBirthDate, const StudentPhone & tempPhone) { setFirstName(tempFirstName); setLastName(tempLastName); setID(tempID); setBirthDate(tempBirthDate); setPhone(tempPhone); } Student::Student(const Student & tempStudent) { setFirstName(tempStudent.getFirstName()); setLastName(tempStudent.getLastName()); setID(tempStudent.getID()); setBirthDate(tempStudent.getBirthDate()); setPhone(tempStudent.getPhone()); } Student::~Student() { } void Student::setValues(const MyString & tempFirstName, const MyString & tempLastName, const MyString & tempID, const StudentDate & tempBirthDate, const StudentPhone & tempPhone) { setFirstName(tempFirstName); setLastName(tempLastName); setID(tempID); setBirthDate(tempBirthDate); setPhone(tempPhone); } void Student::setFirstName(const MyString & tempFirstName) { this->firstName = tempFirstName; } void Student::setLastName(const MyString & tempLastName) { this->lastName = tempLastName; } void Student::setID(const MyString & tempID) { this->id = tempID; } void Student::setPhone(const StudentPhone & tempPhone) { phone.setAreaCode(tempPhone.getAreaCode()); phone.setExchange(tempPhone.getExchange()); phone.setLine(tempPhone.getLine()); } void Student::setBirthDate(const StudentDate & tempDate) { birthDate.setMonth(tempDate.getMonth()); birthDate.setDay(tempDate.getDay()); birthDate.setYear(tempDate.getYear()); } const MyString & Student::getFirstName() const { return (this->firstName); } const MyString & Student::getLastName() const { return (this->lastName); } const MyString & Student::getID() const { return (this->id); } const StudentDate & Student::getBirthDate()const { return (this->birthDate); } const StudentPhone & Student::getPhone()const { return (this->phone); } const StudentTestScores & Student::getScores() const { return (this->tests); } Student & Student::operator=(const Student & tempStudent) { this->firstName = tempStudent.getFirstName(); this->lastName = tempStudent.getLastName(); this->id = tempStudent.getID(); this->birthDate = tempStudent.getBirthDate(); this->phone = tempStudent.getPhone(); return (*this); } istream & operator >> (istream & in, Student & tempStudent) { cin.ignore(); cout << "First Name: "; in >> tempStudent.firstName; cin.ignore(); cout << "Last Name: "; in >> tempStudent.lastName; cout << "Id: "; in >> tempStudent.id; cout << "Enter Birthdate (mm/dd/yyyy): " << endl; in >> tempStudent.birthDate; cout << "Enter Phone Number (###-###-####): "; in >> tempStudent.phone; return in; } ostream & operator << (ostream & out, const Student & tempStudent) { out << "First Name:" << tempStudent.getFirstName() << endl; out << "Last Name:" << tempStudent.getLastName() << endl; out << "Id:" << tempStudent.getID() << endl; out << "Phone:" << tempStudent.getPhone() << endl; out << "Birthdate:" << tempStudent.getBirthDate() << endl; return out; }
true
436f837c4138f7fb773a72ceb88549ed2e026f88
C++
VIWER-S/VIWER-S_OFFLINE_CPP
/Source/DisplaySources.h
UTF-8
1,616
2.515625
3
[]
no_license
/* ============================================================================== DisplaySources.h Created: 23 Nov 2020 7:21:46pm Author: Ulrik ============================================================================== */ #pragma once #include "JuceHeader.h" #include "Constants.h" class DisplaySources : public juce::Component { public: DisplaySources::DisplaySources(); DisplaySources::~DisplaySources(); int DisplaySources::getWidth(); int DisplaySources::getHeight(); void DisplaySources::paint(juce::Graphics& g); void DisplaySources::resized(); void DisplaySources::setLoc(double* loc, double* loc_kal, double* loc_fad); void DisplaySources::setImp(double* imp, double* imp_kal, double* imp_fad); private: float m_width = 120; float m_height = 60; juce::Label m_label_sources, m_label_fading, m_box_sources, m_box_fading; // Pointers to convey found directions from Viwer to DisplayLocalisation double* m_ptrLoc; double* m_ptrImp; // Pointers to convey tracked sources from Viwer to DisplayLocalisation double* m_ptrLoc_kal; double* m_ptrImp_kal; // Pointers to convey fading sources from Viwer to DisplayLocalisation double* m_ptrLoc_fad; double* m_ptrImp_fad; int m_numPeaks; std::vector<std::vector<double>> m_peaks; int m_numPeaks_kal; std::vector<std::vector<double>> m_peaks_kal; int m_numPeaks_fad; std::vector<std::vector<double>> m_peaks_fad; };
true
4f3ff0aa6e689c7ef0efe2101e143cdb893c2dda
C++
x0t1c-01/po
/ProvaScritta/IBRAHEM MOUSTAFA 203798/LezioneMagistrale.h
UTF-8
399
2.640625
3
[]
no_license
#ifndef LEZIONE_MAGISTRALE_H #define LEZIONE_MAGISTRALE_H #include "Lezione.h" class LezioneMagistrale : public Lezione { public: LezioneMagistrale(string d, string a, int p) : Lezione(d,a,p) {} int calcolaDistanziamento(){return partecipanti*4;} //Implementare qui il metodo calcolaDistanziamento calcolato come il numero di partecipanti alla lezione * 4. }; #endif
true
08083673cf303fcc367a82e6614ce6092d42994b
C++
yameenjavaid/Online-Judge-Solutions
/UVa/uva12190.cpp
UTF-8
1,131
2.75
3
[]
no_license
#include <bits/stdc++.h> using namespace std; // Electric Bill #define num long long int num A, B; inline num f(num x){ if(x <= 100) return x * 2; if(x <= 10000) return 2 * 100 + (x - 100) * 3; if(x <= 1000000) return 2 * 100 + 3 * 9900 + (x - 10000) * 5; return 2 * 100 + 3 * 9900 + 5 * 990000 + (x - 1000000) * 7; } inline num af(num x){ if(x <= 2 * 100) return x / 2; if(x <= 2 * 100 + 3 * 9900) return (x - 2 * 100) / 3 + 100; if(x <= 2 * 100 + 3 * 9900 + 5 * 990000) return (x - 2 * 100 - 3 * 9900) / 5 + 10000; return (x - 2 * 100 - 3 * 9900 - 5 * 990000) / 7 + 1000000; } int main(){ while(cin >> A >> B){ if(A + B == 0) break; num left = 0; num right = A; while(left <= right){ num x = (left + right) / 2; num y = af(B + f(x)); num fxy = f(x + y); if(fxy == A){ cout << f(x) << endl; break; } else if(fxy < A) left = x+1; else right = x-1; } } }
true
6927f332e0eb19f5dc12915433e8b6e137a3e468
C++
xiangtian/leetcode
/ValidateBinarySearchTree.cpp
UTF-8
2,816
3.6875
4
[]
no_license
#include<iostream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: bool isValidBST(TreeNode *root) { // null tree is BST if(root == NULL) { return true; } bool isLeftValidBST = true; if(root->left) { // leftChild->right TreeNode* rightestChild = root->left->right; // find rightest chidl while(rightestChild) { if (rightestChild->val >= root->val) { isLeftValidBST = false; break; } rightestChild = rightestChild->right; } // leftChild if (isLeftValidBST && root->left->val < root->val) { isLeftValidBST = isValidBST(root->left); } else { isLeftValidBST = false; } } bool isRightValidBST = true; if (root->right) { // rightChild->leftChild TreeNode* leftestChild = root->right->left; // find leftest child while(leftestChild) { if (leftestChild->val <= root->val) { isRightValidBST = false; break; } leftestChild = leftestChild->left; } if (isRightValidBST && root->right->val > root->val) { isRightValidBST = isValidBST(root->right); } else { isRightValidBST = false; } } return isLeftValidBST && isRightValidBST; } public: void testCase() { TreeNode* root = new TreeNode(5); root->left = new TreeNode(3); root->right = new TreeNode(8); root->left->left = new TreeNode(2); root->left->right = new TreeNode(4); root->right->left = new TreeNode(6); root->right->right = new TreeNode(12); cout << isValidBST(root) << endl; // 1 root->right->right->left = new TreeNode(1); cout << isValidBST(root) << endl; // 0 root->right->right->left = new TreeNode(8); cout << isValidBST(root) << endl; // 0 root->right->right->left = new TreeNode(9); cout << isValidBST(root) << endl; // 1 // root->left->right = new TreeNode(7); // cout << isValidBST(root) << endl; // 0 root->right->left->left = new TreeNode(5); cout << isValidBST(root) << endl; // 1 TreeNode* singleNode = new TreeNode(7); cout << isValidBST(singleNode) << endl; // 1 } }; int main(void) { Solution s; s.testCase(); }
true
19ca227d9025f47b2cffbf4649c55f848977064d
C++
winniezhou0/gpu-cache-model
/src/tracer/tracer.cpp
UTF-8
6,293
2.65625
3
[ "MIT" ]
permissive
////////////////////////////////// // // == A reuse distance based GPU cache model // This file is part of a cache model for GPUs. The cache model is based on // reuse distance theory extended to work with GPUs. The cache model primarly // focusses on modelling NVIDIA's Fermi architecture. // // == More information on the GPU cache model // Article............A Detailed GPU Cache Model Based on Reuse Distance Theory // Authors............C. Nugteren et al. // // == Contents of this file // This file provides the Ocelot-based tracer. The tracer takes as input a CUDA // program emulated in Ocelot and outputs all memory accesses made per thread // (not in the real execution order - it is just an emulation). The output is // written to a file and can be limited to a certain amount of threads. // // == File details // Filename...........src/tracer/tracer.cpp // Author.............Cedric Nugteren <www.cedricnugteren.nl> // Affiliation........Eindhoven University of Technology, The Netherlands // Last modified on...30-Oct-2013 // ////////////////////////////////// // Ocelot includes #include <ocelot/api/interface/ocelot.h> #include <ocelot/trace/interface/TraceGenerator.h> #include <ocelot/trace/interface/TraceEvent.h> #include <ocelot/executive/interface/ExecutableKernel.h> #include <ocelot/ir/interface/PTXInstruction.h> #include <ocelot/ir/interface/PTXOperand.h> // C++ includes #include <iostream> #include <fstream> #include <map> // Set the maximum amount of threads #define MAX_THREADS (8*1024) ////////////////////////////////// // The trace generator class ////////////////////////////////// class TraceGenerator : public trace::TraceGenerator { // Counters unsigned long loadCounter; unsigned long storeCounter; unsigned long computeCounter; unsigned long memoryCounter; unsigned kernel_id; unsigned threads; // Status bool finished; bool initialised; // Base address unsigned long baseAddress; // Mapping of CUDA thread IDs (gid) to trace thread IDs (tid) std::map<unsigned,unsigned> gids; // File streams std::ofstream addrFile; // Name of the program std::string name; // Public methods public: // Constructor with filename TraceGenerator(std::string _name="default") { name = _name; kernel_id = 0; } // Close output files void finish() { if (!finished) { finalise(); } float ratio = computeCounter/(float)memoryCounter; std::cout << "[Finished kernel] Loads: " << loadCounter << ", Stores: " << storeCounter << "\n"; std::cout << "[Finished kernel] Compute (" << computeCounter << ") memory (" << memoryCounter << ") ratio: " << ratio << "\n"; //abort(); // End Ocelot. The exit(1) function does not seem to work. } // Open output files void initialize(const executive::ExecutableKernel & kernel) { std::cout << "Starting with " << kernel.name << "" << std::endl; loadCounter = 0; storeCounter = 0; computeCounter = 0; memoryCounter = 0; baseAddress = 0; threads = 0; finished = false; initialised = false; if (kernel_id < 10) { addrFile.open("../../../output/"+name+"/"+name+"_0"+std::to_string(kernel_id)+".trc"); } else { addrFile.open("../../../output/"+name+"/"+name+"_"+std::to_string(kernel_id)+".trc"); } kernel_id++; } // Finalise the data void finalise() { std::cout << "[Tracer] completed up to " << MAX_THREADS << " threads" << std::endl; finished = true; if( addrFile.is_open()) { addrFile.close(); } } // Ocelot event callback void event(const trace::TraceEvent & event) { // Get a flat thread/block ID/dimension unsigned bid = event.blockId.x*event.gridDim.y*event.gridDim.z + event.blockId.y*event.gridDim.z + event.blockId.z; unsigned bdim = event.blockDim.x*event.blockDim.y*event.blockDim.z; // Initialise the trace if (!initialised) { addrFile << "blocksize: " << event.blockDim.x << " " << event.blockDim.y << " " << event.blockDim.z << std::endl; initialised = true; } // Finalise the trace if (bid == MAX_THREADS/bdim && !finished) { finalise(); } // Only process the first MAX_THREADS threads if (bid < MAX_THREADS/bdim) { // Found a global load/store if (((event.instruction->addressSpace == ir::PTXInstruction::Global) && (event.instruction->opcode == ir::PTXInstruction::Ld || event.instruction->opcode == ir::PTXInstruction::St)) || (event.instruction->opcode == ir::PTXInstruction::Tex )) { // Loop over a warp's memory accesses for (unsigned i=0; i<event.memory_addresses.size(); i++) { while (event.active[i] == 0) { i++; } // Compute the address and thread ID unsigned long address = event.memory_addresses[i]; unsigned gid = bid*bdim + i; // Compute the data size ir::PTXOperand::DataType datatype = event.instruction->type; unsigned vector = event.instruction->vec; unsigned size = vector * ir::PTXOperand::bytes(datatype); // Found a global load or texture load if (event.instruction->opcode == ir::PTXInstruction::Ld || event.instruction->opcode == ir::PTXInstruction::Tex) { loadCounter++; addrFile << "" << gid << " 0 " << address << " " << size << "\n"; } // Found a global store if (event.instruction->opcode == ir::PTXInstruction::St) { storeCounter++; addrFile << "" << gid << " 1 " << address << " " << size << "\n"; } // Next thread in the warp } } // Count 'compute' and 'memory' instructions to get the 'computational intensity' if (event.instruction->addressSpace == ir::PTXInstruction::Global) { ir::PTXOperand::DataType datatype = event.instruction->type; unsigned size = ir::PTXOperand::bytes(datatype); memoryCounter += size; } else { computeCounter++; } } } }; ////////////////////////////////// // Forward declaration of the original main function ////////////////////////////////// extern int original_main(int, char**); ////////////////////////////////// // The new main function to call the Ocelot tracer and the original main ////////////////////////////////// int main(int argc, char** argv) { TraceGenerator generator(NAME); ocelot::addTraceGenerator(generator); return original_main(argc,argv); } //////////////////////////////////
true
fe9d0afeb0414a2b4b2a20952b6ca8933f323dc6
C++
zhouqqhh/VLSI_project
/src/polish/verify.hpp
UTF-8
1,427
3.1875
3
[]
no_license
#pragma once #include <algorithm> #include <vector> #include "polish_node.hpp" namespace polish { namespace detail { inline bool overlap(meta_polish_node::dimension_type lo0, meta_polish_node::dimension_type hi0, meta_polish_node::dimension_type lo1, meta_polish_node::dimension_type hi1) noexcept { return (lo0 < hi1) ^ (lo1 >= hi0); } // Whether two (x, y, w, h) tuples intersect. template<typename Tuple> bool overlap(const Tuple &a, const Tuple &b) noexcept { return overlap(get<0>(a), get<0>(a) + get<2>(a), get<0>(b), get<0>(b) + get<2>(b)) && overlap(get<1>(a), get<1>(a) + get<3>(a), get<1>(b), get<1>(b) + get<3>(b)); } } // Whether a range of (x, y, w, h) tuples overlap. template<typename InIt> bool overlap(InIt first, InIt last) { using tuple_type = typename std::iterator_traits<InIt>::value_type; std::vector<tuple_type> v(first, last); std::sort(v.begin(), v.end(), [](const tuple_type &t1, const tuple_type &t2) { return std::get<0>(t1) < std::get<0>(t2); }); return std::adjacent_find(v.cbegin(), v.cend(), [](const tuple_type &t1, const tuple_type &t2) { return detail::overlap(t1, t2); }) != v.cend(); } }
true
174c51a125cde1acea72fa7d59dae0ca02ca7a02
C++
bmanga/VDB
/src/core/Breakpoint.cpp
UTF-8
2,805
3.09375
3
[]
no_license
#include "Breakpoint.hpp" // DEBUG: Move these functions to their own dedicated file. void procmsg(const char *format, ...); unsigned getChildInstructionPointer(pid_t child_pid); Breakpoint::Breakpoint(void *addr, uint64_t line_number, std::string file_name) { this->addr = addr; this->line_number = line_number; this->file_name = file_name; procmsg("Breakpoint created: 0x%08x\n", addr); } // Enables this breakpoint by replacing the instruction at its assigned address // with an 'int 3' trap instruction. // The original instruction at the address is saved and can be restored by // disabling this breakpoint. void Breakpoint::enable(pid_t pid) { orig_data = ptrace(PTRACE_PEEKTEXT, pid, addr, 0); ptrace(PTRACE_POKETEXT, pid, addr, (orig_data & ~(0xFF)) | 0xCC); procmsg("[DEBUG] Pre-enabled data at 0x%08x: 0x%08x\n", addr, orig_data); procmsg("[DEBUG] Post-enabled data at 0x%08x: 0x%08x\n", addr, ptrace(PTRACE_PEEKTEXT, pid, addr, 0)); } // Disables this breakpoint by replacing the 'int 3' trap instruction at its // assigned address with the original instruction. // The original instruction at the address is saved and can be restored by // enabling this breakpoint. void Breakpoint::disable(pid_t pid) { uint64_t data = ptrace(PTRACE_PEEKTEXT, pid, addr, 0); // Ensure that the instruction being replaced is a trap 'int 3' breakpoint instruction assert((data & 0xFF) == 0xCC); ptrace(PTRACE_POKETEXT, pid, addr, (data & ~(0xFF)) | (orig_data & 0xFF)); procmsg("[DEBUG] Pre-disabled data at 0x%08x: 0x%08x\n", addr, data); procmsg("[DEBUG] Post-disabled data at 0x%08x: 0x%08x\n", addr, ptrace(PTRACE_PEEKTEXT, pid, addr, 0)); } // Disables this breakpoint, steps over it and then re-enables the breakpoint. bool Breakpoint::stepOver(pid_t pid) { user_regs_struct regs; int wait_status; // Get registers ptrace(PTRACE_GETREGS, pid, 0, &regs); procmsg("[DEBUG] Resuming from EIP = 0x%08x\n", regs.rip); // Make sure we are stopped at this breakpoint #if defined ENV64 assert(regs.rip == (unsigned long) addr + 1); #elif defined ENV32 assert(regs.eip == (long) addr + 1); #endif // Set the instruction pointer to this breakpoint's address #if defined ENV64 regs.rip = (long) addr; #elif defined ENV32 regs.eip = (long) addr; #endif ptrace(PTRACE_SETREGS, pid, 0, &regs); // Temporarily disable this breakpoint disable(pid); procmsg("[DEBUG] Pre-step EIP = 0x%08x\n", getChildInstructionPointer(pid)); if (ptrace(PTRACE_SINGLESTEP, pid, 0, 0)) { perror("ptrace"); return false; } wait(&wait_status); procmsg("[DEBUG] Post-step EIP = 0x%08x\n", getChildInstructionPointer(pid)); // Re-enable this breakpoint enable(pid); // Check if the child has exited after stepping if (WIFEXITED(wait_status)) { return false; } return true; }
true
292e21e452812d6960cea4c1daa9af98f6b57049
C++
inigomanuel/Abstracta_Codigos
/Protocolo/src/Enigma.cpp
UTF-8
3,153
2.6875
3
[]
no_license
#include "Enigma.h" Enigma::Enigma(int a,int b,int c,string clave){ this->a=a; this->b=b; this->c=c; this->clave=clave; srotor(rtr1,a,l1); srotor(rtr2,b,l2); srotor(rtr3,c,l3); cout<<"l1= "<<l1<<"l2= "<<l2<<"l3= "<<l3<<endl; } int Enigma::modulo(int a){ int n=alfabeto.size(); int r=a-(a/n*n); if(r<0) r+=n; return r; } void Enigma::srotor(string &rtr,int cr,int l){ switch(cr){ case 1: rtr=rotor1; l=alfabeto.find('Q'); break; case 2: rtr=rotor2; l=alfabeto.find('E'); break; case 3: rtr=rotor3; l=alfabeto.find('V'); break; case 4: rtr=rotor4; l=alfabeto.find('K'); break; case 5: rtr=rotor5; l=alfabeto.find('Z'); break; } } string Enigma::cifrado(string msn){ string cypher; string tmp=clave; int p; int r1=alfabeto.find(clave[0]); int r2=alfabeto.find(clave[1]); int r3=alfabeto.find(clave[2]); for(int i=0;i<msn.size();i++){ r3=modulo(r3+1); if(alfabeto[r3]==alfabeto[modulo(l3+1)]) r2=modulo(r2+1); if(alfabeto[r3]==alfabeto[modulo(l3+1)] && alfabeto[r2]==alfabeto[modulo(l2+1)]) r1=modulo(r1+1); tmp=rtr3[modulo(r3+alfabeto.find(msn[i]))]; ///cout <<"1: "<<modulo(r3+alfabeto.find(msn[i]))<<endl; tmp=rtr2[modulo(r2+alfabeto.find(tmp)-r3)]; ///cout <<"2: "<<modulo(r2+alfabeto.find(tmp)-r3)<<endl; tmp=rtr1[modulo(r1+alfabeto.find(tmp)-r2)]; ///cout <<"3: "<<modulo(r1+alfabeto.find(tmp)-r2)<<endl; tmp=reflec[modulo(alfabeto.find(tmp)-r1)]; p=modulo(rtr1.find(alfabeto[modulo(alfabeto.find(tmp)+r1)])-r1); p=modulo(rtr2.find(alfabeto[modulo(p+r2)])-r2); tmp=alfabeto[modulo(rtr3.find(alfabeto[modulo(p+r3)])-r3)]; cypher+=tmp; } for(int i=0;i<cypher.size();i++) cout<<cypher[i]; cout<<endl; return cypher; } string Enigma::descifrado(string msn){ string decypher; string tmp=clave; int p; int r1=alfabeto.find(clave[0]); int r2=alfabeto.find(clave[1]); int r3=alfabeto.find(clave[2]); for(int i=0;i<msn.size();i++){ r3=modulo(r3+1); if(alfabeto[r3]==alfabeto[modulo(l3+1)]) r2=modulo(r2+1); if(alfabeto[r3]==alfabeto[modulo(l3+1)] && alfabeto[r2]==alfabeto[modulo(l2+1)]) r1=modulo(r1+1); tmp=rtr3[modulo(r3+alfabeto.find(msn[i]))]; tmp=rtr2[modulo(r2+alfabeto.find(tmp)-r3)]; tmp=rtr1[modulo(r1+alfabeto.find(tmp)-r2)]; tmp=reflec[modulo(alfabeto.find(tmp)-r1)]; p=modulo(rtr1.find(alfabeto[modulo(alfabeto.find(tmp)+r1)])-r1); p=modulo(rtr2.find(alfabeto[modulo(p+r2)])-r2); tmp=alfabeto[modulo(rtr3.find(alfabeto[modulo(p+r3)])-r3)]; decypher+=tmp; } for(int i=0;i<decypher.size();i++) cout<<decypher[i]; cout<<endl; return decypher; }
true
88c9313430b18174119ed1e83644a2df1110da7e
C++
Pravesh-Jamgade/code
/dp/couuntStepsN.cpp
UTF-8
721
2.515625
3
[]
no_license
#include<bits/stdc++.h> #include<functional> using namespace std; #define vi vector<int> #define fi first #define se second #define pb push_back typedef long long ll; const int mxN = 1e3; int dp[mxN] = {-1}; int minF(int a, int b, int c){ if(a>b){ if(b>c) return c; else return b; }else{ if(a>c) return c; else return a; } } int solve(int n){ if(n<=1) return 0; if(dp[n]>-1) return dp[n]; if(n%3==0){ n=n/3; } else if(n%2 == 0){ n=n/2; } else n=n-1; dp[n]=1+ solve(n); return dp[n]; } int main(){ freopen("input.txt", "r", stdin); int n; cin>>n; int stp = 0; for(int i=0; i<= n; i++) dp[i]=-1; for(int i=1; i<= n; i++){ cout<<i<<" steps: "<<solve(i)<<endl; } return 0; }
true
dd5ad7e57c139a42ba3cc9e85962f7bbf1274aeb
C++
HannahTin/Leetcode
/二叉树/二叉搜索树/235_Lowest Common Ancestor of a Binary Search Tree.cpp
UTF-8
1,757
3.953125
4
[]
no_license
/* 235. 二叉搜索树的最近公共祖先 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” 例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5] */ using namespace std; #include <vector> #include <stack> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; // 递归法 // 不用使用回溯,二叉搜索树自带方向性,可以方便的从上向下查找目标区间,遇到目标区间内的节点,直接返回。 class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root->val > p->val && root->val > q->val) { return lowestCommonAncestor(root->left, p, q); } else if (root->val < p->val && root->val < q->val) { return lowestCommonAncestor(root->right, p, q); } else return root; } }; // 迭代法 class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { while(root) { if (root->val > p->val && root->val > q->val) { root = root->left; } else if (root->val < p->val && root->val < q->val) { root = root->right; } else return root; } return NULL; } };
true
41ecd250385a0c34edd3c578031ca9142ae63904
C++
shinobi-wonji/CURSO-ARDUINO
/CLASE_7_DebounceLCDShield/CLASE_7_DebounceLCDShield.ino
UTF-8
3,766
2.921875
3
[]
no_license
/* * Ejemplo utilizacion LCD Shield * * Conexiones DHT22 (Visto de frente, de izquiera a derecha) * * DHT22, pin 1, to 5V * DHT22, pin 2, to digital pin 2 (A eleccion) * DHT22, pin 3, No coneccted * DHT22, pin 4, to ground. * * Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor. * * Conexiones LCD KeyPad Shield: * LCD RS pin to digital pin 8 * LCD Enable pin to digital pin 9 * LCD D4 pin to digital pin 4 * LCD D5 pin to digital pin 5 * LCD D6 pin to digital pin 6 * LCD D7 pin to digital pin 7 * * LCD BL pin to digital pin 10 * * KEYS BUTTONS to analog pin 0 * * Pines libres: * Arriba: D13 D12 D11 D3 D1 D0 * Abajo IZQ: RST 3.3V 5V GND GND VIN * Abajo DER: A1 A2 A3 A4 A5 */ /* * Incluyo las librerias arduino qque utilizaremos. */ #include <LiquidCrystal.h> /* * Incluyo el archivo donde defino nuestro nuevo tipo de dato. (Ver mas abajo) */ #include "new_types.h" /* * Incluyo el archivo donde defino las conecciones y y otras configuraciones como el debug */ #include "settings.h" /* * Un numero que modificaremos con los botones y mostraremos en al pantalla. */ int numero = 0; bool blStatus = false; /* * Inicializamos los objetos que utilizaremos. * Un 'LiquidCrystal' llamado 'lcd' conectado segun lo definido en 'settings.h' */ LiquidCrystal lcd(rsLcdPin, enableLcdPin, d4LcdPin, d5LcdPin, d6LcdPin, d7LcdPin); /* * Inicializacion de nuestro proyecto.. */ void setup (void) { /* * Si esta definido DEBUG (Ver archivo 'settings.h') * Inicio el puerto serial para imprimir mensajes. */ #ifdef DEBUG Serial.begin (9600); while (!Serial); #endif /* * Inicializo el objeto lcd indicandole que es una pantalla de 16x2 * Posiciono el cursor arriba a la izquierda y escribo un texto. */ lcd.begin(16, 2); lcd.setCursor(0,0); lcd.print("Presione tecla"); /* Enciendo el blacklight */ pinMode(lcdBlackLight, OUTPUT); digitalWrite(lcdBlackLight, HIGH); blStatus = true; } /* * Codigo principal */ void loop (void) { /* * Creo una nueva variable del tipo KeyButton * cuyo tipo esta definido en el archivo 'new_types.h' */ KeyButton buttonState = KEY_NONE; /* * Obtengo el estado del boton. * * Esta funcion realiza el debounce para evitar el ruido de los botones. * y devuelve solo una vez cuando precionamon el pulsador. * (Si mantenemos presionado el pulsador UP solo una vez va informar * la tecla de forma que paresca que presionamos muchas veces el pulsador * cuando todavia no soltamos el pulsados.) */ buttonState = get_key_debounced_unique(); /* * Segun la tecla presionada modifico el nro e informo en el LCD * o prendo y apago el blackligh del lcd con la tecla SELECT. */ switch (buttonState) { case KEY_RIGHT: numero += 10; break; case KEY_LEFT: numero -= 10; break; case KEY_UP: numero++; break; case KEY_DOWN: numero--; break; case KEY_SELECT: if (blStatus) { digitalWrite(lcdBlackLight, LOW); blStatus = false; } else { digitalWrite(lcdBlackLight, HIGH); blStatus = true; } break; case KEY_NONE: default: break; } /* * Si existe la definicion de DEBUG * Imprimo el nro en el puerto serial como debug.. */ #ifdef DEBUG Serial.print("Numero "); Serial.println(numero); #endif lcd.setCursor(0,1); lcd.print("Numero "); lcd.setCursor(strlen("Numero "), 1); // strlen devuelve el tamaño del string, nos aprovechamos de ello para posicionar el cursor automaticamente. lcd.print(numero); lcd.print(" "); // Imprimo un par de espacios par eviotar que queden nros viejos de fondo.. }
true
51109018d924f042ed1da7ead47fc7a6c3e83628
C++
Tiryoh/radial_menu_ros
/radial_menu_model/include/radial_menu_model/item.hpp
UTF-8
6,842
2.703125
3
[ "MIT" ]
permissive
#ifndef RADIAL_MENU_MODEL_ITEM_HPP #define RADIAL_MENU_MODEL_ITEM_HPP #include <cstdint> #include <memory> #include <string> #include <vector> #include <radial_menu_model/xml_element.hpp> #include <ros/console.h> namespace radial_menu_model { // pointer types class Item; typedef std::shared_ptr< Item > ItemPtr; typedef std::shared_ptr< const Item > ItemConstPtr; // menu item. // state of Item cannot be changed after construction by itemsFromDescription() // because all methods of Item is const. class Item : public std::enable_shared_from_this< Item > { public: enum DisplayType { Name, AltTxt, Image }; protected: Item() {} public: virtual ~Item() {} // propaties std::int32_t itemId() const { return item_id_; } const std::string &name() const { return name_; } std::string path(const char separator = '.') const { const ItemConstPtr p(parent()); return p ? (p->path() + separator + name_) : name_; } DisplayType displayType() const { return display_type_; } const std::string &altTxt() const { return alt_txt_; } const std::string &imgURL() const { return img_url_; } // root ItemConstPtr root() const { const ItemConstPtr p(parent()); return p ? p->root() : shared_from_this(); } // parent ItemConstPtr parent() const { return parent_.lock(); } ItemConstPtr parentLevel() const { const ItemConstPtr p(parent()); return p ? p->sibilingLevel() : ItemConstPtr(); } // sibilings int numSibilings() const { const ItemConstPtr p(parent()); return p ? p->children_.size() : 1; } std::vector< ItemConstPtr > sibilings() const { const ItemConstPtr p(parent()); return p ? p->children_ : std::vector< ItemConstPtr >(1, shared_from_this()); } ItemConstPtr sibiling(const int sid) const { const ItemConstPtr p(parent()); if (p && sid >= 0 && sid < p->children_.size()) { return p->children_[sid]; } else if (!p && sid == 0) { return shared_from_this(); } else { return ItemConstPtr(); } } ItemConstPtr sibilingLevel() const { const ItemConstPtr p(parent()); if (p) { for (const ItemConstPtr &s : p->children_) { if (s) { return s; } } } return shared_from_this(); } int depth() const { const ItemConstPtr p(parent()); return p ? p->depth() + 1 : 0; } // children int numChildren() const { return children_.size(); } const std::vector< ItemConstPtr > &children() const { return children_; } ItemConstPtr child(const int cid) const { return (cid >= 0 && cid < children_.size()) ? children_[cid] : ItemConstPtr(); } ItemConstPtr childLevel() const { for (const ItemConstPtr &c : children_) { if (c) { return c; } } return ItemConstPtr(); } // factory static std::vector< ItemConstPtr > itemsFromDescription(const std::string &desc) { struct Internal { static bool appendItems(const XmlElement &elm, std::vector< ItemConstPtr > *const items, const ItemPtr &parent_item = ItemPtr(), const int default_row = 0) { // is the element name "item"? if (elm.name() != "item") { ROS_ERROR_STREAM("Item::itemsFromDescription(): Unexpected element '" << elm.name() << "'"); return false; } // create an item and append it to the given list const ItemPtr item(new Item()); item->item_id_ = items->size(); items->push_back(item); // associate the item with the parent if (parent_item) { const int row(elm.attribute("row", default_row)); if (row < 0 || row >= parent_item->children_.size()) { ROS_ERROR_STREAM("Item::itemsFromDescription(): '" << row << "' is out of row range"); return false; } if (parent_item->children_[row]) { ROS_ERROR_STREAM("Item::itemsFromDescription(): Multiple items in the row '" << row << "'"); return false; } parent_item->children_[row] = item; item->parent_ = parent_item; } // load the item name from the attribute if (!elm.getAttribute("name", &item->name_)) { ROS_ERROR("Item::itemsFromDescription(): No attribute 'name'"); return false; } // load the display type from the attribute const std::string display(elm.attribute< std::string >("display", "name")); if (display == "name") { item->display_type_ = Item::Name; } else if (display == "alttxt") { item->display_type_ = Item::AltTxt; if (!elm.getAttribute("alttxt", &item->alt_txt_)) { ROS_ERROR("Item::itemsFromDescription(): No attribute 'alttxt'"); return false; } } else if (display == "image") { item->display_type_ = Item::Image; if (!elm.getAttribute("imgurl", &item->img_url_)) { ROS_ERROR("Item::itemsFromDescription(): No attribute 'imgurl'"); return false; } } else { ROS_ERROR_STREAM("Item::itemsFromDescription(): Unknown display type '" << display << "'"); return false; } // allocate child items const int rows(elm.attribute("rows", elm.numChildElements())); if (rows < 0) { ROS_ERROR_STREAM("Item::itemsFromDescription(): Invalid row size '" << rows << "'"); return false; } item->children_.resize(rows); // recursively update the given list const std::vector< XmlElementConstPtr > child_elms(elm.childElements()); for (std::size_t i = 0; i < child_elms.size(); ++i) { if (!appendItems(*child_elms[i], items, item, i)) { return false; } } return true; } }; // parse the given xml description const XmlElementConstPtr elm(XmlElement::fromString(desc)); if (!elm) { return std::vector< ItemConstPtr >(); } // populate items by parsing the root xml element std::vector< ItemConstPtr > items; if (!Internal::appendItems(*elm, &items)) { return std::vector< ItemConstPtr >(); } return items; } protected: typedef std::weak_ptr< const Item > ItemWeakConstPtr; std::int32_t item_id_; // int32_t is the type of ids in State msg std::string name_; DisplayType display_type_; std::string alt_txt_, img_url_; ItemWeakConstPtr parent_; std::vector< ItemConstPtr > children_; }; } // namespace radial_menu_model #endif
true
13e628aa607d699f40fa3165b56ed8bf4da59582
C++
zabeli571/TowerDefense
/GameField.h
UTF-8
1,513
2.609375
3
[]
no_license
#ifndef GAME_FIELD_H #define GAME_FIELD_H #include <iostream> #include <allegro5/allegro.h> #include <allegro5/allegro_primitives.h> #include "MainObject.h" #include <cstdlib> #include <ctime> using namespace std; class GameField: public MainObject { friend class GameObject; private: static const int CREATOR_XPOS=50; static const int CREATOR_YPOS=40; static const int CREATOR_WIDTH=600; static const int CREATOR_HEIGHT=300; static const int CREATOR_ROWS=5; static const int CREATOR_COLUMNS=10; static const int PLAY_XPOS=100; static const int PLAY_YPOS=50; static const int PLAY_WIDTH=800; static const int PLAY_HEIGHT=400; static const int PLAY_ROWS=5; static const int PLAY_COLUMNS=10; int rows,columns; int getSquareSize(); public: static const int GAME_FIELD_CREATOR_CODE = 12; static const int GAME_FIELD_PLAY_CODE = -12; GameField(int code); virtual ~GameField(); void getProperties(int *x, int *y, int *sq);//gamefield xpos, ypos,szerokosc kwadratu void draw(); void whichSquare(int *x,int *y, int *row, int *column);//ktory zostal klikniety void getRandomSquare(int *row, int *column);//losuje kwadracik void changeStateToActive();//pole rozowe void changeStateToInactive();//pole niebieskie void getSquareRelativePos(int row, int column, int *xRelativePos, int *yRelativePos);//wzgledem okna gry int getSquareCount();//wielkosc pola - 50 kwadracikow }; #endif //TOWERDEFENSE_GAMEFIELD_H
true
13e911e2fa4cee6cee36e9edb5772ffb647378b6
C++
Zzzode/myLeetCode
/5635. 构建字典序最大的可行序列.cpp
UTF-8
625
2.796875
3
[]
no_license
#include "Header.h" class Solution { public: vector<int> constructDistancedSequence(int n) { vector<int> ans(2 * n - 1, 0); vector<int> v(n + 1, 0); int l = 0, r = l + n, tmp = n; while (tmp > 1) { ans[l] = ans[r] = tmp; l++, r--; tmp -= 2; } tmp = n; if (r - l == 3) { ans[l + 1] = ans[l + tmp] = tmp - 1; ans[l + 2] = ans[l + tmp - 1] = tmp - 3; tmp -= 3; } else { ans[l + 1] = ans[l + tmp] = tmp - 1; tmp -= 1; } l = n + 1; while (ans[l] && l < ans.size() - 1) l++; tmp -= 2; while (tmp) {} return ans; } };
true
e929d61e1c5c7074db92da3e516f2fbdca7aec3e
C++
Alxndr-GG/client_serverd
/client/main.cpp
UTF-8
3,631
3.046875
3
[]
no_license
#include <iostream> #include <fstream> #include "libs.h" // Прототипы функций с проверкой на ошибки int Socket(int domain, int type, int protocol); void Bind(int sockfd, const sockaddr* addr, socklen_t addrlen); void Listen(int sockfd, int backlog); int Accept(int sockfd, sockaddr* addr, socklen_t* addrlen); void Connect(int sockfd, const sockaddr* addr, socklen_t addrlen); void Inet_pton(int af, const char* src, void* dst); int main(int argc, char *argv[]) { int fd = Socket(AF_INET, SOCK_STREAM, 0); // создание сокета с протоколом TCP sockaddr_in adr = { 0 }; // информация об адресе и порте adr.sin_family = AF_INET; adr.sin_port = htons(50505); Inet_pton(AF_INET, "127.0.0.1", &adr.sin_addr); //преобразование строки в адрес формата IPv4 Connect(fd, (sockaddr *) &adr, sizeof adr); // установка связи с сервером std::ifstream fin; // берем аргумент из консоли как путь к файлу if (argc == 2) { fin.open(argv[1]); if (!fin) { std::cerr << "Open failed:" << argv[1] << "\n"; exit(EXIT_FAILURE); } } // или указываем путь к текстовому файлу else { char path[256]; std::cout << "Enter path to the file (\'q\' to quit): (example: /home/user/source.txt)\n"; std::cin.get(path, 256).get(); if (!(strcmp(path, "q"))) exit(EXIT_FAILURE); fin.open(path); if (!fin) { std::cerr << "Open failed\n"; exit(EXIT_FAILURE); } } std::cout << "File opened successfully.\n"; // читаем текст из файла в буфер и отсылаем на сервер char buf[256]; ssize_t nread; while (fin.good()) { fin.read(buf, 256); ssize_t sz = fin.gcount(); if (!sz) break; send(fd, buf, sz, 0); memset(buf, '\0', 256); nread = recv(fd, buf, sizeof buf, 0); std::cout << buf; memset(buf, '\0', 256); } std::cout << "Done\n"; shutdown(fd, 1); close(fd); return 0; } int Socket(int domain, int type, int protocol) { int res = socket(domain, type, protocol); if (res == -1) { perror("Socket: "); exit(EXIT_FAILURE); } return res; } void Bind(int sockfd, const sockaddr* addr, socklen_t addrlen) { int res = bind(sockfd, addr, addrlen); if (res == -1) { perror("Bind"); exit(EXIT_FAILURE); } } void Listen(int sockfd, int backlog) { int res = listen(sockfd, backlog); if (res == -1) { perror("Listen"); exit(EXIT_FAILURE); } } int Accept(int sockfd, sockaddr* addr, socklen_t* addrlen) { int res = accept(sockfd, addr, addrlen); if (res == -1) { perror("Accept"); exit(EXIT_FAILURE); } return res; } void Connect(int sockfd, const sockaddr* addr, socklen_t addrlen) { int res = connect(sockfd, addr, addrlen); if (res == -1) { perror("Connect"); exit(EXIT_FAILURE); } } void Inet_pton(int af, const char* src, void* dst) { int res = inet_pton(af, src, dst); if (res == 0) { std::cerr << "inet_pton: src does not contain a valid string" << std::endl; exit(EXIT_FAILURE); } else if (res == -1) { perror("inet_pton failed"); exit(EXIT_FAILURE); } }
true
4eb095102e47381eac56f8a24e0ade9d44f3befe
C++
rosen90/GitHub
/Projects/AMineva/Ex1_File_Bonus/src/Ex1_File_Bonus.cpp
UTF-8
777
3.203125
3
[]
no_license
//============================================================================ // Name : Ex1_File_Bonus.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <fstream> #include <string> using namespace std; int main() { int index = 1; string str = ""; ifstream in("line.txt", ios::in); if(!in) { cout<<"Error opening file!"<<endl; return -1; } ofstream out("newLine.txt", ios::out); if(!out) { cout<<"Error opening file!"<<endl; return -1; } while(in.eof()) { getline(in,str); out<<index<<". "<<str<<endl; index++; } in.close(); out.close(); return 0; }
true
b27c233d6b79eb4132b480b8c7a746c0e00a2bed
C++
bootchk/embeddedDutyCycleOld
/src/RTC/timeConverter.h
UTF-8
854
2.625
3
[]
no_license
/* * Knows how to convert time formats. * * !!! With many subtle omissions. * * Goal here is to use Unix std implementations when possible. */ /* * A library similar to Unix std library * * If the platform support Unix std library: * #include <ctime> // C time.h */ #include "timeTypes.h" // Depends on type defined by RTC chip #include "../AB08xx/rtcTime.h" class TimeConverter { public: /* * Convert BCD encoded calendar into int encoded calendar. * and vice versa */ static CalendarTime convertRTCTimeToCalendarTime(RTCTime&); static RTCTime convertCalendarTimeToRTCTime(CalendarTime&); /* * Convert calendar time to epoch time and vice versa */ static EpochTime convertCalendarTimeToEpochTime(CalendarTime&); static CalendarTime convertEpochTimeToCalendarTime(EpochTime); static bool isValidRTCTime(RTCTime&); };
true
45ebf4c6c2b1d8f63a3165017bd9654ff90d5152
C++
ChaitanyaTimmaraju/Thesis
/AmbientOcclusion/modelloader.cpp
UTF-8
3,485
2.640625
3
[]
no_license
#include "modelloader.h" #include <QFile> #include <QTextStream> #include <QDebug> ModelLoader::ModelLoader() { m_indicesID = new QOpenGLBuffer(QOpenGLBuffer::IndexBuffer); } ModelLoader::ModelLoader(QString fileName) : ModelLoader() { loadObjectAndSetBuffers(fileName); } void ModelLoader::loadObjectAndSetBuffers(QString fileName) { QFile file(fileName); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream fileText(&file); while (!fileText.atEnd()) { QString fileLine = fileText.readLine(); QVector3D temp; QVector2D tempUV; if (fileLine.startsWith("v ")) { QStringList list = fileLine.split(" "); temp.setX(list[1].toFloat()); temp.setY(list[2].toFloat()); temp.setZ(list[3].toFloat()); vertices.push_back(temp); } else if (fileLine.startsWith("vn ")) { QStringList list = fileLine.split(" "); temp.setX(list[1].toFloat()); temp.setY(list[2].toFloat()); temp.setZ(list[3].toFloat()); normals.push_back(temp); } else if (fileLine.startsWith("vtangent ")) { QStringList list = fileLine.split(" "); temp.setX(list[1].toFloat()); temp.setY(list[2].toFloat()); temp.setZ(list[3].toFloat()); tangents.push_back(temp); } else if (fileLine.startsWith("vt ")) { QStringList list = fileLine.split(" "); tempUV.setX(list[1].toFloat()); tempUV.setY(list[2].toFloat()); uvs.push_back(tempUV); } else if (fileLine.startsWith("f ")) { QStringList list = fileLine.split(" "); indices.push_back(list[1].toInt() - 1); indices.push_back(list[2].toInt() - 1); indices.push_back(list[3].toInt() - 1); } else if (fileLine.startsWith("ts ")) break; } } else qDebug() << qPrintable(fileName) << " not found.(Make sure to add in resources.qrc)"; // create Index Buffer m_indicesID->create(); m_indicesID->bind(); m_indicesID->setUsagePattern(QOpenGLBuffer::StaticDraw); m_indicesID->allocate(indices.constData(), indices.size() * sizeof(unsigned int)); m_indicesID->release(); // Create Vertex and other Buffers. m_vertexID.create(); m_vertexID.bind(); m_vertexID.setUsagePattern(QOpenGLBuffer::StaticDraw); m_vertexID.allocate(vertices.constData(), vertices.size() * sizeof(QVector3D)); m_vertexID.release(); m_normalID.create(); m_normalID.bind(); m_normalID.setUsagePattern(QOpenGLBuffer::StaticDraw); m_normalID.allocate(normals.constData(), normals.size() * sizeof(QVector3D)); m_normalID.release(); m_tangentsID.create(); m_tangentsID.bind(); m_tangentsID.setUsagePattern(QOpenGLBuffer::StaticDraw); m_tangentsID.allocate(tangents.constData(), tangents.size() * sizeof(QVector3D)); m_tangentsID.release(); m_uvID.create(); m_uvID.bind(); m_uvID.setUsagePattern(QOpenGLBuffer::StaticDraw); m_uvID.allocate(uvs.constData(), uvs.size() * sizeof(QVector2D)); m_uvID.release(); indicesCount = indices.size(); vertices.clear(); indices.clear(); uvs.clear(); normals.clear(); tangents.clear(); } ModelLoader::~ModelLoader() { m_vertexID.destroy(); m_indicesID->destroy(); m_uvID.destroy(); m_tangentsID.destroy(); m_normalID.destroy(); }
true
7cf75eb9fd98dfd650f46f73fc29da83f826b9e1
C++
bl4ckp4nther/cpp-codes
/printsubsetsumtok.cpp
UTF-8
821
3.140625
3
[]
no_license
#include<iostream> using namespace std; void printSubsetSumToKHelper(int input[],int size1,int si,int output[],int size2,int sum,int tempsum) { if(size1==0) { if(tempsum==sum) { for(int i=0;i<size2;i++) { cout<<output[i]<<" "; } cout<<endl; } return; } printSubsetSumToKHelper(input,size1-1,si+1,output,size2,sum,tempsum); output[size2]=input[si]; printSubsetSumToKHelper(input,size1-1,si+1,output,size2+1,sum,tempsum+input[si]); } void printSubsetSumToK(int input[], int size,int k) { int output[20]; printSubsetSumToKHelper(input,size,0,output,0,k,0); } int main() { int input[]={3,2,1,3,4}; printSubsetSumToK(input,5,6); return 0; }
true
49130420592322e9c1b4f8e473d2d92696d1d093
C++
tophack-16/LogParser
/cerrLogParser.cpp
UTF-8
1,504
2.75
3
[]
no_license
// // Created by zhanghuimeng on 19-3-24. // #include <string> #include <fstream> #include "json/json.h" #include <vector> #include "Board.h" using namespace std; static void cerrLogParser(const vector<string>& log) { int round; int turn = 0; Json::Reader reader; Json::Value value; string json; vector<Board> boards; vector<Move> moves; Json::StyledStreamWriter writer; for (const string& line: log) { if (line.empty()) { if (json.empty()) continue; else { reader.parse(json, value); if (!value["input"].isNull()) { Board board(value["input"]); round = board.round; cout << "Board: " << round << ' ' << turn << endl; ofstream fout("output/board_round_" + to_string(round) + "_turn_" + to_string(turn + 1) + ".json"); writer.write(fout, board.toJson()); fout.close(); turn = (turn + 1) % 3; } else if (!value["output"].isNull()) { ofstream fout("output/action_round_" + to_string(round) + "_turn_" + to_string(turn + 1) + ".json"); writer.write(fout, value["output"]); fout.close(); } json.clear(); } } else json += line; } }
true
fc96fe280f8b2e872db36b750605be0df4569850
C++
wkcn/leetcode
/0501-0600/0520.detect-capital.cpp
UTF-8
486
2.765625
3
[]
no_license
class Solution { public: bool detectCapitalUse(string word) { const int n = word.size(); if (n < 2) return true; if (islower(word[1])) { for (int i = 2; i < n; ++i) { if (isupper(word[i])) return false; } } else { if (islower(word[0])) return false; for (int i = 2; i < n; ++i) { if (islower(word[i])) return false; } } return true; } };
true
b68a89f035098df0f65430f84bd34ed4a1d1a907
C++
lizixroy/CANOpenRobotController
/src/apps/X2DemoMachine/X2DemoMachine.h
UTF-8
1,818
2.65625
3
[ "Apache-2.0" ]
permissive
/** * \file X2DemoMachine.h * \author Emek Baris KUcukabak * \version 0.1 * \date 2020-07-06 * \copyright Copyright (c) 2020 * * /brief The <code>X2DemoMachine</code> class represents an example implementation of an X2 state machine. * */ #ifndef SRC_X2DEMOMACHINE_H #define SRC_X2DEMOMACHINE_H #include <sys/time.h> #include <array> #include <cmath> #include <fstream> #include <iostream> #include <string> #include "X2Robot.h" #include "StateMachine.h" // State Classes #include "states/IdleState.h" #include "states/X2DemoState.h" #include "X2DemoMachineROS.h" // Logger #include "LogHelper.h" class X2DemoMachine : public StateMachine { public: X2DemoMachine(int argc, char *argv[]); X2DemoMachineROS *x2DemoMachineRos_; /*<!Pointer to the ROS Class*/ X2Robot *robot_; /*<!Pointer to the Robot*/ // NOTE: For some reason; if this is defined later, it doesn't publish bool running = false; /** * \todo Pilot Parameters would be set in constructor here * */ void init(); void end(); void update(); void hwStateUpdate(); void initRobot(X2Robot *rb); bool configureMasterPDOs(); /** * Pointers to the relevant states - initialised in init * */ IdleState *idleState_; X2DemoState *x2DemoState_; private: /** * * \brief Event Objects defined using Macro defined in StateMachine.h * Defines the Class itself, as well as initialises an object of that class * An events check function are defined in the .cpp file. */ EventObject(StartExo) * startExo; std::string robotName_; // robot name(obtained from node name) std::chrono::steady_clock::time_point time0; // initial time that machine started double time; // time passed after time0 in [s] }; #endif //SRC_X2DEMOMACHINE_H
true
2abe45d6bfee841bd1c6ac3ae766cb0420b95b3c
C++
akash19jain/COMPETITIVE-PROGRAMMING
/CODECHEF/CRAWLER/EID-19859168.cpp
UTF-8
865
3.234375
3
[]
no_license
// C++ program to find minimum difference between // any pair in an unsorted array #include <bits/stdc++.h> using namespace std; // Returns minimum difference between any pair int findMinDiff(long long arr[], long long n) { // Sort array in non-decreasing order sort(arr, arr+n); // Initialize difference as infinite int diff = 1000001; // Find the min diff by comparing adjacent // pairs in sorted array for (long long i=0; i<n-1; i++) if (arr[i+1] - arr[i] < diff) diff = arr[i+1] - arr[i]; // Return min diff return diff; } // Driver code int main() { int t; scanf("%d",&t); while(t--) { long long n; scanf("%lld",&n); long long arr[n]; for(long long i=0;i<n;i++) scanf("%lld",&arr[i]); cout <<findMinDiff(arr, n); cout <<"\n"; } return 0; }
true
174916a50448fc0bdfbd60286871acfa1cb4b154
C++
Babelz/EUS
/EUS/PlayerCursor.h
UTF-8
370
2.515625
3
[]
no_license
#pragma once #include "Entity.h" #include "SpriteAnimator.h" // Class for controlling units and interactions. class PlayerCursor : public Component { private: SpriteAnimator* animator; protected: void onInitialize() override; virtual void onDestroyed() override; public: PlayerCursor(Game& game, Entity& owner); void hide(); void show(); ~PlayerCursor(); };
true
87db652b0e273b916505b9d8fd1d38b3709e3a23
C++
ss6364/practice-CP
/contest-520-problem-B.cpp
UTF-8
891
2.59375
3
[]
no_license
// https://codeforces.com/problemset/problem/520/B // Two balloons #include<bits/stdc++.h> using namespace std ; #define Fors(n) for(int i=1;i<=n;i++) #define For(n) for(i=0;i<n;i++) #define ll long long #define vint(s) vector<int> s #define pb(x) push_back(x) #define mpair(x,y) make_pair(x,y) #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll x=0,y=0,s=0,n=0,i=0; int main(){ IOS; cin>>n>>x; if (x<n){ cout<<abs(x-n)<<endl; return 0; } y = x; ll n1 = n; ll d=0, d1=0; while(n1 < x ){ n1<<=1; d1++; } ll ans = d1 + abs(n1 - x); if(n1 == x){ cout<<d1<<endl; return 0; } while(y > n){ if(y%2==0) y>>=1; else y++; d++; //cout<<y<< ":|:"; } //cout<<d<<"=d y="; y = d + abs(n-y); //cout<<y<<endl; cout<<min(y,ans)<<endl; return 0; }
true
afa2ab0f60508e3eaba7da417eeb13ca15a788b8
C++
HaoYang0123/LeetCode
/Min_Number_of_Steps.cpp
UTF-8
392
2.828125
3
[]
no_license
//Leetcode 1347 class Solution { public: int minSteps(string s, string t) { vector<int> c1(26, 0); vector<int> c2(26, 0); for(int i=0;i<s.length();++i) { c1[int(s[i]-'a')]++; c2[int(t[i]-'a')]++; } int res = 0; for(int i=0;i<26;++i) { res += abs(c1[i] - c2[i]); } return res/2; } };
true
05847cddef2f9736379e7412341ecba56ba9c129
C++
vijayalaxmi777/CPP
/Object oriented programming in CPP/13.cpp
UTF-8
670
3.390625
3
[]
no_license
//13.Array of object #include<iostream> #include<conio.h> #include<String.h> using namespace std; class Customer { int id; char name[30]; public : void getInfo() { cout<<"Enter Id "<<endl; cin>>id; cout<<"Enter name"<<endl; cin>>name; } void dispInfo() { cout<<"Id = "<<id<<endl; cout<<"Name = "<<name<<endl; } }; int main() { Customer c[3]; int i; for( i=0;i<3;i++) { c[i].getInfo(); //i/p block } cout<<"----------------------------------------------------------\n"; for( i=0;i<3;i++) { c[i].dispInfo(); //o/p block cout<<"----------------------------------------------------------\n"; } getch(); return 0; }
true
8bf343d27359d91fbdb6aa0cba671ddef6f5c587
C++
JanFSchulteDummy/cmssw
/PhysicsTools/MVATrainer/interface/LeastSquares.h
UTF-8
1,542
2.53125
3
[ "Apache-2.0" ]
permissive
#ifndef PhysicsTools_MVATrainer_LeastSquares_h #define PhysicsTools_MVATrainer_LeastSquares_h #include <string> #include <vector> #include <TMatrixD.h> #include <TVectorD.h> #include <xercesc/dom/DOM.hpp> namespace PhysicsTools { class LeastSquares { public: LeastSquares(unsigned int n); virtual ~LeastSquares(); void add(const std::vector<double> &values, double dest, double weight = 1.0); void add(const LeastSquares &other, double weight = 1.0); void calculate(); std::vector<double> getWeights() const; std::vector<double> getMeans() const; double getConstant() const; inline unsigned int getSize() const { return n; } inline const TMatrixDSym &getCoefficients() const { return coeffs; } inline const TMatrixDSym &getCovariance() const { return covar; } inline const TMatrixDSym &getCorrelations() const { return corr; } inline const TMatrixD &getRotation() { return rotation; } void load(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *elem); XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *save(XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *doc) const; static TVectorD solveFisher(const TMatrixDSym &coeffs); static TMatrixD solveRotation(const TMatrixDSym &covar, TVectorD &trace); private: TMatrixDSym coeffs; TMatrixDSym covar; TMatrixDSym corr; TMatrixD rotation; TVectorD weights; TVectorD variance; TVectorD trace; const unsigned int n; }; } // namespace PhysicsTools #endif // PhysicsTools_MVATrainer_LeastSquares_h
true
c58cc3df7d8121f1dab26d538541cb3062855f70
C++
Antik98/PA2
/hash_zkouska/main.cpp
UTF-8
2,833
3.640625
4
[]
no_license
#include <string> #include <iostream> #include <cassert> using namespace std; struct TItem { TItem(string key, string val, TItem* nextHash,TItem* nextOrd, TItem * prevOrd) :m_Key(key),m_Val(val),m_NextHash(nextHash),m_NextOrder(nextOrd),m_PrevOrder(prevOrd){} string m_Key,m_Val; TItem * m_NextHash, * m_NextOrder, * m_PrevOrder; }; class CHash{ public: CHash (int m) : m_Table(NULL), m_Size(m), m_FirstOrder(NULL) { m_Table=new TItem*[m]; for (int i =0; i<m; i++){ m_Table[i]=NULL; } } ~CHash(){ } bool IsSet(string key){ TItem * tmp = m_Table[hashFn ( key )]; while(tmp != NULL && tmp->m_Key != key) tmp = tmp->m_NextHash; if(tmp == NULL) return false; return true; } CHash(CHash &) = delete; CHash & operator = (CHash &) = delete; bool Ins(string key, string val){ TItem* tmp= new TItem(key, val, NULL, NULL, NULL); int index = hashFn(key); // order if (m_Table[index]==NULL){ // map m_Table[index]=tmp; }else{ TItem* ListIterator=m_Table[index]; if(ListIterator->m_Key==tmp->m_Key){ delete tmp; return false; } while(ListIterator->m_NextHash){ if(ListIterator->m_Key==tmp->m_Key){ delete tmp; return false; } ListIterator=ListIterator->m_NextHash; } ListIterator->m_NextHash=tmp; } if(m_FirstOrder!=NULL){ // find the last order TItem* iterator=m_FirstOrder; while(iterator->m_NextOrder){ iterator=iterator->m_NextOrder; } tmp->m_PrevOrder=iterator; iterator->m_NextOrder=tmp; m_LastOrder=tmp; }else{ m_FirstOrder=tmp; m_LastOrder=tmp; } } template <typename func> void ForEach(func f){ TItem * tmp = m_FirstOrder; while(tmp != NULL){ f(tmp); tmp = tmp->m_NextOrder; } } private: TItem ** m_Table; unsigned int m_Size; TItem * m_FirstOrder, * m_LastOrder; unsigned int hashFn(string & str){ std::hash<std::string> hash_fn; return hash_fn(str)%m_Size; } }; int main(int argc, char** argv) { CHash hashtable(100); assert(hashtable.Ins("h1","car")); assert(!hashtable.Ins("h1","auto")); assert(hashtable.Ins("h2","phone")); assert(hashtable.Ins("h3","field")); assert(hashtable.Ins("h4","house")); assert(hashtable.Ins("h5","tree")); hashtable.ForEach([](TItem * it ){ cout<<it->m_Key<<" - "<<it->m_Val<<endl; }); return 0; }
true
84def5e25784ccc22300bd9438ed2a860949ace1
C++
jonathan140/LaboratoriosFunda
/labo4/ejercicio5.cpp
UTF-8
431
3.53125
4
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { string palabra; char letrafinal; cout << "Ingrese una palabra: "; cin >> palabra; if (palabra.front()==palabra.back()) { cout << palabra << " inicia y termina con la misma letra" << endl; } else { { cout << palabra << " inicia y termina con letras diferentes" << endl; } } }
true
d30d39375acbf4f3b8b040a4805b3432ece46c71
C++
jstopyra/JSEngine
/Source/Logic/Components/CameraComponent.cpp
UTF-8
2,721
2.734375
3
[]
no_license
#include "CameraComponent.h" #include "../GameObject/GameObject.h" #include "../../Utilities/EventSystem/Events/EventsInclude.h" extern EventSystem* g_pEventSystem; CameraComponent::CameraComponent(int cameraWidth, int cameraHeight, GameObject* pParent) : Component(pParent) , m_cameraWidth(cameraWidth) , m_cameraHeight(cameraHeight) , m_screenCoushion(10) { g_pEventSystem->AttachListener(k_updateEvent, this); g_pEventSystem->AttachListener(k_cameraMoveEvent, this); } CameraComponent::~CameraComponent() { } void CameraComponent::UpdateCamera() { //Check if the pTarget is still in our view Vector3<float>* myPos = GetParent()->GetComponent<TransformComponent>()->GetPosition(); if (m_pTargetPos) { float rightEdge = myPos->GetX() + (m_cameraWidth / 2); float leftEdge = myPos->GetX() - (m_cameraWidth / 2); float topEdge = myPos->GetY() - (m_cameraHeight / 2); float bottomEdge = myPos->GetY() + (m_cameraHeight / 2); if (m_pTargetPos->GetX() + 32 > rightEdge - m_screenCoushion) { GetParent()->GetComponent<TransformComponent>()->SetPosition(rightEdge - m_screenCoushion, myPos->GetY(), myPos->GetZ()); } else if (m_pTargetPos->GetX() + 32 < leftEdge + m_screenCoushion) { GetParent()->GetComponent<TransformComponent>()->SetPosition(leftEdge + m_screenCoushion, myPos->GetY(), myPos->GetZ()); } else if (m_pTargetPos->GetY() + 32 < topEdge + m_screenCoushion) { GetParent()->GetComponent<TransformComponent>()->SetPosition(myPos->GetX(), topEdge + m_screenCoushion, myPos->GetZ()); } else if (m_pTargetPos->GetY() + 32 > bottomEdge - m_screenCoushion) { GetParent()->GetComponent<TransformComponent>()->SetPosition(myPos->GetX(), bottomEdge - m_screenCoushion, myPos->GetZ()); } } } void CameraComponent::SetTarget(Vector3<float>* pTargetVector) { m_pTargetPos = pTargetVector; } void CameraComponent::OnEvent(const Event* pEvent) { if (pEvent->GetEventId() == k_updateEvent) { UpdateCamera(); } if (pEvent->GetEventId() == k_cameraMoveEvent) { //Move the camera CameraMoveEvent* pMoveEvent = (CameraMoveEvent*)(pEvent); Vector3<float>* pPosition = GetParent()->GetComponent<TransformComponent>()->GetPosition(); float xPos = pPosition->GetX() + pMoveEvent->GetDeltaX()*-1; float yPos = pPosition->GetY() + pMoveEvent->GetDeltaY()*-1; float zPos = pPosition->GetZ() + pMoveEvent->GetDeltaZ()*-1; GetParent()->GetComponent<TransformComponent>()->SetPosition(xPos, yPos, zPos); } } Vector3<float>* CameraComponent::GetPosition() { return GetParent()->GetComponent<TransformComponent>()->GetPosition(); } int CameraComponent::GetWidth() { return m_cameraWidth; } int CameraComponent::GetHeight() { return m_cameraHeight; }
true