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
535acc5d768b7b64e91f4de7830c6e8dd87ba0c6
C++
bg1bgst333/Sample
/winapi/SetupDiGetClassDevs/SetupDiGetClassDevs/src/SetupDiGetClassDevs/SetupDiGetClassDevs/SetupDiGetClassDevs.cpp
SHIFT_JIS
993
2.671875
3
[ "MIT" ]
permissive
// wb_t@C̃CN[h #include <tchar.h> // TCHAR^ #include <stdio.h> // Wo #include <windows.h> // WWindowsAPI #include <setupapi.h> // SetUpAPI // _tmain֐̒` int _tmain(int argc, TCHAR *argv[]){ // main֐TCHAR. // ϐ̐錾 HDEVINFO hDevInfo; // foCXnhhDevInfo // {[foCX̃foCXC^[tF[XNX̃foCX擾. hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_VOLUME, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE); // SetupDiGetClassDevsGUID_DEVINTERFACE_VOLUMEhDevInfo擾. if (hDevInfo != INVALID_HANDLE_VALUE){ // INVALID_HANDLE_VALUEłȂ. _tprintf(_T("hDevInfo = 0x%08x\n"), (unsigned long)hDevInfo); // hDevInfoo. SetupDiDestroyDeviceInfoList(hDevInfo); // SetupDiDestroyDeviceInfoListhDevInfoj. } // vȌI. return 0; // 0ԂĐI. }
true
413e4bea03dee30f128403fd377bcda2e7df0a7a
C++
CSEKU160212/C_Programming_And_Data_Structure
/C Programming (Home Practice)/programming/programming/string/cmparison.cpp
UTF-8
1,208
4.53125
5
[]
no_license
/* * C Program to accepts two strings and compare them. Display * the result whether both are equal, or first string is greater * than the second or the first string is less than the second string */ #include <stdio.h> int main() { int count1 = 0, count2 = 0, flag = 0, i; char string1[10], string2[10]; printf("Enter a string:"); gets(string1); printf("Enter another string:"); gets(string2); /* Count the number of characters in string1 */ while (string1[count1] != '\0') count1++; /* Count the number of characters in string2 */ while (string2[count2] != '\0') count2++; i = 0; while ((i < count1) && (i < count2)) { if (string1[i] == string2[i]) { i++; continue; } if (string1[i] < string2[i]) { flag = -1; break; } if (string1[i] > string2[i]) { flag = 1; break; } } if (flag == 0) printf("Both strings are equal \n"); if (flag == 1) printf("String1 is greater than string2 \n"); if (flag == -1) printf("String1 is less than string2 \n"); }
true
4c3db8ea006c5564dfa1c2986997d83ed364f525
C++
coffee-sound/competitive_programming
/library/algorithm/run_length_encoding.cpp
UTF-8
488
2.96875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; // ランレングス圧縮 vector<pair<char, int>> RLE(const string &str) { vector<pair<char, int>> res; char tmp = ' '; int cnt = 0; for (auto c : str) { if (c == tmp) { cnt++; } else { if (tmp != ' ') { res.emplace_back(tmp, cnt); } tmp = c; cnt = 1; } } res.emplace_back(tmp, cnt); return res; }
true
a822c074ddcab979603317dc5bca7c318a1b7443
C++
blockspacer/engine-4
/server_dll/entity_system.h
UTF-8
727
2.53125
3
[]
no_license
#pragma once #include <vector> #include <array> #include "base_entity.h" #include <net/networking.h> using entity_id = size_t; using entity_handle = size_t; class entity_system { public: entity_handle add_entity(base_entity* ent); base_entity* get_entity(entity_handle h); base_entity* get_entity_by_edict(size_t edict); void remove_entity(base_entity* ent); void remove_entity(entity_handle h); void update_entities(); const std::vector<base_entity*>& ptr() const { return m_entities; } entity_handle get_free_edict(bool bPlayer) const; private: std::vector<base_entity*> m_entities; std::map<size_t, size_t> m_map_edicts_entities; std::array<bool, net::max_edicts> m_edicts; };
true
31a84344904e61c08ac188c2542db7b58650434c
C++
xingyun86/RtmpServer
/src/RtmpHeader.h
UTF-8
5,659
2.65625
3
[]
no_license
#ifndef RTMP_HEADER_H #define RTMP_HEADER_H /* +--------------+----------------+--------------------+--------------+ | Basic Header | Message Header | Extended Timestamp | Chunk Data | +--------------+----------------+--------------------+--------------+ | | |<------------------- Chunk Header ----------------->| ##################################################################### 0 1 2 3 4 5 6 7 +-+-+-+-+-+-+-+-+ |fmt| cs id | +-+-+-+-+-+-+-+-+ Chunk basic header 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |fmt| 0 | cs id - 64 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Chunk basic header 2 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |fmt| 1 | cs id - 64 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Chunk basic header 3 ##################################################################### 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | timestamp |message length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | message length (cont) |message type id | msg stream id | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | message stream id (cont) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Chunk Message Header - fmt 0 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | timestamp delta |message length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | message length (cont) |message type id| +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Chunk Message Header - fmt 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | timestamp delta | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Chunk Message Header - fmt 2 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Chunk Message Header - fmt 3 */ #include "ByteStream.h" #include <map> enum RtmpHeaderState { RtmpHeaderState_Ok = 0, RtmpHeaderState_NotEnoughData, RtmpHeaderState_Error, }; struct ChunkBasicHeader { unsigned int fmt; unsigned int csId; ChunkBasicHeader() : fmt(0), csId(0) { } void Reset() { fmt = 0; csId = 0; } }; struct ChunkMsgHeader { // tsField: timestamp field, it would be // 1. absolute time // 2. delta time (if fmt != 0) // 3. 0xFFFFFF unsigned int tsField; unsigned int length; // video type or audio type and so on unsigned int typeId; unsigned int streamId; // the absolute time of message unsigned int timestamp; // externed timestamp unsigned int externedTimestamp; ChunkMsgHeader() : tsField(0), length(0), typeId(0), streamId(0), timestamp(0), externedTimestamp(0) { } void Reset() { tsField = 0; length = 0; typeId = 0; streamId = 0; timestamp = 0; externedTimestamp = 0; } bool operator !=(const ChunkMsgHeader &header) const { return (tsField != header.tsField || length != header.length || typeId != header.typeId || streamId != header.streamId || timestamp != header.timestamp || externedTimestamp != header.externedTimestamp); } }; typedef std::map<int, ChunkMsgHeader> CsIdMsgHeader; class RtmpHeaderDecode { public: RtmpHeaderDecode() : m_complete(false) { } RtmpHeaderState Decode(char *data, size_t len, bool startNewMsg); RtmpHeaderState DecodeCsId(char *data, size_t len); ChunkMsgHeader GetMsgHeader() const; ChunkBasicHeader GetBasicHeader() const; int GetConsumeDataLen(); bool IsComplete(); void Reset(); void Dump(); private: RtmpHeaderState DecodeBasicHeader(); RtmpHeaderState DecodeMsgHeader(bool startNewMsg); bool m_complete; ChunkBasicHeader m_basicHeader; ChunkMsgHeader m_msgHeader; ByteStream m_byteStream; CsIdMsgHeader m_csIdMsgHeader; }; class RtmpHeaderEncode { public: RtmpHeaderEncode(); // Would modify tsField and externedTimestamp // in msgHeader RtmpHeaderState Encode(char *data, size_t *len, unsigned int csId, ChunkMsgHeader &msgHeader, bool startNewMsg); void Dump(); private: void EncodeStartMsg( unsigned int csId, ChunkMsgHeader *msgHeader, const ChunkMsgHeader *lastMsgHeader); void EncodeInterMsg( unsigned int csId, const ChunkMsgHeader *msgHeader); bool IsFmt0(const ChunkMsgHeader *msgHeader, const ChunkMsgHeader *lastMsgHeader); void SetTsField(ChunkMsgHeader *msgHeader, const ChunkMsgHeader *lastMsgHeader); unsigned int GetFmt(const ChunkMsgHeader *msgHeader, const ChunkMsgHeader *lastMsgHeader); void SetBasicHeader(unsigned int fmt, unsigned int csIdchar); void SetMsgHeader(unsigned int fmt, const ChunkMsgHeader *msgHeader); static const int kMaxBytes = 3 + 11; ByteStream m_byteStream; CsIdMsgHeader m_csIdMsgHeader; }; #endif // RTMP_HEADER_H
true
8fe37971d3c8052d0c47f3270460c54479da8eb6
C++
acekiller/poro
/source/utils/easing/penner_cubic.cpp
UTF-8
554
2.59375
3
[ "Zlib" ]
permissive
#include "penner_cubic.h" namespace ceng { namespace easing { Cubic::EaseIn Cubic::easeIn; Cubic::EaseOut Cubic::easeOut; Cubic::EaseInOut Cubic::easeInOut; float Cubic::impl_easeIn (float t,float b , float c, float d) { return c*(t/=d)*t*t + b; } float Cubic::impl_easeOut(float t,float b , float c, float d) { return c*((t=t/d-1)*t*t + 1) + b; } float Cubic::impl_easeInOut(float t,float b , float c, float d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; } } // end of namespace easing } // end of namespace ceng
true
36db0365c59b446577f781800a4d6415e9e772e9
C++
liufei65536/algorithm
/PAT乙级/Project1/Project1/1008数组右移.cpp
UTF-8
621
3.390625
3
[]
no_license
#include<iostream> using std::cin; using std::cout; void move(int arr[], int n_arr); int main() { int n_array; cin >> n_array; int move_times; cin >> move_times; int * original_array = new int[n_array]; for (int i = 0; i < n_array; i++) { cin >> original_array[i]; } for (int j = 0; j < move_times; j++) { move(original_array,n_array); } for (int i = 0; i < n_array-1; i++) { cout<< original_array[i]<<" "; } cout << original_array[n_array - 1]; return 0; } void move(int arr[], int n_arr) { int temp = arr[n_arr - 1]; for (int i = n_arr - 1; i > 0; i--) { arr[i] = arr[i - 1]; } arr[0] = temp; }
true
494ca267c69b051fba132a69105ff2ded7cffb41
C++
boy2000-007man/oop-final-project
/Paper5/sort.cpp
UTF-8
606
2.765625
3
[]
no_license
#include "defs.h" #include "decl.h" void merge_sort(point *p[], point *p_temp[], index l, index r) { index i, j, k, m; if (r - l > 0) { m = (r + l) / 2; merge_sort(p, p_temp, l, m); merge_sort(p, p_temp, m+1, r); for (i = m+1; i > l; i--) p_temp[i-1] = p[i-1]; for (j = m; j < r; j++) p_temp[r+m-j] = p[j+1]; for (k = l; k <= r; k++) if (p_temp[i]->x < p_temp[j]->x) { p[k] = p_temp[i]; i = i + 1; } else if (p_temp[i]->x == p_temp[j]->x && p_temp[i]->y < p_temp[j]->y) { p[k] = p_temp[i]; i = i + 1; } else { p[k] = p_temp[j]; j = j - 1; } } }
true
488e5a54317792ab716d4c5f3de656554bb2a0fa
C++
eka43/ascii-rpg
/hero.h
UTF-8
1,385
2.734375
3
[]
no_license
#ifndef HERO_H #define HERO_H #include "unit.h" //class Item; class Inventory; class Paperdoll; class SLL; class Hero : public Unit { protected: // Item *pocket; Inventory *slots; SLL *backpack; Paperdoll *paperdoll; public: Hero(); Hero(char shape, int row, int col, int hp, int maxHp, int mp, int maxMp, int atk, int def, int gold, int exp); void init(); virtual ~Hero(); virtual void printStat(); virtual bool isHero(); virtual void move(int dir); virtual void useItem(int index); virtual void interact(Unit *unit); virtual void castMagic(int magicNumber); virtual void effect(Unit *unit, Item *item, Prop *prop, int skillNumber); virtual bool equip(Item *itemToEquip); virtual void unequip(int bodyPartIDToUnequip); virtual bool canReceiveItem(); // pre-condition: canReceiveItem() == true virtual void receiveItem(Item *item); virtual void printSlots(); virtual void printBackpack(); virtual Item *getSlotItemAt(int index); virtual Item *removeSlotItemAt(int index); virtual int capacitySlots(); virtual Item *getBackpackItemAt(int index); virtual Item *removeBackpackItemAt(int index); virtual int sizeBackpack(); void moveToBackpack(int index); void moveToSlots(int indexFromBackpack, int getindexPutSlots); }; #endif
true
22b1b36e52c8c8feaeb6d3748292da65067def2d
C++
nico88chessa/ipg-marking-wrapper
/ipg-marking-library-wrapper/VectorWrapper.cpp
UTF-8
3,069
2.578125
3
[]
no_license
#using "ipg/IpgMarkingGraphicsLibrary.dll" #include "stdafx.h" #include <msclr/gcroot.h> #include "VectorWrapper.h" #include "Vector.h" using namespace System; using namespace System::Runtime::InteropServices; namespace ipgml = IpgMarkingGraphicsLibrary; using namespace ipg_marking_library_wrapper; class ipg_marking_library_wrapper::VectorWrapperPrivate { public: msclr::gcroot<ipgml::Vector^> _v; }; VectorWrapper::VectorWrapper(VECTORWRAPPER_HANDLE_PTR ptr) : dPtr(nullptr) { if (ptr == nullptr) return; this->dPtr = new VectorWrapperPrivate(); IntPtr pointer(ptr); GCHandle handle = GCHandle::FromIntPtr(pointer); ipgml::Vector^ obj = (ipgml::Vector^) handle.Target; //this->dPtr->_p = gcnew ipgml::Point();// obj;// gcnew ipgml::Point(obj); //this->dPtr->_p.reset(obj); this->dPtr->_v = obj; } VectorWrapper::VectorWrapper(VectorWrapper&& other) { this->dPtr = other.dPtr; other.dPtr = nullptr; } VectorWrapper::~VectorWrapper() { delete dPtr; } VectorWrapper& VectorWrapper::operator=(VectorWrapper&& other) { if (&other == this) return *this; delete dPtr; this->dPtr = other.dPtr; other.dPtr = nullptr; return *this; } Vector VectorWrapper::clone() { GCHandle handle = GCHandle::Alloc(dPtr->_v); VECTORWRAPPER_HANDLE_PTR ptr = GCHandle::ToIntPtr(handle).ToPointer(); Vector clonedVet(ptr); handle.Free(); return clonedVet; } float VectorWrapper::getLength() const { if (dPtr == nullptr) return 0.0f; return dPtr->_v->Length; } PointWrapper VectorWrapper::getStart() const { if (dPtr == nullptr) return PointWrapper(); ipgml::Point^ p = dPtr->_v->Start; GCHandle handle = GCHandle::Alloc(p); PointWrapper res(GCHandle::ToIntPtr(handle).ToPointer()); handle.Free(); return res; } void VectorWrapper::setStart(const Point& start) { GCHandle hStartPoint = GCHandle::FromIntPtr(IntPtr(const_cast<POINT_HANDLER>(start.getManagedPtr()))); ipgml::Point^ startManaged = (ipgml::Point^) hStartPoint.Target; dPtr->_v->Start = startManaged; } PointWrapper VectorWrapper::getEnd() const { if (dPtr == nullptr) return PointWrapper(); ipgml::Point^ p = dPtr->_v->End; GCHandle handle = GCHandle::Alloc(p); PointWrapper res(GCHandle::ToIntPtr(handle).ToPointer()); handle.Free(); return res; } void VectorWrapper::setEnd(const Point& end) { GCHandle hEndPoint = GCHandle::FromIntPtr(IntPtr(const_cast<POINT_HANDLER>(end.getManagedPtr()))); ipgml::Point^ endManaged = (ipgml::Point^) hEndPoint.Target; dPtr->_v->Start = endManaged; } std::ostream& ipg_marking_library_wrapper::operator<<(std::ostream& os, const VectorWrapper& obj) { PointWrapper start = obj.getStart(); PointWrapper end = obj.getEnd(); /*return os << "Vector Start (" << start.getX() << "; " << start.getY() << ") - " << \ "End (" << end.getX() << "; " << end.getY() << ")" << std::endl;*/ return os << "VectorWrapper: Start " << start << " - End " << end; }
true
3ceeb9cbe9f6c356f02e14ab11f91408a8f8461d
C++
lohith171/Coding-Practice-Problems
/Strings/Reverse the String.cpp
UTF-8
605
3.21875
3
[]
no_license
//https://www.interviewbit.com/problems/reverse-the-string/ string Solution::solve(string A) { int n=A.length(); if(n==0)return ""; string temp; stack<string>st; for(int i=0;i<n;i++){ if(A[i]==' '){ if(!temp.empty()){ st.push(temp); temp.clear(); } }else{ temp.push_back(A[i]); } } if(!temp.empty()){ st.push(temp); } string res; while(!st.empty()){ res+=st.top(); st.pop(); if(!st.empty()){ res+=" "; } } return res; }
true
35ff3bf3c4b10c84c8b4d4e5ff109721c7ab7400
C++
tudormihaieugen/Cpp2009
/Neintensiv/S2_5/V095.cpp
UTF-8
375
2.796875
3
[]
no_license
#include <iostream> #include <string.h> #pragma warning(disable : 4996) //Eroare strcpy visual studio using namespace std; int main() { char s1[21], s2[21]; int n = strlen(s1); cout << "Sir: "; cin.get(s1, 20); char* p = strtok(s1, " "); strcpy(s2 + 3, p); p = strtok(NULL, " "); s2[0] = p[0]; s2[1] = '.'; s2[2] = ' '; cout << s2; }
true
4a882dc25b50e7ff59c5931ef87a63b8ce50d0d2
C++
ashishsurya/Data_Structures_Algorithms
/Arrays/three_sum_closest.cpp
UTF-8
986
3.734375
4
[]
no_license
/* Given an array Arr of N numbers and another number target, find three integers in the array such that the sum is closest to target. Return the sum of the three integers. NOTE: If their exists more than one answer then return the maximum sum. */ int threeSumClosest(vector<int> arr, int target) { // Your code goes here sort(arr.begin(), arr.end()); int n = arr.size(); int mini =INT_MAX,ans =0; for(int i=0;i<n;i++){ int j=i+1; int k = n-1; while(j < k){ int sum = arr[i]+arr[j]+arr[k]; //cout<<target<<" "<<sum<<"\n"; if(abs(target-sum) < mini){ mini = abs(target-sum); ans = sum; } else if(abs(target-sum) == mini && sum > ans ){ ans = sum; } if(sum < target)j++; else k--; } } return ans; } /* IDEA: TC: O(n^2) SC: O(1) */
true
78d418268988f6e110b5c73553a9dedeeb19f872
C++
AlexandreCordaJunior/URI
/Estruturas/uri2482.cpp
UTF-8
440
2.625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int num; scanf("%d", &num); getchar(); map<string, string> mapa; while(num--){ string idioma, natal; getline(cin, idioma); getline(cin, natal); mapa[idioma] = natal; } scanf("%d", &num); getchar(); while(num--){ string nome, idioma; getline(cin, nome); getline(cin, idioma); cout << nome << endl; cout << mapa[idioma] << endl; cout << endl; } }
true
142b2f530c6269e8d7417c10f2ff66bdb02bbaac
C++
SplendidSky/Visual-Studio-2015
/HR1/HR1/源.cpp
UTF-8
359
2.9375
3
[]
no_license
#include <set> using namespace std; template<class T> T& stat(double t, const vector<double> &rec, T& out) { set<double> absolute_error; double sum = 0; for (int i = 0; i < rec.size(); i++) { absolute_error.insert(rec[i] - t); sum += rec[i] - t; } return out << absolute_error[0] << absolute_error[absolute_error.size() - 1] << sum / rec.size(); }
true
44c8bb03cf2f043dba7012dcc2c26ac15f7c2f7a
C++
hushhw/LQOJ
/BASIC/BASIC-03 字母图形.cpp
GB18030
785
3.4375
3
[]
no_license
/* BASIC-3 ϰ ĸͼ ĸһЩͼΣһӣ ABCDEFG BABCDEF CBABCDE DCBABCD EDCBABC һ57еͼΣҳͼεĹɣһnmеͼΡ ʽ һУnmֱʾҪͼε ʽ nУÿmַΪͼΡ 5 7 ABCDEFG BABCDEF CBABCDE DCBABCD EDCBABC ݹģԼ 1 <= n, m <= 26 */ #include <iostream> #include <cmath> using namespace std; int main(){ int n,m; cin>>n>>m; for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ cout<<char('A'+ abs(i-j)); } cout<<endl; } system("pause"); return 0; }
true
a0aa6bce25e231234884eb782d0f218390c86341
C++
vaehx/SpeedPointEngine
/Source/SpeedPointEngine/Common/FileUtils.h
UTF-8
3,535
3.40625
3
[]
no_license
#pragma once #include "SAPI.h" #include <string> #define RESOURCE_PATH_SEPARATOR '/' #define SYSTEM_PATH_SEPARATOR '\\' namespace SpeedPoint { S_API bool IsAbsoluteResourcePath(const std::string& path); S_API bool IsAbsoluteSystemPath(const std::string& path); // Normalizes slashes inside the path and removes trailing slashes S_API std::string NormalizeResourcePath(const std::string& resourcePath); // Normalizes slashes inside the path and removes trailing slashes S_API std::string NormalizeSystemPath(const std::string& systemPath); // Description: // Resolves any upper directory symbols ('..') in the given path // e.g. "/../aaa/bbb/../ccc" becomes "/aaa/ccc" // The resulting path is normalized to the first separator found and does NOT end with a separator. // Arguments: // path - must be an absolute path. If not, the returned path will be unchanged. S_API std::string ExpandPath(const std::string& path); // Description: // Tries to make the given path relative to a reference directory path. // If the pathes don't share the same slash format, any of the paths is not absolute, // or another error occured, will return the original path. // Arguments: // absPath - must be an absolute path // absReferenceDir - must be an absolute path to a directory S_API std::string MakePathRelativeTo(const std::string& absPath, const std::string& absReferenceDir); // Description: // Appends the relative path to the given absolute reference directory by properly inserting // path separators. If the given path was absolute, it will be returned unchanged. S_API std::string MakePathAbsolute(const std::string& relPath, const std::string& absReferenceDir); // Returns the directory part of the given path up to the last separator (exclusive). // The given path is assumed to be pointing to a file if it does not end with a separator. S_API std::string GetDirectoryPath(const std::string& path); // Description: // Returns the part after the last directory separator // Examples: // /bar.txt or /foo/bar.txt -> bar.txt // bar.txt -> bar.txt S_API std::string GetFileNameWithExtension(const std::string& path); // Description: // Returns the part between (after) the last directory separator and (before) the first dot after that separator (if any) // Examples: // /foo/bar.txt -> bar // /foo/ or / -> (empty string) // /foo -> foo // bar.txt -> bar S_API std::string GetFileNameWithoutExtension(const std::string& path); // Description: // Returns the extension of the file, i.e. the part after the last dot in the path (if any). // Does not change the case of the extension part. // Examples: // /foo -> (empty string) // /foo.txt -> txt // /foo.bar.TXT -> TXT S_API std::string GetFileExtension(const std::string& path); // path - An absolute system path // workspacePath - An absolute system path to the workspace root directory // relative - If true, the resource path will be relative to the reference path if possible. // reference - An absolute resource path to a directory that the path will be made relative to. S_API std::string SystemPathToResourcePath(const std::string& path, const std::string& workspacePath, bool relative, const std::string& reference); // path - An absolute system path // workspacePath - An absolute system path to the workspace root directory S_API inline std::string SystemPathToResourcePath(const std::string& path, const std::string& workspacePath) { return SystemPathToResourcePath(path, workspacePath, false, ""); } }
true
52f74599363d8690f66ad3430cb70706d5b1eb37
C++
fmcnish-co/roarse
/sketch01.ino
UTF-8
2,508
2.8125
3
[]
no_license
#define DIGIN_L 12 #define DIGIN_R 4 #define ANAOUT_L 11 #define ANAOUT_R 5 #define MAX_VEL 250 #define MIN_VEL 180 #define inLA 10 #define inLB 9 #define inRA 6 #define inRB 7 const int analogPin = A0; int value; //variable que almacena la lectura analógica int velocity = 0; void setup() { pinMode(DIGIN_L, INPUT); pinMode(DIGIN_R, INPUT); pinMode(inLA, OUTPUT); pinMode(inLB, OUTPUT); pinMode(inRA, OUTPUT); pinMode(inRB, OUTPUT); Serial.begin(9600); } void loop() { int sLeft = 0; int sRight = 0; sLeft = digitalRead(DIGIN_L); sRight = digitalRead(DIGIN_R); value = analogRead(analogPin); // realizar la lectura analógica raw value = map(value, 0, 1023, 0, 100); // convertir a valores de salida value = 33; velocity = (int)(value * MAX_VEL)/100; //Si el sensor izq detecta linea negra => girar izq if((sLeft == HIGH)&&(sRight == LOW)){ velocity = (int) (velocity * 0.8); velocity = (velocity < MIN_VEL ? MIN_VEL : velocity); turnLeft(); }else if((sRight == HIGH)&&(sLeft == LOW)){ //Si el sensor der detecta linea negra => girar der velocity = (int) (velocity * 0.8); velocity = (velocity < MIN_VEL ? MIN_VEL : velocity); turnRight(); } else if((sLeft == HIGH) && (sRight == HIGH) ) { //Si los dos detectan linea negra o no detectan nada => detenerse velocity = 0; stopRobot(); } else { //Si los dos detectan el blanco, seguir adelante velocity = (int) (velocity == 0 ? MIN_VEL : velocity * 1.2); velocity = (velocity > MAX_VEL ? MAX_VEL : velocity); goAhead(); } } void turnRight() { //detener der y avanza izq analogWrite(ANAOUT_R,0); analogWrite(ANAOUT_L,velocity); digitalWrite(inRA, LOW); digitalWrite(inRB, LOW); digitalWrite(inLA, HIGH); digitalWrite(inLB, LOW); } void turnLeft() { //detener izq y anvaza der analogWrite(ANAOUT_R, velocity); analogWrite(ANAOUT_L, 0); digitalWrite(inRA, HIGH); digitalWrite(inRB, LOW); digitalWrite(inLA, LOW); digitalWrite(inLB, LOW); } void goAhead() { //ambos motores activos analogWrite(ANAOUT_R, velocity); analogWrite(ANAOUT_L, velocity); digitalWrite(inRA, HIGH); digitalWrite(inRB, LOW); digitalWrite(inLA, HIGH); digitalWrite(inLB, LOW); } void stopRobot () { //ambos motores detenidos analogWrite(ANAOUT_R, 0); analogWrite(ANAOUT_L, 0); digitalWrite(inRA, LOW); digitalWrite(inRB, LOW); digitalWrite(inLA, LOW); digitalWrite(inLB, LOW); }
true
897e6ccf39c575f2c352a4bf92c7202fd6786cc5
C++
ComesToMind/Theory-of-Information
/TI_lab4/TI_lab4/TI_lab4/Kazakevich.cpp
UTF-8
3,783
3.078125
3
[]
no_license
#include "Kazakevich.h" #include <vector> #include <iostream> #include <fstream> struct Code { size_t offset; size_t length; //string symbols; char symbols; }; void Kaz::Run(vector<char> first_data, string filename) { first_data.push_back('\0'); vector<Code> Codes; Code code; ofstream fout(filename); string vocabulary, temp; for (size_t position = 0; position < first_data.size(); position++) { temp += first_data[position]; //for coding phrases if (vocabulary.find(temp) == string::npos) { //symbol is found for the first time code.offset = 0; code.length = 0; code.symbols = temp[0]; } else { code.length = 1;// while (true) { //r.find - for minimal offset (characters) code.offset = vocabulary.length() - vocabulary.rfind(temp); position++; //look for next matching characters (bigram, trigramm and e.t.c.) temp += first_data[position]; if (vocabulary.find(temp) == string::npos) { if (temp.back() == '\0') { //first_data end temp.pop_back(); code.length--; } code.symbols = temp.back(); break; } else { code.length++; } } } vocabulary += temp; Codes.push_back(code); temp.clear(); } for (auto i = Codes.begin(); i != Codes.end(); ++i) { fout << "<" << i->offset << "," << i->length << "," << i->symbols << ">" << endl; } fout << endl; /////////////// // //decode // /////////////// string temp2; for (size_t i = 0; i < Codes.size(); i++) { //if single symbol if (Codes[i].length == 0) { fout << Codes[i].symbols; temp += Codes[i].symbols; } else { for (size_t j = 0; j < Codes[i].length; j++) { fout << temp[temp.size() - Codes[i].offset + j]; temp2 += temp[temp.size() - Codes[i].offset + j]; } fout << Codes[i].symbols; temp += temp2 + Codes[i].symbols; temp2.clear(); } } } void Kaz::RunCoder(vector<char> first_data, string filename) { first_data.push_back('\0'); vector<Code> Codes; Code code; ofstream fout(filename); string vocabulary, temp; for (size_t position = 0; position < first_data.size(); position++) { temp += first_data[position]; //for coding phrases if (vocabulary.find(temp) == string::npos) { //symbol is found for the first time code.offset = 0; code.length = 0; code.symbols = temp[0]; } else { code.length = 1;// while (true) { //r.find - for minimal offset (characters) code.offset = vocabulary.length() - vocabulary.rfind(temp); position++; //look for next matching characters (bigram, trigramm and e.t.c.) temp += first_data[position]; if (vocabulary.find(temp) == string::npos) { if (temp.back() == '\0') { //first_data end temp.pop_back(); code.length--; } code.symbols = temp.back(); break; } else { code.length++; } } } vocabulary += temp; Codes.push_back(code); temp.clear(); } for (auto i = Codes.begin(); i != Codes.end(); ++i) { fout << i->offset << " " << i->length << " " << i->symbols << endl; } } void Kaz::RunDecoder(string filename_in, string filename_out) { ifstream fin(filename_in); ofstream fout(filename_out); int offset, length; char ch; string vocab,temp2; while (fin.peek() != EOF) { fin >> offset >> length; if (fin.fail()) { break; } fin.get(); fin.get(ch); if (length == 0) { fout << ch; vocab += ch; } else { for (size_t j = 0; j < length;j++) { fout << vocab[vocab.size() - offset + j]; temp2 += vocab[vocab.size() - offset + j]; } fout << ch; vocab += temp2 + ch; temp2.clear(); } } }
true
8d2774ba19526bdb7f3979c16b5270734ee42807
C++
wjgaas/algorithm
/HufmannCoding-150918/HaffmanCoding-wjg.cpp
UTF-8
4,996
3.875
4
[]
no_license
/* ---------------------------------------------------------------------------------- problem : Haffman Coding Author : W.J.G time : 2015.09.20 comment : use min heap to get the minist two nodes and push the sum of them into heap again until the heap size is 1. ---------------------------------------------------------------------------------- */ #include <iostream> #include <vector> using namespace std; //haffman node to store a char and weight struct haffman_node_t { char _val; int _w; haffman_node_t *lchild; haffman_node_t *rchild; haffman_node_t(char val, int weight, \ haffman_node_t *left=NULL, haffman_node_t *right=NULL) : _val(val), _w(weight), lchild(left), rchild(right) {} bool operator < (haffman_node_t rhs) { return this->_w < rhs._w; } }; //min heap for haffman coding class MinHeap { public: MinHeap(vector<haffman_node_t*> &vec); MinHeap(){} ~MinHeap(); void make_heap(); void move_up(int idx); void move_down(int parent); void push(haffman_node_t* elem); void pop(); haffman_node_t* top(); bool empty(); int size() { return __heap.size(); } private: void __swap(haffman_node_t* &a, haffman_node_t* &b); private: vector<haffman_node_t*> __heap; }; MinHeap::MinHeap(vector<haffman_node_t*> &vec) : __heap(vec) { make_heap(); } MinHeap::~MinHeap() { } void MinHeap::__swap(haffman_node_t* &a, haffman_node_t* &b) { haffman_node_t* tmp = a; a = b; b = tmp; } bool MinHeap::empty() { return __heap.size() > 0 ? false : true; } void MinHeap::make_heap() { int idx = __heap.size()/2 - 1; for(int i=idx; i>=0; i--) { move_down(i); } } void MinHeap::move_down(int parent) { int lchild = 2*parent + 1; int rchild = lchild + 1; int min_child; if(lchild >= __heap.size()) return; else if(rchild >= __heap.size()) min_child = lchild; else min_child = *__heap[lchild] < *__heap[rchild] ? lchild : rchild; if(__heap[min_child] < __heap[parent]) { __swap(__heap[min_child], __heap[parent]); move_down(min_child); } } void MinHeap::move_up(int child) { int parent = child/2; if(*__heap[child] < *__heap[parent]) { __swap(__heap[child], __heap[parent]); if(parent != 0) move_up(parent); } } void MinHeap::push(haffman_node_t* elem) { __heap.push_back(elem); move_up(__heap.size() - 1); } haffman_node_t* MinHeap::top() { if(!empty()) return __heap[0]; else return 0; } void MinHeap::pop() { if(!empty()) { __heap[0] = __heap[__heap.size()-1]; __heap.pop_back(); move_down(0); } } //haffman coding argorithm class HaffmanCoding { public: HaffmanCoding(vector<char> &val, vector<int> &w); ~HaffmanCoding() { __destroy(_root); } void coding(); void decoding(); private: void __destroy(haffman_node_t *node); void __traverse(haffman_node_t *node, int layer, vector<int> &code); private: haffman_node_t *_root; MinHeap _heap; int _size; }; //push all nodes into min heap HaffmanCoding::HaffmanCoding(vector<char> &val, vector<int> &w) { _size = val.size(); for(int i=0; i<_size; i++) { _heap.push(new haffman_node_t(val[i], w[i])); } } //pop 2 nodes out and push the sum of them in void HaffmanCoding::coding() { while(_heap.size() > 1) { haffman_node_t *left = _heap.top(); _heap.pop(); haffman_node_t *right = _heap.top(); _heap.pop(); _heap.push(new haffman_node_t('$', left->_w + right->_w, left, right)); } _root = _heap.top(); } //delete nodes from root void HaffmanCoding::__destroy(haffman_node_t *node) { if(node->lchild != NULL) __destroy(node->lchild); if(node->rchild != NULL) __destroy(node->rchild); if(node->lchild == NULL && node->rchild == NULL) delete node; } //traverse all the nodes from left to right void HaffmanCoding::__traverse(haffman_node_t *node, int layer, vector<int> &code) { if(node->lchild != NULL) { code[layer] = 1; __traverse(node->lchild, layer+1, code); } if(node->rchild != NULL) { code[layer] = 0; __traverse(node->rchild, layer+1, code); } if(node->lchild == NULL && node->rchild == NULL) { cout << node->_val << " "; for(int i=0; i<layer; i++) cout << code[i] << " "; cout << endl; } } //left node is coding to 1, and right to 0 void HaffmanCoding::decoding() { vector<int> code(_size, 0); __traverse(_root, 0, code); } #include <string> int main(void) { char val[100]; int weight[100]; int m; cin >> m; while (m--) { int n; cin >> n; for(int i=0; i<n; i++) cin >> val[i]; for(int i=0; i<n; i++) cin >> weight[i]; vector<char> nval(val,val+n); vector<int> nweight(weight, weight+n); HaffmanCoding *hf = new HaffmanCoding(nval, nweight); hf->coding(); hf->decoding(); delete hf; } system("PAUSE"); return 0; }
true
52ed2bfb116cebf82a0170c0483cf2166d0666a4
C++
quangvm2k3/codeC
/4.10.cpp
UTF-8
220
2.625
3
[ "MIT" ]
permissive
#include <stdio.h> int main() { int n; printf("nhap n:"); scanf("%d", &n); int tong = 0; for(int i = 0; i <= n;i = i + 1) { if (i %2 == 1) { tong = tong + i; } } printf("%d", tong); return 0; }
true
19ef8f167b03ac59527fd0963540e6f77be715bc
C++
Roout/tic-tac-toe-solver
/Board.hpp
UTF-8
3,134
3.4375
3
[ "MIT" ]
permissive
#ifndef BOARD_HPP #define BOARD_HPP #include <cassert> #include <cstdint> #include <cstddef> #include <utility> #include <iostream> // Contain game logic implementation namespace game { class Board { public: enum Details: size_t { ROWS = 3, COLS = 3, SIZE = 9 }; enum class Cell: uint8_t { X = 0, O = 1, FREE = 2 }; enum class State: uint8_t { WIN, ONGOING, DRAW }; // TODO: add enums to mark a player: 'o', 'x' constexpr Cell at(size_t row, size_t col) const noexcept { const auto bitIndex = row * Details::ROWS + col; return (m_desk & (1U << bitIndex)) > 0U? Cell::X: (m_desk & (1U << (bitIndex + Details::SIZE))) > 0U? Cell::O : Cell::FREE; } // TODO: add constexpr assignment and clear methods which will return the new board // without modifying this one void assign(size_t row, size_t col, Cell value) noexcept { const auto bitIndex = row * Details::ROWS + col; m_desk |= value == Cell::X? (1U << bitIndex) : value == Cell::O? (1U << (bitIndex + Details::SIZE)): 0U; } void clear(size_t row, size_t col) noexcept { const auto bitIndex = row * Details::ROWS + col; // clear 'x' m_desk &= ~(1U << bitIndex); // clear 'o' m_desk &= ~(1U << (bitIndex + Details::SIZE)); } /** * @return the indication whethere the state of board is final or not, i.e. * returns true if the game is finished, false - ongoing! */ constexpr bool finished() const noexcept { const size_t players[2] = { // clear the bits used by second player - 'o', // leave the bits of player - 'x' untouched m_desk & (~((~(1U << Details::SIZE)) << Details::SIZE)), // 'x' m_desk >> Details::SIZE // 'o' }; constexpr auto fullBoard { 0b111111111 }; assert(players[0] <= fullBoard && "Wrong bit conversation"); assert(players[1] <= fullBoard && "Wrong bit conversation"); assert(((players[0] & players[1]) == 0U) && "Logic error: moves overlaped"); return (players[0]|players[1]) == fullBoard; } // return an unsigned integer which represent the board constexpr size_t unwrap() const noexcept { return m_desk; } friend std::ostream& operator<<(std::ostream&, Board board); private: // `size_t` is at least 32bit value, so let assign it's bits a specific value: // from lsb // [0 ... 8] - indicates whether the cell at i-th place is 'x' or not // [9 ... 17] - indicates whether the cell at i-th place is 'o' or not // [18 ... 32 (64)] - unspecified size_t m_desk { 0U }; }; std::ostream& operator<<(std::ostream& os, Board board); std::pair<Board::State, Board::Cell> GetGameState(Board board) noexcept; } void TestBoard(); #endif // BOARD_HPP
true
c017d1407869341e87e8ce3649fd5aebf8c93981
C++
rsalgad/ConsoleFEM
/VS_2019/ConsoleFEMTest/SparseMatrix.cpp
UTF-8
2,386
3.09375
3
[]
no_license
#include "pch.h" #include "SparseMatrix.h" #include <map> SparseMatrix::SparseMatrix() { } SparseMatrix::SparseMatrix(const int dimX, const int dimY) { _dimX = dimX; _dimY = dimY; } SparseMatrix::~SparseMatrix() { } std::map<int, std::map<int, double>>* SparseMatrix::GetMap() { return &_matrix; } void SparseMatrix::SetSize(const int size) { _size = size; } int SparseMatrix::SparseSize(const Matrix& m) { double countNonZero = 0; for (int i = 0; i < m.GetDimX(); i++) { for (int j = 0; j < m.GetDimY(); j++) { if (m.GetMatrixDouble()[i][j] != 0) { countNonZero++; } } } return countNonZero; } double** SparseMatrix::CreateMatrixDouble(const int size) { double** m = new double* [3]; for (int i = 0; i < 3; i++) m[i] = new double[size] {}; // '{}' initializes everything to zero return m; } SparseMatrix SparseMatrix::ConvertToSparseMatrix(const Matrix& m) { SparseMatrix matrix(m.GetDimX(), m.GetDimY()); std::vector<double> rows, cols, vals; for (int i = 0; i < m.GetDimX(); i++) { for (int j = 0; j < m.GetDimY(); j++) { if (m.GetMatrixDouble()[i][j] != 0) { //This should be ordered by rows then cols. rows.emplace_back((double)i); cols.emplace_back((double)j); vals.emplace_back(m.GetMatrixDouble()[i][j]); } } } double** d = new double* [rows.size()]; for (int i = 0; i < rows.size(); i++) d[i] = new double[3]{ rows[i], cols[i], vals[i] }; //matrix.SetMatrixDouble(d); matrix.SetSize(rows.size()); return matrix; } SparseMatrix SparseMatrix::ConvertToSymmetricSparseMatrix(const Matrix& m) { SparseMatrix matrix(m.GetDimX(), m.GetDimY()); int count = 0; for (int i = 0; i < m.GetDimX(); i++) { std::map<int, double> mapRow; for (int j = 0; j <= i; j++) { if (m.GetMatrixDouble()[i][j] != 0) { //This should be ordered by rows then cols. mapRow.insert(std::pair<int, double>(j, m.GetMatrixDouble()[i][j])); count++; } } matrix.GetMap()->insert(std::pair<int, std::map<int,double>>(i, mapRow)); } matrix.SetSize(count); return matrix; } int SparseMatrix::IndexOfFirstLine(const int line) { for (int i = 0; i < _size; i++) { if (_matrix[i][0] == line) return i; } return -1; } int SparseMatrix::ElementsInLineXBeforeColY(const int lineIndex, const int col) { int index = lineIndex; while (_matrix[index][1] != col) { index++; } return index - lineIndex; }
true
8ba5f3b769bf38be4b242b8ba319c56c0ba836d6
C++
mbielsk/Dune-II---The-Maker
/utils/cSoundPlayer.h
UTF-8
703
2.796875
3
[]
no_license
/* * cSoundPlayer.h * * Created on: 6-aug-2010 * Author: Stefan * * A class responsible for playing sounds. But also managing the sounds being played (ie, not * playing too many sounds in the same frame, etc). * */ #ifndef CSOUNDPLAYER_H_ #define CSOUNDPLAYER_H_ class cSoundPlayer { public: cSoundPlayer(int maxVoices); ~cSoundPlayer(); void playSound(SAMPLE *sample, int pan, int vol); void playSound(int sampleId, int pan, int vol); // think about voices, clear voices, etc. void think(); void destroyAllSounds(); protected: void destroySound(int voice, bool force); private: int maximumVoices; int voices[256]; }; #endif /* CSOUNDPLAYER_H_ */
true
b73cb451ffa3cdf055afc8976917a2854424c8e6
C++
sarum9in/cpp_course
/examples/utility.hpp
UTF-8
301
2.640625
3
[]
no_license
#include <iostream> #include <cassert> #include <cstdint> #define assert_equal_ptr(A, B) \ assert(reinterpret_cast<std::intptr_t>(A) == reinterpret_cast<std::intptr_t>(B)) #define assert_not_equal_ptr(A, B) \ assert(reinterpret_cast<std::intptr_t>(A) != reinterpret_cast<std::intptr_t>(B))
true
87f030e63c4f1e01a92c5c5d9685142c1c8efc37
C++
sunnysetia93/competitive-coding-problems
/LeetCode/All/cpp/191.number-of-1-bits.cpp
UTF-8
149
2.53125
3
[ "MIT" ]
permissive
class Solution { public: int hammingWeight(uint32_t n) { int ones = 0; for (; n; ++ones, n &= n-1); return ones; } };
true
450ef040a90ef3e67044bde5617dacfebd07df36
C++
ektagarg786/Coding-Ninjas-CP
/Graph_1/Largest_piece.cpp
UTF-8
1,880
3.59375
4
[]
no_license
/*Its Gary's birthday today and he has ordered his favourite square cake consisting of '0's and '1's . But Gary wants the biggest piece of '1's and no '0's . A piece of cake is defined as a part which consist of only '1's, and all '1's share an edge with eachother on the cake. Given the size of cake N and the cake , can you find the size of the biggest piece of '1's for Gary ? Constraints : 1<=N<=50 Input Format : Line 1 : An integer N denoting the size of cake Next N lines : N characters denoting the cake Output Format : Size of the biggest piece of '1's and no '0's Sample Input : 2 11 01 Sample Output : 3*/ int dfs(char cake[NMAX][NMAX], int n, int i, int j, bool** visited){ visited[i][j] = true; int count = 0; if(i-1 >= 0 && j>= 0){ if(cake[i-1][j] == '1' && ! visited[i-1][j]){ count += dfs(cake, n, i-1, j, visited); } } if(i >= 0 && j + 1 >= 0){ if(cake[i][j+1] == '1' && ! visited[i][j+1]){ count += dfs(cake, n, i, j+1, visited); } } if(i >= 0 && j-1>= 0){ if(cake[i][j-1] == '1' && ! visited[i][j-1]){ count += dfs(cake, n, i, j-1, visited); } } if(i+1 >= 0 && j>= 0){ if(cake[i+1][j] == '1' && ! visited[i+1][j]){ count += dfs(cake, n, i+1, j, visited); } } return count+1; } int solve(int n, char cake[NMAX][NMAX]){ bool** visited = new bool*[n]; for(int i=0;i<n;i++){ visited[i] = new bool[n]; for(int j=0;j<n;j++){ visited[i][j] = false; } } int max = 0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(cake[i][j] == '1' && ! visited[i][j]){ int x = dfs(cake, n, i, j, visited); if(x > max){ max = x; } } } } return max; }
true
279d9053e9aee3718bab5e7ccdddc0eb8f5f4c49
C++
mime3/bit
/day8/day8/main_tree.cpp
UHC
2,230
3.609375
4
[]
no_license
#include <stdio.h> #include "Queue.h" struct Node { int value; Node * left; Node * right; }; Node * head, *tail; void preOrder(Node * root) { if (root != nullptr) { printf("%d ", root->value); preOrder(root->left); preOrder(root->right); } } // bst ŽƮ ˻ϸ ĵ void inOrder(Node * root) { if (root != nullptr) { inOrder(root->left); printf("%d ", root->value); inOrder(root->right); } } void level(Node * root) { Queue<Node *> q; q.EnQueue(root); while (!q.isEmpty()) { Node * get; q.DeQueue(&get); printf("%d ", get->value); if (get->left != nullptr) q.EnQueue(get->left); if (get->right != nullptr) q.EnQueue(get->right); } } void postOrder(Node * root) { if (root != nullptr) { postOrder(root->left); postOrder(root->right); printf("%d ", root->value); } } int get_Depth(Node * root, int dep) { int l_dep, r_dep; l_dep = r_dep = dep; if (root->left != nullptr) l_dep = get_Depth(root->left, dep + 1); if (root->right != nullptr) r_dep = get_Depth(root->right, dep + 1); if (l_dep >= r_dep) return l_dep; else return r_dep; } int main() { Node a1 = { 1, nullptr, nullptr }; Node b2 = { 2, nullptr, nullptr }; Node c3 = { 3, nullptr, nullptr }; Node d4 = { 4, nullptr, nullptr }; Node e5 = { 5, nullptr, nullptr }; Node f6 = { 6, nullptr, nullptr }; c3.left = &a1; a1.right = &b2; c3.right = &d4; d4.right = &e5; e5.right = &f6; preOrder(&c3); puts(""); inOrder(&c3); puts(""); postOrder(&c3); puts(""); level(&c3); puts(""); printf("%d\n", get_Depth(&c3, 0)); printf("%d\n", get_Depth(c3.left, 0)); printf("%d\n", get_Depth(c3.right, 0)); getchar(); return 0; } // ȸ // Ʈ push // // while // stack popؼ key // pop ༮ , ʼ push // ȸ // while // 1. Ʈ push // 2. Ʈ while push // 3. ̻ pop key // 4. Ʈ Ʈ push // ȸ // ť // root enqueue // while // dequeue // dequeue ༮ left, right enqueue
true
df904961123ef4478bee8db9d7c1274145b7a945
C++
pbcarvalhaes/HapticPaddle
/Contador_Encoder/Contador_Encoder.ino
UTF-8
1,294
2.890625
3
[]
no_license
#define ENCODER_A 2 #define ENCODER_B 3 volatile int pos; volatile bool state_A; volatile bool state_B; //Do not use volatile variables directly! void conta_A() { if(state_A){ if(state_B){ pos+=1; } else{ pos-=1; } } else{ if(state_B){ pos-=1; } else{ pos+=1; } } state_A = !state_A; } void conta_A_K(){ pos += 1 - (2*(state_A|state_B)); state_A = !state_A; } void conta_B() { if(state_B){ if(state_A){ pos-=1; } else{ pos+=1; } } else{ if(state_A){ pos+=1; } else{ pos-=1; } } state_B = !state_B; } void conta_B_K(){ pos -= 1 - (2*(state_A|state_B)); state_B = !state_B; } void setup() { // put your setup code here, to run once: pinMode(ENCODER_A, INPUT); pinMode(ENCODER_B, INPUT); state_A = (digitalRead(ENCODER_A) == HIGH); state_B = (digitalRead(ENCODER_B) == HIGH); attachInterrupt(digitalPinToInterrupt(ENCODER_A), conta_A, CHANGE); attachInterrupt(digitalPinToInterrupt(ENCODER_B), conta_B, CHANGE); } void loop() { // put your main code here, to run repeatedly: }
true
b32483b0ed7bb01a1eb648409e988106026b0c94
C++
ShailendraLohia/os-spring-2019
/data_structures/map/maybe.h
UTF-8
651
3.15625
3
[]
no_license
#ifndef DOCUMENTS_MAP_H #define DOCUMENTS_MAP_H namespace data_structures { namespace map { template<typename ValueType> class Maybe { private: const bool is_present_; const ValueType value_; public: // we have an actual value explicit Maybe(const ValueType& value) : is_present_(true), value_(value) {} // empty case Maybe() : is_present_(false), value_(nullptr) {} bool IsPresent() const { return is_present_; } const ValueType Value() const { return value_; } }; } // namespace map } // namespace data_structures #endif //DOCUMENTS_MAP_H
true
cca677dde34fce0769c0c4782f311be583fd561b
C++
rgreenblatt/apma_2822b
/hw/hw_3/src/test.cpp
UTF-8
1,127
2.875
3
[]
no_license
#include <vector> #include <mpi.h> #include <omp.h> #include "matrix.h" struct TestParams { int size_i; int size_j; int size_k; bool use_mkl; }; int main(int argc, char **argv) { MPI_Init(&argc, &argv); int omp_num_threads = omp_get_max_threads(); int world_size, world_rank; MPI_Comm_size(MPI_COMM_WORLD, &world_size); MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); //test on small matrices std::vector<TestParams> tests = { {240, 60, 120, false}, {240, 60, 120, true}, {240, 120, 60, false}, {240, 120, 60, true}, {120, 60, 240, false}, {120, 60, 240, true}, {120, 240, 60, false}, {120, 240, 60, true}, {60, 240, 120, false}, {60, 240, 120, true}, {60, 120, 240, false}, {60, 120, 240, true}}; auto f_a = [](int i, int j) { return i * 0.3 + j * 0.4; }; auto f_b = [](int j, int k) { return j * 0.5 + k * 0.6; }; for(auto &test : tests) { distributed_matrix_multiply(test.size_i, test.size_j, test.size_k, world_rank, world_size, omp_num_threads, f_a, f_b, test.use_mkl, true); } std::cout << "finished all tests" << std::endl; }
true
8041bd4a02e076df0a4d53d8cd810fe9d7a1a94d
C++
devikakrishnadas/OJ-problems
/codeforces/Laptops.cpp
UTF-8
546
2.609375
3
[]
no_license
#include<bits/stdc++.h> #define ll long long #define vi vector<int> #define vc vector<char> #define vll vector<ll> #define pb push_back #define sf scanf #define pf printf #define mp make_pair #define all(V) V.begin,V.end using namespace std; int main() { int n; cin>>n; vector<pair<int,int> >A; int x,y; for(int i=0;i<n;i++) { cin>>x>>y; A.pb(mp(x,y)); } sort(A.begin(),A.end()); for(int i=1;i<n;i++) { if(A[i-1].second>A[i].second) { cout<<"Happy Alex"<<endl; return 0; } } cout<<"Poor Alex"<<endl; return 0; }
true
d7f3c47b7e32aa7f43be787ef9a008f086f7574e
C++
jcelerier/pfa_guitar_tutor
/GridEditor/TimeEdit.h
UTF-8
783
2.6875
3
[]
no_license
#ifndef TIMEEDIT_H #define TIMEEDIT_H #include <QtWidgets/QTimeEdit> /** * @brief Enfant de la QTimeEdit pour afficher en rouge si données invalide */ class TimeEdit : public QTimeEdit { Q_OBJECT public: explicit TimeEdit(QWidget *parent = 0); void setBad(); void setGood(); virtual void mousePressEvent ( QMouseEvent * event ); signals: /** * @brief hasBeenClicked est émis lorsqu'on clique sur le widget */ void hasBeenClicked(); public slots: void changed(QTime); private: /** * @brief m_hasChanged vrai si a changé (pour éviter les feedbacks) */ bool m_hasChanged; /** * @brief m_badStyle CSS qui correspond à un état invalide */ QString m_badStyle; //TODO mérite de passer en static const }; #endif // TIMEEDIT_H
true
dc0c01dd2f1608e05e6a45ac8b8a1618fe6bd61d
C++
ArthurSonzogni/just-fast
/src/libs/FileSystemOperations/FileSystemOperations.cpp
UTF-8
1,911
3.1875
3
[ "MIT" ]
permissive
#include "FileSystemOperations.h" #include <algorithm> void FileSystemOperations::setSelectedFiles(std::vector<std::filesystem::path> sFiles) { selectedFiles = sFiles; } void FileSystemOperations::appendSelectedFiles(std::filesystem::path fileToAppand) { //I hate that. auto it = std::find(selectedFiles.begin(), selectedFiles.end(), fileToAppand); if (it != selectedFiles.end()) { selectedFiles.erase(it); } else { selectedFiles.push_back(fileToAppand); } } void FileSystemOperations::clearSelectedFiles() { selectedFiles.clear(); } std::vector<std::filesystem::path> FileSystemOperations::getSelectedFiles() { return selectedFiles; } size_t FileSystemOperations::countSelectedFiles() { return selectedFiles.size(); } void FileSystemOperations::setOperation(FileSystemOperations::Operation o) { selectedOperation = o; } FileSystemOperations::Operation FileSystemOperations::getOperation() { return selectedOperation; } void FileSystemOperations::clearOperation() { selectedOperation = NOT_SELECTED; } void FileSystemOperations::performOperation(std::filesystem::path dest) { try { switch (selectedOperation) { case NOT_SELECTED: return; break; case COPY: for (auto& p : selectedFiles) { std::filesystem::copy(p, dest / p.filename(), std::filesystem::copy_options::recursive); } break; case DELETE: for (auto& p : selectedFiles) { std::filesystem::remove_all(p); } break; case MOVE: for (auto& p : selectedFiles) { std::filesystem::rename(p, dest / p.filename()); } break; } } catch (std::filesystem::filesystem_error& e) { throw e; } clearOperation(); clearSelectedFiles(); }
true
2136935bf7194fc078f385bc2e904f980a942545
C++
levankhaduri/StudentManagmentApplication
/StudentsDatabase/StudentsDatabase/courseswindow.cpp
UTF-8
5,659
2.625
3
[]
no_license
#include "courseswindow.h" #include "ui_courseswindow.h" #include "Classes.h" #include <QSqlDatabase> #include <QSqlQuery> #include <QString> #include <QMessageBox> #include <SqlDatabase.h> CoursesWindow::CoursesWindow(QWidget *parent) : QDialog(parent), ui(new Ui::CoursesWindow) { ui->setupUi(this); Database dbModel; db = dbModel.GetDBInstance(); } CoursesWindow::~CoursesWindow() { delete ui; } void CoursesWindow::on_SearchByIdButton_clicked() { ui->SearchWithIdBox->clear(); QString courseId = ui->SearchId->text(); bool recordFound = false; bool lecturerFound = false; QSqlQuery qry; QSqlQuery secondQry; if(db.isOpen()){ if(qry.exec(QString("SELECT * FROM dbo.Course where Course.IdNumber = '%1';").arg(courseId))){ while(qry.next()){ recordFound = true; Course course(qry.value(0).toString(), qry.value(1).toString(), qry.value(2).toString()); ui->SearchWithIdBox->insertPlainText(course.printInfo()); if(secondQry.exec(QString("SELECT * FROM dbo.Lector where Lector.IdNumber = '%1';").arg(course.getLectorId()))){ while(secondQry.next()){ lecturerFound = true; Lector lector(secondQry.value(0).toString(), secondQry.value(1).toString(), secondQry.value(2).toString(), secondQry.value(3).toString(), secondQry.value(4).toString()); ui->SearchWithIdBox->insertPlainText(lector.printInfo()); } } } if(!recordFound) QMessageBox::critical(this, "404", "No courses with this id was found at this moment."); } } else{ QMessageBox::critical(this, "Critical!", "Something went wrong"); } } void CoursesWindow::on_pushButton_2_clicked() { ui->AllCoursesBox->clear(); bool recordFound = false; bool lecturerFound = false; QSqlQuery qry; QSqlQuery secondQry; if(db.isOpen()){ if(qry.exec(QString("SELECT * FROM dbo.Course;"))){ while(qry.next()){ recordFound = true; Course course(qry.value(0).toString(), qry.value(1).toString(), qry.value(2).toString()); ui->AllCoursesBox->insertPlainText(course.printInfo()); if(secondQry.exec(QString("SELECT * FROM dbo.Lector where Lector.IdNumber = '%1';").arg(course.getLectorId()))){ while(secondQry.next()){ lecturerFound = true; Lector lector(secondQry.value(0).toString(), secondQry.value(1).toString(), secondQry.value(2).toString(), secondQry.value(3).toString(), secondQry.value(4).toString()); ui->AllCoursesBox->insertPlainText(lector.printInfo() + "\n"); } } } if(!recordFound) QMessageBox::critical(this, "404", "No courses found at this moment."); } } else{ QMessageBox::critical(this, "Critical!", "Something went wrong"); } } void CoursesWindow::on_AddCourseButton_clicked() { QString courseId = ui->RegisterId->text(); QString courseName = ui->RegisterName->text(); QString lectorId = ui->RegisterLectorId->text(); if(courseId.isEmpty() || courseName.isEmpty() || lectorId.isEmpty()){ QMessageBox::critical(this, "400", "Fields weren't filled."); } if(db.isOpen()) { QSqlQuery qry; bool lectorFound = false; if(qry.exec(QString("SELECT * FROM dbo.Lector where Lector.IdNumber = '%1';").arg(lectorId))){ while(qry.next()){ lectorFound = true; } if(!lectorFound){ QMessageBox::critical(this, "404", "Lector with this id wasn't found."); return; } } db.exec(QString("INSERT INTO dbo.Course VALUES('%1', '%2', '%3')").arg(courseId).arg(courseName).arg(lectorId)); ui->RegisterId->clear(); ui->RegisterName->clear(); ui->RegisterLectorId->clear(); QMessageBox::information(this, "Accepted", "Course was created"); } } void CoursesWindow::on_AddStudentCourseButton_clicked() { QString courseId = ui->CourseIdStudentReg->text(); QString studentId = ui->StudIdStudentReg->text(); if(courseId.isEmpty() || studentId.isEmpty()){ QMessageBox::critical(this, "400", "Fields weren't filled."); } if(db.isOpen()) { QSqlQuery qry; bool studentFound = false; bool courseFound = false; if(qry.exec(QString("SELECT * FROM dbo.Student where Student.IdNumber = '%1';").arg(studentId))){ while(qry.next()){ studentFound = true; } if(!studentFound){ QMessageBox::critical(this, "404", "Student with this id wasn't found."); return; } } if(qry.exec(QString("SELECT * FROM dbo.Course where Course.IdNumber = '%1';").arg(courseId))){ while(qry.next()){ courseFound = true; } if(!studentFound){ QMessageBox::critical(this, "404", "Course with this id wasn't found."); return; } } db.exec(QString("INSERT INTO dbo.CourseScoreMap VALUES('%1', '%2', '%3')").arg(studentId).arg(courseId).arg(0)); ui->RegisterId->clear(); ui->RegisterName->clear(); ui->RegisterLectorId->clear(); QMessageBox::information(this, "Accepted", "Course was assigned to student!"); } }
true
0a66c283f2d20e66207f17ab850f6f3c0df455f2
C++
electrified/cpuqt
/ui/cpm_io.cpp
UTF-8
628
2.546875
3
[]
no_license
#include "cpm_io.h" cpm_io::cpm_io() = default; /* Emulate CP/M bdos call 5 functions 2 (output character on screen) and * 9 (output $-terminated string to screen). */ void cpm_io::in(Rgstr rgstr, const MemoryAddress &i, Registers *registers, Memory *memory) { if (registers->getC() == 2) { // rewrite as code, CP/M BIOS routine emit consoleTextOutput(registers->getE()); } else if (registers->getC() == 9) { std::uint16_t i; //, c; // rewrite as code, CP/M BIOS routine for (i = registers->getDE(); memory->read(i) != '$'; i++) { emit consoleTextOutput(memory->read(i & 0xffff)); } } }
true
41e5d5bea90a84ed83620da97c4437d8e8cb628d
C++
arpit23697/For-Uva-solutions
/Graph/Graph_traversal/Articulation_Bridges.cpp
UTF-8
1,813
2.984375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; vector <vector <int>> graph; int n; vector <int dfs_num; vector <int> dfs_low; int UNVISITED = 0; vector <int> parent; vector <bool> articulation; int dfs_counter; int dfs_root; int root_children; void Articulation_and_bridges (int u) { dfs_num[u] = dfs_low[u] = dfs_counter; //dfs_low[u] <= dfs_num[u] dfs_counter++; for (int i= 0 ; i < graph[u].size() ; i++) { int v = graph[u][v]; if (dfs_num[u] == UNVISITED) { parent[v] = u; if (u == dfs_root) root_children++; Articulation_and_bridges(v); if (dfs_low[v] >= dfs_num[u]) articulation[u] = true; if (dfs_low[v] > dfs_num[u]) cout << u << " " << v << " is a bridge edge " << endl; dfs_low[u] = min (dfs_low[u] , dfs_low[v]); } else if (v != parent[u]) //this is one the back edge dfs_low[u] = min (dfs_low[u] , dfs_num[v]); } } int main () { cin >> n; int edges; cin >> edges; graph.assign (n , vector <int> ()); for (int i = 0 ; i < edges ; i++) { int a , b; cin >> a >> b; graph[a].push_back (b); } dfs_num.assign (n , 0); dfs_low.assign (n , 0); articulation.assign (n , false); parent.assign(n , 0); dfs_counter = 0; for (int i = 0 ; i < n ; i++) if (dfs_num[i] == UNVISITED) { dfs_root = i; root_children = 0; Articulation_and_bridges (i); if (root_children > 1) articulation[i] = true; } for (int i =0 ; i < n ; i++) if (articulation[i] == true) cout << i << " "; cout << endl; return 0; }
true
39266263ff42a000ad46283d5b9b8907b9fe4abd
C++
formichi3/CMPS109
/tadum/Rule_H.h
UTF-8
560
2.703125
3
[]
no_license
#include <iostream> #include <utility> #include <vector> using namespace std; #ifndef Rule_H #define Rule_H class rule{ public: //constructors & destructors rule(); rule(string p_name, vector < string > p_args, int p_Operator, vector < vector < string > > p_preds); ~rule(); string name; //name of rule int logOperator; //0=OR, 1=AND vector < string > args; //args to be returned when inferred vector < vector < string > > predicates; string createString(); void print(); }; #endif
true
52c7d301960aea87b6a89d266cc84a1ee6209b99
C++
bellkyle/GPA-Degree-Audit
/gpa7.cpp
UTF-8
23,003
3.625
4
[]
no_license
#include <iostream> #include <fstream> using namespace std; //class for Courses class Course { public: Course(); // default constructor void get(string& name, string& time, string& number, char& g, int& h) const; //to only get the course number and hours void getRequirements(string& number, int& h); void set(string name, string time, string number, char g, int h); //to only set the course number and hours void setRequirements(string number, int h); void print() const; void printRequirements() const; private: string courseName; string courseTime; string courseNumber; char grade; int hours; }; //Constructor Course to intialized the variables Course::Course() { courseName = "Programming Foundations I"; courseTime = "Fall 2015"; courseNumber = "CSCE 2004"; grade = 'A'; hours = 4; } //print member function void Course::print() const { cout << courseName << endl; cout << courseTime << endl; cout << courseNumber << endl; cout << grade << endl; cout << hours << endl; } //print to print only the requirement courses void Course::printRequirements() const { cout << courseNumber << endl; cout << hours << endl; } //set member function void Course::set(string name, string time, string number, char g, int h) { courseName = name; courseTime = time; courseNumber = number; grade = g; hours = h; } //set member to set the Requirement classes void Course::setRequirements(string number, int h) { courseNumber = number; hours = h; } //get member function void Course::get(string& name, string& time, string& number, char& g, int& h) const { name = courseName; time = courseTime; number = courseNumber; g = grade; h = hours; } //get member to get the Requirement classes void Course::getRequirements(string& number, int& h) { number = courseNumber; h = hours; } //class for Requirements class Requirement { public: Requirement(); void get(string& groups, string& subgroups, int& hours) const; //to get the information from the Course class void getCourses(string courseNum[], int hours[], int& index); void set(string groups, string subgroups, int hours); //to set the information from the Course class void setCourses(string courseNum, int hours, int index); bool validate(Course uniqueCourses[], Course usedCourses[], int& numUsedCourses, int numUniqueCourses); void print() const; void printSubgroup() const; private: static const int INDEX = 200; string group; string subgroup; int requiredHours; Course courses[INDEX]; int numCourses; }; //constructor Requirement::Requirement() { group = "University Core"; subgroup = "Fine Arts"; requiredHours = 3; numCourses = 0; } //getter for the course class void Requirement::getCourses(string courseNum[], int hour[], int& index) { index = numCourses; string number; int h; for(int i = 0; i < numCourses; i++) { courses[i].getRequirements(number, h); courseNum[i] = number; hour[i] = h; } } //print method function void Requirement::print() const { cout << group << endl; cout << subgroup << endl; cout << requiredHours << endl; for(int k = 0; k < numCourses; k++) { courses[k].printRequirements(); } } //to only print the subgroup void Requirement::printSubgroup() const { cout << subgroup << endl; } //getter to get group, subgroup and required Hours void Requirement::get(string& groups, string& subgroups, int& hours) const { groups = group; subgroups = subgroup; hours = requiredHours; } //setter to set group, subgroup and required hours void Requirement::set(string groups, string subgroups, int hours) { group = groups; subgroup = subgroups; requiredHours = hours; } //setter to set the Course class void Requirement::setCourses(string courseNum, int hours, int index) { courses[index].setRequirements(courseNum, hours); numCourses = index + 1; } //method function to perform the degree audit bool Requirement::validate(Course uniqueCourses[], Course usedCourses[], int& numUsedCourses, int numUniqueCourses) { string number, usedNumber; string name, time; char grade; int hour, usedHours; int countHours = 0; for(int i = 0; i < numUniqueCourses; i++) { uniqueCourses[i].get(name, time, number, grade, hour); bool checkUsed = true; //to make sure the course has not already been used for(int j = 0; j < numUsedCourses; j++) { usedCourses[j].getRequirements(usedNumber, usedHours); if(number == usedNumber) checkUsed = false; } if(checkUsed) { string reqNumber; int reqHours; //loop to check the course against all of the possible courses for(int k = 0; k < numCourses; k++) { courses[k].getRequirements(reqNumber, reqHours); if(number == reqNumber) { countHours += hour; usedCourses[numUsedCourses].set(name, time, number, grade, hour); numUsedCourses++; } //checking to see if the required hours have been met if(countHours >= requiredHours) { return true; } } } } return false; } //function to read in the requirement file bool readingRequirements(const char filename[], Requirement requirements[], int capacity, int& n) { ifstream din; din.open( filename ); string group, subgroup; string courseNum; int hours, requiredHours; //checking to see if the file opened if(!din) { cout << "That file does not exist" << endl; return false; } getline(din, group); int requirementIndex = 0; //loop to assign the information to the variables while(!din.eof()) { //error checking if(requirementIndex > capacity) { cout << "You went over capacity for the array" << endl; return false; } int courseIndex = 0; getline(din, subgroup); din >> requiredHours; requirements[requirementIndex].set(group, subgroup, requiredHours); getline(din, courseNum); getline(din, courseNum); while(!din.eof() && courseNum != "") { din >> hours; requirements[requirementIndex].setCourses(courseNum, hours, courseIndex); courseIndex++; getline(din, courseNum); getline(din, courseNum); } requirementIndex++; getline(din, group); } n = requirementIndex; //closing the file din.close(); return true; } //function to separate the University Requirements from the other requirements void getUniversityRequirement (Requirement requirements[], Requirement universityRequirement[], int n, int& numUniversityRequirement) { const int SIZE = 200; string group, subgroup; string number[SIZE]; int requiredHours; int hours[SIZE]; int index; for(int i = 0; i < n; i++) { requirements[i].get(group, subgroup, requiredHours); requirements[i].getCourses(number, hours, index); if (group == "University Core") { universityRequirement[numUniversityRequirement].set(group, subgroup, requiredHours); for(int j = 0; j < index; j++) { universityRequirement[numUniversityRequirement].setCourses(number[j], hours[j], j); } numUniversityRequirement++; } } } //function to get unique courses void getUniqueCourses(Course courses[], Course uniqueCourses[], int numCourses, int& numUnique) { string name, time, number; char grade; int hours; string uniqueName, uniqueTime, uniqueNumber; char uniqueGrade; int uniqueHours; bool checkUnique; for(int i = 0; i < numCourses; i++) { checkUnique = true; courses[i].get(name, time, number, grade, hours); for(int j = 0; j < numUnique; j++) { uniqueCourses[j].get(uniqueName, uniqueTime, uniqueNumber, uniqueGrade, uniqueHours); if(uniqueNumber == number) { if(uniqueGrade == 'D' && (grade == 'C' || grade == 'B' || grade == 'A')) uniqueCourses[j].set(name, time, number, grade, hours); else if(uniqueGrade == 'C' && (grade == 'B' || grade == 'A')) uniqueCourses[j].set(name, time, number, grade, hours); else if(uniqueGrade == 'B' && grade == 'A') uniqueCourses[j].set(name, time, number, grade, hours); checkUnique = false; } } if(checkUnique) { if(grade == 'A' || grade == 'B' || grade == 'C' || grade == 'D') { uniqueCourses[numUnique].set(name, time, number, grade, hours); numUnique++; } } } } //function to read in the file bool reading(const char filename[], Course courses[], int& n, int capacity) { ifstream din; din.open( filename ); string name, time, number; char grade; int hours; //checking to see if the file opened if(!din) { cout << "That file does not exist" << endl; return false; } din >> n; //checking to make sure the file does not go over capacity if(n > capacity) { cout << "Insufficient space in the arrays." << endl; return false; } //loop to assign the information to the variables for (int i = 0; i < n; i++) { getline(din, name); getline(din, name); getline(din, time); getline(din, number); din >> grade; din >> hours; //setting the values to the courses class courses[i].set(name, time, number, grade, hours); } //closing the file din.close(); return true; } //function to write the class into a file bool writing(const char filename[], Course courses[], int n) { ofstream dout; dout.open( filename ); //making sure the file opens if(!dout) return false; dout << n << endl; string name; string time; string number; char grade; int hours; //loop to write in the file for (int i = 0; i < n; i++) { //retrieving the information from the class courses[i].get(name, time, number, grade, hours); dout << name << endl; dout << time << endl; dout << number << endl; dout << grade << endl; dout << hours << endl; } //closing the file dout.close(); return true; } //gpa function double gpa(int n, const Course courses[]) { double gradePoints = 0; double totalHours = 0; string name, time, number; char grade; int hour; //loop to sum the grade points and credit hours for(int index = 0; index < n; index++) { courses[index].get(name, time, number, grade, hour); if(grade == 'A') gradePoints = gradePoints + (hour * 4.0); else if(grade == 'B') gradePoints = gradePoints + (hour * 3.0); else if(grade == 'C') gradePoints = gradePoints + (hour * 2.0); else if(grade == 'D') gradePoints = gradePoints + (hour * 1.0); else if(grade == 'F') gradePoints = gradePoints + (hour * 0.0); if(grade != 'W' && grade != 'I') totalHours = totalHours + hour; } double gpaEquation = 0; //error checking and calculating the GPA if(totalHours == 0) cout << "Cannot divide by 0." << endl; else gpaEquation = gradePoints / totalHours; //if statements to output the GPA if ( gpaEquation >= 3.0) cout << "Excellent! Your GPA is " << gpaEquation << endl; else if ( gpaEquation > 2.5) cout << "Not bad, but you could work harder. Your GPA is " << gpaEquation << endl; else if (gpaEquation >= 2.0) cout << "Put a bit more effort into it. Your GPA is " << gpaEquation << endl; else if (gpaEquation >= 0.0) cout << "That's terrible! Do you even go to class? Your GPA is " << gpaEquation << endl; return gpaEquation; } //function to calculate the GPA for a semester double semesterGpa(int n, const Course courses[], string semester) { double gradePoints = 0; double totalHours = 0; string name, time, number; char grade; int hours; for(int index = 0; index < n; index++) { courses[index].get(name, time, number, grade, hours); //checking the semester and adding up the grade points and credit hours if(time == semester) { if(grade == 'A') gradePoints = gradePoints + (hours * 4.0); else if(grade == 'B') gradePoints = gradePoints + (hours * 3.0); else if(grade == 'C') gradePoints = gradePoints + (hours * 2.0); else if(grade == 'D') gradePoints = gradePoints + (hours * 1.0); else if(grade == 'F') gradePoints = gradePoints + (hours * 0.0); if(grade != 'W' && grade != 'I') totalHours = totalHours + hours; } } double gpaEquation = 0; //calculating the GPA if(totalHours == 0) cout << " You cannot divide by 0." << endl; else gpaEquation = gradePoints / totalHours; //if statements to output the GPA if ( gpaEquation >= 3.0) cout << "Excellent! Your GPA is " << gpaEquation << endl; else if ( gpaEquation > 2.5) cout << "Not bad, but you could work harder. Your GPA is " << gpaEquation << endl; else if (gpaEquation >= 2.0) cout << "Put a bit more effort into it. Your GPA is " << gpaEquation << endl; else if (gpaEquation >= 0.0) cout << "That's terrible! Do you even go to class? Your GPA is " << gpaEquation << endl; return gpaEquation; } //function to sum the credit hours with letter grade D int DRule(int n, Course courses[]) { int totalHours = 0; string name, time, number; char grade; int hours; //loop to sum the hours for(int index = 0; index < n; index++) { courses[index].get(name, time, number, grade, hours); if(grade == 'D') totalHours += hours; } cout << "The total credit hours with the letter grade D is: " << totalHours << endl; return totalHours; } //function to print the courses void print(int n, Course courses[]) { cout << n << endl; //loop to output each input for(int index = 0; index < n; index++) { //printing the class courses[index].print(); } } //function to read in a course void getCourse(int n, Course& courses) { string name, time, number; char grade; int hour; //Command to enter course name cout << "Enter course name for class " << n << endl; getline (cin, name); getline (cin, name); //Command to enter course semester cout << "Enter the semester for the course " << n << endl; getline (cin, time); //Command to enter course number cout << "Enter course number for class " << n << endl; getline (cin, number); //Command to enter the letter grade cout << "Input letter grade(A, B, C, D, F, I, or W) of class " << n <<endl; cin >> grade; //Loop to check if the user input a valid letter while (grade != 'A' && grade != 'B' && grade != 'C' && grade != 'D' && grade != 'F' && grade != 'W' && grade != 'I') { cout << "You did not input a valid response, please input A, B, C, D, or F." << endl; cin >> grade; } //Command to enter the credit hours cout << "Input number of credit hours " << n << endl; cin >> hour; //Loop to check if the user input a valid number of credit hours while (hour < 1 || hour > 5) { cout << "Your did not input a valid respose, please input 1, 2, 3, 4, or 5" << endl; cin >> hour; } courses.set(name, time, number, grade, hour); } //function to output the menu char menu() { char menuInput = 'w'; //menu interface cout << "\n" "Welcome to the interactive menu-driven part of the GPA and Course storage program\n" "Please enter the character next to the choice you wish to pick.\n" "Here are your options:\n" "A(a) . Compute the GPA of all courses\n" "B(b) . List all courses\n" "C(c) . Compute the total credit hours of the courses with grade D\n" "D(d) . Compute the GPA for a particular semester\n" "E(e) . Add another course to the course list\n" "F(f) . Delete a course on the course list\n" "G(g) . Print University Requirements\n" "H(h) . Preform degree audit for University Core\n" "Q(q) . Quit the program\n" "\n" "\n" "Please choose one of the above\n"; cin >> menuInput; return menuInput; } //function to delete a course void deleteCourse(int& n, Course courses[]) { int choice; cout << "Select from 1 to " << n << " for the course to be deleted" << endl; cin >> choice; //error checking to make sure the user can only select valid courses while (choice < 1 || choice > n) cout << "Please select a number from 1 to " << n << "for the course to be deleted" << endl; cout << "Course number " << choice << endl; courses[choice - 1].print(); cout << "Would you like to delete the course above?\n" "Please enter y for yes and n for no\n"; char confirm = 'x'; //confirming that the user wants to delete the course cin >> confirm; //error checking to make sure they input y or n while (confirm != 'y' && confirm != 'n') { cout << "You did not enter y or n\n" "Would you like to delete the course above?\n" "Please enter y for yes and n for no\n"; cin >> confirm; } if (confirm == 'y') { n = n - 1; //loop to delete a course for(int i = choice - 1; i < n; i++) { courses[i] = courses[i + 1]; } cout << "Here is the updated list of courses" << endl; print(n, courses); } if (confirm == 'n') cout << "You did not delete the course." << endl; } //main function int main() { const int SIZE = 200; int classes; Course courses[SIZE]; string filename; bool fileTest; char fileChoice; int capacity = SIZE; Requirement requirements[SIZE]; Requirement universityRequirements[SIZE]; int numRequirements = 0; int numUniversityRequirements = 0; //whether the user wants to input their own file or not cout << "Would you like to use the default file to get the requirements?\n" "Please enter y for yes and n for no\n"; cin >> fileChoice; //error checking to make sure the user inputs a y or n while (fileChoice != 'y' && fileChoice != 'n') { cout << "You did not enter a y or n\n" "Would you like to use the default file\n" "Please enter y for yes and n for no\n"; cin >> fileChoice; } if (fileChoice == 'y') { filename = "requirements.txt"; fileTest = readingRequirements(filename.c_str(), requirements, capacity, numRequirements); //stops the program if the file does not open if (fileTest == false) { cout << "Terminating program" << endl; return 1; } } else if (fileChoice == 'n') { cout << "Enter the file name" << endl; cin >> filename; fileTest = readingRequirements(filename.c_str(), requirements, capacity, numRequirements); if (fileTest == false) { cout << "Terminating program" << endl; return 1; } } getUniversityRequirement(requirements, universityRequirements, numRequirements, numUniversityRequirements); cout << "Would you like to read courses taken from a file?\n" "Please enter y for yes and n for no\n"; cin >> fileChoice; //error checking to make sure the user inputs a y or n while (fileChoice != 'y' && fileChoice != 'n') { cout << "You did not enter a y or n\n" "Would you like to read courses taken from a file?\n" "Please enter y for yes and n for no\n"; cin >> fileChoice; } if ( fileChoice == 'y') { cout << "Would you like to use the default file\n" "Please enter y for yes and n for no\n"; cin >> fileChoice; //error checking to make sure the user inputs a y or n while (fileChoice != 'y' && fileChoice != 'n') { cout << "You did not enter a y or n\n" "Would you like to use the default file\n" "Please enter y for yes and n for no\n"; cin >> fileChoice; } if (fileChoice == 'y') { filename = "courses.txt"; fileTest = reading(filename.c_str(), courses, classes, capacity); //stops the program if the file does not open if (fileTest == false) { cout << "Terminating program" << endl; return 0; } else if (fileTest == true) { //printing out the courses print(classes, courses); } } else if (fileChoice == 'n') { cout << "Enter the file name" << endl; cin >> filename; fileTest = reading(filename.c_str(), courses, classes, capacity); if (fileTest == false) { cout << "Terminating program" << endl; return 0; } else if (fileTest == true) { print(classes, courses); } } } else if (fileChoice == 'n') { //Command to input the number of classes to calculate cout << "Input how many classes you want to calculate." << endl; cin >> classes; while(classes > SIZE || classes < 1) { cout << "You cannot input 0 or a negative number.\n" "You cannot input more than 10 classes.\n" "Please input how many classes you want to calculate.\n"; cin >> classes; } //Loop to input class information for(int i = 0; i < classes; i++) { getCourse(i + 1, courses[i]); } } char menuInput = 'w'; while(menuInput != 'Q' && menuInput != 'q') { menuInput = menu(); if( menuInput == 'A' || menuInput == 'a') gpa(classes, courses); else if(menuInput == 'B' || menuInput == 'b') print(classes, courses); else if(menuInput == 'C' || menuInput == 'c') DRule(classes, courses); else if(menuInput == 'D' || menuInput == 'd') { string semester; cout << "Please input the semester you want to calculate the GPA for." << endl; getline (cin, semester); getline (cin, semester); semesterGpa(classes, courses, semester); } else if(menuInput == 'E' || menuInput == 'e') { classes++; if(classes <= SIZE) { int index = classes - 1; getCourse(classes, courses[index]); } else { classes--; cout << "You cannot enter more than " << SIZE << " courses" << endl; } } else if(menuInput == 'F' || menuInput == 'f') { deleteCourse(classes, courses); } //printing the university requirements else if(menuInput == 'G' || menuInput == 'g') { for(int i = 0; i < numUniversityRequirements; i++) { universityRequirements[i].print(); } } //performing the degree audit else if(menuInput == 'H' || menuInput == 'h') { Course uniqueCourses[SIZE]; Course usedCourses[SIZE]; int numUsedCourses = 0; int numUniqueCourses = 0; //get a list of unique courses getUniqueCourses(courses, uniqueCourses, classes, numUniqueCourses); bool validate = true; //performing the degree audit for(int i = 0; i < numUniversityRequirements; i++) { if(universityRequirements[i].validate(uniqueCourses, usedCourses, numUsedCourses, numUniqueCourses)) { cout << "Passed requirement for "; universityRequirements[i].printSubgroup(); } else { validate = false; cout << "You did not pass the requirement for "; universityRequirements[i].printSubgroup(); } } if(validate) cout << "Congratulations, you passed all of the requirements" << endl; else cout << "You did not pass all fo the requirements" << endl; } else if(menuInput == 'Q' || menuInput == 'q') { filename = "courses.txt"; writing(filename.c_str(), courses, classes); cout << "Program shutting down." << endl; writing("checking.txt", courses, classes); } else cout << "You did not enter an A, a, B, b, C, c, D, d, E, e, F, f, Q, or q, please try again" << endl; //making sure that the user enters a valid response } return 0; }
true
fe95589835a0d5301789d170b55fe8e04fe9fef8
C++
rickbrian/Personal-learning
/通讯录管理系统/通讯录管理系统/01 通讯录管理系统.cpp
GB18030
7,333
3.953125
4
[]
no_license
#include<iostream> using namespace std; #include <string>; #define max 1000 //*ϵ˽ṹ struct person { string m_name; // int m_sex; //Ա 1 2Ů int m_age; // string m_phone; //绰 string m_addr; //ַ }; //* ͨѶ¼ṹ struct addrressboos { //ͨѶ¼бϵ struct person person_arr [max]; //ͨѶ¼еǰ¼ϵ˵ĸ int m_size; }; //ϵ void addperson(struct addrressboos *abs) { //жͨѶ¼Ƿ˾Ͳ if (abs->m_size == max) { cout << "ͨѶ¼޷" << endl; return ; } else { //Ӿϵ // string name; cout << "" << endl; cin >> name; abs->person_arr[abs->m_size].m_name = name; //Ա int sex=0; cout << "Ա" << endl; cout << "1 -- " << endl; cout << "2 -- Ů" << endl; while (true) { //һ߶˳ѭ // cin >> sex; if (sex == 1 || sex == 2) { abs->person_arr[abs->m_size].m_sex = sex; break; } cout << ",룺" << endl; } // cout << "䣺" << endl; int age = 0; cin >> age; abs->person_arr[abs->m_size].m_age = age; //绰 cout << "绰" << endl; string phone;//stringøֵ0 cin >> phone; abs->person_arr[abs->m_size].m_phone = phone; //ͥסַ cout << "ͥסַ" << endl; string address; cin >> address; abs->person_arr[abs->m_size].m_addr = address; //ͨѶ¼ abs->m_size++; cout << "ӳɹ" << endl; system("pause");//밲 system("cls"); } } //ʾеϵ void showperson(struct addrressboos *abs) { //жͨѶ¼ǷΪ00ʾ¼Ϊ if (abs->m_size == 0) { cout << "ǰ¼Ϊ" << endl; } //ѭӡ for (int i = 0; i < abs->m_size; i++) { cout << "" << abs->person_arr[i].m_name << "\t :" << (abs->person_arr[i].m_age==1?"":"Ů") << "\t Ա:" << abs->person_arr[i].m_sex << "\t 绰:" << abs->person_arr[i].m_phone << "\t ַ:" << abs->person_arr[i].m_addr << endl; } system("pause");//밲 system("cls");//Ļ } //װϵǷڣշеľλãڷ-1 int isexist(struct addrressboos *abs, string name) { for (int i = 0; i < abs->m_size; i++) { //жǷ if (abs->person_arr[i].m_name == name) { return i; } } return -1; } //3.װɾϵ˺ void deleteperson(struct addrressboos *abs) { cout << "Ҫɾϵ" << endl; string name; cin >> name; int ret = isexist(abs, name); //жǷ if (ret != -1) { //鵽ˣɾ for (int i = ret; i < abs->m_size; i++) { //Ǩ abs->person_arr[i] = abs->person_arr[i + 1]; } cout << "ɾɹ" << endl; abs->m_size--;// } else { cout << "޴" << endl; } system("pause"); system("cls"); } //4.װϵ˺ void findperson(struct addrressboos *abs) { cout << "Ҫҵϵ" << endl; string name; cin >> name; int ret = isexist(abs, name); if (ret != -1)//ҵϵ { cout << "" << abs->person_arr[ret].m_name << "\t :" << (abs->person_arr[ret].m_age == 1 ? "" : "Ů") << "\t Ա:" << abs->person_arr[ret].m_sex << "\t 绰:" << abs->person_arr[ret].m_phone << "\t ַ:" << abs->person_arr[ret].m_addr << endl; } else//δҵ { cout << "޴" << endl; } system("pause"); system("cls"); } //5\װ޸ϵ˺ void modifyperson(struct addrressboos *abs) { cout << "޸ĵϵ" << endl; string name; cin >> name; int ret = isexist(abs, name); if (ret != -1)//ҵϵ { // string name; cout << "" << endl; cin >> name; abs->person_arr[ret].m_name = name; //Ա int sex = 0; cout << "Ա" << endl; cout << "1 -- " << endl; cout << "2 -- Ů" << endl; while (true) { //һ߶˳ѭ // cin >> sex; if (sex == 1 || sex == 2) { abs->person_arr[ret].m_sex = sex; break; } cout << ",룺" << endl; } // cout << "䣺" << endl; int age = 0; cin >> age; abs->person_arr[ret].m_age = age; //绰 cout << "绰" << endl; string phone;//stringøֵ0 cin >> phone; abs->person_arr[ret].m_phone = phone; //ͥסַ cout << "ͥסַ" << endl; string address; cin >> address; abs->person_arr[ret].m_addr = address; //ͨѶ¼ cout << "޸ijɹ" << endl; } else//δҵ { cout << "޴" << endl; } system("pause"); system("cls"); } //6.װϵ˺ void cleanperson(struct addrressboos *abs) { cout << "кܶϵˣǷȷȫ" << endl; cout << "1.ǣȫ" << endl; cout << "2.ˣ˳" << endl; cout << "֣" << endl; while (true) { int cin_on; cin >> cin_on; if (cin_on == 1) { abs->m_size = 0; cout << "ͨѶ¼" << endl; break; } else if (cin_on == 2) { break; } else { cout << "" << endl;; cout << "룺"; } } system("pause"); system("cls"); } //װʾý `void showMenu()` //mainе÷װõĺ //˵溯 void showmenu() { cout << "*****************************"<< endl; cout << "***** 1ϵ *****" << endl; cout << "***** 2ʾϵ *****" << endl; cout << "***** 3ɾϵ *****" << endl; cout << "***** 4ϵ *****" << endl; cout << "***** 5޸ϵ *****" << endl; cout << "***** 6ϵ *****" << endl; cout << "***** 0˳ϵ *****" << endl; cout << "*****************************" << endl<<endl; cout << "ֽѡ" << endl; } int main() { //ͨѶ¼ṹ struct addrressboos abs; //ʼǰԱĸ abs.m_size = 0; int select = 0; //ûı while (true) { showmenu(); //ò˵溯 cin >> select; switch (select) { case 1: //1ϵ addperson(&abs); // õַݿʵ break; case 2: //2ʾϵ showperson(&abs); // break; case 3: //3ɾϵ deleteperson(&abs); break; case 4: //4ϵ findperson(&abs); break; case 5: //5޸ϵ modifyperson(&abs); break; case 6: //6ϵ cleanperson(&abs); break; case 0: cout << "ӭ´ʹ" << endl; system("pause"); //ͣ return 0; //˳main break;//0˳ϵ default:break; } } system("pause"); return 0; }
true
ed98437a0e478de7272e7ffde5edba71f19a2450
C++
yao-yl/stan
/src/stan/lang/generator/generate_bare_type.hpp
UTF-8
1,869
3.140625
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "GPL-3.0-only" ]
permissive
#ifndef STAN_LANG_GENERATOR_GENERATE_BARE_TYPE_HPP #define STAN_LANG_GENERATOR_GENERATE_BARE_TYPE_HPP #include <stan/lang/ast.hpp> #include <ostream> #include <string> namespace stan { namespace lang { /** * Generate the basic type for the specified expression type * without dimensions, using the specified scalar type string, * writing to the specified stream. * * @param[in] t expression type * @param[in] scalar_t_name name of scalar type for double values * and containers * @param[in] o stream for generating */ void generate_bare_type(const expr_type& t, const std::string& scalar_t_name, std::ostream& o) { for (size_t d = 0; d < t.num_dims_; ++d) o << "std::vector<"; bool is_template_type = false; if (t.base_type_.is_int_type()) { o << "int"; is_template_type = false; } else if (t.base_type_.is_double_type()) { o << scalar_t_name; is_template_type = false; } else if (t.base_type_.is_vector_type()) { o << "Eigen::Matrix<" << scalar_t_name << ", Eigen::Dynamic,1>"; is_template_type = true; } else if (t.base_type_.is_row_vector_type()) { o << "Eigen::Matrix<" << scalar_t_name << ", 1,Eigen::Dynamic>"; is_template_type = true; } else if (t.base_type_.is_matrix_type()) { o << "Eigen::Matrix<" << scalar_t_name << ", Eigen::Dynamic,Eigen::Dynamic>"; is_template_type = true; } else if (t.base_type_.is_void_type()) { o << "void"; } else { o << "UNKNOWN TYPE"; } for (size_t d = 0; d < t.num_dims_; ++d) { if (d > 0 || is_template_type) o << " "; o << ">"; } } } } #endif
true
97382948dd7be418b145966b736daf711aa079db
C++
luckhoi56/girsLabBackEndEngine
/src/core/ParamArray.cpp
UTF-8
16,730
2.546875
3
[]
no_license
// $Id: ParamArray.cpp 2240 2014-02-23 02:14:31Z Dongfeng Zhu $ #include "ParamArray.h" #include "NormalDensityOperator.h" #include "BRASSError.h" #include "SliceSamplerAids.h" #include "NetCorrelation.h" #include <math.h> /** * Constructor. * @param len number of variables. */ ParamArray::ParamArray(const int len) { this->len = len; operators = new NetOperatorPtr[len]; models = new NetModelRefPtr[len]; correlations = new NetCorrelationPtr[len]; params = new float[len]; ranges = new short[len]; sampler_aids = new SliceSamplerAid * [len]; for (int index = 0 ; index < len ; index++) { operators[index] = 0; models[index] = 0; params[index] = 1; ranges[index] = RANGE_UNDEFINED; sampler_aids[index] = 0; correlations[index] = 0; } } /** * Deletes the array and all linked operator objects. */ ParamArray::~ParamArray(void) { for (int index = 0 ; index < len ; index++) { delete operators[index]; delete models[index]; delete sampler_aids[index]; delete correlations[index]; } delete [] params; delete [] operators; delete [] models; delete [] sampler_aids; delete [] correlations; } /** * Associate a copy of the operator with the specified parameter. * Ownership of the operator that is passed in is NOT assumed. * @param index parameter index * @param op operator */ void ParamArray::addOperator(const int index, const NetOperator & op) { operators[index] = op.copy()->link(operators[index]); } /** * Marks the variables as correlated. * i1 must be smaller than i2. */ void ParamArray::addCorrelation(const int i1, const int i2) { NetCorrelationPtr c = new NetCorrelation(); c->setTarget(i2); c->setNext(correlations[i1]); correlations[i1] = c; } /** * Associate a copy of the operator with all applicable parameters. * If the operator determines the value of a variable based on the * values of others, the variable will be marked as RANGE_DEPENDENT. * * This method checks for conflicts, which could occur if * the value of a variable is overdefined, i.e., when multiple operators * want to decide on the value of the variable. The method returns false * if a conflict is detected. The method retunrs true if the operator * was succesfully added without a conflict. * * @param op operator */ bool ParamArray::addOperator(const NetOperator & op) { bool conflict = false; for (int index = 0 ; index < len ; index++) { if (op.appliesTo(index)) { operators[index] = op.copy()->link(operators[index]); } } return !conflict; } /** * Adds a new deterministic model to the network. * The models are used to create deterministic relationships * between the variables in the model. * The method creates a copy of the model, and will not * maintain references to the model that is passed in. */ bool ParamArray::addModel(NetModel & md) { NetModelPtr model = md.copy(); for (int i = 0 ; i < len ; i++) { if (model->appliesTo(i)) { NetModelRefPtr ref = new NetModelRef(); ref->setNext(models[i]); ref->setModel(model); models[i] = ref; } } return true; } /** * Sets the sampler aid for the specified variable. * If an aid was previously specified, the old aid is destructed. */ void ParamArray::setAid(const int index, SliceSamplerAid * aid) { delete sampler_aids[index]; sampler_aids[index] = aid; if (aid != 0) setRange(index,RANGE_VARIABLE); else setRange(index,RANGE_UNDEFINED); } /** * Computes the (unnormalized) full conditional density function. * * The function returns the unnormalized full conditional density for * the variable specified by index. * * First, the list of linked (deterministic) models is traversed to * update the values of dependent variables. Then, the density function * is computed by iterating through the list of density operators for * the variable. * * @param index variable index. */ double ParamArray::getLnDensity(const int index) { double ln_like = 0; double ln_total = 0; int next_var = -1; // update the dependent variables ln_total = updateLinks(index); // iterate through the density operators NetOperatorPtr op = operators[index]; while (op != 0) { ln_like = op->compute(params,0); ln_total += ln_like; op = op->getNext(); } return ln_total; } /** * Sets the value of the specified variable. * This function has no impact on linked or correlated variables. */ void ParamArray::setParam(const int index, const float value) { params[index] = value; } /** * Sets the value of the specified variable. * This function also moves linked or correlated variables. */ void ParamArray::updateParam(const int index, const float value) { float distance = value - params[index]; params[index] = value; updateCorrelated(index,distance); updateLinks(index); } /** * Updates the value of the correlated variables. * * This causes any free variable marked as correlated to be * translated by the specified distance. In addition, links to any * translated variable will also be updated. */ void ParamArray::updateCorrelated(const int index, const float distance) { NetCorrelationPtr c = correlations[index]; while (c != 0) { int t = c->getTarget(); if (ranges[t] == this->RANGE_VARIABLE) { // Only update the value of the variable if the type is // RANGE_VARIABLE; for other types, the value should be // calculated instead of updated by this function. params[t] += distance; updateLinks(t); } c = c->getNext(); } } /** * Recursively updates the values in the array. * This method updates the values in the model according to the * deterministic models during the analysis. * * @param index index of the variable that was last changed * * @return double 0 */ double ParamArray::updateLinks(const int index) { int next_var; NetModelRef * md = models[index]; while (md != 0) { md->getModel()->update(params,next_var); md = md->getNext(); } return 0; } /** * Explores the model links to build a list of relevant operators. * * This function builds a list of operators associated with all * variables that are directly or indirectly affected by the * variable with the specified index. * * This function relies on the fact that the model link lists have * been reduced, and thus that all affected variables can be found * simply by traversing through the model linked list. * * The implementation is fairly simple, and requires more computations * than absolutely necessary, but should still be fast enough. */ void ParamArray::exploreLinks(const int index) { NetOperatorPtr ops_lst = operators[index]; // loop through all model links in the list NetModelRef * md = models[index]; while (md != 0) { int next_var; // determine the next affected/dependent variable next_var = md->getModel()->getSpecified(); // loop through all the operators for the dependent variable NetOperatorPtr var_ops = this->operators[next_var]; while (var_ops != 0) { if (!ops_lst->contains(var_ops)) { // add a copy of varops to the list ops_lst = var_ops->copy()->link(ops_lst); } var_ops = var_ops->getNext(); } // move to next model link in the list md = md->getNext(); } operators[index] = ops_lst; } /** * Absorbs any operators related to correlated variables. * * This function causes operators for variables correlated to the * specified variable to be absorbed. This is necessary when * the correlation causes the other variables to be moved along * with the specified variable. */ void ParamArray::exploreCorrelated(const int index) { NetOperatorPtr ops_lst = operators[index]; NetCorrelationPtr c = correlations[index]; while (c != 0) { int t = c->getTarget(); if (this->ranges[t] == RANGE_VARIABLE) { NetOperatorPtr var_ops = this->operators[t]; while (var_ops != 0) { if (!ops_lst->contains(var_ops)) { // add a copy of varops to the list ops_lst = var_ops->copy()->link(ops_lst); } var_ops = var_ops->getNext(); } } c = c->getNext(); } operators[index] = ops_lst; } /** * Recursively initializes the sampling order in the model. * The purpose of this method is to set up the sampling order, * and the direction in which deterministic model links are * evaluated. * * The code returns an error code ERR_LOOP_IN_MODEL when a loop * is detected in the model. In this case, the links will not be * initialized correctly. */ int ParamArray::initLinks(const int index) { int next_var; int retval = 0; // recursively call initLinks for models associated with current variable // NetOperatorPtr op_copy = 0; NetModelRef * md = models[index]; while (md != 0 && retval == 0) { next_var = md->getModel()->init(index); if (next_var != -1) { int cur_range = getRange(next_var); if ((cur_range != RANGE_VARIABLE) && (cur_range != RANGE_FIXED)) { retval = BRASSError::ERR_LOOP_IN_MODEL; } else { if (cur_range != RANGE_FIXED) { short range = getRange(index); // temporarily modify range to allow loop detection setRange(index,RANGE_DEPENDENT); setRange(next_var,RANGE_DEPENDENT); retval = initLinks(next_var); // restore original range parameter setRange(index,range); } } } md = md->getNext(); } return retval; } /** * Creates a reduced list of model links. * * This method first ensures that a 'reduced' list of model links is * available for the specified variable. The list is a list of model links * that are directly or indirectly affected by changes to the specified * variable. After the list is compiled, a simple traversal of the list * updates all variables. * * @param index variable index. * @param reduced_nodes array indicating which nodes were already reduced. */ void ParamArray::reduceLinks(const int index, bool * reduced_vars) { if (!reduced_vars[index]) { // the model links for this node were not reduced: // explore the model links to build a single list // of model references that ensure that each variable // is updated only once. NetModelRefPtr ref = models[index]; // unreduced model refs NetModelRefPtr lst = 0; // list of reduced model refs while (ref != 0) { // decouple from the list NetModelRefPtr nxt = ref->getNext(); ref->setNext(0); int var = ref->getModel()->getSpecified(); if (var == index) { // self reference: delete delete ref; } else { // recursively reduce the dependent variables reduceLinks(var,reduced_vars); // attach the model links list of dependent variables // to the current reference. if (models[var] != 0) { ref->setNext(models[var]->copy()); } // merge with the main list of reduced nodes NetModelRefPtr ref_iterator = ref; NetModelRefPtr acc_iterator = 0; // last accepted while (ref_iterator != 0) { if (!lst->contains(ref_iterator->getModel())) { // ref was not found: accept by moving acc_iterator acc_iterator = ref_iterator; // continue with next reference in the list ref_iterator = ref_iterator->getNext(); } else { // stop the loop: all further references rejected // note that rejection implies that all subsequent // references would also be rejected. ref_iterator = 0; } } if (acc_iterator != 0) { // delete rejected references delete acc_iterator->getNext(); // append prior list to accepted list acc_iterator->setNext(lst); lst = ref; } else { // list was fully rejected delete ref; } } // move to the next reference in the original list ref = nxt; } // store the reduced list models[index] = lst; reduced_vars[index] = true; } } /** * Initializes the model. * * This method should be called just before sampling starts, in order to * make the correct sampling order, and reduce the model to the extent * possible. * * <b>Explanation of initialization:</b> * * The initialization first sets the sampling * order, and determines which variables should be marked as dependent * (meaning that their value is dependent on the value of other variables in * the model). This is done by traversing the model links. A list of such links * is maintained for each variable in the models member. For each link, the * direction in which each link is evaluated is determined during this traversal. * * Secondly, unnecessary links are removed from the model. Links are unnecessary * when they point to the same variable from which the link starts (due to the * direction of the link this is possible). * * Thirdly, a list of density operators (NetOperator) is built for each non- * dependent variable, by repeatedly traversing the network (following the * links) according to the link directions determined earlier, and to create * copies of all operators encountered. Note that each variable encountered * during the traversal is dependent on the starting variable. A first list * is created using exploreLinks(). The list is then reduced to remove * duplicates. The heads of the (single-linked) lists of operators are stored * in the operators array. * * Finally, the operator lists for dependent variables are removed and destroyed. * * The code returns an error code if the resulting model is not valid. * @see #validate() */ int ParamArray::initialize(void) { // initialize the link directions / sampling order for (int i = 0 ; i < len ; i++) { if (this->ranges[i] != RANGE_DEPENDENT) { // init the model/links int retval = initLinks(i); // abort in case of invalid link structure if (retval != 0) return retval; } } bool * reduced_vars = new bool[len]; for (int i = 0 ; i < len ; i++) reduced_vars[i] = false; // build model link lists for each variable. for (int i = 0 ; i < len ; i++) { reduceLinks(i,reduced_vars); } delete [] reduced_vars; // construct operator lists for non-dependent variables for (int i = 0 ; i < len ; i++) { if (ranges[i] != RANGE_DEPENDENT && ranges[i] != RANGE_FIXED ) { exploreLinks(i); } } for (int i = 0 ; i < len ; i++) { if (ranges[i] != RANGE_DEPENDENT && ranges[i] != RANGE_FIXED ) { exploreCorrelated(i); } } // clean up operators associated with dependent variables for (int i = 0 ; i < len ; i++) { if (ranges[i] == RANGE_DEPENDENT || ranges[i] == RANGE_FIXED) { delete operators[i]; operators[i] = 0; } } // validate the model int retval = validate(); return retval; } /** * Dumps a summary of the array to cout. * Use for debugging purposes only. */ void ParamArray::dumpSummary(void) { cout << "VARIABLES : " << this->len << endl; for (int i = 0 ; i < len ; i++) { cout << i << " (" << ranges[i] << ") "; NetOperatorPtr op = operators[i]; while (op != 0) { cout << op->getOperatorID() << " ("; // cout << typeid(*op).name() << ") "; op = op->getNext(); } cout << endl; } cout << "DEPENDENCIES" << endl; for (int i = 0 ; i < len ; i++) { cout << i << " (" << ranges[i] << ") "; NetModelRefPtr ref = models[i]; while (ref != 0) { cout << *(ref->getModel()) << " "; ref = ref->getNext(); } cout << endl; } } /** * Stream operator for parameter arrays. */ ostream & operator<<(ostream & os, const ParamArray & a) { int cnt = a.size(); for (int i = 0 ; i < cnt ; i++) { os << a.getParam(i) << "\t"; } return os; } /** * Validates the model. * Simple implementation that checks: * - some density operator is defined for all free variables * - no cycles are contained in the model. * The validation is executed as part of the initialization of * the model. */ int ParamArray::validate(void) { // check all free variables have a density model for (int i = 0 ; i < this->len ; i++) { if (this->ranges[i] != this->RANGE_DEPENDENT && this->ranges[i] != this->RANGE_FIXED) { // no density model for free variable if (this->operators[i] == 0 /* || !this->operators[i]->isDensity(i) */ ) { return BRASSError::ERR_NO_OPERATOR; } } } return 0; }
true
eea03731cfe1c29133905a88db1279eecac5a040
C++
GWBryant/CSC310-FileStructures
/quiz1/char.cpp
UTF-8
223
2.9375
3
[]
no_license
#include <iostream> using namespace std; struct student { char gender; int age; char name[20]; }; int main() { student s; int i = 0; char c = 'a'; char cs[20]; cout << sizeof(s) << endl; }
true
ebb4acd4fc2318f21c9b855ec7b42cc4a1b36107
C++
kevinsunguchoi/monstrous-mosaics
/mp_mosaics/kdtree.hpp
UTF-8
6,675
3.59375
4
[]
no_license
/** * @file kdtree.cpp * Implementation of KDTree class. */ #include <utility> #include <algorithm> using namespace std; template <int Dim> bool KDTree<Dim>::smallerDimVal(const Point<Dim>& first, const Point<Dim>& second, int curDim) const { /** * @todo Implement this function! */ if(first[curDim] < second[curDim]){ return true; } else if(first[curDim] > second[curDim]){ return false; } return first < second; } template <int Dim> bool KDTree<Dim>::shouldReplace(const Point<Dim>& target, const Point<Dim>& currentBest, const Point<Dim>& potential) const { /** * @todo Implement this function! */ double euclidPtoT = 0.0; double euclidPtoC = 0.0; for(int i = 0; i < Dim; i++){ euclidPtoT += (target[i] - potential[i])*(target[i] - potential[i]); euclidPtoC += (target[i]-currentBest[i])*(target[i]-currentBest[i]); } if(euclidPtoT < euclidPtoC){ return true; } else if(euclidPtoT > euclidPtoC){ return false; } return potential < currentBest; } template <int Dim> KDTree<Dim>::KDTree(const vector<Point<Dim>>& newPoints) { /** * @todo Implement this function! */ size = 0; if(newPoints.empty()){ //check empty case root = NULL; } else { int dimension = 0; vector<Point<Dim>> tempPoints; //copy into new vector so we can edit the values for (unsigned long i = 0; i < newPoints.size(); i++) { tempPoints.push_back(newPoints[i]); } root = split(tempPoints, 0, tempPoints.size() - 1, dimension); } } template <int Dim> typename KDTree<Dim>::KDTreeNode* KDTree<Dim>::split(vector<Point<Dim>>& newPoints, int left, int right, int dimension){ if(left > right){ return NULL; } int medianIndex = (left + right)/2; Point<Dim> median = select(newPoints, left, right, medianIndex, dimension); KDTreeNode* subRoot = new KDTreeNode(median); size += 1; subRoot->left = split(newPoints, left, medianIndex - 1, (dimension + 1) % Dim); subRoot->right = split(newPoints, medianIndex + 1, right, (dimension + 1) % Dim); return subRoot; } template <int Dim> int KDTree<Dim>::partition(vector<Point<Dim>>& newPoints, int left, int right, int pivotIndex, int dimension){ Point<Dim> pivotValue = newPoints[pivotIndex]; swap(newPoints, pivotIndex, right); int storeIndex = left; for(int i = left; i < right; i++){ if(smallerDimVal(newPoints[i], pivotValue, dimension)){ swap(newPoints, storeIndex, i); storeIndex++; } } swap(newPoints, right, storeIndex); return storeIndex; } template <int Dim> void KDTree<Dim>::swap(vector<Point<Dim>>& newPoints, int leftswap, int rightswap){ Point<Dim> c = newPoints[leftswap]; newPoints[leftswap] = newPoints[rightswap]; newPoints[rightswap] = c; } template <int Dim> Point<Dim> KDTree<Dim>::select(vector<Point<Dim>>& newPoints, int left, int right, int k, int dimension){ if(left == right){ return newPoints[left]; } int pivotIndex = (left + right)/2; pivotIndex = partition(newPoints, left, right, pivotIndex, dimension); if(k == pivotIndex) { return newPoints[k]; } else if(k < pivotIndex){ return select(newPoints, left, pivotIndex - 1, k, dimension); } else{ return select(newPoints, pivotIndex + 1, right, k, dimension); } } template <int Dim> KDTree<Dim>::KDTree(const KDTree<Dim>& other) { /** * @todo Implement this function! */ copy_(root, other->root); size = other.size; } template <int Dim> void KDTree<Dim>::copy_(KDTreeNode*& curr, KDTreeNode*& other){ if(other == NULL){ return; } curr = new KDTreeNode(other->print); copy_(curr->left, other->left); copy_(curr->right, other->right); } template <int Dim> const KDTree<Dim>& KDTree<Dim>::operator=(const KDTree<Dim>& rhs) { /** * @todo Implement this function! */ delete(root); copy_(root, rhs->root); size = rhs.size; return *this; } template <int Dim> KDTree<Dim>::~KDTree() { /** * @todo Implement this function! */ delete(root); } template <int Dim> void KDTree<Dim>::delete_(KDTreeNode*& subroot){ if(subroot == NULL){ return; } if(subroot->left){ delete_(subroot->left); } if(subroot->right){ delete_(subroot->right); } delete subroot; subroot = NULL; } template <int Dim> Point<Dim> KDTree<Dim>::findNearestNeighbor(const Point<Dim>& query) const { /** * @todo Implement this function! */ //variables needed return findNearestNeighbor_(query, root, 0); } template <int Dim> //helper function for findNearestNeighbor Point<Dim> KDTree<Dim>::findNearestNeighbor_(const Point<Dim>&query, KDTreeNode* subRoot, int dimension) const{ //recursive depth first search to find the leaf node with the same splitting plane as the target bool flag; Point<Dim> currentBest = subRoot->point; if(subRoot->left == NULL & subRoot->right == NULL){ //base case return subRoot->point; } //if less, traverse left if(smallerDimVal(query, subRoot->point, dimension)){ if (subRoot->left == NULL) { currentBest = findNearestNeighbor_(query, subRoot->right, (dimension + 1) % Dim); } if (subRoot->left != NULL) { currentBest = findNearestNeighbor_(query, subRoot->left, (dimension + 1) % Dim); } flag = true; } else { if (subRoot->right == NULL) { currentBest = findNearestNeighbor_(query, subRoot->left, (dimension + 1) % Dim); } if (subRoot->right != NULL) { currentBest = findNearestNeighbor_(query, subRoot->right, (dimension + 1) % Dim); } flag = false; } if(shouldReplace(query, currentBest, subRoot->point)){ currentBest = subRoot->point; } //calculate radius double radius = 0; for(int i = 0; i < Dim; i++){ radius += (currentBest[i] - query[i])*(currentBest[i] - query[i]); } double distance = (subRoot->point[dimension] - query[dimension])*(subRoot->point[dimension] - query[dimension]); if(radius >= distance) { if (flag == true && subRoot->right != NULL) { Point<Dim> pointCheck = findNearestNeighbor_(query, subRoot->right, (dimension + 1) % Dim); if (shouldReplace(query, currentBest, pointCheck)) { currentBest = pointCheck; } } else if (flag == false && subRoot->left != NULL) { Point<Dim> pointCheck = findNearestNeighbor_(query, subRoot->left, (dimension + 1) % Dim); if (shouldReplace(query, currentBest, pointCheck)) { currentBest = pointCheck; } } } return currentBest; }
true
29c0ef0345657b3f345043958c70aab96aa6c3b4
C++
Darkknight1299/C-plus-plus
/Misc/AdjacentListGraph.cpp
UTF-8
913
3.140625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; class Graph{ int V; //Array of lists(containg key and nodes) list<int> *l; public: Graph(int V){ this->V=V; l = new list<int>[V]; } void AddEdge(int x,int y){ l[x].push_back(y); l[y].push_back(x); } void PrintAdjList(){ //Itterate Overall Vertices for(int i=0;i<V;i++){ cout<<"Vertex "<<i<<"->"; for(int nbr:l[i]){ cout<<nbr<<","; } cout<<endl; } } }; int main () { #ifndef ONLINE_JUDGE // for getting input from input.txt freopen("input.txt", "r", stdin); // for writing output to output.txt freopen("output.txt", "w", stdout); #endif Graph g(4); g.AddEdge(0,1); g.AddEdge(0,2); g.AddEdge(2,3); g.AddEdge(1,2); g.PrintAdjList(); }
true
d53b2750ae630bc3a4a515b4cc7c9317fec9f84f
C++
IluckyI/01---bank
/projectEND/user.cpp
GB18030
4,062
2.515625
3
[]
no_license
#include<cstdio> #include"user.h" #define _CRT_SECURE_NO_WARNINGS void outputRecord(UserPtr user) //ûʾԼ˻Ϣ⣩ { printf("\t\t\t\t%-6s %-16s%10s %-3s\n", "acctnum", "name", "balance","password"); printf("\t\t\t\t%-6d %-16s%10.2lf %-3d\n", user->acctNum, user->name, user->balance,user->password); } //void userUpdateRecord(FILE*file, UserPtr user)// û޸ //{ // getchar(); // char a = 0; // printf("\t\t\t\t change your password?(Y/N):"); // scanf("%c", &a); // if (a == 'N' || a == 'n') // return; // int Newinfo; // printf("\t\t\t\t Please input New password:"); // scanf("%d", &Newinfo); // //data.balance += transaction; // user->password = Newinfo; // printf("\t\t\t\t your New password is %d\n", user->password); // fseek(file, -sizeof(UserData), SEEK_CUR); // fwrite(user, sizeof(UserData), 1, file); // ss_clients[index].balance = user->password);//ݻ // fseek(cfPtr, // index * sizeof(UserData), // SEEK_SET); // fwrite(&ss_clients[index], sizeof(UserData), 1, // cfPtr);//ļ // //// updateData(UPDATE, user);// //} int enterUserAcc(void) //˻ { int accnum; printf("\t\t\tPlease input your accNum:"); scanf("%d", &accnum); return accnum; } char enterUser(void) //ûѡ { char menuChoice[100]; printf( "\t\t ***************************\n" "\t\t * Enter your choice *\n" "\t\t * 1 - save information *\n" "\t\t * 2 - update password *\n" "\t\t * 3 - output information *\n" "\t\t * 4 - find acctnum info *\n" "\t\t * 5 - end program? *\n" "\t\t ***************************\n"); printf("\t\t\t---------------------------------------------------\n"); printf("\t\t\t your choice:"); scanf("%s", menuChoice); if (strlen(menuChoice) == 1) return menuChoice[0]; else { printf("\t\t\t\t error!!!\n"); return '0'; } //return menuChoice; } void Userchoice(UserData client[100]) //û { ufPtr = fopen(FILE_PATH, "r+");//ӦΪr+ UserPtr user = (UserPtr)malloc(sizeof(UserData)); int acc = 0; acc = enterUserAcc(); int i = 0; fseek(ufPtr, 0, SEEK_SET); while (!feof(ufPtr)) { size_t ret = fread(user, sizeof(UserData), 1, ufPtr); if (ret != 1) { break; } //fread(user, sizeof(UserData), 1, ufPtr); if (acc == user->acctNum) { break; } fseek(ufPtr, i * sizeof(UserData), SEEK_SET); i++; } if (feof(ufPtr)) { printf("\t\t\t Don't have this account!\n"); return; } printf("\n"); int index = recordIndex(acc); int password; //= enterPassword(); int j; for (j = 0; j < 3; j++) { password = enterPassword(); if (password == client[index].password) break; printf("\t\t\t this password is error!\n"); printf("\t\t\t---------------------------------------------------\n"); } if (j == 3) { printf("\t\t\t input three error password!\n"); printf("\t\t\t---------------------------------------------------\n"); return; } printf("\t\t\t---------------------------------------------------\n"); FILE *file = ufPtr; char choice; while ((choice = enterUser()) != USEREXIT) { for (; choice == '\n';) { choice = getchar(); if (choice == USEREXIT) return; } switch (choice) { case USERWRITE: //textFile(ufPtr); printf("\t\t\t---------------------------------------------------\n"); break; case USERUPDATE: userUpdateRecord(ufPtr, user); printf("\t\t\t---------------------------------------------------\n"); break; case USEROUTPUT: outputRecord(user); printf("\t\t\t---------------------------------------------------\n"); break; case USERFIND: int acctnum = 0; printf("\t\t\t\tPlease input you find acctnum:"); scanf("%d", &acctnum); findRecord(file, acctnum); printf("\t\t\t---------------------------------------------------\n"); break; } //getchar(); } free(user); }
true
4c2b3465eae7a82197bbc9d0d4882bedc26b512e
C++
turi-code/GraphLab-Create-SDK
/graphlab/util/lru.hpp
UTF-8
3,781
2.921875
3
[ "BSD-3-Clause" ]
permissive
/** * Copyright (C) 2016 Turi * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #include <utility> #include <boost/multi_index_container.hpp> #include <boost/multi_index/tag.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/sequenced_index.hpp> namespace graphlab { /** * A simple general purpose LRU cache implementation. */ template <typename Key, typename Value> struct lru_cache { typedef std::pair<Key, Value> value_type; typedef boost::multi_index_container <value_type, boost::multi_index::indexed_by < boost::multi_index::hashed_unique<BOOST_MULTI_INDEX_MEMBER(value_type, Key, first)>, boost::multi_index::sequenced<> > > cache_type; typedef typename cache_type::template nth_index<1>::type::iterator iterator; typedef iterator const_iterator; lru_cache() = default; lru_cache(const lru_cache&) = default; lru_cache(lru_cache&&) = default; lru_cache& operator=(const lru_cache&) = default; lru_cache& operator=(lru_cache&&) = default; /** * queries for a particular key. If it does not exist {false, Value()} is * returned. If it exists {true, value} is returned and the key is bumped * to the front of the cache. */ std::pair<bool, Value> query(const Key& key) { auto& hash_container = m_cache.template get<0>(); auto& seq_container = m_cache.template get<1>(); auto iter = hash_container.find(key); if (iter == hash_container.end()) { ++m_misses; return {false, Value()}; } else { ++m_hits; seq_container.relocate(seq_container.begin(), m_cache.template project<1>(iter)); return {true, iter->second}; } } /** * Inserts a key into the cache. If the key already exists, it is overwritten. * If the size of the cache is larger than the limit, the least recently * used items are erased. */ void insert(const Key& key, const Value& value) { auto& hash_container = m_cache.template get<0>(); auto& seq_container = m_cache.template get<1>(); auto iter = hash_container.find(key); if (iter == hash_container.end()) { seq_container.push_front(value_type{key, value}); if (size() > get_size_limit()) { seq_container.pop_back(); } } else { hash_container.replace(iter, value_type{key, value}); seq_container.relocate(seq_container.begin(), m_cache.template project<1>(iter)); } } void erase(const Key& key) { auto& hash_container = m_cache.template get<0>(); auto iter = hash_container.find(key); if (iter != hash_container.end()) { hash_container.erase(iter); } } /** * Retuns an iterator to the data */ const_iterator begin() const { auto& seq_container = m_cache.template get<1>(); return seq_container.begin(); } /** * Retuns an iterator to the data */ const_iterator end() const { auto& seq_container = m_cache.template get<1>(); return seq_container.end(); } /// Returns the current size of the cache size_t size() const { return m_cache.size(); } /// Sets the upper limit on the size of the cache void set_size_limit(size_t limit) { m_limit = limit; } /// Gets the upper limit of the size of the cache size_t get_size_limit() const { return m_limit; } /// Returns the number of query hits size_t hits() const { return m_hits; } /// Returns the number of query misses size_t misses() const { return m_misses; } private: cache_type m_cache; size_t m_limit = (size_t)(-1); size_t m_hits = 0; size_t m_misses = 0; }; } // namespace graphlab
true
79b5d677b359fdfac6b157daf2cd6d295d317b9a
C++
sdaingade/cpplabs
/TemplateMethodSol/shape.h
UTF-8
809
2.78125
3
[]
no_license
#ifndef SHAPE_H #define SHAPE_H /************************************************************** * * File: shape.h * * Description: Class Shape is defined in this class. * * Author: SciSpike * * Modification History: * ***************************************************************/ /* Include Files */ /* Pre-Declarations */ /* Constants and defines */ /**************************************************************** * * Description: The Shape class which represents drawable objects * in a graphical editor like Rectangle, Circle, etc. * * Exceptions: None * ***************************************************************/ class Shape { public: virtual void paint() = 0; virtual void printLocation() = 0; virtual void print() = 0; }; #endif // SHAPE_H
true
0b0847cdcbcdaed01dcc5fe5ab46fe877d2ad5b5
C++
git-patrick/math
/include/box.h
UTF-8
5,934
2.953125
3
[]
no_license
// // box.h // math // // Created by Patrick Sauter on 3/21/14. // Copyright (c) 2014 Patrick Sauter. All rights reserved. // #ifndef math_box_h #define math_box_h #include <limits> #include <utility> #include <numeric> #include <functional> #include "vector.h" namespace math { template <typename Vector> class box_divider; template <typename Vector> class box { public: typedef Vector vector_type; typedef box_divider<box> divide_type; box() = default; box(box const &) = default; box(box &&) = default; ~box() = default; box(vector_type const & x, vector_type const & y) : _a(x), _b(y) { } // when casting the box to a vector, we just return our center (or close to if integral storage) // this is used in integrals operator vector_type() { return _a + diagonal() / 2; } vector_type diagonal() const { return _b - _a; } vector_type const & a() const { return _a; } void a(vector_type const & val) { _a = val; } vector_type const & b() const { return _b; } void b(vector_type const & val) { _b = val; } divide_type operator/(typename vector_type::template convert_type<std::size_t> denominator) { return divide_type(*this, denominator); } private: vector_type _a, _b; }; template <typename Vector> box<Vector> make_box(Vector const & a, Vector const & b) { return box<Vector>(a,b); } template <typename Box> class box_divider_iterator; template <typename Box> class box_divider { public: typedef Box value_type; typedef typename value_type::vector_type vector_type; typedef typename vector_type::template convert_type<std::size_t> step_vector_type; typedef step_vector_type size_type; typedef box_divider_iterator<value_type> iterator; typedef std::reverse_iterator<iterator> reverse_iterator; virtual ~box_divider() = default; box_divider() : _box{}, _size{} { } template <typename V> box_divider(box_divider<V> const & v) : _box(v._box), _size(v._size), _divide(v._divide) { } box_divider(value_type box, step_vector_type steps) : _box(std::move(box)) { resize(steps); } iterator begin() const { return iterator(this, 0); } iterator end() const { return iterator(this, size_total()); } reverse_iterator rbegin() const { return reverse_iterator(begin()); } reverse_iterator rend() const { return reverse_iterator(end()); } bool empty() { return size() == 0; } void resize(size_type const & s) { _size = s; // setup our index_mod vector from the step vector. used to divide the 1D index into the appropriate n dimensinoal index. for (std::size_t i = 0; i < _size.size(); i++) { _divide[i] = (i > 0 ? _size[i - 1] * _divide[i - 1] : 1); } _total = std::accumulate(_size.begin(), _size.end(), 1, std::multiplies<typename size_type::value_type>()); _diagonal = _box.diagonal(); { auto i = _diagonal.begin(); auto j = _size.begin(); for (; i != _diagonal.end(); ++i, ++j) { *i /= *j; } } } value_type operator[](std::size_t index) const { auto t = r(index); return value_type(t, t + _diagonal); } value_type at(std::size_t index) const { if (index >= _total) throw std::out_of_range("Index out of range of box divider."); return (*this)[index]; } size_type size() const { return _size; } size_type max_size() const { return (size_type)(-1); } // returns all the dimensions of size multiplied together. typename size_type::value_type size_total() const { return _total; } private: vector_type r(std::size_t index) const { vector_type R = _box.a(); for (int i = 0; i < _size.size(); i++) { R[i] += (_box.b()[i] - R[i]) / _size[i] * ((index / _divide[i]) % _size[i]); } return R; } vector_type _diagonal; step_vector_type _divide; // used to break the 1 dimensional index into the N dimensional vector type, calculated from steps. step_vector_type _size; // number of subdivisions in each dimension value_type _box; typename size_type::value_type _total; }; template <typename Box> class box_divider_iterator { public: typedef Box box_type; typedef box_divider<box_type> box_divider_type; typedef typename box_type::vector_type vector_type; typedef typename box_divider_type::value_type value_type; typedef typename box_divider_type::value_type reference; // not actually a reference since the elements are created on access. typedef typename box_divider_type::value_type* pointer; typedef typename std::size_t difference_type; typedef std::forward_iterator_tag iterator_category; box_divider_iterator() : _R(nullptr), _I(0) { } box_divider_iterator(box_divider_type const * R, difference_type I) : _R(R), _I(I) { } box_divider_iterator(box_divider_iterator const & a) : _R(a._R), _I(a._I) { } box_divider_iterator& operator=(box_divider_iterator const & a) { _R = a._R; _I = a._I; return *this; } virtual ~box_divider_iterator() = default; bool operator==(box_divider_iterator const & a) const { return (_I == a._I || (is_end() && a.is_end())); } bool operator!=(box_divider_iterator const & a) const { return !(_I == a._I); } box_divider_iterator & operator++() { ++_I; return *this; } box_divider_iterator operator++(int) { box_divider_iterator t(*this); ++_I; return t; } reference operator*() const { assert(!is_end()); return (*_R)[_I]; } private: bool is_end() const { return (_R == nullptr || _I >= _R->size_total()); } box_divider_type const* _R; difference_type _I; // current index; }; } namespace std { template <typename T> std::ostream& operator<<(std::ostream & out, math::box<T> const & r) { return out << "box [" << r.a() << " -> " << r.b() << "]"; } } #endif
true
d000178bf0284fa16dcf4f85d3cebea786f92c50
C++
bhavishrohilla/c-plus-plus
/hacker.cpp
UTF-8
281
2.734375
3
[]
no_license
#include <iostream> #include <cstdio> #include<climits> using namespace std; int main() { int no; int max_so_far = INT_MIN; for(int i=0; i<=4;i++){ cin>>no; if(no>max_so_far){ max_so_far=no; } } cout<<max_so_far<<endl; return 0; }
true
cfd5b292e2b3022266cc1c0576d270748920a9db
C++
arielofer/C-projects-and-homework
/Project1/menu_funcs.cpp
UTF-8
19,882
2.859375
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS // also adds all structs #include "menu_funcs.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #define MAX_STRING_LENGTH 50 //global head instant extern headder head; //file names const char* PFILENAME = "players.dat"; const char* TFILENAME = "teams.dat"; //----------------------------------------------------------------------------- // Get String // ---------- // // General : The function gets input from user, builds a dynamic // string and return it // // Parameters : // // Return Value : a pointer to a dynamic string. // //----------------------------------------------------------------------------- char* GetString() { char chr; int len = 1; char* str = NULL; str = (char*)realloc(str, sizeof(char) * (len + 1)); chr = getchar(); str[len - 1] = chr; while (chr != '\n') { chr = getchar(); ++len; str = (char*)realloc(str, sizeof(char) * (len + 1)); str[len - 1] = chr; if (len == MAX_STRING_LENGTH) break; } str[len - 1] = '\0'; return str; } //----------------------------------------------------------------------------- // Build Players file // ------------------ // // General : The function gets input from user, builds a player instance // and writes to the players file N times // // Parameters : // N (In) // // Return Value : // //----------------------------------------------------------------------------- void BuildPlayersFile(int N) { FILE* fp = fopen(PFILENAME, "wb"); char *ID, *Fname, *Lname; int age; playerRec player; getchar(); for (int i = 0; i < N; i++) { printf("~ enter id: "); player.playerID = GetString(); printf("~ enter first name: "); player.firstName = GetString(); printf("~ enter last name: "); player.lastName = GetString(); printf("~ enter age: "); scanf("%d", &player.age); fwrite(&player, sizeof(playerRec), 1, fp); fseek(fp, 0, SEEK_CUR); } } //----------------------------------------------------------------------------- // Build Teams file // ---------------- // // General : The function gets input from user, builds a team instance // and writes to the players file N times // // Parameters : // N (In) // // Return Value : // //----------------------------------------------------------------------------- void BuildTeamsFile(int N) { FILE* fp = fopen(TFILENAME, "wb"); char* Tname; teamRec team; getchar(); for (int i = 0; i < N; i++) { printf("~ enter team name: "); team.teamName = GetString(); team.num_of_players = 0; team.plarray = NULL; fwrite(&team, sizeof(teamRec), 1, fp); fseek(fp, 0, SEEK_CUR); } } //----------------------------------------------------------------------------- // Build Head instance // ------------------- // // General : The function reads data from the players and teams files, // and enters it to the head instance. // // Parameters : // // Return Value : // //----------------------------------------------------------------------------- void HeadBuild() { statusType status; FILE* fp; playerRec player; teamRec team; fp = fopen(PFILENAME, "rb"); fread(&player, sizeof(playerRec), 1, fp); fseek(fp, 0, SEEK_CUR); while (!feof(fp)) { status = insertPlayer(player.playerID, player.lastName, player.firstName, player.age); if (status == DUPLICATE_RECORD) break; fread(&player, sizeof(playerRec), 1, fp); fseek(fp, 0, SEEK_CUR); } fclose(fp); fp = fopen(TFILENAME, "rb"); fread(&team, sizeof(teamRec), 1, fp); fseek(fp, 0, SEEK_CUR); while (!feof(fp)) { status = insertTeam(team.teamName); if (status == DUPLICATE_RECORD) break; fread(&team, sizeof(teamRec), 1, fp); fseek(fp, 0, SEEK_CUR); } fclose(fp); } //----------------------------------------------------------------------------- // Find Player // ------------- // // General : The function looks for the player with the given ID // in the players linked list // // Parameters : // playerID (In) // // Return Value : a pointer to the player node in the linked list or // NULL if not found // //----------------------------------------------------------------------------- playerNodePtr findPlayer(char *playerID) { playerNodePtr p = head.playerList; while (p) { if (!strcmp(p->PL.playerID, playerID)) return p; p = p->next; } return NULL; } //----------------------------------------------------------------------------- // Insert Player // ------------- // // General : The function adds a new player to the start // of the Players linked list // // Parameters : // playerID (In) // lastName (In) // firstName (In) // age (In) // // Return Value : SUCCESS if the operation was successful or // DUPLICATE_RECORD if the player already exists in the system // //----------------------------------------------------------------------------- statusType insertPlayer(char *playerID, char* lastName, char* firstName, int age) { statusType status = SUCCESS; playerNodePtr p, q = findPlayer(playerID); if (q) { status = DUPLICATE_RECORD; return status; } // new player p = (playerNodePtr)malloc(sizeof(playerNode)); p->PL.playerID = _strdup(playerID); p->PL.lastName = _strdup(lastName); p->PL.firstName = _strdup(firstName); p->PL.age = age; p->tmptr = NULL; // teamless player p->next = head.playerList; head.playerList = p; return status; } //----------------------------------------------------------------------------- // Delete Player from team // ----------------------- // // General : The function deletes a the pointer to this player // from the team he played for. // // Parameters : // playerID (In) // // Return Value : SUCCESS if the operation was successful or // MISSING_RECORD if the player does not exists in the system // or the player doesn't belong to any team //----------------------------------------------------------------------------- statusType deletePlayerFromTeam(char* playerID) { playerNodePtr p = findPlayer(playerID); teamPtr t; int i, k = 0; statusType status = SUCCESS; if (!p || !p->tmptr) status = MISSING_RECORD; else { t = p->tmptr; p->tmptr = NULL; // remove pointer to team //find the player index in the team's player array for (i = 0; i < t->num_of_players; i++) { if(t->plarray[i]->playerID == playerID) { k = i; break; } } //remove player from array for (i = k + 1; i < t->num_of_players; i++) t->plarray[i - 1] = t->plarray[i]; t->num_of_players--; t->plarray = (playerPtr*)realloc(t->plarray, t->num_of_players * sizeof(playerPtr)); } return status; } //----------------------------------------------------------------------------- // Delete Player // ------------- // // General : The function deletes a player with the given ID // from the Player linked list and the pointer to this player from // the team he played for if he does. // // Parameters : // playerID (In) // // Return Value : SUCCESS if the operation was successful or // MISSING_RECORD if the player doesn't exists in the system // //----------------------------------------------------------------------------- statusType deletePlayer(char* playerID) { playerNodePtr p = findPlayer(playerID), q = head.playerList; statusType status = SUCCESS; if (!p) status = MISSING_RECORD; else { if (p->tmptr) status = deletePlayerFromTeam(playerID); //if the player is at the head of the list if (head.playerList == p) { head.playerList = q->next; free(p->PL.playerID); free(p->PL.firstName); free(p->PL.lastName); free(p); } else { //look for the player until one node before the end while (q->next) { if (q->next == p) { q->next = p->next; free(p->PL.playerID); free(p->PL.firstName); free(p->PL.lastName); free(p); break; } q = q->next; } } } return status; } //----------------------------------------------------------------------------- // Find Team // --------- // // General : The function looks for the team with the given name // in the teams linked list // // Parameters : // name (In) // // Return Value : a pointer to the team node in the linked list or // NULL if not found // //----------------------------------------------------------------------------- teamPtr findTeam(char* name) { teamPtr t = head.teamlist; while (t) { if (!strcmp(t->teamName, name)) return t; t = t->next; } return NULL; } //----------------------------------------------------------------------------- // Insert Team // ----------- // // General : The function adds a new team to the start // of the Teams linked list // // Parameters : // name (In) // // Return Value : SUCCESS if the operation was successful or // DUPLICATE_RECORD if the team already exists in the system // //----------------------------------------------------------------------------- statusType insertTeam(char* name) { statusType status = SUCCESS; teamPtr t, k = findTeam(name); if (k) { status = DUPLICATE_RECORD; return status; } // new team t = (teamPtr)malloc(sizeof(Team)); t->teamName = _strdup(name); t->num_of_players = 0; t->plarray = NULL; // no players in the new team t->next = head.teamlist; head.teamlist = t; return status; } //----------------------------------------------------------------------------- // Delete Team // ----------- // // General : The function deletes a team with the given name // from the Team linked list and the pointers to this team from // all the players that played for this team. // // Parameters : // name (In) // // Return Value : SUCCESS if the operation was successful or // MISSING_RECORD if the team doesn't exists in the system // //----------------------------------------------------------------------------- statusType deleteTeam(char* name) { int i; teamPtr t = findTeam(name), k = head.teamlist; statusType status = SUCCESS; if (!t) status = MISSING_RECORD; else { if (t->plarray) { for (i = 0; i < t->num_of_players; i++) deletePlayerFromTeam(t->plarray[i]->playerID); } //if the player is at the head of the list if (head.teamlist == t) head.teamlist = t->next; else { //look for the team in the linked list while (k->next != t) { k = k->next; } k->next = t->next; } free(t->teamName); free(t->plarray); free(t); } return status; } //----------------------------------------------------------------------------- // Join player to Team // ------------------- // // General : The function adds the player with the given ID // (if he doesnt play for a team) to the team with the given name. // // Parameters : // playerID (In) // team_name (In) // // Return Value : SUCCESS if the operation was successful or // MISSING_RECORD if the team or player doesn't exists in the system // or the player already plays for a team // //----------------------------------------------------------------------------- statusType joinPlayerToTeam(char* playerID, char* team_name) { statusType status = SUCCESS; playerNodePtr p = findPlayer(playerID); teamPtr t = findTeam(team_name); if (!p || !t) status = MISSING_RECORD; else { if (p->tmptr) status = MISSING_RECORD; else { p->tmptr = t; if (!t->num_of_players) // team has no players { t->plarray = (playerPtr*)realloc(t->plarray, sizeof(playerPtr)); t->plarray[0] = &(p->PL); t->num_of_players = 1; } else { t->plarray = (playerPtr*)realloc (t->plarray, (t->num_of_players + 1) * sizeof(playerPtr)); t->plarray[t->num_of_players] = &(p->PL); t->num_of_players++; } } } return status; } //----------------------------------------------------------------------------- // print players // ------------- // // General : The function prints all the players according // to the order they appear in the linked list. // // Parameters : // None // // Return Value : // None // //----------------------------------------------------------------------------- void printPlayers(void) { playerNodePtr p = head.playerList; if (!p) printf("[-] No players"); else { int i = 1; while (p) { printf("[%d] first name: %s, last name: %s, id: %s, age: %d\n", i++, p->PL.firstName, p->PL.lastName, p->PL.playerID, p->PL.age); p = p->next; } } } //----------------------------------------------------------------------------- // print teams // ----------- // // General : The function prints all the teams according // to the order they appear in the linked list. // // Parameters : // None // // Return Value : // None // //----------------------------------------------------------------------------- void printTeams(void) { teamPtr t = head.teamlist; if (!t) printf("[-] No teams"); else { int i = 1; while (t) { printf("[%d] team name: %s\n", i++, t->teamName); t = t->next; } } } //----------------------------------------------------------------------------- // print team details // ------------------ // // General : The function prints all the details of the // team with the given name if it exists. if the team has no // players the function will print 0 // // Parameters : // name (In) // // Return Value : // SUCCESS if the team exists in the system else MISSING_RECORD // //----------------------------------------------------------------------------- statusType printTeamDetails(char* name) { playerNodePtr p; teamPtr t = findTeam(name); statusType status = SUCCESS; if (!t) status = MISSING_RECORD; else { printf("-- players in %s --\n\n", name); if (!t->plarray) printf("0"); else { for (int i = 0; i < t->num_of_players; i++) { p = findPlayer(t->plarray[i]->playerID); printf("[%d] first name: %s, last name: %s, id: %s, age: %d\n", i+1, p->PL.firstName, p->PL.lastName, p->PL.playerID, p->PL.age); } } } return status; } //----------------------------------------------------------------------------- // sort and print team details // --------------------------- // // General : The function sorts the players array of the // team with the given name if it exists and has players it prints // the players details. // // Parameters : // name (In) // // Return Value : // SUCCESS if the team exists in the system else MISSING_RECORD // //----------------------------------------------------------------------------- statusType sortAndPrintTeamDetails(char* name) { playerNodePtr p, q; playerPtr temp; teamPtr t = findTeam(name); statusType status = SUCCESS; if (!t || !t->plarray) status = MISSING_RECORD; else { int ok = 1, k =0; while (ok) { ok = 0; for (int i = 0; i < t->num_of_players - 1 - k; i++) { p = findPlayer(t->plarray[i]->playerID); q = findPlayer(t->plarray[i + 1]->playerID); if (strcmp(p->PL.lastName, q->PL.lastName) == 1) { temp = t->plarray[i]; t->plarray[i] = t->plarray[i + 1]; t->plarray[i + 1] = temp; ok = 1; } } k++; } printTeamDetails(name); } return status; } //----------------------------------------------------------------------------- // Player Node Count // ----------------- // // General : The function gets a linked list of players and counts how // many nodes it has // // Parameters : // list (In) // // Return Value : the amount of nodes in the linked list // //----------------------------------------------------------------------------- int PlayerNodeCount(playerNodePtr list) { int counter = 0; while (list) { list = list->next; ++counter; } return counter; } //----------------------------------------------------------------------------- // team Node Count // --------------- // // General : The function gets a linked list of teams and counts how // many nodes it has // // Parameters : // list (In) // // Return Value : the amount of nodes in the linked list // //----------------------------------------------------------------------------- int TeamsNodeCount(teamPtr list) { int counter = 0; while (list) { list = list->next; ++counter; } return counter; } //----------------------------------------------------------------------------- // sort team list by name // ---------------------- // // General : The function sorts the teams linked list // by name in an ascending order. // // Parameters : // // Return Value : // SUCCESS if the team linked list isnt empty else MISSING_RECORD // //----------------------------------------------------------------------------- statusType SortTeamsByName() { statusType status = SUCCESS; teamPtr t = head.teamlist, s, temp ,prev; if (!t) status = MISSING_RECORD; else { int len = TeamsNodeCount(head.teamlist); if (len > 1) { int ok = 1, k = 0; while (ok) { t = head.teamlist, prev = t, s = t->next; ok = 0; for (int i = 0; i < len - 1 - k; i++) { if (strcmp(t->teamName, s->teamName) == 1) { if (t == head.teamlist) { t->next = s->next; s->next = t; head.teamlist = s; prev = s; } else { prev->next = s; t->next = s->next; s->next = t; prev = s; } temp = t; t = s; s = temp; ok = 1; } t= t->next; if (prev->next != t) prev = prev->next; s = s->next; } k++; } } } return status; } //----------------------------------------------------------------------------- // sort team list by size // ---------------------- // // General : The function sorts the teams linked list // by the number of players in an ascending order. // // Parameters : // // Return Value : // SUCCESS if the team linked list isnt empty else MISSING_RECORD // //----------------------------------------------------------------------------- statusType SortTeamsBySize() { statusType status = SUCCESS; teamPtr t = head.teamlist, s, temp, prev; if (!t) status = MISSING_RECORD; else { int len = TeamsNodeCount(head.teamlist); if (len > 1) { int ok = 1, k = 0; while (ok) { t = head.teamlist, prev = t, s = t->next; ok = 0; for (int i = 0; i < len - 1 - k; i++) { if (t->num_of_players > s->num_of_players) { // if t is at head if (t == head.teamlist) { t->next = s->next; s->next = t; head.teamlist = s; prev = s; } else { prev->next = s; t->next = s->next; s->next = t; prev = s; } //switch back to t before s temp = t; t = s; s = temp; ok = 1; } t = t->next; if (prev->next != t) prev = prev->next; s = s->next; } k++; } } } return status; } //----------------------------------------------------------------------------- // Is player available // ------------------- // // General : The function gets the id of a player and checks if // exists and if he plays for a team // // Parameters : // ID (In) // // Return Value : // SUCCESS if the the player exists else MISSING_RECORD // //----------------------------------------------------------------------------- statusType IsPlayerAvailable(char* ID) { statusType status = SUCCESS; playerNodePtr p = findPlayer(ID); if (!p) status = MISSING_RECORD; else { if (!p->tmptr) printf("player with id: %s is available!\n", ID); else { printf("player with id: %s is not available, plays for %s\n\n", ID, p->tmptr->teamName); printTeamDetails(p->tmptr->teamName); } } return status; } void Exit() { printf("Bye!\n"); //delete players playerNodePtr p = head.playerList; while (p) { deletePlayer(p->PL.playerID); p = head.playerList; } //delete teams teamPtr t = head.teamlist; while (t) { deleteTeam(t->teamName); t = head.teamlist; } }
true
950da5805f41bbd7893b2419b527aee8d17705d0
C++
OperatorFoundation/Crypto
/src/GHASH.cpp
UTF-8
4,488
2.53125
3
[ "MIT" ]
permissive
/* * Copyright (C) 2015 Southern Storm Software, Pty Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "GHASH.h" #include "GF128.h" #include "Crypto.h" #include <string.h> /** * \class GHASH GHASH.h <GHASH.h> * \brief Implementation of the GHASH message authenticator. * * GHASH is the message authentication part of Galois Counter Mode (GCM). * * \note GHASH is not the same as GMAC. GHASH implements the low level * hashing primitive that is used by both GCM and GMAC. GMAC can be * simulated using GCM and an empty plaintext/ciphertext. * * References: <a href="http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf">NIST SP 800-38D</a>, * http://en.wikipedia.org/wiki/Galois/Counter_Mode * * \sa GCM */ /** * \brief Constructs a new GHASH message authenticator. */ GHASH::GHASH() { state.posn = 0; } /** * \brief Destroys this GHASH message authenticator. */ GHASH::~GHASH() { clean(state); } /** * \brief Resets the GHASH message authenticator for a new session. * * \param key Points to the 16 byte authentication key. * * \sa update(), finalize() */ void GHASH::reset(const void *key) { GF128::mulInit(state.H, key); memset(state.Y, 0, sizeof(state.Y)); state.posn = 0; } /** * \brief Updates the message authenticator with more data. * * \param data Data to be hashed. * \param len Number of bytes of data to be hashed. * * If finalize() has already been called, then the behavior of update() will * be undefined. Call reset() first to start a new authentication process. * * \sa pad(), reset(), finalize() */ void GHASH::update(const void *data, size_t len) { // XOR the input with state.Y in 128-bit chunks and process them. const uint8_t *d = (const uint8_t *)data; while (len > 0) { uint8_t size = 16 - state.posn; if (size > len) size = len; uint8_t *y = ((uint8_t *)state.Y) + state.posn; for (uint8_t i = 0; i < size; ++i) y[i] ^= d[i]; state.posn += size; len -= size; d += size; if (state.posn == 16) { GF128::mul(state.Y, state.H); state.posn = 0; } } } /** * \brief Finalizes the authentication process and returns the token. * * \param token The buffer to return the token value in. * \param len The length of the \a token buffer between 0 and 16. * * If \a len is less than 16, then the token value will be truncated to * the first \a len bytes. If \a len is greater than 16, then the remaining * bytes will left unchanged. * * If finalize() is called again, then the returned \a token value is * undefined. Call reset() first to start a new authentication process. * * \sa reset(), update() */ void GHASH::finalize(void *token, size_t len) { // Pad with zeroes to a multiple of 16 bytes. pad(); // The token is the current value of Y. if (len > 16) len = 16; memcpy(token, state.Y, len); } /** * \brief Pads the input stream with zero bytes to a multiple of 16. * * \sa update() */ void GHASH::pad() { if (state.posn != 0) { // Padding involves XOR'ing the rest of state.Y with zeroes, // which does nothing. Immediately process the next chunk. GF128::mul(state.Y, state.H); state.posn = 0; } } /** * \brief Clears the authenticator's state, removing all sensitive data. */ void GHASH::clear() { clean(state); }
true
b865bc78046ac425b833f9492193785f92dbec2c
C++
lamyj/odil
/examples/cpp/dump.cpp
UTF-8
2,186
3.109375
3
[ "LicenseRef-scancode-cecill-b-en" ]
permissive
#include <fstream> #include <iostream> #include <ostream> #include <string> #include <utility> #include <odil/DataSet.h> #include <odil/Reader.h> #include <odil/Value.h> struct Printer { typedef void result_type; std::ostream & stream; std::string indent; Printer(std::ostream & stream, std::string const & indent="") : stream(stream), indent(indent) { // Nothing else } template<typename T> void operator()(T const & value) const { for(auto const & item: value) { this->stream << item << " "; } } void operator()(odil::Value::DataSets const & value) const { this->stream << "\n"; auto const last_it = --value.end(); for(auto it=value.begin(); it!= value.end(); ++it) { Printer const printer(this->stream, this->indent+" "); printer(*it); if(it != last_it) { this->stream << "----\n"; } } } void operator()(odil::Value::Binary const &) const { this->stream << this->indent << "(binary)"; } void operator()(std::shared_ptr<odil::DataSet> const & data_set) const { for(auto const & item: *data_set) { this->stream << this->indent << item.first << " " << as_string(item.second.vr) << " "; odil::apply_visitor(*this, item.second.get_value()); this->stream << "\n"; } } }; int main(int argc, char** argv) { for(int i=1; i<argc; ++i) { std::ifstream stream(argv[i], std::ios::in | std::ios::binary); std::pair<std::shared_ptr<odil::DataSet>, std::shared_ptr<odil::DataSet>> file; try { file = odil::Reader::read_file(stream); } catch(std::exception & e) { std::cout << "Could not read " << argv[i] << ": " << e.what() << "\n"; } auto const & meta_information = file.first; auto const & data_set = file.second; Printer printer(std::cout); printer(meta_information); std::cout << "\n"; printer(data_set); } return 0; }
true
589ee341fcd705a5de14af2eb536944c70d40c2e
C++
ytsurkan/uni-tasks
/public/uni/tasks/details/Task.hpp
UTF-8
1,941
2.875
3
[]
no_license
#pragma once #include "uni/tasks/ITask.hpp" #include "uni/tasks/details/TaskImpl.hpp" namespace uni { template < typename F, typename... Args > class Task : public ITask { public: /** * @brief * std::decay_t models the type conversions applied to function arguments when passed by value. * std::is_same_v<C, Task> is true for case "auto task2 = task;" * std::enable_if_t disables calling of this constructor instead of copy constructor for * non-const objects. */ template < typename TF, typename C = std::decay_t< TF >, typename = typename std::enable_if_t< !( std::is_same_v< C, Task > ) >, typename... TArgs > Task( TF&& f, TArgs&&... args ) : m_impl( std::forward< TF >( f ), std::forward< TArgs >( args )... ) { } ~Task( ) override = default; Task( const Task& ) = delete; Task& operator=( const Task& ) = delete; Task( Task&& ) = default; Task& operator=( Task&& ) = default; private: /// ITask interface implementation void run( ) override { m_impl.run_impl( ); } RequestId request_id( ) const override { return m_impl.request_id_impl( ); } void set_request_id( RequestId request_id ) override { m_impl.set_request_id_impl( request_id ); } SequenceId sequence_id( ) const override { return m_impl.sequence_id_impl( ); } void set_due_time( TimeInterval delay ) override { m_impl.set_due_time_impl( delay ); } TimeInterval due_time( ) const override { return m_impl.due_time_impl( ); } TimeInterval delay( ) const override { return m_impl.delay_impl( ); } std::future< void > get_future( ) override { return m_impl.get_future_impl( ); } private: TaskImpl< F, Args... > m_impl; }; } // namespace uni
true
13984b9f869eb012e64400d40b3508544b68cbd1
C++
ch200c/leetcode-cpp
/UnitTests/src/p169/p169_test.cpp
UTF-8
629
2.671875
3
[ "MIT" ]
permissive
#include "pch.h" #include "CppUnitTest.h" #include "leetcode-cpp/p169/p169_solution.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace tests { TEST_CLASS(p169_test) { public: TEST_METHOD(test1) { auto solution{ leetcode::p169::Solution() }; auto input{ std::vector<int>{3, 2, 3} }; auto result{ solution.majorityElement(input) }; Assert::AreEqual(3, result); } TEST_METHOD(test2) { auto solution{ leetcode::p169::Solution() }; auto input{ std::vector<int>{2, 2, 1, 1, 1, 2, 2} }; auto result{ solution.majorityElement(input) }; Assert::AreEqual(2, result); } }; }
true
be60b579237a0843c0f5b31399410fffdff7931b
C++
alexander-jones/NCV
/gui/utilities/combowidget.h
UTF-8
3,760
2.890625
3
[]
no_license
#ifndef SIDEBAR_H #define SIDEBAR_H #include <QWidget> #include <QLabel> #include <QCheckBox> #include <QSignalMapper> #include <QSpinBox> #include <QComboBox> #include <QHBoxLayout> /*! \class ComboWidget \author Alex Jones \brief A widget class for cycling through a number of widgets through a combo box. */ class ComboWidget : public QWidget { Q_OBJECT public: /*! \param parent A pointer to the parent widget. \brief Constructs a ComboWidget */ explicit ComboWidget(QWidget *parent = 0); /*! \param tool A tool to added to the ComboWidget toolbar. \brief Adds a tool the to the toolbar which always contains the combo box switcher. */ void addTool(QWidget * tool); /*! \param index The index in the toolbar to insert the new tool. \param tool A tool to added to the ComboWidget toolbar. \brief Inserts a tool the to the toolbar which always contains the combo box switcher. */ void insertTool(int index,QWidget * tool); /*! \param tool The tool to remove from the ComboWidget toolbar. \brief Removes a tool the from the toolbar. */ void removeTool(QWidget * tool); /*! \param widget The widget to add. \param key The key for the widget that will appear in the combo box. \brief Adds a widget reffered to with key to the list of widgets. */ void addWidget(QWidget * widget,const QString& key); /*! \param key The key that appears in the combo box for the widget . \brief Removes a widget reffered to with key from the list of widgets. */ void removeWidget(QString key); /*! \brief Returns the current number of widgets contained in the list of widgets. */ int count(); /*! \param key The key that appears in the combo box for the widget . \brief Returns whether or not the widget reffered to with key is present in the list of widgets. */ bool containsWidget(QString key); /*! \param key The tool to check for. \brief Returns whether or not the tool is contained in the toolbar alongside the combo widget. */ bool containsTool(QWidget * tool); /*! \brief Returns the current widget. If no widget has been added, returns the void widget pointer. */ QWidget * currentWidget(); /*! \brief Returns the widget presented when no widgets are in the list of widgets. */ QWidget * voidWidget(); /*! \brief Returns the key of the current widget. Returns "" if no widgets have been added. */ QString currentWidgetKey(); /*! \param widget The widget to use. \brief Sets' widget' to be presented when no widgets have been added. */ void setVoidWidget(QWidget * widget); signals: /*! \param key The key of the new current widget. \brief This signal emits when the current widget has changed. */ void widgetChanged(QString key); /*! \param widget The new current widget. \brief This signal emits when the current widget has changed. */ void widgetChanged(QWidget * widget); public slots: /*! \param key The key of the widget to set as current. \brief This slot lets the current widget be set to be the widget reffered to by key. */ void setWidget( QString key); /*! \param widget The widget to set as current \brief This slot lets the current widget be set to be the widget 'widget'. */ void setWidget( QWidget * widget); private: QWidget * m_currentWidget, *m_toolbar; QComboBox * m_widgetSelector; QHBoxLayout * m_toolbarLayout; QVBoxLayout * m_layout; QWidget * m_voidWidget; QFrame *m_separator; QMap<QString, QWidget *> m_widgets; }; #endif // SIDEBAR_H
true
39a1c0ab1b5802d9cdab37d98f22c28e40d68447
C++
Wzhoooh/Turtle_graphic
/parser.cpp
UTF-8
671
2.9375
3
[]
no_license
#include "parser.hpp" #include "list.hpp" #include "string.hpp" #include "command_handler.hpp" Parser::Parser(DS::string&& input, Command_Handler&& handler): s(input), _handler(handler){} void Parser::handle() { DS::list<DS::string> commandsList; for (size_t i = 0; i < s.size();) { for (; s[i] == ' ' && i < s.size(); ++i) continue; DS::string word; for (; s[i] != ' ' && i < s.size(); ++i) word += s[i]; if (word.size() != 0) commandsList.push_back(std::move(word)); } for (auto&& i : commandsList) i.changeToUpperCase(); _handler.handle(commandsList); }
true
d7fff419a8a6112bd33c7373763ab25f68a2bcac
C++
waewing/CS246
/Mains/NodeSum.cpp
UTF-8
381
2.78125
3
[]
no_license
#include <iostream> #include <cmath> #include "node.h" using namespace std; int Sum(Node<int>* root) { int sum; for(Node<int>* tmp = head; tmp!=NULL; tmp = tmp->GetLink()) { if(tmp = root) { sum = tmp->GetData(); } else { sum = sum + tmp->GetData(); } } return sum; } int main() { }
true
9871d328cf57f6ad636846517e1396d680532dd3
C++
elemaryo/Ubisoft-NEXT-2021-Tower-Defense
/WDAU_API2020/GameTest/Level.cpp
UTF-8
3,525
2.59375
3
[]
no_license
//------------------------------------------------------------------- // Level.h // The class manages all aspects of the level entity // Derived from GameEntity //------------------------------------------------------------------- #include "stdafx.h" #include "Level.h" #include "MathHelper.h" #include "CanonTower.h" #include "RocketTower.h" //------------------------------------------------------------------- Level::Level(int stage, PlaySideBar* sideBar, Player* player){ mSideBar = sideBar; mPlayer = player; mMap = Map::Instance(); mTimer = Timer::Instance(); mEnemyDeployDelay = 2.0f; mEnemySpawnTimer = 0.0f; mStage = stage; mTowerType = TowerEntity::TYPE::unknown; SpawnEnemy(); } Level::~Level(){ //mSideBar = NULL; mMap = NULL; mPlayer = NULL; for (int i = 0; i < mEnemy.size(); i++) { delete mEnemy[i]; mEnemy[i] = NULL; } } Level::LEVEL_STATES Level::State(){ return running; } void Level::SpawnEnemy() { mEnemy.push_back(new Enemy(mMap->GetTileXPos(mMap->GetPathStart().second), mMap->GetTileYPos(mMap->GetPathStart().first))); int index = mEnemy.size() - 1; mEnemy[index]->Parent(mMap); mEnemy[index]->XPos(0.0f); mEnemy[index]->YPos(0.0f); } void Level::SpawnTower(TowerEntity::TYPE type, float x, float y) { mMap->CreateTower(x, y); mMap->ConvertMouseToTile(x, y); //switch (type) { // case canon: // mTowers.push_back(new CanonTower(x, y)); // break; // case rocket: // mTowers.push_back(new RocketTower(x, y)); // break; //} mTowers.push_back(new CanonTower(x, y)); mTowers[mTowers.size() - 1]->Parent(mMap); mTowers[mTowers.size() - 1]->XPos(x); mTowers[mTowers.size() - 1]->YPos(y); } void Level::Update(){ if (mEnemy.size() < MAX_NUMBER_OF_ENEMIES) { mEnemySpawnTimer += mTimer->DeltaTime(); if (mEnemySpawnTimer >= mEnemyDeployDelay) { SpawnEnemy(); mEnemySpawnTimer = 0.0f; } } for (int i = 0; i < mEnemy.size(); i++) { mEnemy[i]->Update(); int pathIndex = MathHelper::Clamp(mEnemy[i]->GetPathIndex(), 0, mMap->GetPathSize() - 1); mEnemy[i]->SetPos(mMap->GetTileXPos(mMap->GetPathIndex(pathIndex).second), mMap->GetTileYPos(mMap->GetPathIndex(pathIndex).first)); //if (mEnemy[i]->GetDirection() == mEnemy::DIRECTION::right) { // mEnemy[i]->SetAngle(90); //} } for (int i = 0; i < mTowers.size(); i++) { mTowers[i]->FindNearestEnemy(mEnemy); } if (App::IsKeyPressed(VK_LBUTTON)) { //if (mMap->GetTileRow(xMouse) float xMouse; float yMouse; App::GetMousePos(xMouse, yMouse); //set mTowerType? SpawnTower(mSideBar->GetSelectedTower(), xMouse, yMouse); } // controls to destroy towers //if (App::IsKeyPressed(VK_RBUTTON)) { // float xMouse; // float yMouse; // App::GetMousePos(xMouse, yMouse); // mMap->CreateTower(xMouse, yMouse); // mMap->ConvertMouseToTile(xMouse, yMouse); // mTowers.push_back(new CanonTower(xMouse, yMouse)); // mTowers[mTowers.size() - 1]->Parent(mMap); // mTowers[mTowers.size() - 1]->XPos(xMouse); // mTowers[mTowers.size() - 1]->YPos(yMouse); // /*PlaceTower(xMouse, yMouse);*/ //} // check enemy position to rotate } void Level::Render() { // if mStageStarted condition mMap->Render(); // mEnemy respawn delay // render enemies for (int i = 0; i < mEnemy.size(); i++) { mEnemy[i]->Render(); } // render towers for (int i = 0; i < mTowers.size(); i++) { mTowers[i]->Render(); } };
true
32d5c070de5adf7fb234cc32f3c7a831e2a18779
C++
DiegoCV/programacion_competitiva
/el_sueno_del_emperador.cpp
UTF-8
738
2.921875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int const MAX_N = 30 + 1; vector<int> adj[MAX_N]; bool visited[MAX_N]; void dfs(int s){ if(visited[s]) return; visited[s] = true; for(auto u: adj[s]) dfs(u); } int main() { int t, n, m, a, b, cant_islas; cin >> t; while(t){ cant_islas = 0; cin >> n >> m; for(int i = 0; i <= n; i++)adj[i].clear(); while(m){ cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); m--; } memset(visited, false, MAX_N); for(int i = 1; i <= n; i++){ if(!visited[i]){ cant_islas++; dfs(i); } } cout << "El sueno del emperador se ha roto en " << cant_islas << " partes" << "\n"; t--; } return 0; }
true
fcefcb3efb80edd1ac86030a5efe8d12b80c92a1
C++
staticfloat/liblsl
/src/udp_server.cpp
UTF-8
7,418
2.53125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include "udp_server.h" #include "socket_utils.h" #include "stream_info_impl.h" #include <boost/asio/ip/address.hpp> #include <boost/asio/ip/multicast.hpp> #include <boost/asio/ip/udp.hpp> #include <boost/asio/placeholders.hpp> #include <boost/bind.hpp> #include <boost/thread/thread_only.hpp> // === implementation of the udp_server class === using namespace lsl; using namespace lslboost::asio; /* * Create a UDP responder in unicast mode that listens next to a TCP server. * This server will listen on a free local port for timedata and shortinfo requests -- mainly for timing information (unless shortinfo is needed by clients). * @param info The stream_info of the stream to serve (shared). After success, the appropriate service port will be assigned. * @param protocol The protocol stack to use (tcp::v4() or tcp::v6()). */ udp_server::udp_server(const stream_info_impl_p &info, io_context &io, udp protocol): info_(info), io_(io), socket_(new udp::socket(io)), time_services_enabled_(true) { // open the socket for the specified protocol socket_->open(protocol); // bind to a free port uint16_t port = bind_port_in_range(*socket_,protocol); // assign the service port field if (protocol == udp::v4()) info_->v4service_port(port); else info_->v6service_port(port); LOG_F(2, "%s: Started unicast udp server %p at port %d", info_->name().c_str(), this, port); } /* * Create a new UDP server in multicast mode. * This server will listen on a multicast address and responds only to LSL:shortinfo requests. This is for multicast/broadcast local service discovery. */ udp_server::udp_server(const stream_info_impl_p &info, io_context &io, const std::string &address, uint16_t port, int ttl, const std::string &listen_address): info_(info), io_(io), socket_(new udp::socket(io)), time_services_enabled_(false) { ip::address addr = ip::make_address(address); bool is_broadcast = addr == ip::address_v4::broadcast(); // set up the endpoint where we listen (note: this is not yet the multicast address) udp::endpoint listen_endpoint; if (listen_address.empty()) { // pick the default endpoint if (addr.is_v4()) listen_endpoint = udp::endpoint(udp::v4(), port); else listen_endpoint = udp::endpoint(udp::v6(), port); } else { // choose an endpoint explicitly ip::address listen_addr = ip::make_address(listen_address); listen_endpoint = udp::endpoint(listen_addr, (uint16_t)port); } // open the socket and make sure that we can reuse the address, and bind it socket_->open(listen_endpoint.protocol()); socket_->set_option(udp::socket::reuse_address(true)); // set the multicast TTL if (addr.is_multicast() && !is_broadcast) socket_->set_option(ip::multicast::hops(ttl)); // bind to the listen endpoint socket_->bind(listen_endpoint); // join the multicast group, if any if (addr.is_multicast() && !is_broadcast) { if (addr.is_v4()) socket_->set_option(ip::multicast::join_group(addr.to_v4(),listen_endpoint.address().to_v4())); else socket_->set_option(ip::multicast::join_group(addr)); } LOG_F(2, "%s: Started multicast udp server at %s port %d", this->info_->name().c_str(), address.c_str(), port); } // === externally issued asynchronous commands === /// Start serving UDP traffic. /// Call this only after the (shared) info object has been initialized by all other parties, too. void udp_server::begin_serving() { // pre-calculate the shortinfo message (now that everyone should have initialized their part). shortinfo_msg_ = info_->to_shortinfo_message(); // start asking for a packet request_next_packet(); } /// Gracefully close a socket. void close_if_open(udp_socket_p sock) { try { if (sock->is_open()) sock->close(); } catch (std::exception &e) { LOG_F(ERROR, "Error during %s: %s", __func__, e.what()); } } /// Initiate teardown of UDP traffic. void udp_server::end_serving() { // gracefully close the socket; this will eventually lead to the cancellation of the IO operation(s) tied to its socket post(io_, lslboost::bind(&close_if_open, socket_)); } // === receive / reply loop === /// Initiate next packet request. /// The result of the operation will eventually trigger the handle_receive_outcome() handler. void udp_server::request_next_packet() { DLOG_F(5, "udp_server::request_next_packet"); socket_->async_receive_from(lslboost::asio::buffer(buffer_), remote_endpoint_, lslboost::bind(&udp_server::handle_receive_outcome, shared_from_this(), placeholders::error, placeholders::bytes_transferred)); } /// Handler that gets called when the next packet was received (or the op was cancelled). void udp_server::handle_receive_outcome(error_code err, std::size_t len) { DLOG_F(6, "udp_server::handle_receive_outcome (%lub)", len); if (err != error::operation_aborted && err != error::shut_down) { try { if (!err) { // remember the time of packet reception for possible later use double t1 = time_services_enabled_ ? lsl_clock() : 0.0; // wrap received packet into a request stream and parse the method from it std::istringstream request_stream(std::string(buffer_,buffer_+len)); std::string method; getline(request_stream,method); method = trim(method); if (method == "LSL:shortinfo") { // shortinfo request: parse content query string std::string query; getline(request_stream,query); query = trim(query); // parse return address, port, and query ID uint16_t return_port; request_stream >> return_port; std::string query_id; request_stream >> query_id; // check query if (info_->matches_query(query)) { // query matches: send back reply udp::endpoint return_endpoint(remote_endpoint_.address(), return_port); string_p replymsg(new std::string((query_id += "\r\n") += shortinfo_msg_)); socket_->async_send_to(lslboost::asio::buffer(*replymsg), return_endpoint, lslboost::bind(&udp_server::handle_send_outcome, shared_from_this(), replymsg, placeholders::error)); return; } else { LOG_F(INFO, "%p Got shortinfo query for mismatching query string: %s", this, query.c_str()); } } else if (time_services_enabled_ && method == "LSL:timedata") { // timedata request: parse time of original transmission int wave_id; request_stream >> wave_id; double t0; request_stream >> t0; // send it off (including the time of packet submission and a shared ptr to the // message content owned by the handler) std::ostringstream reply; reply.precision(16); reply << " " << wave_id << " " << t0 << " " << t1 << " " << lsl_clock(); string_p replymsg(new std::string(reply.str())); socket_->async_send_to(lslboost::asio::buffer(*replymsg), remote_endpoint_, lslboost::bind(&udp_server::handle_send_outcome, shared_from_this(), replymsg, placeholders::error)); return; } else { DLOG_F(INFO, "Unknown method '%s' received by udp-server", method.c_str()); } } } catch (std::exception &e) { LOG_F(WARNING, "udp_server: hiccup during request processing: %s", e.what()); } request_next_packet(); } } /// Handler that's called after a response packet has been sent off. void udp_server::handle_send_outcome(string_p /*replymsg*/, error_code err) { if (err != error::operation_aborted && err != error::shut_down) // done sending: ask for next packet request_next_packet(); }
true
14874e046b01872451fe14e964d4f1d411006e4f
C++
SoPlump/POO2
/src/Trajet.cpp
UTF-8
3,482
2.84375
3
[]
no_license
/************************************************************************* Trajet - description ------------------- debut : 14 decembre 2018 copyright : (C) 2018 par CERBA, RAUDRANT e-mail : guilhem.cerba@insa-lyon.fr, sophie.raudrant@insa-lyon.fr *************************************************************************/ //---------- Realisation de la classe <Trajet> (fichier Trajet.cpp) ------------ //---------------------------------------------------------------- INCLUDE //-------------------------------------------------------- Include systeme #include <iostream> #include <cstring> #include <stdio.h> using namespace std; //------------------------------------------------------ Include personnel #include "trajet.h" //------------------------------------------------------------- Constantes //----------------------------------------------------------------- PUBLIC //----------------------------------------------------- Methodes publiques void Trajet::Afficher() const // Algorithme : // Affiche les attributs de Trajet { cout << "Depart : " << m_depart << ", Arrivee : " << m_arrivee; } //----- Fin de Afficher Trajet * Trajet::Copier() // Algorithme : // Methode virtuelle donc va chercher la fonction Copier de la specialisation // correspondante. { return nullptr; } //----- Fin de Copier char* Trajet::GetDepart() const // Algorithme : // Retourne le depart d'une instance de TrajetSimple. { return m_depart; } //----- Fin de GetDepart char* Trajet::GetArrivee() const // Algorithme : // Retourne l'arrivee d'une instance de TrajetSimple. { return m_arrivee; } //----- Fin de GetArrivee //-------------------------------------------- Destructeur Trajet::~Trajet() // Algorithme : // Destructeur d'une instance de Trajet. { delete[] m_depart; delete[] m_arrivee; #ifdef MAP cout << "Appel au destructeur de <Trajet>" << endl; #endif } //----- Fin de ~TrajetSimple //------------------------------------------------------------------ PRIVE //----------------------------------------------------- Methodes protegees void Trajet::SetDepart(const char * depart) // Algorithme : // Modifie l'attribut m_depart par le parametre formel. { int lg = strlen(depart); if (m_depart != nullptr) delete[] m_depart; m_depart = new char[lg + 1]; m_depart = strcpy(m_depart, depart); } //----- Fin de SetDepart void Trajet::SetArrivee(const char * arrivee) // Algorithme : // Modifie l'attribut m_arrivee par le parametre formel. { int lg = strlen(arrivee); if (m_arrivee != nullptr)delete[] m_arrivee; m_arrivee = new char[lg + 1]; m_arrivee = strcpy(m_arrivee, arrivee); } //----- Fin de SetArrivee //-------------------------------------------- Constructeurs Trajet::Trajet(const char* depart, const char* arrivee) // Algorithme : // Constructeur qui prend comme argument un depart, une arrivee. { int lg = strlen(depart); m_depart = new char[lg + 1]; m_depart = strcpy(m_depart, depart); lg = strlen(arrivee); m_arrivee = new char[lg + 1]; m_arrivee = strcpy(m_arrivee, arrivee); #ifdef MAP cout << "Appel au constructeur de <Trajet>" << endl; #endif } //----- Fin de Trajet (constructeur) Trajet::Trajet(Trajet const& model) // Algorithme : // Constructeur par copie qui... copie une reference d'un Trajet donne // en parametre. { m_arrivee = model.m_arrivee; m_depart = model.m_depart; #ifdef MAP cout << "Appel au constructeur par copie de <Trajet>" << endl; #endif } //----- Fin de Trajet (constructeur de copie)
true
922f2bd36dcfc87183f1289ebb5c8a58c22e1d50
C++
GabeOchieng/ggnn.tensorflow
/program_data/PKU_raw/88/873.c
UTF-8
215
2.921875
3
[]
no_license
void main() { char str[32]; gets(str); char *p=str; int i; for(i=0;*(p+i)!='\0';i++) { if(*(p+i)>='0'&&*(p+i)<='9')putchar(*(p+i)); else if(*(p+i-1)>='0'&&*(p+i-1)<='9')putchar('\n'); } }
true
7baab54295ac7d56ace10fbe52f76acac20b0aba
C++
Saman-Ahmari/CIS
/Hmwk/Assignment_3/Gaddis_9thEd_Chap4_Prob12_BankCharges/main.cpp
UTF-8
1,960
3.078125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp * Author: samanahmari * * Created on March 14, 2019, 8:22 PM */ #include <iostream> #include <iomanip> using namespace std; int main() { float balance, fees, m_fee, lb_fee, n_bal; int checks; cout << "Monthly Bank Fees" << endl; cout << "Input Current Bank Balance and Number of Checks" << endl; cin >> balance >> checks; if (balance < .01) { cout << "URGENT: The Account is Overdrawn" <<endl; } cout << "Balance $" << setw(9) << setprecision(2) << fixed << balance << endl; m_fee = 10.00; if (checks <20) { fees = checks * .20; cout << "Check Fee $" << setw(9)<< setprecision(2) << fixed << fees << endl; } if (checks>19 && checks <40) { fees = checks * .08; cout << "Check Fee $" << setw(9)<< setprecision(2) << fixed << fees << endl; } if (checks>39 && checks<60) { fees = checks * .06; cout << "Check Fee $" << setw(9)<< setprecision(2) << fixed << fees << endl; } if (checks >= 60) { fees = checks * .04; cout << "Check Fee $" << setw(9)<< setprecision(2) << fixed << fees << endl; } cout << "Monthly Fee $" << setw(9)<< setprecision(2) << fixed << m_fee << endl; if (balance < 400.00) { lb_fee = 15.00; cout << "Low Balance $" << setw(9)<< setprecision(2) << fixed << lb_fee << endl; } else if (balance >= 400) { lb_fee = 0.00; cout << "Low Balance $" << setw(9)<< setprecision(2) << fixed << lb_fee << endl; } n_bal = balance - lb_fee - m_fee - fees; cout << "New Balance $" << setw(9)<< setprecision(2) << fixed << n_bal; return 0; }
true
7a26252db03db982efd511abb6571a865ad2c492
C++
VladislavKuzevanov/cpp_spring_2019
/05/ping_pong_block.cpp
UTF-8
697
3.15625
3
[]
no_license
#include <iostream> #include <thread> #include <condition_variable> const int n = 500000; int amount_in_process = 1; std::mutex mtx; std::condition_variable c_v; void print1() { for (int i = 0; i < n; i++) { std::unique_lock<std::mutex> lock(mtx); c_v.wait(lock, []() {return amount_in_process > 0; }); printf("ping\n"); --amount_in_process; c_v.notify_one(); } } void print2() { for (int i = 0; i < n; i++) { std::unique_lock<std::mutex> lock(mtx); c_v.wait(lock, []() {return amount_in_process == 0; }); printf("pong\n"); ++amount_in_process; c_v.notify_one(); } } int main() { std::thread th1(print1); std::thread th2(print2); th1.join(); th2.join(); return 0; }
true
3beb76fdbe72f59b3326437b655a0673ed9db6cc
C++
ThomasCLee/funnyvale
/hackabot_nano/Tutorial4_receving_message_over_bluetooth/Tutorial4_receving_message_over_bluetooth.ino
UTF-8
3,280
2.921875
3
[]
no_license
/*************************************************************************************************** * This sample code is designed for Hackabot Nano (Arduino Compatible Robotic Kit) * * Tutorial 4: * In this example, the robot receives commands through bluetooth. It moves forward, backward, * left, right or stops based on the command received. * * Please refer to tutorial 3 and the following article on how to connect bluetooth module: * http://hackarobot.com/arduino-bluetooth-example-tutorial-1/ * * For more information about Hackabot Nano, please check out our web site: * http://www.hackarobot.com * * Comments, questions? Please check out our Google+ community: * https://plus.google.com/u/0/communities/111064186308711245928 * **************************************************************************************************/ // pins controller motors #define motor1_pos 3 #define motor1_neg 10 #define motor2_pos 6 #define motor2_neg 9 #define motor_en A2 #define actionTime 300 // move left,right,forward,backward for 300ms void setup() { Serial.begin(9600); // assmes that bluetooth module is connected. setupMotor(); } void loop() { int ch; if (Serial.available()) { ch=Serial.read(); switch(ch) { case 'f': robotForward(actionTime); robotStop(actionTime); break; case 'b': robotBackward(actionTime); robotStop(actionTime); break; case 'l': robotLeft(actionTime); robotStop(actionTime); break; case 'r': robotRight(actionTime); robotStop(actionTime); break; case 's': robotStop(actionTime); break; } } } void setupMotor() { pinMode(motor1_pos,OUTPUT); pinMode(motor1_neg,OUTPUT); pinMode(motor2_pos,OUTPUT); pinMode(motor2_neg,OUTPUT); pinMode(motor_en,OUTPUT); enableMotor(); robotStop(50); } //----------------------------------------------------------------------------------------------------- // motor //----------------------------------------------------------------------------------------------------- void enableMotor() { //Turn on the motor driver chip : L293D digitalWrite(motor_en, HIGH); } void disableMotor() { //Turn off the motor driver chip : L293D digitalWrite(motor_en, LOW); } void robotStop(int ms){ digitalWrite(motor1_pos, LOW); digitalWrite(motor1_neg, LOW); digitalWrite(motor2_pos, LOW); digitalWrite(motor2_neg, LOW); delay(ms); } void robotForward(int ms){ digitalWrite(motor1_pos, HIGH); digitalWrite(motor1_neg, LOW); digitalWrite(motor2_pos, HIGH); digitalWrite(motor2_neg, LOW); delay(ms); } void robotBackward(int ms){ digitalWrite(motor1_pos, LOW); digitalWrite(motor1_neg, HIGH); digitalWrite(motor2_pos, LOW); digitalWrite(motor2_neg, HIGH); delay(ms); } void robotRight(int ms){ digitalWrite(motor1_pos, LOW); digitalWrite(motor1_neg, HIGH); digitalWrite(motor2_pos, HIGH); digitalWrite(motor2_neg, LOW); delay(ms); } void robotLeft(int ms){ digitalWrite(motor1_pos, HIGH); digitalWrite(motor1_neg, LOW); digitalWrite(motor2_pos, LOW); digitalWrite(motor2_neg, HIGH); delay(ms); }
true
74b44179d5a72b413c20ee47ea5b919e7e594e0e
C++
fancyGenTatsu/HOMEWORK
/今天星期几.cpp
UTF-8
1,026
2.59375
3
[]
no_license
#include <stdio.h> int main() { int year,month,day; int tempmonth,yearday; int week,weekday; int sum=0; int tag=0; scanf("%d-%d-%d",&year,&month,&day); tag =( year - 1900 )/4; sum=(year-1900)*365 + tag; tempmonth = month - 1; yearday = 0; switch(tempmonth) { case 12:yearday+=31; case 11:yearday+=30; case 10:yearday+=31; case 9:yearday+=30; case 8:yearday+=31; case 7:yearday+=31; case 6:yearday+=30; case 5:yearday+=31; case 4:yearday+=30; case 3:yearday+=31; case 2:yearday+=28; case 1:yearday+=31; } yearday = yearday+day; if ((year-190)%4==0 && month > 2) { yearday+=1; } sum=sum+yearday; weekday = (sum-1) % 7+1; if(weekday==1) printf("Monday\n"); if(weekday==2) printf("Tuesday\n"); if(weekday==3) printf("Wendesday\n"); if(weekday==4) printf("Thursday\n"); if(weekday==5) printf("Friday\n"); if(weekday==6) printf("Saturday\n"); if(weekday==7) printf("Sunday\n"); return 0; }
true
e6bd1231baf1978c3e16064759dcc7d7c46e4138
C++
iisword/copyright-infringement-elementals
/Game Project/Elementals/Elementals/source/Renderer/D3DObjects.cpp
UTF-8
1,358
2.515625
3
[]
no_license
#include "D3DObjects.h" #include "Renderer.h" D3DObject::D3DObject(void) { tempObj = nullptr; XMStoreFloat4x4(m_XMmatrix.GetMatrix(), XMMatrixIdentity()); copy = false; shader = nullptr; } D3DObject::~D3DObject(void) { if(tempObj && !copy && tempObj->Size()) { delete tempObj; } tempObj = nullptr; } void D3DObject::FileReader(const char * modelTexLoc) { tempObj = new OBJLoader; tempObj->FileReader(modelTexLoc); } // Assignment operator D3DObject& D3DObject::operator=(const D3DObject& _RHS) { // Make sure we aren't trying to copy ourself if(this != &_RHS) { m_XMmatrix = _RHS.m_XMmatrix; tempObj = _RHS.tempObj; buffer = _RHS.buffer; uav = _RHS.uav; srv = _RHS.srv; matrixBuffer = _RHS.matrixBuffer; copy = true; } // Return our updated self return *this; } void D3DObject::SetMatrixToIdentity() { XMStoreFloat4x4(m_XMmatrix.GetMatrix(), XMMatrixIdentity()); } void D3DObject::SetMatrix(XMFLOAT4X4 inMat) { m_XMmatrix.SetMatrix(inMat); } XMFLOAT4X4 * D3DObject::GetMatrix() { return m_XMmatrix.GetMatrix(); } CMatrix * D3DObject::GetCMatrix() { return &m_XMmatrix; } XMFLOAT3 D3DObject::GetPosition() { return m_XMmatrix.GetPosition(); } void D3DObject::SetPosition(XMFLOAT3 posIn) { m_XMmatrix.SetPosition(posIn); } XMFLOAT3 D3DObject::GetForward() { return m_XMmatrix.GetForward(); }
true
0be650d8062b547706a82268a42dd390bae0fb6b
C++
TacianasdOliveira/ExerciciosCPlusPlus
/Pacote-Download/Lista2/lista6_ex6_taciana_oliveira.cpp
UTF-8
786
3.203125
3
[ "MIT" ]
permissive
#include <iostream> #include <cmath> #include <Windows.h>// usei para imprimir os acentos using namespace std; namespace maria { int idade= 18; float cre= 8.3; void incrementar_idade() {idade++;} } namespace jose { int idade=21; float cre= 4.3; } namespace taciana { int idade= 28; float cre= 5.35; void incrementar_idade() {idade++;} void incrementar_cre() {cre++;} } int main(){ SetConsoleOutputCP(CP_UTF8); cout<<"Idade da Taciana: "<< taciana::idade <<" anos"<< endl; taciana::incrementar_idade(); cout<< "Idade da Taciana encrementada: "<<taciana::idade <<" anos"<< endl; cout<< "CRE da Taciana: "<<taciana::cre<<endl; taciana::incrementar_cre(); cout<<" CRE TACIANA ENCREMENTADO: "<<taciana::cre<<endl; return 0; }
true
3048125f959afa2ee38491cf051d7f8b923e6268
C++
BrianArch96/QT_Game
/QtZelda-master/mainwindow.cpp
UTF-8
1,733
2.609375
3
[]
no_license
#include "mainwindow.h" #include "ui_mainwindow.h" #include "gameframe.h" #include "input.h" #include "gametextbox.h" #include <QGridLayout> #include <iostream> #include <map> #include <QMediaPlayer> #include "globals.h" #include "inventoryframe.h" #include <QSound> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); GameTextbox *tb = new GameTextbox; ui->gridLayout->setRowStretch(1, 2); ui->gridLayout->setRowStretch(3, 1); ui->gridLayout->setColumnStretch(1, 2); ui->gridLayout->setColumnStretch(2, 2); ui->gridLayout->addWidget(new inventoryframe, 0, 0, 4, 1); // Matthew's inventory goes here ui->gridLayout->addWidget(new GameFrame, 0, 1, 3, 2); // Shane's game frame goes here ui->gridLayout->addWidget(tb, 3, 1, 1, 2); // Brian's textbox goes here setWindowTitle("The legend of Ysolda"); globals::textbox = tb; globals::textbox->addText("Welcome to the Legend of Ysolda! Use the WASD " "keys to move around, and the `E` key to interact with the environment. " "Try talking to that yellow guy over there"); } MainWindow::~MainWindow() { delete ui; } void MainWindow::keyPressEvent(QKeyEvent *event) { QMainWindow::keyPressEvent(event); Input::getInstance()->setKey(event->key(), true); if (!event->isAutoRepeat()) Input::getInstance()->setKeyJustPressed(event->key(), true); } void MainWindow::keyReleaseEvent(QKeyEvent *event) { QMainWindow::keyReleaseEvent(event); Input::getInstance()->setKey(event->key(), false); Input::getInstance()->setKeyJustPressed(event->key(), false); std::cout << width() << ", " << height() << std::endl; }
true
a39272bd1137e388b3eb4b7c62abeb737f9df33c
C++
PineappleCompote/EE312_Cheaters
/LinkedList.cpp
UTF-8
1,186
3.671875
4
[]
no_license
/* LinkedList.cpp * Methods for the Linked List class used for separate chaining * Created by Dilya Anvarbekova and Teddy Hsieh * Last Modified: 05/06/2020 */ #include <iostream> #include <string> #include "LinkedList.h" using namespace std; Node *LinkedList::getHead() { return head; } Node* LinkedList::getTail() { return tail; } bool LinkedList::isEmpty() { return head == NULL; } void LinkedList::push(int data) { Node* temp = new Node; temp->data = data; temp->next = NULL; if(isEmpty()){ head = temp; tail = temp; } else{ temp->next = head; head = temp; } size += 1; } void LinkedList::showList() { if(isEmpty()){ cout << "EMPTY" << endl; } else{ Node *curr = head; while (curr != NULL){ cout << curr->data << " "; curr = curr->next; } cout << endl; } } int LinkedList::getSize() { return size; } void LinkedList::deleteList() { Node *current = getHead(); Node *next; while (current != NULL) { next = current->next; free(current); current = next; } } LinkedList::~LinkedList(){ }
true
5d9c02f18c4d2eb49ec45e617c0589694c1482b6
C++
IvanIsCoding/OlympiadSolutions
/beecrowd/2089.cpp
UTF-8
1,070
2.546875
3
[]
no_license
// Ivan Carvalho // Solution to https://www.beecrowd.com.br/judge/problems/view/2089 #include <cstdio> #include <unordered_map> #define MAXN 100001 #define MAXM 1001 #define gc getchar_unlocked void getint(int &x) { register int c = gc(); x = 0; for (; (c < 48 || c > 57); c = gc()) ; for (; c > 47 && c < 58; c = gc()) { x = (x << 1) + (x << 3) + c - 48; } } using namespace std; unordered_map<int, int> dp[MAXN]; int vetor[MAXM], n, m; int possivel(int soma, int davez) { if (soma == 0) return dp[soma][davez] = 1; if (soma < 0 || davez <= 0) return 0; if (dp[soma].count(davez)) return dp[soma][davez]; return dp[soma][davez] = possivel(soma - vetor[davez], davez - 1) || possivel(soma, davez - 1); } int main() { while (true) { getint(n); getint(m); if (n == 0 && m == 0) break; for (int i = 0; i <= n; i++) dp[i].clear(); for (int i = 1; i <= m; i++) getint(vetor[i]); printf("%s\n", possivel(n, m) ? "sim" : "nao"); } return 0; }
true
728b602cce17cdd3243b242c1368a81f0d20312c
C++
marco-c/gecko-dev-comments-removed
/third_party/libwebrtc/rtc_base/numerics/moving_percentile_filter_unittest.cc
UTF-8
2,621
2.84375
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include "rtc_base/numerics/moving_percentile_filter.h" #include <stdint.h> #include <algorithm> #include "test/gtest.h" namespace webrtc { TEST(MovingPercentileFilter, Percentile25ReturnsMovingPercentile25WithWindow4) { MovingPercentileFilter<int> perc25(0.25f, 4); const int64_t kSamples[10] = {1, 2, 3, 4, 4, 4, 5, 6, 7, 8}; const int64_t kExpectedFilteredValues[10] = {1, 1, 1, 1, 2, 3, 4, 4, 4, 5}; for (size_t i = 0; i < 10; ++i) { perc25.Insert(kSamples[i]); EXPECT_EQ(kExpectedFilteredValues[i], perc25.GetFilteredValue()); EXPECT_EQ(std::min<size_t>(i + 1, 4), perc25.GetNumberOfSamplesStored()); } } TEST(MovingPercentileFilter, Percentile90ReturnsMovingPercentile67WithWindow4) { MovingPercentileFilter<int> perc67(0.67f, 4); MovingPercentileFilter<int> perc90(0.9f, 4); const int64_t kSamples[8] = {1, 10, 1, 9, 1, 10, 1, 8}; const int64_t kExpectedFilteredValues[9] = {1, 1, 1, 9, 9, 9, 9, 8}; for (size_t i = 0; i < 8; ++i) { perc67.Insert(kSamples[i]); perc90.Insert(kSamples[i]); EXPECT_EQ(kExpectedFilteredValues[i], perc67.GetFilteredValue()); EXPECT_EQ(kExpectedFilteredValues[i], perc90.GetFilteredValue()); } } TEST(MovingMedianFilterTest, ProcessesNoSamples) { MovingMedianFilter<int> filter(2); EXPECT_EQ(0, filter.GetFilteredValue()); EXPECT_EQ(0u, filter.GetNumberOfSamplesStored()); } TEST(MovingMedianFilterTest, ReturnsMovingMedianWindow5) { MovingMedianFilter<int> filter(5); const int64_t kSamples[5] = {1, 5, 2, 3, 4}; const int64_t kExpectedFilteredValues[5] = {1, 1, 2, 2, 3}; for (size_t i = 0; i < 5; ++i) { filter.Insert(kSamples[i]); EXPECT_EQ(kExpectedFilteredValues[i], filter.GetFilteredValue()); EXPECT_EQ(i + 1, filter.GetNumberOfSamplesStored()); } } TEST(MovingMedianFilterTest, ReturnsMovingMedianWindow3) { MovingMedianFilter<int> filter(3); const int64_t kSamples[5] = {1, 5, 2, 3, 4}; const int64_t kExpectedFilteredValues[5] = {1, 1, 2, 3, 3}; for (int i = 0; i < 5; ++i) { filter.Insert(kSamples[i]); EXPECT_EQ(kExpectedFilteredValues[i], filter.GetFilteredValue()); EXPECT_EQ(std::min<size_t>(i + 1, 3), filter.GetNumberOfSamplesStored()); } } TEST(MovingMedianFilterTest, ReturnsMovingMedianWindow1) { MovingMedianFilter<int> filter(1); const int64_t kSamples[5] = {1, 5, 2, 3, 4}; const int64_t kExpectedFilteredValues[5] = {1, 5, 2, 3, 4}; for (int i = 0; i < 5; ++i) { filter.Insert(kSamples[i]); EXPECT_EQ(kExpectedFilteredValues[i], filter.GetFilteredValue()); EXPECT_EQ(1u, filter.GetNumberOfSamplesStored()); } } }
true
74e5c7a69bf357575a9e23be0511b47a512b82a9
C++
bird11329/TwoTools
/common_tools.cc
UTF-8
30,885
2.6875
3
[]
no_license
// ************************************************************************* // // File: common_tools.cc // Contents: common functions that both tools will use // Classes: // MySQLInterface // BaseParser::ColumnAcquirer // BaseParser // RecordsHolder // ************************************************************************* // #include "common_tools.h" #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #include <algorithm> #include <functional> #include <vector> #include <string> #include <iostream> #include <fstream> #include <cstdlib> // For getenv using namespace std; const char* const INSTALLATION_FOLDER = "---"; const char* const CONFIGURATION_FOLDER = "./"; // ===> MySQLInterface <=== // MySQL interface. Handles all MySQL query // Constructor: initialize variables and connect to database MySQLInterface::MySQLInterface(): rows(-1), fields(-1), errorNum(0), errorInfo("ok"), result(0) { mysql_init(&mysqlInstance); } // Destructor (close the connection) MySQLInterface::~MySQLInterface() { //cerr<<"Closing MYSQL connection."<<endl; closeMySQL(); //cerr<<"MySQLInterface destructed."<<endl; } // Connect to MYSQL server // Need 5 arguments (but last 4 with default values): // 1. server (IP address) // 2. Account to log in the server // 3. Password of the account // 4. Database to use // 5. Port // Returns true if connected, false otherwise bool MySQLInterface::connectMySQL(const char* server, const char* username, const char* password, const char* database, int port) { if(::mysql_real_connect(&mysqlInstance,server,username,password,database,port,0,0)) return true; else { errorIntoMySQL(); return false; } } // Data retriever // Need two arguments: // 1. MySQL query // 2. vector of vector of string. Saves what is retrieved from database // Returns true if nothing wrong bool MySQLInterface::GetDataFromDB(const string& queryStr, vector<vector<string> >& data) { // Empty string check if(queryStr.empty()) { cerr<<"No command to query."<<endl; return false; } else if(!TestingQueryCommand(queryStr, "select")) { // If <queryStr> doesn't start with "select" cerr << "Illegal query: command shall start with \"insert\"." << endl; return false; } // Real query int res = ::mysql_real_query(&mysqlInstance,queryStr.c_str(),queryStr.size()); if(res) { cerr<<"Query |\033[3m"<<queryStr<<"\033[0m| failed."<<endl; this->errorIntoMySQL(); return false; } // Clear the buffer here ClearData(); // Retrieve info from database result = ::mysql_store_result(&mysqlInstance); if(!result) { cerr<<"No result retrieved from database."<<endl; return false; } // Update the number of rows and fields of this query rows = ::mysql_num_rows(result); fields = ::mysql_num_fields(result); //cerr<<rows<<" rows in set, each with "<<fields<<" columns."<<endl; // Remove the content of outer container if any if(data.size()) { // cerr<<"Container not empty. Clearing them..."<<endl; int NSize = data.size(); for(int i=0;i<NSize;++i) data[i].clear(); data.clear(); // cerr<<"All "<<NSize<<" vector"<<(NSize>1?"s ":" ")<<"cleared."<<endl; } // Reserve enough space data.reserve(rows); // Redirect info from within this object to the outer container, i.e., <data> for(int i=0;i<rows;++i) { MYSQL_ROW line = ::mysql_fetch_row(result); if(!line) { cerr<<"No. "<<i+1<<" row is empty."<<endl; continue; } vector<string> linedata; linedata.reserve(fields); for(int i=0;i<fields;i++) { if(line[i]) { string temp = line[i]; linedata.push_back(temp); } else { linedata.push_back(""); } } data.push_back(linedata); } return true; } // Error messages void MySQLInterface::errorIntoMySQL() { errorNum = ::mysql_errno(&mysqlInstance); errorInfo = ::mysql_error(&mysqlInstance); cerr<<"\033[31mError INFO: "<<errorInfo<<"\033[0m"<<endl; cerr<<"\033[31mError code: "<<errorNum<<"\033[0m"<<endl; } // Close the connection void MySQLInterface::closeMySQL() { ClearData(); ::mysql_close(&mysqlInstance); ::mysql_library_end(); } // Displaying data from MySQL in MySQL's way // Need 2 arguments: // 1: vector of vector of string of contents from mysql query. Inner vectors // shall have identical number of elements. // 2: name of columns in the query. Can be empty, and thus not displayed. void MySQLInterface::PrintingValues(const vector<vector<string> >& data, const vector<string>& names_of_column) { int Length = data.size(); if(0 == Length) { cout<<"No value to print."<<endl; return; } int NSize = data.front().size(); // Maximal width for each column. Used later. vector<int> width(NSize, 0); // Find the width of each column (maximal width of each row plus 2) if(!names_of_column.empty()) { // If names of columns are given if(names_of_column.size() != NSize) { // Names and values don't match cerr<<"\033[31mFATAL ERROR!!! Names of columns and their values don't match!!!\033[0m"<<endl; cerr<<"\033[31mNumber of columns: "<<names_of_column.size()<<" that of values: "<<NSize<<"\033[0m"<<endl; throw runtime_error("Unmatched columns"); } // Initiate the width by each title for(int i=0;i<NSize;++i) width[i] = names_of_column[i].size(); } //cout<<"Size of one set: "<<NSize<<endl; // Loop every record and find the maximal width for each column for(int i=0;i<Length;++i) { const vector<string>& one_set = data.at(i); int one_set_size = one_set.size(); if(one_set_size != NSize) { cout<<"\033[33mFATAL ERROR... Size of No. "<<i+1<<" ("<<one_set_size<<") differs from that of the first ("<<NSize<<")..."<<endl; throw; } for(int j=0;j<one_set_size;++j) { const string& one_element = one_set[j]; if(one_element.empty() && 4 < width[j]) width[j] = 4; else if(one_element.size() > width[j]) width[j] = one_element.size(); } } // 1 for a whitespace, leading one. The tailing one is added later for(int i=0;i<NSize;++i) width[i] += 1; string concatenation("+"); // Border vector<string> on_screen; // Content to be displayed; serves as a buffer // Length: one line for each set // 2: border on the top and bottom // names_of_column staff: top border and names of columns on_screen.reserve(Length+2+(int(!names_of_column.empty()))*2); // Prepare for the border for(int i=0;i<NSize;++i) { // This 1 is the tailing one concatenation.append(width[i]+1, '-'); concatenation.append("+"); } // Add top border on_screen.push_back(concatenation); if(!names_of_column.empty()) { // Add titles and a second border on_screen.push_back("| "); for(int i=0;i<NSize;++i) { on_screen[1] += names_of_column[i]; on_screen[1].append(width[i]-names_of_column[i].size(), ' '); on_screen[1].append("| "); } on_screen.push_back(concatenation); } // Join each set and insert into the buffer for(int i=0;i<Length;++i) { string one_line("| "); const vector<string>& one_set = data[i]; for(int j=0;j<NSize;++j) { string one_element = one_set[j]; // For empty elements if(one_element.empty()) one_element = "NULL"; one_line += one_element; one_line.append(width[j]-one_element.size(), ' '); one_line.append("| "); } on_screen.push_back(one_line); } // Add bottom border on_screen.push_back(concatenation); // Displaying Length = on_screen.size(); for(int i=0;i<Length;++i) cout<<on_screen[i]<<endl; Length = data.size(); cout << Length << (Length>1?" rows":" row") << " in set." << endl; } // Print name of columns of last query (selection), but only their names void MySQLInterface::PrintNameOfColumns() const { vector<string> names; if(!this->GenerateNameOfColumns(names)) { cerr<<"No names of columns found."<<endl; return; } int NNames = names.size(); if(NNames != fields) { cerr<<"Warning... "<<NNames<<" columns don't match that acuqired before ("<<fields<<")..."<<endl; } cerr<<"Printing "<<NNames<<" columns of this query."<<endl; for(int i=0;i<NNames;++i) { const string& one_name = names.at(i); if(one_name.empty()) cerr<<"\033[31mColumn "<<i+1<<" is unavailable.\033[0m"<<endl; else cerr<<"Column "<<i+1<<": "<<one_name<<endl; } cerr<<"Columns printed.\n"<<endl; } // Retrieve names of columns of last selection bool MySQLInterface::GetNameOfColumns(vector<string>& names) const { return this->GenerateNameOfColumns(names); } // Deduce names of columns of last selection bool MySQLInterface::GenerateNameOfColumns(vector<string>& names) const { names.clear(); if(!result) { // No result. cerr<<"Query failed."<<endl; return false; } if(-1 == fields) { // No columns acquired, due to no query at all or failed queries, etc. cerr<<"No column acquired."<<endl; return false; } // Fetch the names of columns for(int i=0;i<fields;i++) { MYSQL_FIELD *fd = ::mysql_fetch_field(result); if(fd) names.push_back(fd->name); else names.push_back(""); } return bool(names.size()); } // Performing non-selection query of MySQL // Need 1 argument: // 1. MySQL query command // (Not suggested to be called directly) bool MySQLInterface::Non_Select_Query(const string& queryStr) { if(queryStr.empty()) { cerr << "Empty non-select query command..." << endl; return false; } int result = ::mysql_real_query(&mysqlInstance, queryStr.c_str(), queryStr.size()); if(result) { cerr << "Error code: " << result << endl; return false; } rows = ::mysql_affected_rows(&mysqlInstance); return true; } // Called by non-select query; testing if a query command matches // Need 2 arguments: // 1. Query command // 2. Expected type of command, a word, that shall be found in the command // Returns true if matches, false otherwise bool MySQLInterface::TestingQueryCommand(const string& queryStr, const string& expected) { if(queryStr.empty()) { cerr << "Empty command..." << endl; return false; } string to_split(queryStr); if(';' == queryStr[0]) { // To remove leading semicolon(s) in the <queryStr> const char* command = queryStr.c_str(); int counts = 0; while(';' == *command) { ++command; ++counts; } to_split = to_split.substr(counts); boost::trim_left(to_split); } // Use whitespace to split <queryStr> (no leading ";" version) vector<string> holder; boost::split(holder, to_split, boost::is_space()); if(holder.empty()) return false; if(expected == boost::to_lower_copy(holder[0])) return true; else return false; } bool MySQLInterface::Insert(const string& queryStr) { if(!TestingQueryCommand(queryStr, "insert")) { cerr << "Illegal query: command shall start with \"insert\"." << endl; return false; } return Non_Select_Query(queryStr); } bool MySQLInterface::Update(const string& queryStr) { if(!TestingQueryCommand(queryStr, "update")) { cerr << "Illegal query: command shall start with \"update\"." << endl; return false; } return Non_Select_Query(queryStr); } bool MySQLInterface::Delete(const string& queryStr) { if(!TestingQueryCommand(queryStr, "delete")) { cerr << "Illegal query: command shall start with \"delete\"." << endl; return false; } return Non_Select_Query(queryStr); } // Direct query. Should be used only when necessary bool MySQLInterface::DirectQuery(const string& queryStr) { cerr << "Warning... Direct query (no result to fetch) called..." << endl; return Non_Select_Query(queryStr); } // ===> BaseParser::ColumnAcquirer <=== // Prepare the structure of table for BaseParser // Constructor BaseParser::ColumnAcquirer::ColumnAcquirer() { names.reserve(32); levels.reserve(16); } // Retrieve the structure of the target table from database // Need 4 arguments: // 1. server // 2. database // 3. port // 4. name of table // Returns true if retrieved, false otherwise bool BaseParser::ColumnAcquirer::Acquire(const string& server, const string& database, int port, const string& table) { // Uses default account to log in if(!connectMySQL(server.c_str(), "anonymous", "testing", database.c_str(), port)) { cerr << "Error connecting while getting columns..." << endl; return false; } if(table.empty()) { cout << "NULL TABLE..." << endl; return false; } string describing("describe "); describing.append(table); // describing: describe <table name> vector<vector<string> > data; if(!GetDataFromDB(describing, data)) { cout << "Can't retrieve the structure..." << endl; return false; } else if(data[0].empty()) { cout << "Nothing available for the table " << table << endl; return false; } else if(data[0].size() < 4) { cout << "Error element scale |" << data[0].size() << "|." << endl; return false; } size_t s = data.size(); names.resize(s*2); // [0] - [s-1]: the name of columns // [s] - [s+s-1]: the type of the columns map<string, size_t> index_of_column; for(size_t i=0;i<s;++i) { names[i].assign(data[i][0]); names[i+s].assign(data[i][1]); data[i].clear(); index_of_column.insert(make_pair(data[i][0], i)); } // Clearing the buffer. Prepare the object for printing levels from comments // of each column. data.clear(); ClearData(); describing.clear(); describing.assign("select column_name Name, column_comment comment from information_schema.columns where table_name = '"); describing.append(table); describing.append("' and table_schema = '"); describing.append(database); describing.append("'"); if(!GetDataFromDB(describing, data)) { cerr << "Can't retrieve printing levels..." << endl; return false; } else if(data.size() != s) { cerr << "Warning... Size of printing levels doesn't match (" << data.size() << ", " << s << ")..." << endl; return false; } for(size_t i=0;i<s;++i) { const vector<string>& one_column = data[i]; if(index_of_column.end() == index_of_column.find(one_column[0])) { cout << "Warning... No " << one_column[0] << " found..." << endl; continue; } string level = one_column[1]; // Comment of a column, if multiple properties, uses "|" to separate them if(string::npos != level.find("|")) { vector<string> levels; boost::split(levels, level, boost::is_any_of("|")); int found = -1; for(int i=0;i<levels.size();++i) { // Hint of printing level is either "PL" or "PrintingLevel" if(string::npos == levels[i].find("PL") && string::npos == levels[i].find("PrintingLevel")) continue; if(-1 != found) cout << "Warning... Multiple PrintingLevel detected... Overwriting (" << found << " => " << i << ")..." << endl; found = i; } if(-1 == found) { cout << "Warning... Unrecognized printing level for |" << one_column[0] << "|: " << level << endl; continue; } else level.assign(levels[found]); } if(string::npos != level.find("PL")) level.erase(0, level.find("PL") + 2); else if(string::npos != level.find("PrintingLevel")) level.erase(0, level.find("PrintingLevel") + 13); else { cout << "Warning... Unrecognized printing level for " << one_column[0] << ": " << level << endl; continue; } levels.push_back(atoi(level.c_str())); } return true; } // Deliver structure of table // Need two arguments: // 1. outer container of names of columns // 2. outer container of printing levels of each column bool BaseParser::ColumnAcquirer::Deliver(vector<string>& o_names, vector<int>& o_levels) const { if(!o_names.empty()) o_names.clear(); if(!o_levels.empty()) o_levels.clear(); size_t scale = names.size() / 2; if(0 == scale) { cout << "Nothing to transfer..." << endl; return false; } o_names.resize(scale); o_levels.resize(scale); for(size_t i=0;i<scale;++i) { o_names[i].assign(names[i]); o_levels[i] = levels[i]; } if(o_names.empty()) { cerr << "Error! No column retrieved." << endl; return false; } else return true; } // ===> BaseParser <=== // Base class of SelectionTool and OperationTool // Constructor BaseParser::BaseParser(): default_account("anonymous"), // Default account default_password("testing") // Default password { port = 3306; number_of_columns = 0; } // Destructor BaseParser::~BaseParser() {} // General components assembler and some common properties both tools share // Need 1 argument: // 1. option descriptions (BOOST_PROGRAM_OPTIONS) void BaseParser::GeneralAssembler(boost::program_options::options_description& opts) const throw(runtime_error) { if(!opts.options().empty()) { cerr << "FATAL ERROR!!!" << endl; cerr << "There are option(s) in the description:" << endl; cerr << opts << endl; cerr << "This method shall be called at first!" << endl; throw runtime_error("MYSQL FAILED"); } using boost::program_options::value; // Add common options opts.add_options() ("server,S", value<string>(), "Server of database") ("user,U", value<string>()->default_value(default_account), "User account") ("passwd,W", value<string>()->default_value(default_password), "Password for that user to login") ("database,D", value<string>(), "Name of Database") ("port,P", value<int>()->default_value(3306), "Port of connection") ("options,o", value<string>(), "Options for the query") ("type,T", value<string>(), "Type of records concerned") ("help,h", "Print help message and exit") ("manual,m", "Print detailed help message and exit") ; } // Get general parameters that either tool will use // Need 2 argument: // 1. variables_map (BOOST_PROGRAM_OPTIONS) // 2. print level as priority (not used yet) void BaseParser::GetGeneralParameters(const boost::program_options::variables_map& v_map, int level) throw(runtime_error) { try { // To parse the configuration file if any if(v_map.count("options")) IngestOptions(v_map["options"].as<string>()); // Replace the default value of general parameters with real ones from // terminal arguments if it is given. for(int i=0;i<5;++i) { if(2 == i) continue; if(v_map.count(general_parameter_names[i])) general_parameters[i].assign(v_map[general_parameter_names[i]].as<string>()); } // Special reaction for password. A trivial password is used if none given. if(v_map.count(general_parameter_names[2])) { string password(v_map[general_parameter_names[2]].as<string>()); if(default_password != password) general_parameters[2].assign(password); } // But default password is trivial and should be acquired if(default_password == general_parameters[2]) InteractivePassword(); if(v_map.count("port")) port = v_map["port"].as<int>(); } catch(exception& e) { throw runtime_error(e.what()); } // Check if all general parameters are ready. for(int i=0;i<5;++i) { if(general_parameters[i].empty()) throw runtime_error(" unavailable " + general_parameter_names[i]); } // Checking for repulsive options string repulsive(ReplusiveOptions(v_map)); if(!repulsive.empty()) throw runtime_error(repulsive); try { PrepareColumns(); } catch(runtime_error& e) { throw; } } // Interactively take in the password void BaseParser::InteractivePassword() { cout << "Enter password:"; cout.flush(); string password; cin >> password; if(!password.empty() && default_password != password) general_parameters[2].assign(password); else general_parameters[2].clear(); } #include <netdb.h> #include <sys/socket.h> #include <arpa/inet.h> // Use DNS to convert the domain name of the server into its IP address void BaseParser::AcquiringRealServer() { if(general_parameters[0].empty()) { cerr << "No hint for server available..." << endl; return; } int expected = general_parameters[0][0] - '0'; if(0 <= expected && 3 > expected) // the first char is 0, 1 or 2: return; // all numbers assumed string ptr = general_parameters[0]; struct hostent *hptr = gethostbyname(ptr.c_str()); if(hptr == NULL) { cerr << "gethostbyname error: |" << ptr << "|." << endl; return; } if(AF_INET == hptr->h_addrtype || AF_INET6 == hptr->h_addrtype) { char str[32] = {0}; general_parameters[0].assign( inet_ntop(hptr->h_addrtype, hptr->h_addr, str, sizeof(str)) ); } else general_parameters[0].clear(); } // Parse the option file acquired by terminal arguments void BaseParser::IngestOptions(string option_file) { if(option_file.empty()) { cout << "NULL name for options..." << endl; return; } int open_state = GuessOptionFileName(option_file); if(NoSuchFile == open_state) { cerr << "Can't locate configuration file..." << endl; return; } else if(IllegalFile == open_state) { cout << "Can't open option file \"" << option_file << "\"..." << endl; return; } ifstream in(option_file.c_str()); if(!in.is_open()) { cout << "Can't open configuration file |" << option_file << "|..." << endl; return; } string line; int N_parameter_names = sizeof(general_parameter_names)/sizeof(general_parameter_names[0]); // Trying to ingest the configuration file. A line after another. while(getline(in, line)) { if(3 > line.size()) continue; if(string::npos == line.find("=")) continue; size_t equal = line.find("="); string options = line.substr(0, equal); boost::to_lower(options); int index = find(general_parameter_names, general_parameter_names+N_parameter_names, options) - general_parameter_names; if(N_parameter_names == index) continue; else if(5 == index) port = atoi(line.substr(equal+1).c_str()); else if(0 <= index && 5 > index) general_parameters[index] = line.substr(equal+1); else cout << "Error parsing " << line << ": (" << index << ", " << equal << ", " << options << ")." << endl; } } // Guess name of option file. // Returns 0 if valid name, non-0 otherwise. int BaseParser::GuessOptionFileName(string& option_file) const { // First, if option_file is good, returns directly. ifstream in(option_file.c_str()); if(in.is_open()) return SuccessfulAccess; string basename(option_file); if(string::npos != option_file.find("/")) { // Guessing option_file's path is unnecessary basename.erase(0, basename.find("/")+1); if(basename.empty()) return NoSuchFile; in.open(basename.c_str()); if(in.is_open()) { cout << "Configuration file in the current folder selected." << endl; option_file.assign(basename); return SuccessfulAccess; } } // Try to locate the option in one's HOME string new_option_file(getenv("HOME")); if(boost::ends_with(new_option_file, "/")) new_option_file.append("/"); new_option_file.append(basename); in.open(new_option_file.c_str()); if(in.is_open()) { cout << "Configuration file in HOME selected." << endl; option_file.assign(new_option_file); return SuccessfulAccess; } // Try to locate the option in the installation prefix string installation_folder(Configuration::GetInstance().InstallationFolder()); if(string::npos == installation_folder.find("---")) { new_option_file.assign(installation_folder); if(boost::ends_with(new_option_file, "/")) new_option_file.append("/"); new_option_file.append(basename); in.open(new_option_file.c_str()); if(in.is_open()) { cout << "Configuration file in installation folder selected." << endl; option_file.assign(new_option_file); return SuccessfulAccess; } } // Try to locate the option in ConfigurationFolder from Configuration new_option_file.assign(Configuration::GetInstance().ConfigurationFolder()); if(boost::ends_with(new_option_file, "/")) new_option_file.append("/"); new_option_file.append(basename); in.open(new_option_file.c_str()); if(in.is_open()) { cout << "Configuration file in installation folder selected." << endl; option_file.assign(new_option_file); return SuccessfulAccess; } return IllegalFile; } // Testing if replusive options co-exist // Need 1 argument: // 1. variables_map (BOOST_PROGRAM_OPTIONS) // Returns the replusive options given (empty string if none) string BaseParser::ReplusiveOptions(const boost::program_options::variables_map& v_map) { size_t N_repulsives = repulsive_options.size(); if(0 == N_repulsives) return ""; string repulsives; int counts = 0; for(size_t i=0;i<N_repulsives;i+=2) { if(v_map.count(repulsive_options[i]) && v_map.count(repulsive_options[i+1])) { repulsives.append("|"); repulsives.append(repulsive_options[i]); repulsives.append(" <==> "); repulsives.append(repulsive_options[i+1]); repulsives.append("|; "); ++counts; } } if(counts) { cout << counts << (1<counts?" pairs":" pair") << "Replusive options detected! " << endl; repulsives.erase(repulsives.size() - 2); } return repulsives; } // Preparation. Load columns, find names and levels. void BaseParser::PrepareColumns() throw(runtime_error) { // general_parameters[3]: database if(general_parameters[3].empty()) { cerr << "NO database to query..." << endl; throw runtime_error("NULL DATABASE"); } ColumnAcquirer tool; if(!tool.Acquire(general_parameters[0], general_parameters[3], port, general_parameters[4])) { cerr << "Can't load the columns..." << endl; throw runtime_error("NO COLUMN"); } // In the calling below, three arguments are all updated if(!tool.Deliver(name_of_columns, level_of_columns)) throw runtime_error("No column received"); // Update the value of number_of_columns number_of_columns = name_of_columns.size(); // In case of mismatch... if(level_of_columns.size() != number_of_columns) { ostringstream os; os << "Names and levels don't match: " << number_of_columns; os << " <===> " << level_of_columns.size(); throw runtime_error(os.str()); } } size_t BaseParser::N_Records() const { return 200; } // Retrieve names of columns // Need 2 arguments: // 1. outer container // 2. print level as priority (not used yet) void BaseParser::Columns(vector<string>& target, int level) const { if(!target.empty()) target.clear(); size_t scale = name_of_columns.size(); target.reserve(scale); if(0 == scale) return; for(size_t i=0;i<scale;++i) target.push_back(name_of_columns[i]); } // Common options const string BaseParser::general_parameter_names[] = { "server", "user", "passwd", "database", "type", "port" }; // ===> RecordsHolder <=== // Container of records // Constructor RecordsHolder::RecordsHolder(): records(), first_column(), number_of_columns(0), number_of_records(0), name_of_columns() {} // Ingest the common info for RecordsHolder from terminal via BaseParser bool RecordsHolder::Initialize(const BaseParser& parser) { if(parser.NotReady()) return false; Reserve(parser.N_Records()); parser.Columns(name_of_columns); number_of_columns = name_of_columns.size(); return true; } // Insert a record, elements of vector being each column void RecordsHolder::Insert(const vector<string>& record, int index_of_lfn) { if(record.empty()) { cerr << "NULL RECORD..." << endl; return; } else if(-1 == index_of_lfn) { cerr << "No index of LFN received..." << endl; return; } string token; // If index_of_lfn == -2, the caller of this method doesn't know where lfn is // so it requires a search locally. if(-2 == index_of_lfn) index_of_lfn = FindLFN(); // After the search, or if -1 is passed from outside, it means no lfn is // found. Use the first two aspects. if(-1 == index_of_lfn) { token.assign(record.front()); if(record.size() > 1) { token.append("|"); token.append(record[1]); } } else if(record.size() <= index_of_lfn) { // In case of invalid index of lfn cerr << "Invalid index of LFN received: " << index_of_lfn << " (0-" << record.size() << ")." << endl; return; } else token.assign(record[index_of_lfn]); if(first_column.end() != find(first_column.begin(), first_column.end(), token)) { // Inserted records are omitted. cerr << "This record has been inserted..." << endl; cerr << "Telling token: |" << token << "|." << endl; return; } records.push_back(record); first_column.push_back(token); ++number_of_records; } // Insert a record, with all columns joined by one char in <separator> void RecordsHolder::Insert(const string& record, const string& separator) { if(record.empty()) { cerr << "NULL RECORD..." << endl; return; } vector<string> splitted; boost::split(splitted, record, boost::is_any_of(separator.c_str()), boost::token_compress_on); Insert(splitted); } // Retrieve a record with a vector. Empty vector results if wrong <location> void RecordsHolder::GetRecord(size_t location, vector<string>& target) const { if(!target.empty()) target.clear(); if(!ValidLocation(location)) return; target.reserve(N_columns()); copy(records[location].begin(), records[location].end(), back_inserter(target)); } // Retrieve a record with a string joining all columns with a ';'. Empty // string results if wrong <location> string RecordsHolder::GetRecord(size_t location) const { if(!ValidLocation(location)) return ""; const vector<string>& wanted = records[location]; if(wanted.empty()) return ""; else return boost::join(wanted, ";"); } void RecordsHolder::Print() const { MySQLInterface::PrintingValues(records, name_of_columns); } #include <boost/io/ios_state.hpp> void RecordsHolder::Print(ostream& outflow) const { boost::io::ios_all_saver saver(cout); cout.rdbuf(outflow.rdbuf()); MySQLInterface::PrintingValues(records, name_of_columns); } // Find the index of Logical File Name from name_of_columns int RecordsHolder::FindLFN() const { if(name_of_columns.empty()) return -1; int index_of_lfn = -1; vector<string>::const_iterator it = find(name_of_columns.begin(), name_of_columns.end(), "lfn"); if(name_of_columns.end() != it) index_of_lfn = it - name_of_columns.begin(); return index_of_lfn; }
true
ef034e5750b6ef02f493f2ec4938a09511c5ddb9
C++
creep06/competitive-programming
/PCCB/p066_DivisionNumber.cpp
UTF-8
1,006
2.875
3
[]
no_license
/* dp[i][j]: jをi個以下の自然数に分割するパターンの総和 順序は無視 と定義すると↓こういう漸化式になる dp[i][j] = dp[i][j-i] + dp[i-1][j] 右辺の2つの項について 1) jをi個に分割するパターンの総数 まずj個の品物からi個の箱へ1個ずつ入れてから、残ったj-i個をi個の箱へ振り分けていく と考えられるのでdp[i][j-i]と書ける 2) jをi-1個以下に分割するパターンの総数 これはそのまんま dp[i-1][j] 本の解説はクソわかりづらい http://techtipshoge.blogspot.jp/2011/01/blog-post_28.html ここが参考になった */ #include <bits/stdc++.h> using namespace std; #define rep(i,n) for(int (i);(i)<(n);(i)++) int n, m, M, dp[1010][1010]; int main() { cin >> n >> m >> M; dp[0][0] = 1; for (int i = 1; i <= m; ++i) { for (int j = 0; j <= n; ++j) { if (j>=i) dp[i][j] = (dp[i-1][j] + dp[i][j-i]) % M; else dp[i][j] = dp[i-1][j]; } } cout << dp[m][n] << endl; }
true
52c861eaf798e84d4efc61ca3aa4f1ba70302f80
C++
romit0226/DS_Algo
/LeetCode/1217. Minimum Cost to Move Chips to The Same Position.cpp
UTF-8
262
2.53125
3
[]
no_license
class Solution { public: int minCostToMoveChips(vector<int>& position) { int i, ec=0, oc=0; for(i=0; i<position.size(); i++) { if(position[i]&1) oc++; else ec++; } return min(oc, ec); } };
true
c54daa712676050b1efbf77dcf2f9bbaea9a97e2
C++
a-mandy/ProjectoFinalEstructurasDatos
/ProjectoFinalEstructurasDatos/NodoListaMejoresPuntajes.cpp
UTF-8
906
2.890625
3
[]
no_license
#include "NodoListaMejoresPuntajes.h" NodoListaMejoresPuntajes::NodoListaMejoresPuntajes(){ puntaje = 0; nombre = " "; siguiente = NULL; } NodoListaMejoresPuntajes::NodoListaMejoresPuntajes(int pPuntaje) { puntaje = pPuntaje; } NodoListaMejoresPuntajes::NodoListaMejoresPuntajes(string pNombre, int pPuntaje) { nombre = pNombre; puntaje = pPuntaje; } NodoListaMejoresPuntajes::~NodoListaMejoresPuntajes(){ } void NodoListaMejoresPuntajes::setNombre(string pNombre){ nombre = pNombre; } string NodoListaMejoresPuntajes::getNombre(){ return nombre; } int NodoListaMejoresPuntajes::getPuntaje(){ return puntaje; } void NodoListaMejoresPuntajes::setPuntaje(int pPuntaje){ puntaje = pPuntaje; } NodoListaMejoresPuntajes * NodoListaMejoresPuntajes::getSig() { return siguiente; } void NodoListaMejoresPuntajes::setSig(NodoListaMejoresPuntajes * pSiguiente){ siguiente = pSiguiente; }
true
2a875759dc3bf7a586e10df88455c0d1596ff714
C++
JanMfa/MatchingWordApp
/MatchingWordsApp.cpp
UTF-8
7,017
3.546875
4
[]
no_license
// MatchingWordsApp is an application to create an output of substring matching words. // Condition: commonwords.txt and allwords.txt has to be in the same folder/path. // allwords.txt consist of single word on each line in alphabetical order // commonwords.txt consist of substrings on each line // Output: matchingwords.txt will be in the same folder/path // matchingwords.txt consist of substring matches presented in alphabetical order, e.g.: // that: at, hat #include <iostream> #include <cstdio> #include <stdio.h> #include <errno.h> #include <string> #include <vector> #include <fstream> #include <thread> #include <algorithm> #include <pthread.h> #include <cmath> // --VECTORS -- std::vector<std::string> allwords; std::vector<std::vector<std::string>> allwordsArr; std::vector<std::string> commonwords; std::vector<std::string> matchwords; std::vector<std::vector<std::string>> matchwordsArr; std::vector<std::string> finalWords; std::vector<std::vector<std::string>> finalWordsArr; // -- LOCKS -- pthread_mutex_t mutex; // -- VARIABLES -- static int divide = 0; //========================== readAllWords() ============================= //Purpose: Open the file allwords.txt and push the line into allwords vector. // Create empty vector of matchwords for the pairing of vector that is use later. //PRE: //PARAM: //POST: Create an initialize value of vector of allwords //======================================================================== void readAllWords() { std::string line; // Open file allwords.txt. std::ifstream file("allwords.txt"); int counter = 0; // When the file is open. if (file.is_open()) { // Get the line in the file. while (std::getline(file, line)) { // Push the line into wholewords vector. allwords.push_back(line); // Push empty string into matchwords vector. matchwords.push_back(""); } // Close the file. file.close(); } } //========================== readAllWords() ============================= //Purpose: Divide the allwords into allwordsArr //PRE: //PARAM: //POST: Create an array of vector of allwordsArr from allwords //======================================================================== void divideAllWords() { //get the total number of allwords vector int allWordsSize = allwords.size(); // splitting the square root number of size of allwords divide = round(sqrt(allWordsSize)); int counter = 0; int arr_counter = 0; // allocating empty vectors // the number of vectors will be the square root of number of allwords for (int i = 0; i < divide;i++) { std::vector<std::string> allwordsv; std::vector<std::string> matchwordsv; allwordsArr.push_back(allwordsv); matchwordsArr.push_back(matchwordsv); } // allocate filled-in vectors into the arrays // each array will consist of vector with the size of sqaure root of number of allwords while (counter < allWordsSize) { allwordsArr[arr_counter].push_back(allwords[counter]); matchwordsArr[arr_counter].push_back(matchwords[counter]); // increment the array when the counter is reach the number of divide and its multiplication if (counter!= 0 && counter % divide == 0) { arr_counter++; } counter++; } } //========================== readCommonWords() ============================= //Purpose: Open the file commonwords.txt and push the line into commonwords vector. //PRE: //PARAM: //POST: Create a sorted value of vector commonwords. //======================================================================== void readCommonWords() { std::string line; // Open file commonwords.txt. std::ifstream file1("commonwords.txt"); // When the file is open. if (file1.is_open()) { // Get the line in the file. while (std::getline(file1, line)) { // Push the line into commonwords vector. commonwords.push_back(line); } // Close the file. file1.close(); } // Sort the commonwords vector. std::sort(commonwords.begin(), commonwords.end()); } //========================== readCommonWords() ============================= //Purpose: Create 30 array of matchwords vector //PRE: allwordsArr and commonwords has to be initialized //PARAM: index: index of where the matching start //POST: Create 30 array of matchwords vector by appending the string of the allwordsArr and commonwords //======================================================================== void matchCommonWords(int index) { // Initialize the lock. pthread_mutex_init(&mutex, NULL); // Loop through the wholewords vector. for (int i = 0; i < allwordsArr[index].size(); i++) { // Initialized the string to be pushed in as empty string matchwords vector index i. std::string push_in_string = matchwordsArr[index][i]; for (int j = 0; j < commonwords.size(); j++) { // Find commonwords of index j inside the wholewords of index i. if (std::string::npos != allwordsArr[index][i].find(commonwords[j])) { // Push in the commonwords if the commonwords is find inside the wholewords vector of index i. push_in_string.append(" "); push_in_string.append(commonwords[j]); push_in_string.append(","); } } // Push in the string into the matchwords after all of the commonwords have been appended. matchwordsArr[index][i] = push_in_string; } // Release the lock. pthread_mutex_unlock(&mutex); } //========================== main() ============================= //Purpose: Where the program starts //PRE: commonwords.txt and allwords.txt exist //PARAM: //POST: Create a text file output called matchingwords.txt //======================================================================== int main() { // Open the file matchingwords.txt as output of the whole project. std::ofstream ofs; ofs.open("matchingwords.txt", std::ofstream::out); // Create thread of thread1 to execute readAllWords function. std::thread thread1{ readAllWords }; // Create thread of thread2 to execute readCommonWords function. std::thread thread2{ readCommonWords }; // Block the threads until the two functions are done executing. thread1.join(); thread2.join(); divideAllWords(); // Create array of thread. std::vector<std::thread> thread_arr; for (int i = 0; i < divide; i++) { thread_arr.push_back(std::thread(matchCommonWords, i)); } // Make sure that the thread wait until the rest of the thread completes its execution for (int i = 0; i < divide; i++) { thread_arr[i].join(); } // Outputing to into the file matchingwords.txt. for (int i = 0; i < divide; i++) { for (int j = 0; j < allwordsArr[i].size(); j++) { // Remove the last ',' if the matchwords has a trailing ','. if (!matchwordsArr[i][j].empty() && matchwordsArr[i][j].back() == ',') { matchwordsArr[i][j].pop_back(); } // Writing into file. ofs << allwordsArr[i][j] << ":" << matchwordsArr[i][j] << "\n"; } } // Close mathingwords.txt file ofs.close(); std::cout << "Execution is done. Please check matchingwords.txt file for output."; // To hold the console, so it does not close upon execution std::getchar(); return 0; }
true
131e4f1d2a2b9d28f5d9e5e1bc5e8cf2453aa1c4
C++
Sumethh/BlueGengineProject
/BlueEngine/BlueEngine/BlueCore/Source/Public/BlueCore/Components/ComponentRegistery.h
UTF-8
2,791
2.609375
3
[]
no_license
#pragma once #include "BlueCore/BlueCore.h" #include "BlueCore/Core/Log.h" #include "BlueCore/Hashing/CompileTimeHashing.h" #include "BlueCore/Managers/MemoryManager.h" #include <map> #include <vector> namespace Blue { class ActorComponent; class Actor; template<typename T> ActorComponent* __ConstructComponent(Actor* aOwner) { //IMemoryAllocator* smallAllocator = MemoryManager::GI()->GetSmallBlockAllocator(); //return new (smallAllocator->Allocate(sizeof(T), 0)) T(aOwner); return new T(aOwner); } struct RegisteredComponentInfo { RegisteredComponentInfo& AddRequiredComponent(uint64 aHash); uint64 componentHash; size_t componentSize; ActorComponent* (*Construct)(Actor*); std::vector<uint64> requiredComponents; }; class ComponentRegistery { public: ComponentRegistery(); ~ComponentRegistery(); void Init(); template<typename T> __forceinline RegisteredComponentInfo& RegisterComponent() { RegisteredComponentInfo& info = GetStaticComponentInfo<T>(); info.Construct = &__ConstructComponent<T>; T* component = static_cast<T*>(info.Construct(nullptr)); mRegisteryMap.emplace(component->ID(), info); info.componentHash = component->ID(); info.componentSize = sizeof(T); T::__ComponentSize = info.componentSize; Blue::Log::Info("Registering Component with ID: " + std::to_string(info.componentHash) + " Size: " + std::to_string(sizeof(T))); uint64 size(component->ComponentSize()); //IMemoryAllocator* smallBlockAllocator = MemoryManager::GI()->GetSmallBlockAllocator(); // //component->~T(); //smallBlockAllocator->Deallocate((void*)component, size); delete component; return info; } template<typename T> ActorComponent* Construct(Actor* aOwner) { return GetStaticComponentInfo<T>().Construct(aOwner); } ActorComponent* Construct(uint64 aID, Actor* aOwner) { return mRegisteryMap.find(aID)->second.Construct(aOwner); } const RegisteredComponentInfo& GetComponentInfo(uint64 aID) { return mRegisteryMap.find(aID)->second; } template<typename T> const RegisteredComponentInfo& GetComponentInfo() { return GetStaticComponentInfo<T>(); } static ComponentRegistery* GI() { if (!mInstance) { mInstance = new ComponentRegistery(); mInstance->Init(); } return mInstance; } private: static ComponentRegistery* mInstance; std::map<uint64, RegisteredComponentInfo&> mRegisteryMap; template<typename T> RegisteredComponentInfo& GetStaticComponentInfo() { static RegisteredComponentInfo info; return info; } }; } #define RegisterComponentType(type) Blue::ComponentRegistery::GI()->RegisterComponent<type>()
true
5c82e6b987085d7e6930047b04c59a9d9b3ec59e
C++
ganshuoos/C-Primer-
/stocks.cpp
UTF-8
1,977
3.828125
4
[]
no_license
//stocks.cpp -- the whole program #include<iostream> #include<cstring> class stocks { private: char company[30]; int shares; double share_val; double total_val; void set_tot(){ total_val = shares * share_val; } public: void acquire(const char* co, int n, double pr); void buy(int num, double price); void sell(int num, double price); void update(double price); void show(); }; void stocks::acquire(const char* co, int n, double pr){ std::strncpy(company,co,29); company[29] = '\0'; if (n < 0) { /* code */ std::cerr << "Number of shares can't be negative." << company << " shares set to 0.\n"; shares = 0; } else shares = n; share_val = pr; set_tot(); } void stocks::buy(int num, double price){ if (num < 0) { /* code */ std::cerr << "Number of shares purchased can't be negative." << company << " Transaction is aborted.\n"; } else { shares += num; share_val = price; set_tot(); } } void stocks::sell(int num, double price){ using std::cerr; if (num < 0) { /* code */ std::cerr << "Number of shares purchased can't be negative." << company << " Transaction is aborted.\n"; } else if (num > shares) { /* code */ std::cerr << "You can't sell more than you have ! " << " Transaction is aborted.\n"; } else { shares -= num; share_val = price; set_tot(); } } void stocks::update(double price){ share_val = price; set_tot(); } void stocks::show(){ std::cout << "Company : " << company << std::endl; std::cout << "Shares : " << shares << std::endl; std::cout << "Share price : " << share_val << std::endl; std::cout << "Total worth : " << total_val << std::endl; } int main(int argc, char const *argv[]) { using std::cout; using std::ios_base; stocks stock1; stock1.acquire("NanoSmart" , 20 , 12.50); cout.setf(ios_base::fixed); cout.precision(2); cout.setf(ios_base::showpoint); stock1.show(); stock1.buy(15,18.25); stock1.show(); stock1.sell(400,20.00); stock1.show(); return 0; }
true
f822a14265708423d42cd52593a2fa7795e7d874
C++
venkat-oss/SPOJ
/KAOS.cpp
UTF-8
1,476
2.515625
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <numeric> #include <algorithm> #include <functional> #include <vector> #include <queue> #include <set> #include <map> #include <utility> #include <cassert> #include <iomanip> #include <ctime> using namespace std; const int me = 100025; int n; int ft[me], pos[me]; pair<string, int> a[me], b[me]; void add(int pos, int value){ pos += 5; for( ; pos < me; pos += (pos & -pos)) ft[pos] += value; } int get(int pos){ pos += 5; int s = 0; for( ; pos > 0; pos -= (pos & -pos)) s += ft[pos]; return s; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cin >> n; for(int i = 0; i < n; i ++) cin >> a[i].first; for(int i = 0; i < n; i ++){ a[i].second = i; b[i].second = i; b[i].first = a[i].first; reverse(b[i].first.begin(), b[i].first.end()); } sort(a, a + n); sort(b, b + n); //for(int i = 0; i < n; i ++) // cout << b[i].first << " " << b[i].second << endl; for(int i = 0; i < n; i ++) pos[b[i].second] = i; for(int i = 0; i < n; i ++) add(pos[i], 1); //for(int i = 0; i < n; i ++) // cout << i << " " << pos[i] << endl; long long ans = 0; for(int i = 0; i < n; i ++){ ans += get(pos[a[i].second] - 1); add(pos[a[i].second], -1); } cout << ans << endl; return 0; }
true
25bf09904019f6410925b1245f6a4b897ecb1db0
C++
aalin/gta2-level-viewer
/src/geometry.cpp
UTF-8
1,355
2.90625
3
[]
no_license
#include "common.hpp" Geometry::Geometry() { } void Geometry::pushVertex(const Vertex& vertex) { _positions.push_back(vertex.position); _normals.push_back(vertex.normal); _texcoords.push_back(vertex.texcoord); } void Geometry::draw() { if(_positions.size() % 3 != 0) throw std::runtime_error("The number of vertices is not dividable by 3."); readyBuffers(); drawBuffers(); } void Geometry::readyBuffers() { if(!_position_buffer) { _position_buffer.reset(new VBO); _position_buffer->updateData(_positions, VBO::StaticDraw); } /* if(!_normal_buffer) { _normal_buffer.reset(new VBO); _normal_buffer->updateData(_normals, VBO::StaticDraw); }*/ if(!_texcoord_buffer) { _texcoord_buffer.reset(new VBO); _texcoord_buffer->updateData(_texcoords, VBO::StaticDraw); } } void Geometry::drawBuffers() { glEnableClientState(GL_VERTEX_ARRAY); _position_buffer->bind(); glVertexPointer(3, GL_FLOAT, 0, 0); /* glEnableClientState(GL_NORMAL_ARRAY); _normal_buffer->bind(); glNormalPointer(GL_FLOAT, 0, 0);*/ glEnableClientState(GL_TEXTURE_COORD_ARRAY); _texcoord_buffer->bind(); glTexCoordPointer(2, GL_FLOAT, 0, 0); glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(_positions.size())); glDisableClientState(GL_TEXTURE_COORD_ARRAY); // glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); }
true
d4da50859edf028299e9bc116c0fa872283a586e
C++
ganzena/BOJ
/[2839] 설탕 배달/[2839] 설탕 배달/main.cpp
UTF-8
585
2.5625
3
[]
no_license
// // main.cpp // [2839] 설탕 배달 // // Created by YOO TAEWOOK on 2018. 1. 17.. // Copyright © 2018년 YooTae-Ook. All rights reserved. // #include <iostream> using namespace std; int main(int argc, const char * argv[]) { int sugar; int total = 0; cin>>sugar; while(1){ if(sugar % 5 == 0){ total = sugar/5 + total; cout<<total<<endl; break; }else if(sugar <= 0){ cout<<-1<<endl; break; } sugar -= 3; total++; } return 0; }
true
54b79ea13f3ac56fb3ad8cc74542514d235b6392
C++
CrossCompiled/lvm
/includes/LittleVirtualMachine/LittleCompiler/CompilerExceptions.h
UTF-8
1,063
2.671875
3
[]
no_license
#ifndef LITTLEVIRTUALMACHINE_COMPILEREXCEPTIONS_H #define LITTLEVIRTUALMACHINE_COMPILEREXCEPTIONS_H #include <stdexcept> #include <string> namespace lvm{ namespace compiler { struct CompilerException : std::runtime_error { explicit CompilerException(const std::string& message) : runtime_error(message) {} }; struct WrongOpcode : public CompilerException { WrongOpcode(const std::string& message) : CompilerException(message) {} }; struct MissingLabel : public CompilerException { MissingLabel(const std::string& message) : CompilerException(message) {} }; struct DuplicateLabel : public CompilerException { DuplicateLabel(const std::string& message) : CompilerException(message) {} }; struct ParsingError : public CompilerException { ParsingError(const std::string& message) : CompilerException(message) {} }; struct StreamError : public CompilerException { StreamError(const std::string& message) : CompilerException(message) {} }; } } #endif //LITTLEVIRTUALMACHINE_COMPILEREXCEPTIONS_H
true
14f030d90c71476558240b4679031f436bf62adc
C++
Chantico-org/smart_board
/Main/Client.cpp
UTF-8
578
2.5625
3
[ "MIT" ]
permissive
#include "Client.h" void smart::Client::connect() { Serial.printf("Conneting to %s:[%d]\n", host, port); int state = LOW; digitalWrite(HOST_CONNECTION_PIN, state); bool connected = wifi_client->connect(host, port); state = !state; digitalWrite(HOST_CONNECTION_PIN, state); unsigned long begin_millis = millis(); while(!connected) { Serial.println(F("Cannot connect to host")); delay(500); connected = wifi_client->connect(host, port); state = !state; digitalWrite(HOST_CONNECTION_PIN, state); } digitalWrite(HOST_CONNECTION_PIN, LOW); }
true
4ac1881b5485cf30fd5d4547369c70154abe539e
C++
Eunno-An/ACMICPC_boj
/ACMICPC/같은 수로 만들기_2374_골.cpp
UTF-8
693
2.625
3
[]
no_license
#include <stdio.h> #include <stack> #include <vector> using namespace std; long long int A[1000001]; vector<long long int> v; int main() { int n; long long int output = 0; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%lld", &A[i]); if (v.empty()) v.push_back(A[i]); else { while (v.back() < A[i]) { int del = v.back(); v.pop_back(); if (v.empty() || v.back() > A[i]) { output += A[i] - del; break; } else { output += v.back() - del; } } v.push_back(A[i]); } // printf("de %d %d %d ", output, v.front(), v.back()); } // printf("\n"); if (v.size() > 1) output += v.front() - v.back(); printf("%lld\n", output); }
true
f3030f668febdd9431e77aa6f1a210b56e8bf620
C++
jiangtao89/kraken
/plugins/devtools/bridge/inspector/protocol/exception_details.h
UTF-8
5,669
2.578125
3
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2020-present The Kraken authors. All rights reserved. */ #ifndef KRAKEN_DEBUGGER_EXCEPTION_DETAILS_H #define KRAKEN_DEBUGGER_EXCEPTION_DETAILS_H #include "inspector/protocol/error_support.h" #include "inspector/protocol/remote_object.h" #include "inspector/protocol/stacktrace.h" #include <memory> #include <string> #include <vector> namespace kraken::debugger { class ExceptionDetails { KRAKEN_DISALLOW_COPY(ExceptionDetails); public: static std::unique_ptr<ExceptionDetails> fromValue(rapidjson::Value *value, ErrorSupport *errors); ~ExceptionDetails() {} int getExceptionId() { return m_exceptionId; } void setExceptionId(int value) { m_exceptionId = value; } std::string getText() { return m_text; } void setText(const std::string &value) { m_text = value; } int getLineNumber() { return m_lineNumber; } void setLineNumber(int value) { m_lineNumber = value; } int getColumnNumber() { return m_columnNumber; } void setColumnNumber(int value) { m_columnNumber = value; } bool hasScriptId() { return m_scriptId.isJust(); } std::string getScriptId(const std::string &defaultValue) { return m_scriptId.isJust() ? m_scriptId.fromJust() : defaultValue; } void setScriptId(const std::string &value) { m_scriptId = value; } bool hasUrl() { return m_url.isJust(); } std::string getUrl(const std::string &defaultValue) { return m_url.isJust() ? m_url.fromJust() : defaultValue; } void setUrl(const std::string &value) { m_url = value; } bool hasStackTrace() { return m_stackTrace.isJust(); } StackTrace *getStackTrace(StackTrace *defaultValue) { return m_stackTrace.isJust() ? m_stackTrace.fromJust() : defaultValue; } void setStackTrace(std::unique_ptr<StackTrace> value) { m_stackTrace = std::move(value); } bool hasException() { return m_exception.isJust(); } RemoteObject *getException(RemoteObject *defaultValue) { return m_exception.isJust() ? m_exception.fromJust() : defaultValue; } void setException(std::unique_ptr<RemoteObject> value) { m_exception = std::move(value); } bool hasExecutionContextId() { return m_executionContextId.isJust(); } int getExecutionContextId(int defaultValue) { return m_executionContextId.isJust() ? m_executionContextId.fromJust() : defaultValue; } void setExecutionContextId(int value) { m_executionContextId = value; } rapidjson::Value toValue(rapidjson::Document::AllocatorType &allocator) const; template <int STATE> class ExceptionDetailsBuilder { public: enum { NoFieldsSet = 0, ExceptionIdSet = 1 << 1, TextSet = 1 << 2, LineNumberSet = 1 << 3, ColumnNumberSet = 1 << 4, AllFieldsSet = (ExceptionIdSet | TextSet | LineNumberSet | ColumnNumberSet | 0) }; ExceptionDetailsBuilder<STATE | ExceptionIdSet> &setExceptionId(int value) { static_assert(!(STATE & ExceptionIdSet), "property exceptionId should not be set yet"); m_result->setExceptionId(value); return castState<ExceptionIdSet>(); } ExceptionDetailsBuilder<STATE | TextSet> &setText(const std::string &value) { static_assert(!(STATE & TextSet), "property text should not be set yet"); m_result->setText(value); return castState<TextSet>(); } ExceptionDetailsBuilder<STATE | LineNumberSet> &setLineNumber(int value) { static_assert(!(STATE & LineNumberSet), "property lineNumber should not be set yet"); m_result->setLineNumber(value); return castState<LineNumberSet>(); } ExceptionDetailsBuilder<STATE | ColumnNumberSet> &setColumnNumber(int value) { static_assert(!(STATE & ColumnNumberSet), "property columnNumber should not be set yet"); m_result->setColumnNumber(value); return castState<ColumnNumberSet>(); } ExceptionDetailsBuilder<STATE> &setScriptId(const std::string &value) { m_result->setScriptId(value); return *this; } ExceptionDetailsBuilder<STATE> &setUrl(const std::string &value) { m_result->setUrl(value); return *this; } ExceptionDetailsBuilder<STATE> &setStackTrace(std::unique_ptr<StackTrace> value) { m_result->setStackTrace(std::move(value)); return *this; } ExceptionDetailsBuilder<STATE> &setException(std::unique_ptr<RemoteObject> value) { m_result->setException(std::move(value)); return *this; } ExceptionDetailsBuilder<STATE> &setExecutionContextId(int value) { m_result->setExecutionContextId(value); return *this; } std::unique_ptr<ExceptionDetails> build() { static_assert(STATE == AllFieldsSet, "state should be AllFieldsSet"); return std::move(m_result); } private: friend class ExceptionDetails; ExceptionDetailsBuilder() : m_result(new ExceptionDetails()) {} template <int STEP> ExceptionDetailsBuilder<STATE | STEP> &castState() { return *reinterpret_cast<ExceptionDetailsBuilder<STATE | STEP> *>(this); } std::unique_ptr<ExceptionDetails> m_result; }; static ExceptionDetailsBuilder<0> create() { return ExceptionDetailsBuilder<0>(); } private: ExceptionDetails() { m_exceptionId = 0; m_lineNumber = 0; m_columnNumber = 0; } int m_exceptionId; std::string m_text; int m_lineNumber; int m_columnNumber; Maybe<std::string> m_scriptId; Maybe<std::string> m_url; Maybe<StackTrace> m_stackTrace; Maybe<RemoteObject> m_exception; Maybe<int> m_executionContextId; }; } // namespace kraken #endif // KRAKEN_DEBUGGER_EXCEPTION_DETAILS_H
true
bab1a4d82d2bdc4ef3ebd68b61f797bf39a2f18e
C++
CharlsPalm/ejercicios_C
/19_seccion/arboles.cpp
UTF-8
1,304
3.40625
3
[]
no_license
#include <iostream> #include "nodo3.h" /* run this program using the console pauser or add your own getch, system("pause") or input loop */ using namespace std; nodo3 *R, *T; void agregar(nodo3 *); void presentar(nodo3 *); void ordenar(nodo3 *); int op,x; int main(int argc, char** argv) { do{ cout<<"Menu"<<endl; cout<<"1) Agregar"<<endl; cout<<"2) Presentar"<<endl; cout<<"3) Ordenado"<<endl; cout<<"0) Salir"<<endl; cin>>op; switch(op){ case 1: cout<<"Ingrese un numero"<<endl; cin>>x; T=new nodo3(); T->id=x; T->De=NULL; T->Iz=NULL; agregar(R); break; case 2: presentar(R); break; case 3: ordenar(R); case 0: break; default: cout<<"Opcion no valida"<<endl; } }while(op!=0); return 0; } void agregar(nodo3 *p){ if(R==NULL){ R=T; return; } else if(T->id>p->id){ if(p->De==NULL){ p->De=T; } else{ agregar(p->De); } } else{ if(p->Iz==NULL){ p->Iz=T; } else{ agregar(p->Iz); } } } void presentar(nodo3 *p){ if(p==NULL){ return; } else{ cout<<"Id: "<<p->id<<endl; presentar(p->De); presentar(p->Iz); } } void ordenar(nodo3 *p){ if(p==NULL){ return; } else{ ordenar(p->De); cout<<"Id: "<<p->id<<endl; ordenar(p->Iz); } }
true
6e611cb44094a5867299dc911b5b911218e51895
C++
BoykoMihail/ML_HomeWork_NeuralNetwork
/SoftPlus.h
UTF-8
788
2.765625
3
[]
no_license
/* * File: SoftPlus.h * Author: boyko_mihail * * Created on 30 октября 2019 г., 19:47 */ #ifndef SOFTPLUS_H #define SOFTPLUS_H #include <eigen3/Eigen/Core> #include "Configuration.h" class SoftPlus : public Activation { private: typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix; public: SoftPlus(){} // activation(z) = log (1 + exp(-z)) void activate(const Matrix& Z, Matrix& A) { A.array() = (Scalar(1) + (-Z.array()).exp()).log(); } // J = d_a / d_z = 1 / 1 + exp(-z)) // g = J * f = z / 1 + exp(-z)) void calculate_jacobian(const Matrix& Z, const Matrix& A, const Matrix& F, Matrix& G) { G.array() = Z.array() / (Scalar(1) + (-Z.array()).exp()); } }; #endif /* SOFTPLUS_H */
true
88af3ea633248c63df3710a43c31fbb806c48fae
C++
oLESHIYka/PdfConsoleParser_QT
/PdfConsoleParser_QT/source/Document/Issue/Page/Page.h
WINDOWS-1251
1,010
3.078125
3
[]
no_license
#pragma once /*====================================================*\ Page.h - Page , \*====================================================*/ #include "../../../Text/Block/TextBlock.h" #include <algorithm> class Page : public std::vector<TextBlock> { public: Page() {}; void findRunningTitles(); std::string print() { uint32 blockId = 0; std::stringstream ss; ss << "Page: {\nBlocks: [\n"; std::for_each( this->begin(), this->end(), [this, &blockId, &ss](TextBlock& block){ ss << (blockId ? ", " : "") << "[" << blockId << "]:" << block.print() << "\n"; ++blockId; }); ss << "]\n"; return ss.str(); } protected: void findTopRunningTitle(); void findBottomRunningTitle(); };
true
f026cf5598f9b925e970746b33a8732aa55aba87
C++
longshadian/estl
/redis/test/rediscpp/test/TestSet.cpp
UTF-8
1,150
2.625
3
[]
no_license
#include "RedisCpp.h" #include <cstdio> #include <iostream> #include <string> #include <vector> #include <chrono> #include "TestTool.h" std::string ip = "127.0.0.1"; int port = 6379; using namespace rediscpp; ContextGuard g_context; bool test_Set() { try { Buffer key{"test_set"}; DEL(g_context, key); Set redis{g_context}; TEST(redis.SADD(key, Buffer("a")) == 1); TEST(redis.SADD(key, Buffer("b")) == 1); TEST(redis.SADD(key, Buffer("c")) == 1); TEST(redis.SADD(key, Buffer("c")) == 0); TEST(redis.SISMEMBER(key, Buffer("a"))); TEST(!redis.SISMEMBER(key, Buffer("aa"))); return true; } catch (const RedisExceiption& e) { std::cout << "RedisException:" << __LINE__ << ":" << __FUNCTION__ << ":" << e.what() << "\n"; return false; } return true; } int main() { auto context = rediscpp::redisConnect(ip, port); if (!context) { std::cout << "error context error\n"; return 0; } g_context = std::move(context); test_Set(); return 0; }
true
5aba282414a840791b764e640404a741f51479c4
C++
sanish-khadgi/cpp_projects2
/LEC_C++/Lab_works/types-of_user_defined_functions/from_assignment-using_area_of_triangle/no_arument_but_return_type.cpp
UTF-8
1,047
3.578125
4
[]
no_license
//area of triangle using funtion with no argument and return type /*no argument mean "the called function" does not received any data from "the calling function"*/ #include<iostream> #include<math.h> #include<conio.h> using namespace std; float area_Triangle(); int main() { float area; area=area_Triangle();/*Is this a function call?/*the whole function "area-Triangle()" is assign to "area"*/ cout<<"area of the triangle is:\t"<<area; /*is this area is from fuction call or answer (function beloe)*/ getch(); return 0; } float area_Triangle() { float a, b, c; cout<<"Enter the side of a triangle"<<endl; cout<<"Enter the side a: "<<endl; cin>>a; cout<<"Enter the side b: "<<endl; cin>>b; cout<<"Enter the side c: "<<endl; cin>>c; float area, s; s=((a+b+c)/2); area=sqrt(s*(s-a)*(s-b)*(s-c)); return area;/*compulsary to return value to main function else return "nan" in "area" ,,,, if we put return 0; area=0 no matter a,b,c;*/ }
true
e58212baa6c3db40c4af5a1de88ff8919a2f3eb4
C++
gonzanicorodriguez/juego_topo
/BaseProject/main.cpp
UTF-8
9,744
2.9375
3
[]
no_license
#include "mbed.h" #include <stdlib.h> /** * @brief Estos son los estados de la MEF (Máquina de Estados Finitos), para comprobar el estado del boton. * El botón está configurado como PullUp, establece un valor lógico 1 cuando no se presiona * y cambia a valor lógico 0 cuando es presionado. */ typedef enum{ BUTTON_DOWN, //0 BUTTON_UP, //1 BUTTON_FALLING, //2 BUTTON_RISING //3 }_eButtonState; /** * @brief Estructura que define a los pulsadores. * Posicion (pos): Como un entero, para saber que boton es el que se presionó * Estado: Como un entero, para saber si el boton fue presionado. * TimeDown: definido como un entero, que guarda el tiempo que el boton estuvo presionado, para no provocar errores. * TimeDiff: Es la resta entre el valor del tiempo del programa, y el valor de TimeDown, para saber cuando entrar al juego. */ typedef struct{ int pos; uint8_t estado; int32_t timeDown; int32_t timeDiff; }_sTeclas; #define TRUE 1 #define FALSE 0 #define TIMEMAX 2001//1501 #define BASETIME 5000 /** * @brief Tiempo mínimo de presionado de un boton para iniciar el juego * */ #define TIMETOSTART 1000 /** * @brief Intervalo entre presiones de botones para "filtrar" el ruido. * */ #define INTERVAL 40 /** * @brief Tiempo en el que el LED que se prendió cambia de estado. * */ #define ESTADO 1000 /** * @brief Intervalo donde cambian de estado los cuatro led por causa de ganarle al topo * */ #define CAMBIO 500 /** * @brief Cantidad de botones * */ #define NROBOTONES 4 /** * @brief Cantidad de Leds * */ #define MAXLED 4 /** * @brief Valor del acumulador para el parpadeo * */ #define PARPADEO 6 /** * @brief Estado inicial de la Maquina de Estado del juego. * Este va a cambiar, cuando el usuario presione por más de 1 segundo un boton. */ #define STANDBY 0 /** * @brief Segundo estado de la Maquina de Estado del juego. * Se controla que se haya presionado un solo botón. */ #define KEYS 1 /** * @brief Tercer estado de la Maquina de Estado del juego. * Arranca el juego * Enciende un LED aleatorio * A ese LED aleatorio, se le asigna un tiempo aleatorio para "pegarle" (tocar el boton correspondiente) */ #define GAMEMOLE 2 /** * @brief Cuarto estado de la Maquina de Estado del juego. * Comprueba si el boton presionado corresponde al LED encendido * Si acierta, pasa al estado WIN * Si falla, pasa al estado MOLECELEBRATES */ #define COMP 3 /** * @brief Quinto estado de la Maquina de Estado del juego. * El usuario GANÓ * Los cuatro LED parpadean 3 veces. * Vuelve al estado STANBY */ #define WIN 4 /** * @brief Ultimo estado de la Maquina de Estado del juego. * El usuario PERDIÓ * "El topo festeja" * El LED que se prendió parpadea 3 veces y vuelve al estado STANDBY */ #define MOLEWIN 5 /** * @brief Inicializa la MEF * Le dá un estado inicial a indice * @param indice Este parametro recibe el estado de la MEF */ void startMef(uint8_t indice); /** * @brief Máquina de Estados Finitos(MEF) * Actualiza el estado del botón cada vez que se invoca. * * @param indice Este parámetro le pasa a la MEF el estado del botón. */ void actuallizaMef(uint8_t indice ); /** * @brief Función para cambiar el estado del LED cada vez que sea llamada. * */ void togleLed(uint8_t indice); /** * @brief Dato del tipo Enum para asignar los estados de la MEF * */ _eButtonState myButton; _sTeclas ourButton[NROBOTONES]; uint16_t mask[]={0x0001,0x0002,0x0004,0x0008};//!<Mascara con las posiciones de los botones o leds BusIn botones(PB_6,PB_7,PB_8,PB_9); BusOut leds(PB_12,PB_13,PB_14,PB_15); Timer miTimer; //!< Timer para hacer la espera de 40 milisegundos int tiempoMs=0; //!< variable donde voy a almacenar el tiempo del timmer una vez cumplido uint8_t estado=STANDBY; unsigned int ultimo=0; //!< variable para el control del heartbeats. guarda un valor de tiempo en ms uint16_t ledAuxRandom=0; uint16_t ledOn; //Guarda el led que se activó uint16_t posBoton;//guarda el pulsador que se activo int main() { miTimer.start(); int tiempoRandom=0; int ledAuxRandomTime=0; int ledAuxJuegoStart=0; uint8_t indiceAux=0; uint8_t control=FALSE; int check=0; int acumTime=0; uint8_t acum=1; for(uint8_t indice=0; indice<NROBOTONES;indice++){ startMef(indice); ourButton[indice].pos = indice; } while(TRUE) { if((miTimer.read_ms()-ultimo)>ESTADO){ ultimo=miTimer.read_ms(); } switch(estado){ case STANDBY: if ((miTimer.read_ms()-tiempoMs)>INTERVAL){ tiempoMs=miTimer.read_ms(); for(uint8_t indice=0; indice<NROBOTONES;indice++){ actuallizaMef(indice); if(ourButton[indice].timeDiff >= TIMETOSTART){ srand(miTimer.read_us()); estado=KEYS; } } } break; case KEYS: for( indiceAux=0; indiceAux<NROBOTONES;indiceAux++){ actuallizaMef(indiceAux); if(ourButton[indiceAux].estado!=BUTTON_UP){ break; } } if(indiceAux==NROBOTONES){ estado=GAMEMOLE; leds=15; ledAuxJuegoStart=miTimer.read_ms(); } break; case GAMEMOLE: if(leds==0){ tiempoRandom=miTimer.read_ms(); ledAuxRandom = rand() % (MAXLED); //selecciona uno de los 4 led para encender ledAuxRandomTime = ((rand() % TIMEMAX)+BASETIME); //Determina cuanto tiempo estara encendido el led //leds=mask[ledAuxRandom]; togleLed(ledAuxRandom); control=0; }else{ if((miTimer.read_ms() - ledAuxJuegoStart)> TIMETOSTART) { if(leds==15){ ledAuxJuegoStart=miTimer.read_ms(); leds=0; } } } if (((miTimer.read_ms()-ledAuxJuegoStart)>ledAuxRandomTime)&&(control)){ estado=MOLEWIN; } if((leds!=0)&&(leds!=15)){ if((miTimer.read_ms()-check)>INTERVAL){ check=miTimer.read_ms(); for(uint8_t indice=0; indice<NROBOTONES;indice++){ actuallizaMef(indice); if(ourButton[indice].estado==BUTTON_DOWN){ estado=COMP; posBoton=ourButton[indice].pos; ledOn=ledAuxRandom; } } } } break; case COMP: if(mask[ledOn]==mask[posBoton]){ estado=WIN; }else{ estado=MOLEWIN; } break; case MOLEWIN: if((miTimer.read_ms()-acumTime)>CAMBIO){ acumTime = miTimer.read_ms(); if((acum%2)==0){ leds=0; }else{ togleLed(ledAuxRandom); } if(acum==PARPADEO){ estado=STANDBY; acum=0; } acum++; } break; case WIN: if((miTimer.read_ms()-acumTime)>CAMBIO){ acumTime = miTimer.read_ms(); if((acum%2)==0){ leds=0; }else{ leds=15; } if(acum==PARPADEO){ estado=STANDBY; acum=0; } acum++; } break; default: estado=STANDBY; } } return 0; } void startMef(uint8_t indice){ ourButton[indice].estado=BUTTON_UP; } void actuallizaMef(uint8_t indice){ switch (ourButton[indice].estado) { case BUTTON_DOWN: if(botones.read() & mask[indice] ) ourButton[indice].estado=BUTTON_RISING; break; case BUTTON_UP: if(!(botones.read() & mask[indice])) ourButton[indice].estado=BUTTON_FALLING; break; case BUTTON_FALLING: if(!(botones.read() & mask[indice])) { ourButton[indice].timeDown=miTimer.read_ms(); ourButton[indice].estado=BUTTON_DOWN; //Flanco de bajada } else ourButton[indice].estado=BUTTON_UP; break; case BUTTON_RISING: if(botones.read() & mask[indice]){ ourButton[indice].estado=BUTTON_UP; //Flanco de Subida ourButton[indice].timeDiff=miTimer.read_ms()-ourButton[indice].timeDown; } else ourButton[indice].estado=BUTTON_DOWN; break; default: startMef(indice); break; } } void togleLed(uint8_t indice){ leds=mask[indice]; }
true
531a1853c5da2a4a0283501153356975c15507a1
C++
rodoufu/challenges
/leetCode/interview/strings/LongestCommonPrefix.hpp
UTF-8
742
3.203125
3
[]
no_license
//https://leetcode.com/problems/longest-common-prefix/ class Solution { public: string longestCommonPrefix(vector<string>& strs) { string resp; int len = strs.size(); if (len == 0) { return resp; } int smallLen = strs[0].length(); for (int i = 1; i < len; ++i) { smallLen = smallLen < strs[i].length() ? smallLen : strs[i].length(); } char actual; for (int i = 0; i < smallLen; ++i) { actual = strs[0][i]; for (int j = 1; j < len; ++j) { if (actual != strs[j][i]) { return resp; } } resp += actual; } return resp; } };
true
26b107234d3545e67f332b2f01dad4138ce251d2
C++
tridibsamanta/LeetCode_Solutions
/ValidateBinarySearchTree_98.cpp
UTF-8
864
3.375
3
[]
no_license
/* ~ Author : leetcode.com/tridib_2003/ ~ Problem : 98. Validate Binary Search Tree ~ Link : https://leetcode.com/problems/validate-binary-search-tree/ */ /** * 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: bool isValidBST(TreeNode* root) { return IsBstUtil(root, LLONG_MIN, LLONG_MAX); } bool IsBstUtil(TreeNode* root, long long int minValue, long long int maxValue) { if(root == NULL) return true; if((root->val > minValue && root->val < maxValue) && IsBstUtil(root->left, minValue, root->val) && IsBstUtil(root->right, root->val, maxValue)) return true; else return false; } };
true
f296956838b6fd62065ead5c1ce416b61097c886
C++
ccharp/School
/ku/560/lab4/BinarySearchTree.h
UTF-8
1,008
3.140625
3
[]
no_license
#ifndef BINARYSEARCHTREE_H_ #define BINARYSEARCHTREE_H_ #include "TNode.h" class BinarySearchTree { private: TNode *root; void insert(int v, TNode* &t); void inOrderTraversal(TNode* &t); void preOrderTraversal(TNode* &t); void postOrderTraversal(TNode* &t); int leafCount(TNode* &t); int treeHeight(TNode* &t); void makeEmpty(TNode* &t); public: void bst2ll(TNode *root, TNode *first, TNode *last ); BinarySearchTree(){ root = NULL; } void insert(int v){ insert(v, root); } void inOrderTraversal(){ inOrderTraversal(root); cout << endl; } void preOrderTraversal(){ preOrderTraversal(root); cout << endl; } void postOrderTraversal(){ postOrderTraversal(root); cout << endl; } int leafCount(){ return leafCount(root); } int treeHeight(){ return treeHeight(root); } void makeEmpty(){ makeEmpty(root); } ~BinarySearchTree(){ makeEmpty(); } }; #endif /* BINARYSEARCHTREE_H_ */
true
922370622fcf918fee182370a52cba3d35820bf1
C++
rgianluca00/ROS_exercises_tutorial
/exercise_2/src/saturation_controller.cpp
UTF-8
3,734
3.09375
3
[]
no_license
/* * saturation_controller.cpp * * Created on: March, 2020 * Author: Gianluca Rinaldi */ #include "ros/ros.h" #include <iostream> #include <exercise_2/CustomVelMsg.h> #include <geometry_msgs/Twist.h> /* Global variables */ float vel; // linear_velocity float ang; // angular_velocity bool command_ready = false; /* Function for unpacking custom control velocity command message */ void ControlMsgCallback(const exercise_2::CustomVelMsg::ConstPtr& ctrl_msg) { vel = ctrl_msg->linear_velocity; ang = ctrl_msg->angular_yaw; command_ready = true; // set command_ready as true because command message is arrived } /* Function for applying saturation on the command velocity control */ float saturate(float min_limit, float max_limit, float input) { if (input < min_limit) // if min limit is exceeded return min limit as command velocity control { ROS_INFO("Current value is exceeding minimum limit"); return min_limit; } else if (input > max_limit) // if max limit is exceeded return max limit as command velocity control { ROS_INFO("Current value is exceeding maximum limit"); return max_limit; } return input; } /* Main function */ int main(int argc, char **argv) { ros::init(argc, argv, "saturation_controller"); ros::NodeHandle nh("~"); float min_linear; // saturation limit for robot minimum linear velocity float max_linear; // saturation limit for robot max linear velocity float min_angular; // saturation limit for robot min angualr velocity float max_angular; // saturation limit for robot max angular velocity /* Get saturation limits from launch or set them to default value */ if (nh.getParam("min_linear", min_linear)) ROS_INFO("Found parameter: setting saturation limit for robot min linear velocity at: %f", min_linear); else { min_linear = -2.0; ROS_INFO("Parameter not found: setting saturation limit for robot min linear velocity at: %f", min_linear); } if (nh.getParam("max_linear", max_linear)) ROS_INFO("Found parameter: setting saturation limit for robot max linear velocity at: %f", max_linear); else { max_linear = 2.0; ROS_INFO("Parameter not found: setting saturation limit for robot max linear velocity at: %f", max_linear); } if (nh.getParam("min_angular", min_angular)) ROS_INFO("Found parameter: setting saturation limit for robot min angualr velocity at: %f", min_angular); else { min_angular = -2.0; ROS_INFO("Parameter not found: setting saturation limit for robot min angular velocity at: %f", min_angular); } if (nh.getParam("max_angular", max_angular)) ROS_INFO("Found parameter: setting saturation limit for robot max angular velocity at: %f", max_angular); else { max_angular = 2.0; ROS_INFO("Parameter not found: setting saturation limit for robot max angular velocity at: %f", max_angular); } ros::Rate rate(100); /* Publisher and Subscriber */ ros::Publisher vel_pub = nh.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel",1000); ros::Subscriber control_sub = nh.subscribe("/custom_vel_control",1000, &ControlMsgCallback); /* Control Loop */ while(ros::ok()) // Keep spinning loop until user presses Ctrl+C { geometry_msgs::Twist cmd_vel; // velocity command to be published (with saturation applied) if(command_ready) // if command is arrived { cmd_vel.linear.x = saturate(min_linear, max_linear, vel); // apply saturation on the linear velocity along x-axis cmd_vel.angular.z = saturate(min_angular, max_angular, ang); // apply saturation on the angular velocity around z-axis (yaw rate) vel_pub.publish(cmd_vel); // publish desired velocity values command_ready = false; } ros::spinOnce(); rate.sleep(); } return 0; }
true
0c3c862178feda1cdc6e0a8b6e146bf6e0d15613
C++
Madness-D/CodeUp
/2 c c++快速入门/2.5 数组/J 字符串求最大值.cpp
UTF-8
357
3.3125
3
[]
no_license
//三个字符串 输出最大的那个 #include <stdio.h> #include <string.h> int main() { char a[20],b[20],c[20]; char *max; //两种c语言字符数输入方式 gets(a); scanf("%s",&b); //getchar(); gets(c); //找出a b最大者 if(strcmp(a,b)>0) max = a; else max =b; if(strcmp(max,c)>0) puts(max); else puts(c); return 0; }
true
914253386233906bba2992ce56a5755f44a408ef
C++
michaelbprice/default-arguments
/examples/slide36.cpp
UTF-8
606
3.21875
3
[ "MIT" ]
permissive
// GCC> g++ -std=c++14 #include <cassert> #include <string> using std::string; struct Base { auto fn (string s = "foo") { return s; } }; struct D_one : Base { void fn (char); using Base::fn; // Bring Base names back into overload set! }; struct D_two : Base { using Base::fn; auto fn (string s = "bar") { return s + "!!!"; // Hides Base::fn! } }; int main () { Base b; assert(b.fn() == "foo"); D_one d_one; assert(d_one.fn() == "foo"); D_two d_two; assert(d_two.fn() == "bar!!!"); assert(d_two.Base::fn() == "foo"); }
true
4fe3daabca310ffd065ef121875a1a0af3d78489
C++
HamzaHajeir/IoT_Learning_Kit
/Distance/Applications/Car_Sensor/Car_Sensor.ino
UTF-8
1,566
2.515625
3
[]
no_license
/* This example shows how to use continuous mode to take range measurements with the VL53L0X. It is based on vl53l0x_ContinuousRanging_Example.c from the VL53L0X API. The range readings are in units of mm. */ #include <Wire.h> #include <VL53L0X.h> #include <H4Plugins.h> H4_USE_PLUGINS(115200, 20, false); H4P_GPIOManager h4gm; H4P_FlasherController h4fc; VL53L0X sensor; void h4setup() { Serial.begin(115200); Wire.begin(); sensor.setTimeout(500); if (!sensor.init()) { Serial.println("Failed to detect and initialize sensor!"); while (1) {} } // Start continuous back-to-back mode (take readings as // fast as possible). To use continuous timed mode // instead, provide a desired inter-measurement period in // ms (e.g. sensor.startContinuous(100)). sensor.startContinuous(20); pinMode(D5, OUTPUT); h4.every(1000, []() { int distance = sensor.readRangeContinuousMillimeters(); Serial.print(distance); if (sensor.timeoutOccurred()) { Serial.println(" TIMEOUT"); } else { Serial.println(" mm"); } int time_period = -1; if (50 < distance && distance < 600 ) { static int previous_time_period; time_period = ::map(distance, 50, 600, 75, 500); Serial.print("new time_period = "); Serial.println(time_period); if (abs(time_period - previous_time_period) > 50) { h4fc.flashPattern("101000", time_period, D5, ACTIVE_HIGH); previous_time_period = time_period; } return; } h4fc.stopLED(D5); }); }
true