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
edf7d6402d6b46be25962bd69341b48288bbfb9f
C++
damarbo33/crosslib
/src/rijndael/rijndael.cpp
ISO-8859-7
12,651
3.015625
3
[]
no_license
#include "rijndael.h" /** * Constructor */ Rijndael::Rijndael(){ b = NULL; k = NULL; //setKeyBlockLength(ks128/8, ks128/8); } /** * Destructor */ Rijndael::~Rijndael(){ } /** * cifrar: Se encarga de cifrar el bloque recibido */ void Rijndael::cifrar(){ //Creacion de claves //cout << "************ CLAVES ************" << endl << endl; //crearClaves(); //Acciones para el cifrado //Ronda inicial //cout << "************ RONDA INICIAL ************" << endl << endl; addroundkey(b,kExp, 0); //print(b); //Se realizan las 9 rondas siguientes unsigned char i; for (i=1; i <= Nr - 1; i++){ //cout << "************ RONDA " << i << " ************" << endl << endl; bytesub(b); //print(b); shiftrow(b); //print(b); mixcolumn(b); //print(b); addroundkey(b,kExp, i); //cout << (int)i << ": "; //print(b); } //cout << "************ RONDA 10 ************" << endl << endl; bytesub(b); //print(b); shiftrow(b); //print(b); addroundkey(b,kExp, Nr); // cout << (int)Nr << ": "; // print(b); // cout << "Texto cifrado: "; // print(b); //Acciones para la generacion de las claves } /** * descifrar: Se encarga de descifrar el bloque recibido */ void Rijndael::descifrar(){ //Creacion de claves //cout << "************ CLAVES ************" << endl << endl; //crearClaves(); unsigned char i; //cout << "************ RONDA 10 ************" << endl << endl; addroundkey(b,kExp, Nr); //print(b); invShiftrow(b); //print(b); invBytesub(b); //print(b); //Se realizan las 9 rondas siguientes for (i = Nr - 1; i > 0; i--){ //cout << "************ RONDA " << i << " ************" << endl << endl; addroundkey(b,kExp, i); //print(b); invMixcolumn(b); //print(b); invShiftrow(b); //print(b); invBytesub(b); //print(b); } //cout << "************ RONDA 0 ************" << endl << endl; addroundkey(b,kExp, 0); // cout << "Texto descifrado: "; // print(b); //print(b); } /** * setClave */ void Rijndael::setClave(unsigned char *clave){ k = clave; } /** * setData */ void Rijndael::setData(unsigned char *data){ b = data; } /** * crearClaves */ void Rijndael::crearClaves(unsigned int lenk, unsigned int lenb){ //Primero copiamos la clave original en las primeras posiciones unsigned char i; setKeyBlockLength(lenk, lenb); for (i = 0; i < Nk * 4; i++){ kExp[i] = k[i]; } expand_key(kExp); } /** * setKeyBlockLength */ void Rijndael::setKeyBlockLength(unsigned int varKey, unsigned int varBlock){ blocklength = varBlock; Nb = blocklength * 8 /32; keylength = varKey; Nk = keylength * 8 / 32; if (Nb == 8 || (Nb == 6 && Nk == 8) || (Nb == 4 && Nk == 8)){ Nr = 14; //CASO AES-256 } else if ((Nb == 6 && Nk < 8) || (Nb == 4 && Nk == 6)){ Nr = 12; //CASO AES-192 } else { Nr = 10; //CASO AES-128 } } /**************************************************/ /**Metodos para el proceso de creacion de la clave*/ /**************************************************/ /** * expand_key */ void Rijndael::expand_key(unsigned char *in) { unsigned char t[4]; /* c is 16 because the first sub-key is the user-supplied key 128bits = 16 192bits = 24 256bits = 32 */ unsigned char incrOffset = 4 * Nk; unsigned char c = incrOffset; unsigned char i = 1; unsigned char a; //El tamanyo de las claves debe ser igual al tamanyo de los bloques para cuando hagamos el addroundkey unsigned char numsets = (Nr + 1) * Nb * 4; // bool flag = false; /* We need 11 sets of sixteen bytes each for 128-bit mode 1 set for the original key and 10 sets for the rest of rounds in 128-bit mode*/ while(c < numsets) { // flag = false; /* Copy the temporary variable over from the last 4-byte * block */ for(a = 0; a < 4; a++) t[a] = in[a + c - 4]; /* Every four blocks (of four bytes), * do a complex calculation */ if(c % incrOffset == 0) { schedule_core(t,i); i++; } else if (c % incrOffset == (Nb * 4) and Nk > 6){ for(a = 0; a < 4; a++) { t[a] = sbox(t[a]); } } for(a = 0; a < 4; a++) { in[c] = in[c - incrOffset] ^ t[a]; c++; } } } /** * This is the core key expansion, which, given a 4-byte value, * does some scrambling */ void Rijndael::schedule_core(unsigned char *in, unsigned char i) { unsigned char a; /* Rotate the input 8 bits to the left */ rotate(in); /* Apply Rijndael's s-box on all 4 bytes */ for(a = 0; a < 4; a++) in[a] = sbox(in[a]); /* On just the first byte, add 2^i to the byte */ in[0] ^= rcon(i); } /** * rotate */ void Rijndael::rotate(unsigned char *in) { unsigned char a,c; a = in[0]; for(c=0;c<3;c++) in[c] = in[c + 1]; in[3] = a; return; } /** * Calculate the rcon used in key expansion */ unsigned char Rijndael::rcon(unsigned char in) { unsigned char c=1; if(in == 0) return 0; while(in != 1) { unsigned char b; b = c & 0x80; c <<= 1; if(b == 0x80) { c ^= 0x1b; } in--; } return c; } /******************************************/ /**Metodos para el proceso de codificacion*/ /******************************************/ /** * bytesub * La tabla ya hace la transformacion lineal */ void Rijndael::bytesub(unsigned char *myB){ unsigned char i; for (i=0; i < Nb * 4; i++){ ////cout << hex << showbase << (int)myB[i] << ": "; myB[i] = sbox(myB[i]); } } /** * bytesub * La tabla ya hace la transformacion lineal */ void Rijndael::invBytesub(unsigned char *myB){ unsigned char i; for (i=0; i < Nb * 4; i++){ ////cout << hex << showbase << (int)myB[i] << ": "; myB[i] =invSbox(myB[i]); } } /** * sbox */ unsigned char Rijndael::sbox(unsigned char value){ return s[value]; } /** * invSbox */ unsigned char Rijndael::invSbox(unsigned char value){ return inv_s [value]; } /** * shiftrow */ void Rijndael::shiftrow(unsigned char *myB){ //cout << "shiftrow" << endl; unsigned char temp1; //Variable temporal para almacenar la primera celda unsigned char i; //Contador para las filas unsigned char j; //Contador para las rotaciones unsigned char k; //Contador para recorrer las columnas de cada fila //Especificamos las rotaciones que hay que hacer para las filas 1, 2, 3 unsigned char rotFilas[3] = {1,2,3}; //Si Nb == 8 las filas 2 y 3 tienen que hacer 3 y 4 rotaciones respectivamente if (Nb == 8) { rotFilas[1] = 3; rotFilas[2] = 4; } //Las rotaciones son para las filas 1 hasta la 3 for (i = 1; i < 4; i++){ //Hacemos las rotaciones de cada fila dependiendo del tamao de bloque for (j = 0; j < rotFilas[i-1]; j++){ //Guardamos el primer byte temp1 = myB[i]; //Rotamos los bytes hacia la izquierda for (k = 0 ;k < Nb-1; k++){ //cout << "Movemos: " << (4 * (k+1) + i) << " a: " << (4 * (k) + i) << endl; myB[4 * k + i] = myB[4 * (k+1) + i]; } //Ponemos el primer byte guardado en la ultima posicion //cout << "Pos last: " << (4 * (k) + i) << endl; myB[4 * k + i] = temp1; } } } /** * invShiftrow */ void Rijndael::invShiftrow(unsigned char *myB){ //cout << "invshiftrow" << endl; unsigned char temp1; //Variable temporal para almacenar la ultima celda unsigned char i; //Contador para las filas unsigned char j; //Contador para las rotaciones unsigned char k; //Contador para recorrer las columnas de cada fila //Especificamos las rotaciones que hay que hacer para las filas 1, 2, 3 unsigned char rotFilas[3] = {1,2,3}; //Si Nb == 8 las filas 2 y 3 tienen que hacer 3 y 4 rotaciones respectivamente if (Nb == 8) { rotFilas[1] = 3; rotFilas[2] = 4; } //Las rotaciones son para las filas 1 hasta la 3 for (i=1; i < 4; i++){ //Hacemos las rotaciones de cada fila dependiendo del tamao de bloque for (j = rotFilas[i-1]; j > 0; j--){ k = Nb-1; //Guardamos el ultimo byte temp1 = myB[ 4 * k + i]; //Rotamos los bytes hacia la derecha for (;k > 0; k--){ myB[4 * k + i] = myB[4 * (k-1) + i]; } //Ponemos el ultimo byte guardado en la primera posicion myB[i] = temp1; } } } /** * mixcolumn */ void Rijndael::mixcolumn(unsigned char *myB){ //cout << "mixcolumn" << endl; unsigned char a[4]; //Almacena las filas de cada columna unsigned char i; //Contador para las columnas de la matriz de datos unsigned char c; //Contador para las filas de la matriz de datos //Recorremos cada columna for (i=0; i < Nb; i++){ //Almacenamos las filas de cada columna en "a" for(c=i*4; c < i*4 + 4; c++) { a[c - i*4] = myB[c]; // cout << "c: " << (int)c << endl; } //Realizamos la multiplicacion de polinomios //c(x ) = 03 x3 + 01 x2 + 01 x + 02 //Como es multiplicacion en el campo finito 2^8 mejor si usamos tablas. Sino seria //Ej. multiplicar x por 2: (2 * x) MOD 2^8 //La suma la hacemos mediante XOR para que no pase del campo finito 2^8 myB[i*4] = galoisX2[a[0]] ^ a[3] ^ a[2] ^ galoisX3[a[1]]; /* 2 * a0 + a3 + a2 + 3 * a1 */ myB[i*4 + 1] = galoisX2[a[1]] ^ a[0] ^ a[3] ^ galoisX3[a[2]]; /* 2 * a1 + a0 + a3 + 3 * a2 */ myB[i*4 + 2] = galoisX2[a[2]] ^ a[1] ^ a[0] ^ galoisX3[a[3]]; /* 2 * a2 + a1 + a0 + 3 * a3 */ myB[i*4 + 3] = galoisX2[a[3]] ^ a[2] ^ a[1] ^ galoisX3[a[0]]; /* 2 * a3 + a2 + a1 + 3 * a0 */ // cout << "calculando"<<endl; } } /** * invMixcolumn */ void Rijndael::invMixcolumn(unsigned char *myB){ //cout << "invMixcolumn" << endl; unsigned char a[4]; //Almacena las filas de cada columna int i; //Contador para las columnas de la matriz de datos int c; //Contador para las filas de la matriz de datos //Recorremos cada columna for (i=0; i < Nb; i++ ){ //Almacenamos las filas de cada columna en "a" for(c=i*4;c < i*4 + 4;c++) { a[c - i*4] = myB[c]; } //Realizamos la multiplicacion de polinomios //d(x ) = 0B x3 + 0D x2 + 09 x + 0E //Como es multiplicacion en el campo finito 2^8 mejor si usamos tablas. Sino seria //Ej. multiplicar x por 2: (2 * x) MOD 2^8 //La suma la hacemos mediante XOR para que no pase del campo finito 2^8 myB[i*4] = galoisX14[a[0]] ^ galoisX9[a[3]] ^ galoisX13[a[2]] ^ galoisX11[a[1]]; /* 14 * a0 + 9 * a3 + 13 * a2 + 11 * a1 */ myB[i*4 + 1] = galoisX14[a[1]] ^ galoisX9[a[0]] ^ galoisX13[a[3]] ^ galoisX11[a[2]]; /* 14 * a1 + 9 * a0 + 13 * a3 + 11 * a2 */ myB[i*4 + 2] = galoisX14[a[2]] ^ galoisX9[a[1]] ^ galoisX13[a[0]] ^ galoisX11[a[3]]; /* 14 * a2 + 9 * a1 + 13 * a0 + 11 * a3 */ myB[i*4 + 3] = galoisX14[a[3]] ^ galoisX9[a[2]] ^ galoisX13[a[1]] ^ galoisX11[a[0]]; /* 14 * a3 + 9 * a2 + 13 * a1 + 11 * a0 */ } } /** * addroundkey */ void Rijndael::addroundkey(unsigned char *myB, unsigned char *myK, unsigned char ronda){ //cout << "addroundkey" << endl; unsigned char i; unsigned char elemsRonda = Nb * 4; for (i = 0; i < elemsRonda; i++){ myB[i] = myB[i] ^ myK[(ronda * elemsRonda) + i]; ////cout << hex << showbase << (int) b[i] << " XOR " << (int)k[(ronda * 16) + i] << " = " << (int)b[i] << endl; } } /** * printKey */ void Rijndael::printKey(unsigned char *data){ cout << "[" ; unsigned char i; for (i=0;i<176;i++){ if (i % 16 == 0 && i > 0) cout << endl; cout << hex << showbase << (int)data[i]; if (i < 175) cout << ","; } cout << "]" << endl ; } /** * print */ void Rijndael::print(unsigned char *data){ cout << "[" ; unsigned char i; for (i = 0; i < 16; i++){ cout << hex << showbase << (int)data[i]; if (i < 15) cout << ","; } cout << "]" << endl ; }
true
c5e43552d6b7f7e129e6e6760691a4ae547024c3
C++
MatheusFerreiradeOliveira/Codes
/Questões Aleatórias/Circuito bioquimico.cpp
UTF-8
783
2.6875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int c,l,palito; cin>>c>>l>>palito; while(c!=0 and l!=0 and palito!=0) { int matriz[l][c]; for(int i =0; i < l; i++) { for(int j=0; j < c;j++) { cin>>matriz[i][j]; } } int atual =0, resp =0; for(int i =0; i < c; i++) { for(int j=0; j < l; j++) { if(matriz[j][i] == 0) atual = 0; if(matriz[j][i] == 1) atual++; if(atual == palito){ resp++; } } atual = 0; } cout<<resp<<endl; cin>>c>>l>>palito; } }
true
9aba87f64937cb2b78394b144e5157777ca9e3fd
C++
shader-slang/slang
/source/core/slang-crypto.h
UTF-8
4,799
3.03125
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#pragma once #include "../../slang.h" #include "../core/slang-string.h" #include "../core/slang-blob.h" #include "../core/slang-list.h" namespace Slang { struct DigestUtil { /// Convert a binary digest to a string (lower-case hexadecimal). /// Returned string is double the length of the digest. static String digestToString(const void* digest, SlangInt digestSize); /// Convert a string to a binary digest. /// Expects a string of double the length of the digest size in hexadecimal format. /// Sets the digest to all zeros if the string is invalid. /// Returns true if string was converted successfully. static bool stringToDigest(const char* str, SlangInt strLength, void *digest, SlangInt digestSize); }; /// Represents a hash digest. Only sizes of multiple of 4 are supported. template<SlangInt N> class HashDigest { public: static_assert(N % 4 == 0, "size must be multiple of 4"); uint32_t data[N / 4] = { 0 }; HashDigest() = default; HashDigest(const char* str) { DigestUtil::stringToDigest(str, ::strlen(str), data, N); } HashDigest(const String& str) { DigestUtil::stringToDigest(str.getBuffer(), str.getLength(), data, N); } HashDigest(const UnownedStringSlice& str) { DigestUtil::stringToDigest(str.begin(), str.getLength(), data, N); } HashDigest(ISlangBlob* blob) { if (blob->getBufferSize() == N) { ::memcpy(data, blob->getBufferPointer(), N); } } String toString() const { return DigestUtil::digestToString(data, N); } ComPtr<ISlangBlob> toBlob() const { return RawBlob::create(data, sizeof(data)); } bool operator==(const HashDigest& other) const { return ::memcmp(data, other.data, sizeof(data)) == 0; } bool operator!=(const HashDigest& other) const { return !(*this == other); } uint32_t getHashCode() const { return data[0]; } }; /// MD5 hash generator implementing https://www.ietf.org/rfc/rfc1321.txt class MD5 { public: using Digest = HashDigest<16>; MD5(); void init(); void update(const void* data, SlangSizeT size); Digest finalize(); static Digest compute(const void* data, SlangInt size); private: const void* processBlock(const void* data, SlangInt size); uint32_t m_lo, m_hi; uint32_t m_a, m_b, m_c, m_d; uint32_t m_block[16]; uint8_t m_buffer[64]; }; /// SHA1 hash generator implementing https://www.ietf.org/rfc/rfc3174.txt class SHA1 { public: using Digest = HashDigest<20>; SHA1(); void init(); void update(const void* data, SlangSizeT size); Digest finalize(); static Digest compute(const void* data, SlangInt size); private: void addByte(uint8_t x); void processBlock(const uint8_t* ptr); uint32_t m_index; uint64_t m_bits; uint32_t m_state[5]; uint8_t m_buf[64]; }; // Helper class for building hashes. template<typename Hash> struct DigestBuilder { public: void append(const void* data, SlangInt size) { m_hash.update(data, size); } template<typename T, typename std::enable_if<std::is_arithmetic<T>::value || std::is_enum<T>::value, int>::type = 0> void append(const T value) { append(&value, sizeof(T)); } void append(const String& str) { append(str.getBuffer(), str.getLength()); } void append(const StringSlice& str) { append(str.begin(), str.getLength()); } void append(const UnownedStringSlice& str) { append(str.begin(), str.getLength()); } void append(ISlangBlob* blob) { append(blob->getBufferPointer(), blob->getBufferSize()); } template<SlangInt N> void append(const HashDigest<N>& digest) { append(digest.data, sizeof(digest.data)); } template<typename T, std::enable_if_t<std::has_unique_object_representations_v<T>, int> = 0> void append(const List<T>& list) { append(list.getBuffer(), list.getCount() * sizeof(T)); } typename Hash::Digest finalize() { return m_hash.finalize(); } private: Hash m_hash; }; }
true
861686590db328218100ec99e2b4ef687ee3073c
C++
andeplane/molecular-dynamics
/src/atomlist.cpp
UTF-8
4,328
2.859375
3
[]
no_license
#include <atomlist.h> #include <utility> #include <iostream> #include <includes.h> using CompPhys::Utils::at; AtomList::AtomList(int initialAtomCount) : m_atomsDirty(false), m_onAtomMoved(0), m_isIterating(false) { m_atoms.reserve(initialAtomCount); } AtomList::~AtomList() { m_indexMap.clear(); m_atoms.clear(); } int AtomList::numberOfAtoms() { return atoms().size(); } bool AtomList::containsAtomWithUniqueId(unsigned long uniqueId) { return m_indexMap.find(uniqueId) != m_indexMap.end(); } Atom &AtomList::getAtomByUniqueId(unsigned long uniqueId) { if(!containsAtomWithUniqueId(uniqueId)) { throw std::range_error("The atom is not in this list"); } return at(m_atoms,m_indexMap[uniqueId]); } void AtomList::rebuildIndexMap() { m_indexMap.clear(); iterate([&](Atom &atom, const int &index) { m_indexMap[atom.uniqueId()] = index; }); } Atom &AtomList::addAtom(shared_ptr<AtomType> atomType) { vector<Atom> *list = &m_atoms; if(m_isIterating) list = &m_tempAtoms; list->push_back(Atom(atomType)); Atom &atom = list->back(); unsigned long indexOfThisAtom = m_atoms.size()-1; m_indexMap[atom.uniqueId()] = indexOfThisAtom; // m_indexMap.insert(pair<unsigned long, unsigned long>(atom.uniqueId(),indexOfThisAtom)); atom.setType(atomType); atom.addOnRemoved([&]() { // This list should know if an atom has been moved m_atomsDirty = true; }); atom.addOnMoved(m_onAtomMoved); // Set default function that will be called on move function on atoms return atom; } void AtomList::removeAllAtoms() { m_indexMap.clear(); m_atoms.clear(); } void AtomList::moveTempAtomsToList() { if(m_tempAtoms.size() == 0) return; m_atoms.insert(m_atoms.end(), m_tempAtoms.begin(), m_tempAtoms.end()); m_tempAtoms.clear(); rebuildIndexMap(); } void AtomList::iterate(function<void (Atom &atom)> action) { m_isIterating = true; for(unsigned long atomIndex=0; atomIndex<m_atoms.size(); atomIndex++) { Atom &atom = at(m_atoms,atomIndex); action(atom); } m_isIterating = false; moveTempAtomsToList(); } void AtomList::iterate(function<void (Atom &atom, const int &atomIndex)> action) { m_isIterating = true; for(unsigned long atomIndex=0; atomIndex<m_atoms.size(); atomIndex++) { Atom &atom = at(m_atoms,atomIndex); action(atom, atomIndex); } m_isIterating = false; moveTempAtomsToList(); } const vector<Atom> &AtomList::atoms() { if(m_atomsDirty) cleanupList(); return m_atoms; } void AtomList::cleanupList() { m_atomsDirty = false; if(m_atoms.size() == 0) return; int numberOfAtoms = m_atoms.size(); // Point on the back element so we can switch a moved atom with this one vector<Atom>::iterator lastElementIterator = --m_atoms.end(); for(int atomIndex=0; atomIndex<numberOfAtoms; atomIndex++) { Atom &atom = at(m_atoms,atomIndex); if(atom.removed()) { Atom &lastAtomInList = *lastElementIterator; std::swap(atom,lastAtomInList); // Swap this moved element and the back element std::swap(m_indexMap[atom.uniqueId()], m_indexMap[lastAtomInList.uniqueId()]); // Swap the index map for these two atoms lastElementIterator--; // Now, choose the previous element as back element numberOfAtoms--; // For the for loop range check atomIndex--; // Re-check this index, a new atom has taken its place } } m_atoms.resize(numberOfAtoms); } void AtomList::resetVelocityZero() { iterate([](Atom &atom) { atom.setVelocity(0,0,0); }); } void AtomList::resetVelocityMaxwellian(double temperature) { iterate([&](Atom &atom) { atom.resetVelocityMaxwellian(temperature); }); } void AtomList::setOnAtomMoved(const function<void ()> &onAtomMoved) { m_onAtomMoved = onAtomMoved; } std::ostream& operator<<(std::ostream &stream, AtomList &atomList) { stream << "Atom list has " << atomList.numberOfAtoms() << " atoms." << std::endl; atomList.iterate([&](Atom &atom, const int &atomIndex) { stream << atomIndex << ": " << atom << std::endl; }); return stream; }
true
7e6ba18221475541173b8cfa1a77ee98134dffbb
C++
Streamlet/ZLibWrap
/src/encoding_win.cc
UTF-8
2,791
2.59375
3
[ "MIT" ]
permissive
#include "encoding.h" #include <Windows.h> #if MSC_VER < 1600 #define nullptr NULL #endif namespace encoding { namespace { std::wstring ANSIToUCS2(const char *ansi, size_t length, UINT code_page) { std::wstring ucs2; int size = ::MultiByteToWideChar(code_page, 0, ansi, (int)length, nullptr, 0); if (size == 0) return ucs2; ucs2.resize(length == -1 || ansi[length - 1] == '\0' ? size - 1 : size); ::MultiByteToWideChar(code_page, 0, ansi, (int)length, &ucs2[0], size); return ucs2; } std::string UCS2ToANSI(const wchar_t *ucs2, size_t length, UINT code_page) { std::string ansi; int size = ::WideCharToMultiByte(code_page, 0, ucs2, (int)length, nullptr, 0, nullptr, nullptr); if (size == 0) return ansi; ansi.resize(length == -1 || ucs2[length - 1] == L'\0' ? size - 1 : size); ::WideCharToMultiByte(code_page, 0, ucs2, (int)length, &ansi[0], size, nullptr, nullptr); return ansi; } } // namespace std::wstring UTF8ToUCS2(const std::string &utf8) { return UTF8ToUCS2(utf8.c_str(), utf8.length()); } #if __cplusplus >= 201703L std::wstring UTF8ToUCS2(const std::string_view &utf8) { return UTF8ToUCS2(utf8.data(), utf8.length()); } #endif std::wstring UTF8ToUCS2(const char *utf8) { return UTF8ToUCS2(utf8, -1); } std::wstring UTF8ToUCS2(const char *utf8, size_t length) { return ANSIToUCS2(utf8, length, CP_UTF8); } std::string UCS2ToUTF8(const std::wstring &ucs2) { return UCS2ToUTF8(ucs2.c_str(), ucs2.length()); } #if __cplusplus >= 201703L std::string UCS2ToUTF8(const std::wstring_view &ucs2) { return UCS2ToUTF8(ucs2.data(), ucs2.length()); } #endif std::string UCS2ToUTF8(const wchar_t *ucs2) { return UCS2ToUTF8(ucs2, -1); } std::string UCS2ToUTF8(const wchar_t *ucs2, size_t length) { return UCS2ToANSI(ucs2, length, CP_UTF8); } std::wstring ANSIToUCS2(const std::string &ansi) { return ANSIToUCS2(ansi.c_str(), ansi.length()); } #if __cplusplus >= 201703L std::wstring ANSIToUCS2(const std::string_view &ansi) { return ANSIToUCS2(ansi.data(), ansi.length()); } #endif std::wstring ANSIToUCS2(const char *ansi) { return ANSIToUCS2(ansi, -1); } std::wstring ANSIToUCS2(const char *ansi, size_t length) { return ANSIToUCS2(ansi, length, CP_ACP); } std::string UCS2ToANSI(const std::wstring &ucs2) { return UCS2ToANSI(ucs2.c_str(), ucs2.length()); } #if __cplusplus >= 201703L std::string UCS2ToANSI(const std::wstring_view &ucs2) { return UCS2ToANSI(ucs2.data(), ucs2.length()); } #endif std::string UCS2ToANSI(const wchar_t *ucs2) { return UCS2ToANSI(ucs2, -1); } std::string UCS2ToANSI(const wchar_t *ucs2, size_t length) { return UCS2ToANSI(ucs2, length, CP_ACP); } } // namespace encoding
true
ad459fefd26c3e104427e67746ae75ffaa7776aa
C++
rebiscov/ACM
/S12/11506-vrebisco.cpp
UTF-8
2,550
2.890625
3
[]
no_license
#include <cstdio> #include <vector> #include <queue> /* C'est comme le premier exo sauf qu'on double les noeuds (hors s et t) en deux noeuds, un noeud "in" ou les flux entre et un noeud "out" ou les flux sortent et entre les deux une arrete qui represente le cout pour retirer la machine */ unsigned int s, t, n, count; bool bfs(std::vector<std::vector<unsigned int>> &graph, std::vector<std::vector<unsigned int>> &b, std::vector<unsigned int> &path){ unsigned int u; std::queue<unsigned int> q; std::vector<bool> seen(n, false); std::vector<int> pred(n, -1); q.push(s); seen[s] = true; pred[s] = s; while(!q.empty()){ u = q.front(); q.pop(); for (unsigned int i = 0; i < graph[u].size(); i++){ if (!seen[graph[u][i]] && b[u][graph[u][i]] > 0){ seen[graph[u][i]] = true; q.push(graph[u][i]); pred[graph[u][i]] = u; } } } if (pred[t] == -1) return false; u = t; while(pred[u] != u){ path.push_back(u); u = pred[u]; } path.push_back(s); return true; } void adjust(std::vector<std::vector<unsigned int>> &graph, std::vector<std::vector<unsigned int>> &b, std::vector<unsigned int> &path){ unsigned int min = b[path[1]][path[0]]; for(unsigned int i = 0; i < path.size() - 1; i++){ if (b[path[i+1]][path[i]] < min) min = b[path[i+1]][path[i]]; } for(unsigned int i = 0; i < path.size() - 1; i++){ b[path[i+1]][path[i]] -= min; b[path[i]][path[i+1]] += min; } count += min; } int main(void){ unsigned int W, u, v, np, cost, up, vp; s = 0; while(scanf("%u %u", &n, &W) > 0 && n != 0 && W != 0){ np = n; n = 2*n -1; std::vector<std::vector<unsigned int>> graph(n); std::vector<std::vector<unsigned int>> f(n, std::vector<unsigned int> (n, 0)); std::vector<std::vector<unsigned int>> b(n, std::vector<unsigned int> (n, 0)); count = 0; t = np-1; for (unsigned int i = 0; i < np-2; i++){ scanf("%u %u", &u, &cost); u--; b[u][u+np] += cost; graph[u].push_back(u+np); } for (unsigned int i = 0; i < W; i++){ scanf("%u %u %u", &u, &v, &cost); u--; v--; if (u != 0 && u != t) up = u + np; else up = u; if (v != 0 && v != t) vp = v + np; else vp = v; graph[up].push_back(v); graph[vp].push_back(u); b[up][v] += cost; b[vp][u] += cost; } std::vector<unsigned int> path; while(bfs(graph, b, path)){ adjust(graph, b, path); path.clear(); } printf("%u\n", count); } return 0; }
true
57fef8555154ada13202a67b3261e0270df888dd
C++
BearZerk/Old-Code-Samples
/C Scripts/C++ OpenGL/Building.cpp
UTF-8
11,122
2.96875
3
[]
no_license
#include "Building.h" Building::~Building() { } Building::Building() : xrot (0.0f), yrot(0.0f), zrot(0.0f), scale(0.5) { //Set up the 3 dfferent textures that's going to be used tex_wall_id = Scene::GetTexture("./Brick.bmp"); if (tex_wall_id != NULL) { toTexture_wall = true; }else{ toTexture_wall = false; } tex_roof_id = Scene::GetTexture("./Terracotta.bmp"); if (tex_roof_id != NULL) { toTexture_roof = true; }else{ toTexture_roof = false; } tex_floor_id = Scene::GetTexture("./Gravel.bmp"); if (tex_floor_id != NULL) { toTexture_floor = true; }else{ toTexture_floor = false; } } void Building::Draw() { //Standard set up of attributes and matrix glPushMatrix(); if(toTexture_wall) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, tex_wall_id); } float r = 25.0f; glTranslatef(0.0f, 0.0f, -r*16); glDisable(GL_CULL_FACE); //Set materials for lighting values. float mat_colour[] // colour reflected by diffuse light = { 0.5f, 0.5f, 0.5f, 1.f }; float mat_ambient[] // ambient colour = { 0.333f, 0.333f, 0.333f, 1.f }; float mat_spec[] // specular colour = { 0.125f, 0.125f, 0.125f, 1.f }; glPushAttrib(GL_ALL_ATTRIB_BITS); // save current style attributes (inc. material properties) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient); // set colour for ambient reflectance glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_colour); // set colour for diffuse reflectance glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_spec); // set colour for specular reflectance //Actually start drawing glPushMatrix(); //head backwards, draw the front wall, go back a little more draw the back wall //come toward camera & down, draw floor //Store current point glTranslatef(0, 0, -r*20); glNormal3f(0, 0, 1); Wall(r*10, r*2, 1); glTranslatef(0, 0, -r*2); glNormal3f(0, 0, -1); Wall(r*10, r*2, 1); glTranslatef(0, -r*2, r); glNormal3f(0, -1, 0); Wall(r*10, 1, r); glPushMatrix(); //Go Left & Up, draw wall, head further up, draw triangluar wall head for roof to rest upon. //pop matrix and do this all again but go the right hand side. glTranslatef(-r*10, r*2, 0); glNormal3f(-1, 0, 0); Wall(1, r*2, r); glTranslatef(0, r*2, 0); glRotatef(90.0f, 0, 1.0f, 0); glNormal3f(-1, 0, 0); Wall_Top(r, r, 1); glPopMatrix(); glPushMatrix(); glTranslatef(r*10, r*2, 0); glNormal3f(1, 0, 0); Wall(1, r*2, r); glTranslatef(0, r*2, 0); glRotatef(90.0f, 0, 1.0f, 0); glNormal3f(1, 0, 0); Wall_Top(r, r, 1); glPopMatrix(); glPopMatrix(); //Create the building off shoots left & right glPushMatrix(); Building_Side(r*10, r, 1); glPopMatrix(); glPushMatrix(); Building_Side(-r*6, r, -1); glPopMatrix(); //Switch over to drawing the roof by changing the texture buffer if (toTexture_roof) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, tex_roof_id); } //From original starting point //Move back and up, rotate to draw more easily //Draw nearest roofing, translate re-rotate and do the right hand side for the middle building glPushMatrix(); glTranslatef(0, r*2, -r*20); glNormal3f(0, 1, 1); glRotatef(-45.0f, 1.0f, 0, 0); Roof(r*10, r*1.5f, 1); glRotatef(45.0f, 1.0f, 0, 0); glTranslatef(0, 0, -r*2); glRotatef(45.0f, 1.0f, 0, 0); glNormal3f(0, 1, -1); Roof(r*10, r*1.5f, 1); glPopMatrix(); //From original point, move right & up. //Translate, rotate, rotate again so that it's perpendicular to the x axis //Draw roof, move more to the right, re-rotate and draw the far side roof on the right hand side building glPushMatrix(); glTranslatef(r*7, r*0.5f, -r*10); glRotatef(90.0f, 0, 1.0f, 0); glRotatef(65.0f, 1.0f, 0, 0); glNormal3f(-1, 1, 0); Roof(r*10, r*1.25f, 1); glRotatef(-65.0f, 1.0f, 0, 0); glTranslatef(0, 0, r*2); glRotatef(-65.0f, 1.0f, 0, 0); glNormal3f(0, 1, 1); Roof(r*10, r*1.25, 1); glPopMatrix(); //Do everything from the last push/pop but on the left hand side instead glPushMatrix(); glTranslatef(-r*9, r*0.5f, -r*10); glRotatef(90.0f, 0, 1.0f, 0); glRotatef(65.0f, 1.0f, 0, 0); glNormal3f(-1, 1, 0); Roof(r*10, r*1.25f, 1); glRotatef(-65.0f, 1.0f, 0, 0); glTranslatef(0, 0, r*2); glRotatef(-65.0f, 1.0f, 0, 0); glNormal3f(0, 1, 1); Roof(r*10, r*1.25, 1); glPopMatrix(); //Change to floor texture if (toTexture_floor) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, tex_floor_id); } //Create 2 floor quads, 1 looks TOO stetched, 2 is reasonable glPushMatrix(); glTranslatef(0, -r*2, -r*15); Floor(r*6); glTranslatef(0, 0, r*12); Floor(r*6); glPopMatrix(); //Pop all values, enable cull facing again, disable texturing glPopAttrib(); glEnable(GL_CULL_FACE); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); glPopMatrix(); } void Building::Wall(float x, float y, float z) { glBegin(GL_QUADS); // Near face if(toTexture_wall) glTexCoord2f(0.f, 0.f); glVertex3f(-x, -y, z); if(toTexture_wall) glTexCoord2f(0.f, 1.f); glVertex3f(-x, y, z); if(toTexture_wall) glTexCoord2f(1.f, 1.f); glVertex3f(x, y, z); if(toTexture_wall) glTexCoord2f(1.f, 0.f); glVertex3f(x, -y, z); // Right face if(toTexture_wall) glTexCoord2f(0.f, 0.f); glVertex3f(x, -y, z); if(toTexture_wall) glTexCoord2f(0.f, 1.f); glVertex3f(x, y, z); if(toTexture_wall) glTexCoord2f(1.f, 1.f); glVertex3f(x, y, -z); if(toTexture_wall) glTexCoord2f(1.f, 0.f); glVertex3f(x, -y, -z); // Back face if(toTexture_wall) glTexCoord2f(0.f, 0.f); glVertex3f(-x, -y, -z); if(toTexture_wall) glTexCoord2f(0.f, 1.f); glVertex3f(-x, y, -z); if(toTexture_wall) glTexCoord2f(1.f, 1.f); glVertex3f(x, y, -z); if(toTexture_wall) glTexCoord2f(1.f, 0.f); glVertex3f(x, -y, -z); // Left face if(toTexture_wall) glTexCoord2f(0.f, 0.f); glVertex3f(-x, -y, z); if(toTexture_wall) glTexCoord2f(0.f, 1.f); glVertex3f(-x, y, z); if(toTexture_wall) glTexCoord2f(1.f, 1.f); glVertex3f(-x, y, -z); if(toTexture_wall) glTexCoord2f(1.f, 0.f); glVertex3f(-x, -y, -z); // Top face if(toTexture_wall) glTexCoord2f(0.f, 0.f); glVertex3f(-x, -y, z); if(toTexture_wall) glTexCoord2f(0.f, 1.f); glVertex3f(-x, -y, -z); if(toTexture_wall) glTexCoord2f(1.f, 1.f); glVertex3f(x, -y, -z); if(toTexture_wall) glTexCoord2f(1.f, 0.f); glVertex3f(x, -y, z); // Bottom face if(toTexture_wall) glTexCoord2f(0.f, 0.f); glVertex3f(-x, y, z); if(toTexture_wall) glTexCoord2f(0.f, 1.f); glVertex3f(-x, y, -z); if(toTexture_wall) glTexCoord2f(1.f, 1.f); glVertex3f(x, y, -z); if(toTexture_wall) glTexCoord2f(1.f, 0.f); glVertex3f(x, y, z); glEnd(); } void Building::Roof(float x, float y, float z) { glBegin(GL_QUADS); // Near face if(toTexture_roof) glTexCoord2f(0.f, 0.f); glVertex3f(-x, -y, z); if(toTexture_roof) glTexCoord2f(0.f, 1.f); glVertex3f(-x, y, z); if(toTexture_roof) glTexCoord2f(1.f, 1.f); glVertex3f(x, y, z); if(toTexture_roof) glTexCoord2f(1.f, 0.f); glVertex3f(x, -y, z); // Right face if(toTexture_roof) glTexCoord2f(0.f, 0.f); glVertex3f(x, -y, z); if(toTexture_roof) glTexCoord2f(0.f, 1.f); glVertex3f(x, y, z); if(toTexture_roof) glTexCoord2f(1.f, 1.f); glVertex3f(x, y, -z); if(toTexture_roof) glTexCoord2f(1.f, 0.f); glVertex3f(x, -y, -z); // Back face if(toTexture_roof) glTexCoord2f(0.f, 0.f); glVertex3f(-x, -y, -z); if(toTexture_roof) glTexCoord2f(0.f, 1.f); glVertex3f(-x, y, -z); if(toTexture_roof) glTexCoord2f(1.f, 1.f); glVertex3f(x, y, -z); if(toTexture_roof) glTexCoord2f(1.f, 0.f); glVertex3f(x, -y, -z); // Left face if(toTexture_roof) glTexCoord2f(0.f, 0.f); glVertex3f(-x, -y, z); if(toTexture_roof) glTexCoord2f(0.f, 1.f); glVertex3f(-x, y, z); if(toTexture_roof) glTexCoord2f(1.f, 1.f); glVertex3f(-x, y, -z); if(toTexture_roof) glTexCoord2f(1.f, 0.f); glVertex3f(-x, -y, -z); // Top face if(toTexture_roof) glTexCoord2f(0.f, 0.f); glVertex3f(-x, -y, z); if(toTexture_roof) glTexCoord2f(0.f, 1.f); glVertex3f(-x, -y, -z); if(toTexture_roof) glTexCoord2f(1.f, 1.f); glVertex3f(x, -y, -z); if(toTexture_roof) glTexCoord2f(1.f, 0.f); glVertex3f(x, -y, z); // Bottom face if(toTexture_roof) glTexCoord2f(0.f, 0.f); glVertex3f(-x, y, z); if(toTexture_roof) glTexCoord2f(0.f, 1.f); glVertex3f(-x, y, -z); if(toTexture_roof) glTexCoord2f(1.f, 1.f); glVertex3f(x, y, -z); if(toTexture_roof) glTexCoord2f(1.f, 0.f); glVertex3f(x, y, z); glEnd(); } void Building::Wall_Top(float x, float y, float z) { glBegin(GL_TRIANGLES); if(toTexture_wall) glTexCoord2f(0.f, 0.f); glVertex3f(-x, 0, z); if(toTexture_wall) glTexCoord2f(1.f, 0.f); glVertex3f(x, 0, z); if(toTexture_wall) glTexCoord2f(1.f, 1.f); glVertex3f(0, y, z); if(toTexture_wall) glTexCoord2f(0.f, 0.f); glVertex3f(-x, 0, -z); if(toTexture_wall) glTexCoord2f(1.f, 0.f); glVertex3f(x, 0, -z); if(toTexture_wall) glTexCoord2f(1.f, 1.f); glVertex3f(0, y, -z); glEnd(); glBegin(GL_QUADS); //Left if(toTexture_wall) glTexCoord2f(0.f, 0.f); glVertex3f(-x, 0, z); if(toTexture_wall) glTexCoord2f(0.f, 1.f); glVertex3f(0, y, z); if(toTexture_wall) glTexCoord2f(1.f, 1.f); glVertex3f(0, y, -z); if(toTexture_wall) glTexCoord2f(1.f, 0.f); glVertex3f(-x, 0, -z); //Right if(toTexture_wall) glTexCoord2f(0.f, 0.f); glVertex3f(x, 0, z); if(toTexture_wall) glTexCoord2f(0.f, 1.f); glVertex3f(0, y, z); if(toTexture_wall) glTexCoord2f(1.f, 1.f); glVertex3f(0, y, -z); if(toTexture_wall) glTexCoord2f(1.f, 0.f); glVertex3f(x, 0, -z); //Bottom if(toTexture_wall) glTexCoord2f(0.f, 0.f); glVertex3f(-x, 0, z); if(toTexture_wall) glTexCoord2f(0.f, 1.f); glVertex3f(-x, 0, -z); if(toTexture_wall) glTexCoord2f(1.f, 1.f); glVertex3f(x, 0, -z); if(toTexture_wall) glTexCoord2f(1.f, 0.f); glVertex3f(x, 0, z); glEnd(); } void Building::Building_Side(float x, float r, int normal) { int p; glTranslatef(x, -r, -r*10); glRotatef(90.0f, 0, 1.0f, 0); p = (normal == 1) ? 1 : -1; glNormal3f(p, 0, 0); Wall(r*10, r, 1); glTranslatef(0, 0, -r*4); p = (normal == 1) ? -1 : 1; glNormal3f(p, 0, 0); Wall(r*10, r, 1); glTranslatef(0, -r, r*2); glNormal3f(0, 1, 0); Wall(r*10, 1, r*2); glTranslatef(-r*10, r, 0); glNormal3f(0, 0, 1); Wall(1, r, r*2); glTranslatef(0, r, 0); glRotatef(90.0f, 0, 1.0f, 0); glNormal3f(0, 0, -1); Wall_Top(r*2, r, 1); } void Building::Floor(float x) { glPushMatrix(); glRotatef(90.0f, 1.0f, 0, 0); glBegin(GL_QUADS); glNormal3f(0, 0, -1); if(toTexture_floor) glTexCoord2f(0.f, 0.f); glVertex3f(-x, -x, 0); if(toTexture_floor) glTexCoord2f(0.f, 1.f); glVertex3f(-x, x, 0); if(toTexture_floor) glTexCoord2f(1.f, 1.f); glVertex3f(x, x, 0); if(toTexture_floor) glTexCoord2f(1.f, 0.f); glVertex3f(x, -x, 0); glEnd(); glPopMatrix(); }
true
8106e59f53b41c0ac4ab8a2dc5be882c9823c2ef
C++
XFeiF/DataStructures
/7-Tree/BinaryTree/biTreeFunc.cpp
UTF-8
1,796
3.578125
4
[]
no_license
#include <iostream> #include <cstdio> #include <cstdlib> using namespace std; // judge empty bool isEmpty(BTree T){ if(!T) return true; else return false; } // find the size of the binary tree void findSize(BTree T, int &size){ if(!isEmpty(T)) { size++; findSize(T->left, size); findSize(T->right, size); }else return; } int getDepth(BTree T){ int depth, lDepth, rDepth; if(isEmpty(T)) return 0; lDepth = getDepth(T->left) + 1; rDepth = getDepth(T->right) + 1; depth = (lDepth>rDepth) ? lDepth : rDepth; // cout<<"depth = " << depth << endl; return depth; } // Finds the element x in the binary tree // 这里的 if(T->data == x) return true; 必须放最后一句 bool find(BTree T, const DataType x){ // cout << "in" << (int)(T->data == x) << endl; if(T->right) find(T->right, x); else if(T->left) find(T->left, x); else if(T->data == x) return true; } //递归创建树 BTree createTree(BTree &root){ root = (BTree)malloc(sizeof(BTNode)); if(root == NULL){ cout<<"malloc failed\n"; exit(-1); } DataType val; cout << "Please input a data (here is int , q to quit):"; if(scanf("%d",&val)==1){ root->data = val; cout << "create left child tree:\n"; root->left = createTree(root->left); fflush(stdin); cout << "create right child tree:\n"; root->right = createTree(root->right); } else return NULL; return root; } //取根节点的data域 返回给x bool root(DataType &x, const BTree T){ if(isEmpty(T)) return false; else x = T->data; return true; } //清空二叉树 void clearBTree(BTree T){ if(isEmpty(T)) return; clearBTree(T->left); clearBTree(T->right); free(T); }
true
b81d1d1c66fe10450511ab4cade753630474eff6
C++
gzsus/COMP345-PROJECT
/COMP345 - PROJECT/assignment1/MapLoader.h
UTF-8
2,715
3.09375
3
[]
no_license
////////////////////////////////////////////////////////////////////////////////////////////////////// // // MapLoader.h Samuel Renaud // ////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include<string> #include<vector> #include "Map.h" class MapLoader { public: MapLoader(); MapLoader(const MapLoader& a); //copy constructor MapLoader(std::string mapfile); MapLoader& operator =(const MapLoader& oldloader);// assignment operator void setfile(std::string newfile); void setmap(Map* new_map){this->created_map = new_map;} Map* getmap() { return this->created_map; } std::string getfile(); virtual void FileReader(std::string mapfile); Map LoadMap(std::vector<std::vector<std::string>>continents, std::vector<std::vector<std::string>> territories, std::vector<std::vector<std::string>>borders); ~MapLoader(); private: Map* created_map; //this will store the map objects once they are created std::string file; //lists used to store informaion taken from .map files std::vector<std::vector<std::string>> continent_list; std::vector<std::vector<std::string>> country_list; std::vector<std::vector<std::string>> border_list; friend std::ostream& operator<<(std::ostream&, const MapLoader&); //stream insertion operator }; class ConquestFileReader { public: ConquestFileReader(); ConquestFileReader(const ConquestFileReader&a); //copy constructer ConquestFileReader(std::string mapfile); void setfile(std::string newfile) { file = newfile; }; void setmap(Map* new_map) { this->created_map = new_map; } Map* getmap() { return this->created_map; } std::string getfile() { return file; }; void FileReader(std::string mapfile); Map LoadMap(std::vector<std::vector<std::string>>continents, std::vector<std::vector<std::string>> territories, std::vector<std::vector<std::string>>borders); ConquestFileReader& operator=(const ConquestFileReader& oldloader);// assignment operator ~ConquestFileReader(); private: Map* created_map; //this will store the map objects once they are created std::string file; //lists used to store informaion taken from .map files std::vector<std::vector<std::string>> continent_list; std::vector<std::vector<std::string>> country_list; std::vector<std::vector<std::string>> border_list; friend std::ostream& operator<<(std::ostream&, const MapLoader&); //stream insertion operator }; class ConquestFileReaderAdapter :public MapLoader { private: ConquestFileReader *conquest_map; public: ConquestFileReaderAdapter(ConquestFileReader conquest_file_reader); void FileReader(std::string mapfile); Map* getmap() { return this->conquest_map->getmap(); } };
true
c12c08df14496672f538f2987d2256829a7beb68
C++
ascheglov/tile_game
/tests/regression_tests/move_tests.cpp
UTF-8
6,018
2.734375
3
[]
no_license
#include "Game.hpp" #include "catch.hpp" #include "test_printers.hpp" #include "test_game_config.hpp" #include "TestClient.hpp" TEST_CASE("move alone", "[game]") { Game game{TestGameCfg}; TestClient A(game, "A", {3, 2}); REQUIRE(A.m_state == PlayerState::Idle); A.requestMove(Dir::Right); game.tick(); REQUIRE(A.m_state == PlayerState::MovingOut); REQUIRE(A.m_moveDir == Dir::Right); game.tick(); REQUIRE(A.m_state == PlayerState::MovingIn); REQUIRE(A.m_pos == Point(4, 2)); game.tick(); REQUIRE(A.m_state == PlayerState::Idle); } TEST_CASE("observe move", "[game]") { Game game{TestGameCfg}; TestClient A(game, "A", {3, 2}); TestClient B(game, "B", {3, 3}); A.requestMove(Dir::Right); game.tick(); REQUIRE(B.see("A").m_state == PlayerState::MovingOut); REQUIRE(B.see("A").m_moveDir == Dir::Right); game.tick(); REQUIRE(B.see("A").m_state == PlayerState::MovingIn); REQUIRE(B.see("A").m_pos == Point(4, 2)); game.tick(); REQUIRE(B.see("A").m_state == PlayerState::Idle); } TEST_CASE("spawn and see move out", "[game]") { Game game{TestGameCfg}; TestClient A(game, "A", {3, 2}); A.requestMove(Dir::Right); game.tick(); TestClient B(game, "B", {3, 3}); REQUIRE(B.see("A").m_state == PlayerState::MovingOut); REQUIRE(B.see("A").m_moveDir == Dir::Right); } TEST_CASE("spawn and see move in", "[game]") { Game game{TestGameCfg}; TestClient A(game, "A", {3, 2}); A.requestMove(Dir::Right); game.tick(); game.tick(); TestClient B(game, "B", {3, 3}); REQUIRE(B.see("A").m_state == PlayerState::MovingIn); REQUIRE(B.see("A").m_moveDir == Dir::Right); REQUIRE(B.see("A").m_pos == Point(4, 2)); } TEST_CASE("spawn after move and see idle", "[game]") { Game game{TestGameCfg}; TestClient A(game, "A", {3, 2}); A.requestMove(Dir::Right); game.tick(); game.tick(); game.tick(); TestClient B(game, "B", {3, 3}); REQUIRE(B.see("A").m_state == PlayerState::Idle); } TEST_CASE("move out of view area", "[game]") { Game game{TestGameCfg}; TestClient A(game, "A", {3, 2}); TestClient B(game, "B", {1, 2}); REQUIRE_FALSE(A.seeNothing()); REQUIRE_FALSE(B.seeNothing()); A.requestMove(Dir::Right); game.tick(); game.tick(); REQUIRE(A.seeNothing()); REQUIRE(B.seeNothing()); game.tick(); // just in case REQUIRE(A.seeNothing()); REQUIRE(B.seeNothing()); } TEST_CASE("move into view area", "[game]") { Game game{TestGameCfg}; TestClient A(game, "A", {4, 2}); TestClient B(game, "B", {1, 2}); REQUIRE(A.seeNothing()); REQUIRE(B.seeNothing()); A.requestMove(Dir::Left); game.tick(); game.tick(); REQUIRE_FALSE(A.seeNothing()); REQUIRE(A.see("B").m_state == PlayerState::Idle); REQUIRE(A.see("B").m_pos == Point(1, 2)); REQUIRE_FALSE(B.seeNothing()); REQUIRE(B.see("A").m_state == PlayerState::MovingIn); REQUIRE(B.see("A").m_moveDir == Dir::Left); REQUIRE(B.see("A").m_pos == Point(3, 2)); game.tick(); REQUIRE_FALSE(B.seeNothing()); } TEST_CASE("move not in view area", "[game]") { Game game{TestGameCfg}; TestClient A(game, "A", {1, 1}); TestClient B(game, "B", {5, 5}); REQUIRE(B.seeNothing()); A.requestMove(Dir::Right); game.tick(); game.tick(); game.tick(); REQUIRE(B.seeNothing()); } TEST_CASE("move across world boundaries", "[game]") { Game game{TestGameCfg}; TestClient A(game, "A", {0, 0}); A.requestMove(Dir::Left); game.tick(); REQUIRE(A.m_state == PlayerState::Idle); A.requestMove(Dir::Up); game.tick(); REQUIRE(A.m_state == PlayerState::Idle); TestClient B(game, "B", {7, 7}); B.requestMove(Dir::Right); game.tick(); REQUIRE(B.m_state == PlayerState::Idle); B.requestMove(Dir::Down); game.tick(); REQUIRE(B.m_state == PlayerState::Idle); } TEST_CASE("ignore move request when moving", "[game]") { Game game{TestGameCfg}; TestClient A(game, "A", {1, 1}); A.requestMove(Dir::Right); game.tick(); A.requestMove(Dir::Left); game.tick(); REQUIRE(A.m_state == PlayerState::MovingIn); REQUIRE(A.m_moveDir == Dir::Right); } TEST_CASE("move to occupied cell", "[game]") { Game game{TestGameCfg}; TestClient A{game, "A", {1, 1}}; TestClient B{game, "B", {2, 1}}; A.requestMove(Dir::Right); game.tick(); REQUIRE(A.m_state == PlayerState::Idle); } TEST_CASE("two move to same cell", "[game]") { Game game{TestGameCfg}; TestClient A{game, "A", {1, 1}}; TestClient B{game, "B", {3, 1}}; A.requestMove(Dir::Right); game.tick(); REQUIRE(A.m_state == PlayerState::MovingOut); B.requestMove(Dir::Left); game.tick(); REQUIRE(B.m_state == PlayerState::Idle); A.requestDisconnect(); game.tick(); B.requestMove(Dir::Left); game.tick(); REQUIRE(B.m_state == PlayerState::MovingOut); } TEST_CASE("move after another", "[game]") { Game game{TestGameCfg}; TestClient A{game, "A", {1, 1}}; TestClient B{game, "B", {2, 1}}; B.requestMove(Dir::Right); game.tick(); game.tick(); A.requestMove(Dir::Right); game.tick(); REQUIRE(A.m_state == PlayerState::MovingOut); } TEST_CASE("move near a wall", "[game]") { Game game{TestGameCfg}; game.m_geodata.addWall({1, 1}); auto&& testMove = [&](Point spawnPt, Dir moveDir) -> PlayerState { TestClient A{game, "A", spawnPt}; A.requestMove(moveDir); game.tick(); return A.m_state; }; SECTION("move into wall at Right") { REQUIRE(testMove({0, 1}, Dir::Right) == PlayerState::Idle); } SECTION("move into wall at Down") { REQUIRE(testMove({1, 0}, Dir::Down) == PlayerState::Idle); } SECTION("move near wall") { REQUIRE(testMove({1, 0}, Dir::Right) == PlayerState::MovingOut); } }
true
73adf6540783d898f64c3cb279e7e0018507cf1c
C++
ytong3/coding_practice
/leetcode/two_sum.cpp
UTF-8
883
3.125
3
[]
no_license
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { multimap<int,int> valIdx; for(int i=0;i<numbers.size();i++){ valIdx.insert(make_pair(numbers[i],i+1)); } multimap<int,int>::iterator it1,it2; it1=valIdx.begin(); it2=valIdx.end(); it2--;//very important as valIdx.end() points to the position next to the last element. int sum(0); vector<int> res(2,0); while(it1->first<=it2->first){ sum=it1->first+it2->first; if(sum==target){ res[0]=it1->second; res[1]=it2->second; sort(res.begin(),res.end()); return res; }else if (sum>target){ it2--; }else{ it1++; } } return res; } };
true
a8ea4ea657f788f3a2a4755d91a2213a8d4f6da1
C++
rykvlv/Console-Match3
/ConsoleMatch3/src/Model.cpp
UTF-8
7,521
2.796875
3
[]
no_license
#include "Model.h" namespace RBW { Model::Model() : _g{_rd()} { _distro = {std::uniform_int_distribution<int>{0, COUNT_OF_CRYSTALLS - 1}}; _map.resize(HEIGHT); for (auto& row : _map) { row.resize(WIDTH); } } void Model::Init() { fillMapRandomly(); performTick(); } void Model::Move(Point from, Point to) { std::swap(_map[from.y][from.x], _map[to.y][to.x]); performTick(); if (lookForMatches().size() == 0) { std::swap(_map[from.y][from.x], _map[to.y][to.x]); performTick(); return; } updateField(); } void Model::Dump() { while (!_ticks.empty()) { _ticks.pop(); } } std::queue<std::vector<std::vector<Crystall>>> Model::Tick() { return _ticks; } void Model::Mix() { std::shuffle(_map.begin(), _map.end(), _g); for (auto& row : _map) { std::shuffle(row.begin(), row.end(), _g); } performTick(); if (!lookForPossibleMoves() || lookForMatches().size() != 0) { Mix(); } } void Model::performTick() { _ticks.push(_map); } void Model::fillMapRandomly() { for (int row = 0; row < HEIGHT; ++row) { for (int column = 0; column < WIDTH; ++column) { char type = 65 + _distro(_random_engine); Crystall crystall = {type, '0'}; _map[row][column] = crystall; } } if (lookForMatches().size() != 0 || !lookForPossibleMoves()) { fillMapRandomly(); } } void Model::updateField() { auto matches = lookForMatches(); if (matches.size() == 0) return; removeMatches(matches); for (int i = 0; i < matches.size(); ++i) { for (int j = 0; j < matches[i].size(); ++j) { affectAbove(matches[i][j]); } } fillEmptyCells(); if (lookForMatches().size() != 0) { updateField(); } if (!lookForPossibleMoves()) { Mix(); } } void Model::removeMatches(std::vector<std::vector<Point>> matches) { for (int i = 0; i < matches.size(); ++i) { for (int j = 0; j < matches[i].size(); ++j) { auto x = matches[i][j].x; auto y = matches[i][j].y; deleteCrystall({x, y}); performTick(); } } } void Model::deleteCrystall(Point point) { _map[point.y][point.x].OnDestroy(); performTick(); } void Model::affectAbove(Point point) { for (int row = point.y; row > 0; --row) { if (_map[row][point.x].type == ' ') { _map[row][point.x] = _map[row - 1][point.x]; _map[row - 1][point.x].type = ' '; performTick(); } } } void Model::fillEmptyCells() { for (int row = 0; row < HEIGHT; ++row) { for (int column = 0; column < WIDTH; ++column) { if (_map[row][column].type == ' ') { char type = 65 + _distro(_random_engine); Crystall crystall = {type, '0'}; _map[row][column] = crystall; performTick(); } } } } std::vector<std::vector<Point>> Model::lookForMatches() const { std::vector<std::vector<Point>> matchList; for (int row = 0; row < _map.size(); ++row) { for (int column = 0; column < _map[row].size() - 2; ++column) { auto match = getMatchHorizontal({column, row}); if (match.size() > 2) { matchList.push_back(match); column += match.size() - 1; } } } for (int row = 0; row < _map.size(); ++row) { for (int column = 0; column < _map[row].size(); ++column) { auto match = getMatchVertical({column, row}); if (match.size() > 2) { matchList.push_back(match); row += match.size() - 1; } } } return matchList; } bool Model::lookForPossibleMoves() const { for (int row = 0; row < _map.size(); ++row) { for (int column = 0; column < _map[row].size(); ++column) { if (matchPattern({column, row}, { {0, 1} }, { {-2, 0}, {-1, -1}, {-1, 1}, {2, -1}, {2, 1}, {3, 0} })) { return true; } if (matchPattern({column, row}, { {2, 0} }, { {1, -1}, {1, 1} })) { return true; } if (matchPattern({column, row}, { {0, 1} }, { {0, -2}, {-1, -1}, {1, -1}, {-1, 2}, {1, 2}, {0, 3} })) { return true; } if (matchPattern({column, row}, { {0, 2} }, { {-1, 1}, {1, 1} })) { return true; } } } return false; } bool Model::matchPattern(Point point, std::vector<std::vector<int>> mustHave, std::vector<std::vector<int>> needOne) const { const auto &[x, y] = point; auto type = _map[y][x].type; for (int i = 0; i < mustHave.size(); ++i) { if (!matchType({x + mustHave[i][0], y + mustHave[i][1]}, type)) { return false; } } for (int i = 0; i < needOne.size(); ++i) { if (matchType({x + needOne[i][0], y + needOne[i][1]}, type)) { return true; } } return false; } bool Model::matchType(Point point, char type) const { auto [x, y] = point; if ((x < 0) || (x >= _map[0].size()) || (y < 0) || (y >= _map.size())) { return false; } return _map[y][x].type == type; } std::vector<Point> Model::getMatchHorizontal(Point point) const { std::vector<Point> match; match.emplace_back(point); auto [x, y] = point; for (int i = 1; x + i < _map[y].size(); ++i) { if (_map[y][x].type == _map[y][x + i].type) { Point matchPoint {x + i, y}; match.emplace_back(matchPoint); } else { return match; } } return match; } std::vector<Point> Model::getMatchVertical(Point point) const { std::vector<Point> match; match.emplace_back(point); auto [x, y] = point; for (int i = 1; point.y + i < _map.size(); ++i) { if (_map[y][x].type == _map[y + i][x].type) { Point matchPoint { x, y + i}; match.emplace_back(matchPoint); } else { return match; } } return match; } }
true
2bce87883a7295a616ac2a1fd0d43676558f5b7d
C++
nadarb/Competitive-Coding
/Old/Gravity Guy/Gravity Guy/Gravity Guy.cpp
UTF-8
794
2.734375
3
[]
no_license
// Gravity Guy.cpp : Defines the entry point for the console application. // #include <stdio.h> int main() { long T, i, j, ans; int willCross, lane; char str[2][200001]; scanf("%ld", &T); while (T--) { scanf("%s%s", str[0], str[1]); i = 0; ans = 0; willCross = 1; lane = -1; while (str[0][i] != '\0' && lane == -1) { if (str[0][i] == '#') { lane = 1; i--; } else if (str[1][i] == '#') { lane = 0; i--; } i++; } while (str[0][i] != '\0' && willCross) { if (str[0][i] == '#' && str[1][i] == '#') { willCross = 0; } else if (str[lane][i] == '#') { lane = (lane + 1) % 2; ans++; } i++; } if (willCross) { printf("Yes\n%ld\n", ans); } else { printf("No\n"); } } return 0; }
true
609c761213c11c4c0429a39fe30a5c4d1eefcfbb
C++
santosh7961/Competitive-programming
/Divide and Prune/Guess Number - leetcode 374.cpp
UTF-8
1,206
3.6875
4
[ "MIT" ]
permissive
// Problem Description @ https://leetcode.com/problems/guess-number-higher-or-lower/description/ // Forward declaration of guess API. // @param num, your guess // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 // C++ int guess(int num); class Solution { public: int guessNumber(int n) { int low = 0; int high = n; while (high - low > 1) { int mid = low + (high - low)/2; int res = guess(mid); if (res == 0) return mid; else if (res == -1) high = mid; else low = mid; } return n; } }; // JAVA - 4th Feb 2020 public class Solution extends GuessGame { public int guessNumber(int n) { int low = 1; int high = n; while (low < high - 1) { int mid = low + (high - low) / 2; int result = guess(mid); if (result == 0) return mid; else if (result == -1) high = mid; else low = mid; } if (guess(low) == 0) return low; return high; } }
true
ed033c1321ecff74fa7c6b2539e15cf60647626d
C++
techmatt/d3d11-interceptor
/mLib/include/core-base/grid3.h
UTF-8
5,151
3.15625
3
[ "MIT" ]
permissive
#ifndef CORE_BASE_GRID3D_H_ #define CORE_BASE_GRID3D_H_ namespace ml { template <class T> class Grid3 { public: Grid3(); Grid3(size_t dimX, size_t dimY, size_t dimZ); Grid3(size_t dimX, size_t dimY, size_t dimZ, const T &value); Grid3(const vec3ul& dim) : Grid3(dim.x, dim.y, dim.z) {} Grid3(const vec3ul& dim, const T& value) : Grid3(dim.x, dim.y, dim.z, value) {} Grid3(const Grid3<T> &G); Grid3(Grid3<T> &&G); Grid3(size_t dimX, size_t dimY, size_t dimZ, const std::function< T(size_t x, size_t y, size_t z) > &fillFunction); ~Grid3(); // // Memory // void free(); Grid3<T>& operator = (const Grid3<T> &G); Grid3<T>& operator = (Grid3<T> &&G); void allocate(size_t dimX, size_t dimY, size_t dimZ); void allocate(size_t dimX, size_t dimY, size_t dimZ, const T &value); void allocate(const vec3ul& dim) { allocate(dim.x, dim.y, dim.z); } void allocate(const vec3ul& dim, const T& value) { allocate(dim.x, dim.y, dim.z, value); } inline Grid3<T>& operator += (const Grid3<T> &right) { MLIB_ASSERT_STR(m_dimX == right.m_dimX && m_dimY == right.m_dimY && m_dimZ == right.m_dimZ, "grid dimensions must be equal"); for (size_t i = 0; i < getNumElements(); i++) { m_data[i] += right.m_data[i]; } return *this; } inline Grid3<T>& operator *= (T right) { for (size_t i = 0; i < getNumElements(); i++) { m_data[i] *= right.m_data[i]; } return *this; } inline Grid3<T> operator * (T x) { Grid3<T> result(m_dimX, m_dimY, m_dimZ); for (size_t i = 0; i < getNumElements(); i++) { result.m_data = m_data * x; } return result; } // // Accessors // inline T& operator() (size_t x, size_t y, size_t z) { #if defined(MLIB_BOUNDS_CHECK) || defined(_DEBUG) MLIB_ASSERT_STR((x < m_dimX) && (y < m_dimY) && (z < m_dimZ), "Out-of-bounds grid access"); #endif return m_data[z*m_dimY*m_dimX + x*m_dimY + y]; } inline const T& operator() (size_t dimX, size_t dimY, size_t slice) const { #if defined(MLIB_BOUNDS_CHECK) || defined(_DEBUG) MLIB_ASSERT_STR((dimX < m_dimX) && (dimY < m_dimY) && (slice < m_dimZ), "Out-of-bounds grid access"); #endif return m_data[slice*m_dimY*m_dimX + dimX*m_dimY + dimY]; } inline size_t getDimX() const { return m_dimX; } inline size_t getDimY() const { return m_dimY; } inline size_t getDimZ() const { return m_dimZ; } inline vec3ul getDimensions() const { return vec3ul(getDimX(), getDimY(), getDimZ()); } size_t getNumElements() const { return m_dimX * m_dimY * m_dimZ; } inline bool isSquare() const { return (m_dimX == m_dimY && m_dimY == m_dimZ); } inline T* getPointer() { return m_data; } inline const T* getPointer() const { return m_data; } // // Query // inline bool isValidCoordinate(size_t x, size_t y, size_t z) const { return (x < m_dimX && y < m_dimY && z < m_dimZ); } vec3ul getMaxIndex() const; const T& getMaxValue() const; vec3ul getMinIndex() const; const T& getMinValue() const; // // Modifiers // void setValues(const T &clearValue); void fill(const std::function<T(size_t x, size_t y, size_t z)> &fillFunction) { for (UINT xIndex = 0; xIndex < m_dimX; xIndex++) for (UINT yIndex = 0; yIndex < m_dimY; yIndex++) for (UINT zIndex = 0; zIndex < m_dimZ; zIndex++) { (*this)(xIndex, yIndex, zIndex) = fillFunction(xIndex, yIndex, zIndex); } } protected: T *m_data; size_t m_dimX, m_dimY, m_dimZ; }; template <class T> inline bool operator == (const Grid3<T> &a, const Grid3<T> &b) { if (a.getDimX() != b.getDimX() || a.getDimY() != b.getDimY() || a.getDimZ() != b.getDimZ()) return false; const size_t totalEntries = a.getNumElements(); for (size_t i = 0; i < totalEntries; i++) { if (a.ptr()[i] != b.ptr()[i]) return false; } return true; } template <class T> inline bool operator != (const Grid3<T> &a, const Grid3<T> &b) { return !(a == b); } template<class BinaryDataBuffer, class BinaryDataCompressor, class T> inline BinaryDataStream<BinaryDataBuffer, BinaryDataCompressor>& operator<<(BinaryDataStream<BinaryDataBuffer, BinaryDataCompressor>& s, const Grid3<T>& g) { s << (UINT64)g.getDimX() << (UINT64)g.getDimY() << (UINT64)g.getDimZ(); s.reserve(sizeof(T) * g.getDimX() * g.getDimY() * g.getDimZ()); for (UINT64 z = 0; z < g.getDimZ(); z++) for (UINT64 y = 0; y < g.getDimY(); y++) for (UINT64 x = 0; x < g.getDimX(); x++) s << g(y, x, z); return s; } template<class BinaryDataBuffer, class BinaryDataCompressor, class T> inline BinaryDataStream<BinaryDataBuffer, BinaryDataCompressor>& operator>>(BinaryDataStream<BinaryDataBuffer, BinaryDataCompressor>& s, Grid3<T>& g) { UINT64 dimX, dimY, dimZ; s >> dimX >> dimY, dimZ; g.allocate(dimX, dimY, dimZ); for (UINT64 z = 0; z < g.getDimZ(); z++) for (UINT64 y = 0; y < g.getDimY(); y++) for (UINT x = 0; x < g.getDimX(); x++) s << g(x, y, z); return s; } typedef Grid3<float> Grid3f; typedef Grid3<double> Grid3d; } // namespace ml #include "grid3.cpp" #endif // CORE_BASE_GRID3D_H_
true
de5e932503296913d61bd48156cd51c6bee09bc9
C++
imoverflow/mycode
/3C/main.cpp
UTF-8
990
2.703125
3
[]
no_license
#include <iostream> #include <stdio.h> using namespace std; int s[3]={0}; int res[3]={0}; void dfs(int b,int g,int r) { if(res[0]&&res[1]&&res[2]) return; if(b+g+r<2) { if(b==1) res[0]=1; if(g==1) res[1]=1; if(r==1) res[2]=1; return; } if(b>=2) dfs(b-1,g,r); if(g>=2) dfs(b,g-1,r); if(r>=2) dfs(b,g,r-1); if(b>=1&&g>=1) dfs(b-1,g-1,r+1); if(b>=1&&r>=1) dfs(b-1,g+1,r-1); if(r>=1&&g>=1) dfs(b+1,g-1,r-1); } int main() { int n; scanf("%d",&n); getchar(); char t; for(int i=0;i<n;i++) { scanf("%c",&t); if(t=='B') s[0]++; if(t=='G') s[1]++; if(t=='R') s[2]++; } if(s[0]>2) s[0]=2; if(s[1]>2) s[1]=2; if(s[2]>2) s[2]=2; dfs(s[0],s[1],s[2]); if(res[0]) printf("B"); if(res[1]) printf("G"); if(res[2]) printf("R"); return 0; }
true
4ee31c427c8f140d9e283f16c7f11499f5655486
C++
trarck/yhgui
/yhgui/control/NormalButton.h
UTF-8
1,980
2.6875
3
[]
no_license
#ifndef COCOS_YHGUI_CONTROL_NormalButton_H_ #define COCOS_YHGUI_CONTROL_NormalButton_H_ #include "Button.h" NS_CC_YHGUI_BEGIN /** * 普通的按钮 * 尽量减少资源占用 * 只有一个label,根据不同的状态来改变label属性。 * 背景会有多个,根据不同状态来切换。 */ class NormalButton:public Button { public: NormalButton(); ~NormalButton(); bool init(); /** * 设置通用的label */ void setLabel(CCNode* label); /** * 取得通用的label */ CCNode* getLabel() { return m_label; } /** * 设置状态对应的ttf label */ void setLabelTTF(const std::string& text,const std::string& fontName,float fontSize); /** * 设置状态对应的ttf label */ void setLabelTTF(const std::string& text, ccFontDefinition &textDefinition); /** * 设置状态对应的bmfont label */ void setLabelBMFont(const std::string& text,const std::string& fontFile); /** * 设置label状态对应的颜色 */ void setStateLabelColor(State state,const ccColor3B& color); /** * 设置状态对应的background */ void setStateBackground(State state,CCNode* background); /** * 设置状态对应的background */ void setStateBackground(State state,const std::string& imageFile); enum LabelType { kLabelTypeTTF=1, kLabelTypeBMFont, kLabelTypeAtlas }; inline void setLabelType(LabelType labelType) { m_labelType = labelType; } inline LabelType getLabelType() { return m_labelType; } protected: virtual void changeStateComponent(State newState); protected: CCNode* m_label; std::map<State, ccColor3B> m_stateColors; LabelType m_labelType; }; NS_CC_YHGUI_END #endif // COCOS_YHGUI_CONTROL_NormalButton_H_
true
931f5848a3d8dde4ab0d8857eb8637ceeba0e15a
C++
e-dzia/pea_3
/Timer.cpp
UTF-8
882
2.984375
3
[]
no_license
#include "Timer.h" Timer::Timer() { } Timer::~Timer() { } LARGE_INTEGER Timer::getTime() { LARGE_INTEGER timer; QueryPerformanceCounter(&timer); return timer; } void Timer::start() { time_start = getTime(); time_state = TIMER_STARTED; } void Timer::stop() { if(time_state != TIMER_STARTED) return; time_end = getTime(); time_state = TIMER_DONE; } double Timer::get() { if(time_state != TIMER_DONE) return -1.f; LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); return (double)(time_end.QuadPart - time_start.QuadPart)/frequency.QuadPart; } double Timer::getWithoutStopping() { LARGE_INTEGER timer; QueryPerformanceCounter(&timer); LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); return (double)(timer.QuadPart - time_start.QuadPart)/frequency.QuadPart; }
true
c2c3cf4a9bbdf46ccad8416acb644c3b45aed8ad
C++
JiangWeiGitHub/Trial
/C/DesignPattern/SimpleFactory/factory.h
UTF-8
686
3.703125
4
[]
no_license
#include <iostream> using namespace std; enum PRODUCT_TYPE { TYPE_A, TYPE_B }; class product { public: virtual void show() = 0; }; class productA: public product { public: void show(void) { cout<<"I'm product A!"<<endl; } }; class productB: public product { public: void show(void) { cout<<"I'm product B!"<<endl; } }; class factory { public: product *create_product(PRODUCT_TYPE type) { switch (type) { case TYPE_A: return new productA(); case TYPE_B: return new productB(); default: return NULL; } } };
true
0db8dc06f1e0b0db699aac42e4d6c4d86a4f8865
C++
shiyishiaa/DiskC
/Stack.h
UTF-8
407
3.546875
4
[]
no_license
#pragma once #include "Vector.h" template<typename ElemType> class Stack : public Vector<ElemType> { public: void push(ElemType const &elem) { this->insert(this->size(), elem); } ElemType pop() { return this->remove(this->size() - 1); } ElemType &top() { return (*this)[this->size() - 1]; } bool empty() { return (this->size() == 0); } };
true
7e73dbe166900f065f4baa2546230fb927d3fd8d
C++
Zeimd/crender-mt
/software-renderer/include/ceng/datatypes/release-deleter.h
UTF-8
577
2.65625
3
[]
no_license
/***************************************************************************** * * release-deleter.h * * Created By Jari Korkala 2/2015 * *****************************************************************************/ #ifndef CENG_RELEASE_DELETER_H #define CENG_RELEASE_DELETER_H namespace Ceng { template<class t_ElemType> class ReleaseDeleter { public: ReleaseDeleter() { } ~ReleaseDeleter() { } ReleaseDeleter(const ReleaseDeleter &source) { } void operator()(t_ElemType *ptr) { if (ptr != nullptr) { ptr->Release(); } } }; } #endif
true
a5cf84295c7192fe7a52d3518737d3e134e6ef22
C++
forest1102/Co-Sci-136
/classwork7.cpp
UTF-8
601
3.421875
3
[]
no_license
#include <iostream> #include <string> #include <random> using namespace std; string randomString(default_random_engine &e, uniform_int_distribution<int> &uchrs, uniform_int_distribution<int> &ulens) { int rlength = ulens(e); int rchr = uchrs(e); string rstring(rlength, rchr); return rstring; } int main() { default_random_engine e; uniform_int_distribution<int> uchrs((int) 'A', (int) 'Z'); uniform_int_distribution<int> ulens(1, 32); const int nStrings = 16; for (int k = 1; k <= nStrings; ++k) cout << randomString(e, uchrs, ulens) << endl; }
true
dc6d3e83cf5bf5188f94f246106281184590e46f
C++
OhSeungJin/GIFT
/GIFT_FUSE_prototype/util.cpp
UTF-8
1,058
3.171875
3
[]
no_license
#include <cassert> #include <cstdlib> #include <errno.h> #include <fcntl.h> #include <unistd.h> ssize_t writeAll(int fd, const void *buf, size_t len) { const char *ptr = (const char *)buf; size_t num_written = 0; do { ssize_t rc = write(fd, ptr + num_written, len - num_written); if (rc == -1) { if (errno == EINTR || errno == EAGAIN) { continue; } else { return rc; } } else if (rc == 0) { break; } else { // else rc > 0 num_written += rc; } } while (num_written < len); // assert(num_written == len); return num_written; } ssize_t readAll(int fd, void *buf, size_t len) { ssize_t rc; char *ptr = (char *)buf; size_t num_read = 0; for (num_read = 0; num_read < len;) { rc = read(fd, ptr + num_read, len - num_read); if (rc == -1) { if (errno == EINTR || errno == EAGAIN) { continue; } else { return -1; } } else if (rc == 0) { break; } else { // else rc > 0 num_read += rc; } } return num_read; }
true
17d2b52008500fa407c6eae1a2bf6a17c7d118c8
C++
prepare/fog
/branches/stefanvt/Fog/Fog/Core/Misc.h
UTF-8
3,991
2.796875
3
[ "LicenseRef-scancode-boost-original", "LicenseRef-scancode-public-domain", "BSD-3-Clause", "MIT", "X11", "HPND" ]
permissive
// [Fog-Core Library - Public API] // // [License] // MIT, See COPYING file in package // [Guard] #ifndef _FOG_CORE_MISC_H #define _FOG_CORE_MISC_H // [Dependencies] #include <Fog/Build/Build.h> #include <Fog/Core/Assert.h> #include <Fog/Core/Constants.h> #include <Fog/Core/Memory.h> namespace Fog { //! @brief This template is for fast routines that needs to alloc memory on //! the stack. Maximum size of memory allocated on the stack is @a N. //! //! If N is zero, it will always use heap allocation. //! //! This class is used internaly in Core and all upper libraries to simplify //! some code, because there are situations where we need to alloc memory by //! alloca(), but if the amount of requested memory is too big, it's better //! to use memory on heap. //! //! @c alloc() member can be called only once. Memory allocated on the heap is //! freed by destructor or explicit @c free() call. //! //! If you use @c free() to free allocated bytes, you can use @c alloc() again. //! //! This template simulates the @c alloca() behavior. template<sysuint_t N = 0> struct LocalBuffer { private: void *_mem; uint8_t _storage[N]; public: FOG_INLINE LocalBuffer() : _mem(0) { } FOG_INLINE ~LocalBuffer() { _free(); } FOG_INLINE void* alloc(sysuint_t size) { FOG_ASSERT(_mem == NULL); if (N == 0) return (_mem = Memory::alloc(size)); else if (size > N) return (_mem = Memory::alloc(size)); else return (_mem = (void*)_storage); } FOG_INLINE void free() { _free(); _mem = NULL; } FOG_INLINE void* mem() const { return _mem; } private: FOG_INLINE void _free() { if (N == 0) { if (_mem != NULL) Memory::free(_mem); } else { if (_mem != NULL && _mem != (void*)_storage) Memory::free(_mem); } } FOG_DISABLE_COPY(LocalBuffer) }; //! @brief Fast and secure stack implementation for critical routines. //! //! This stack class allocates some memory on the <b>stack</b> and if //! it's needed it allocs blocks of memory on the heap. template<ulong N> struct LocalStack { struct Node { //! @brief Pointer to current position in buffer for this node. uint8_t* cur; //! @brief Pointer to next node. Node* next; //! @brief Pointer to previous node. Node* prev; //! @brief Remaining bytes in bufer. sysuint_t remain; //! @brief Node data. uint8_t buffer[N]; }; Node* _current; Node _first; FOG_INLINE LocalStack() { _current = &_first; _first.prev = NULL; _first.next = NULL; _first.cur = _first.buffer; _first.remain = N; } FOG_INLINE ~LocalStack() { Node* node = _first.next; while (node) { Node* next = node->next; Memory::free(node); node = next; } } template<class T> FOG_INLINE err_t push(T& data) { if (FOG_UNLIKELY(_current->remain < sizeof(T))) { if (_current->next == NULL) { Node* node = (Node*)Memory::alloc(sizeof(Node) - N + (1024*32)); if (!node) return ERR_RT_OUT_OF_MEMORY; node->cur = node->buffer; node->prev = _current; node->next = NULL; node->remain = 1024*32; _current->next = node; _current = node; } else { _current = _current->next; } } *(T *)(_current->cur) = data; _current->cur += sizeof(T); _current->remain -= sizeof(T); return ERR_OK; } template<class T> FOG_INLINE void pop(T& data) { if (FOG_UNLIKELY(_current->cur == _current->buffer)) { _current = _current->prev; } FOG_ASSERT(_current->cur != _current->buffer); _current->cur -= sizeof(T); _current->remain += sizeof(T); data = *(T *)(_current->cur); } FOG_INLINE bool isEmpty() const { return (_current == &_first && _first.cur == _first.buffer); } private: FOG_DISABLE_COPY(LocalStack) }; } // Fog namespace // [Guard] #endif // _FOG_CORE_MISC_H
true
4df3b24b28b337af0710f76e361945f07f244004
C++
sillyamao/alphatree
/libalphatree/bi/basebi.h
UTF-8
12,911
2.71875
3
[]
no_license
// // Created by godpgf on 18-9-4. // #ifndef ALPHATREE_BASEBI_H #define ALPHATREE_BASEBI_H #include "../base/normal.h" #include "string.h" #include <iostream> using namespace std; void callstsq_(const float *x, const float *y, int len, float &beta, float &alpha) { float sumx = 0.f; float sumy = 0.f; float sumxy = 0.f; float sumxx = 0.f; for (int j = 0; j < len; ++j) { sumx += x[j]; sumy += y[j]; sumxy += x[j] * y[j]; sumxx += x[j] * x[j]; } float tmp = (len * sumxx - sumx * sumx); beta = abs(tmp) < 0.0001f ? 0 : (len * sumxy - sumx * sumy) / tmp; alpha = abs(tmp) < 0.0001f ? 0 : sumy / len - beta * sumx / len; } float correlation_(const float *a, const float *b, int len) { //计算当前股票的均值和方差 double meanLeft = 0; double meanRight = 0; double sumSqrLeft = 0; double sumSqrRight = 0; for (int j = 0; j < len; ++j) { meanLeft += a[j]; sumSqrLeft += a[j] * a[j]; meanRight += b[j]; sumSqrRight += b[j] * b[j]; } meanLeft /= len; meanRight /= len; float cov = 0; for (int k = 0; k < len; ++k) { cov += (a[k] - meanLeft) * (b[k] - meanRight); } float xDiff2 = (sumSqrLeft - meanLeft * meanLeft * len); float yDiff2 = (sumSqrRight - meanRight * meanRight * len); if (isnormal(cov) && isnormal(xDiff2) && isnormal(yDiff2)) { float corr = cov / sqrtf(xDiff2) / sqrtf(yDiff2); if (isnormal(corr)) { return fmaxf(fminf(corr, 1.0f), -1.0f); } return 1; } return 1; } void quickSort_(const float *src, int *index, int left, int right) { if (left >= right) return; int key = index[left]; int low = left; int high = right; while (low < high) { //while (low < high && (isnan(src[(int)index[high]]) || src[(int)index[high]] > src[key])){ while (low < high && src[(int) index[high]] > src[key]) { --high; } if (low < high) index[low++] = index[high]; else break; //while (low < high && (isnan(src[(int)index[low]]) || src[(int)index[low]] <= src[key])){ while (low < high && src[(int) index[low]] <= src[key]) { ++low; } if (low < high) index[high--] = index[low]; } index[low] = (float) key; quickSort_(src, index, left, low - 1); quickSort_(src, index, low + 1, right); } //给每个时间段的特征排序,排序后数据保存在缓存中 void sortFeature_(const float* cache, int* index, size_t len, size_t sampleTime){ for(int splitId = 0; splitId < sampleTime; ++splitId){ int preId = (int)(splitId * len / (float)sampleTime); int nextId = (int)((splitId + 1) * len / (float)sampleTime); quickSort_(cache, index, preId, nextId-1); // for(int j = preId; j < nextId; ++j){ // cout<<cache[index[j]]<<" "; // } // cout<<endl; } } //将数据排序后将头尾最有代表性的focusPercent这么多的数据再经过第二个特征的排序 void mulSortFeature_(const float* firstFeature, const float* secondFeature, int* index, size_t len, size_t sampleTime, float focusPercent){ for(int splitId = 0; splitId < sampleTime; ++splitId){ int preId = (int)(splitId * len / (float)sampleTime); int nextId = (int)((splitId + 1) * len / (float)sampleTime); int segmentSize = nextId - preId; quickSort_(firstFeature, index, preId, nextId-1); int focusSize = segmentSize * focusPercent * 0.5; int* indexData = index + preId; for(int i = 0; i < focusSize; ++i){ indexData[focusSize + i] = indexData[segmentSize - focusSize + i]; } quickSort_(secondFeature, index, preId, preId + focusSize - 1); quickSort_(secondFeature, index, preId + focusSize, preId + 2 * focusSize - 1); // cout<<segmentSize<<" "<<focusPercent<<endl; // for(int i = 0; i < focusSize * 2; ++i){ // cout<<secondFeature[(int)(indexData[i])]<<" "; // } // cout<<endl; } } void calReturnsRatioAvgAndStd_(const float* returns, const int* index, size_t len, size_t sampleTime, float support, float expectReturn, float* avg, float* std){ memset(avg, 0, sampleTime * sizeof(float)); memset(std, 0, sampleTime * sizeof(float)); for(size_t splitId = 0; splitId < sampleTime; ++splitId){ size_t nextId = (size_t)((splitId + 1) * len / (float)sampleTime); size_t preId = (size_t)(splitId * len / (float)sampleTime); size_t supportNextId = preId + (nextId - preId) * support * 0.5f; for(int j = preId; j < supportNextId; ++j){ int lid = index[j]; int rid = index[nextId - 1 - (j - preId)]; float v = (returns[rid] > expectReturn ? 1.f : 0.f) - (returns[lid] > expectReturn ? 1.f : 0.f); // cout<<v<<"="<<(returns[rid] + 1.f)<<"/"<<(returns[lid] + 1.f)<<endl; //v = returns[lid] + returns[rid]; avg[splitId] += v; std[splitId] += v * v; } avg[splitId] /= (supportNextId - preId); std[splitId] = sqrtf(std[splitId] / (supportNextId - preId) - avg[splitId] * avg[splitId]); //样本均值的标准差=样本的标准差 / sqrt(样本数量) std[splitId] /= sqrtf(supportNextId - preId); // cout<<avg[splitId]<<" "<<std[splitId]<<endl; } } bool getIsDirectlyPropor(const float* feature, const float* returns, int* index, size_t len, float support, float expectReturn){ quickSort_(feature, index, 0, len-1); float leftReturns = 0, rightReturns = 0; size_t midSize = (size_t)(len * 0.5f * support); for(int i = 0; i < midSize; ++i){ leftReturns += ((returns[index[i]] > expectReturn) ? 1 : 0); rightReturns += ((returns[index[len - i - 1]] > expectReturn) ? 1 : 0); } // cout<<leftReturns<<" "<<rightReturns<<endl; bool isDirectlyPropor = (rightReturns > leftReturns); return isDirectlyPropor; } void calFeatureAvg_(const float* cache, const int* index, size_t len, size_t sampleTime, float support, float* featureAvg){ memset(featureAvg, 0, sampleTime * sizeof(float)); for(size_t splitId = 0; splitId < sampleTime; ++splitId){ size_t nextId = (size_t)((splitId + 1) * len / (float)sampleTime); size_t preId = (size_t)(splitId * len / (float)sampleTime); int supportNextId = preId + (nextId - preId) * support * 0.5f; for(int j = preId; j < supportNextId; ++j){ int lid = index[j]; int rid = index[nextId - 1 - (j - preId)]; featureAvg[splitId] += cache[lid]; featureAvg[splitId] += cache[rid]; } featureAvg[splitId] /= 2 * (supportNextId - preId); } } //传染排序后的特征,计算光看这个特征的auc值 void calAUCSeq_(const float* cache, const int* index, const float* target, float targetThreshold, size_t len, size_t sampleTime, float support, float* aucList){ // cout<<"auc:"; for(size_t splitId = 0; splitId < sampleTime; ++splitId){ size_t preId = (size_t)(splitId * len / (float)sampleTime); size_t nextId = (size_t)((splitId + 1) * len / (float)sampleTime); size_t supportSize =(nextId - preId) * support * 0.5f; //计算所有正类样本数 int pcnt = 0; int rankSum = 0; int id = 0; for(int j = preId; j < nextId; ++j){ //仅仅观察头尾两块的数据 if(j < preId + supportSize || j >= nextId - supportSize){ ++id; if(target[index[j]] > targetThreshold){ ++pcnt; rankSum += id; } } } aucList[splitId] = (rankSum - pcnt * (1 + pcnt) * 0.5f) / (pcnt * (2 * supportSize - pcnt)); // cout<<aucList[splitId]<<" "; } // cout<<endl; } //数据先经过助手特征排序后再经过主要特征排序 void calAUCIncSeq_(const float* returns, const int* index, size_t len, size_t sampleTime, float expectReturn, float* discList){ for(size_t splitId = 0; splitId < sampleTime; ++splitId){ size_t preId = (size_t)(splitId * len / (float)sampleTime); size_t nextId = (size_t)((splitId + 1) * len / (float)sampleTime); int segmentSize = nextId - preId; int focusSize = segmentSize * 0.5; int midId = preId + focusSize / 2; //计算所有正类样本数 int pcntL = 0, pcntR = 0; int rankSumL = 0, rankSumR = 0; for(int j = preId; j < midId; ++j){ int lid = index[j]; int rid = index[focusSize + j]; if(returns[lid] > expectReturn){ ++pcntL; rankSumL += (j - preId + 1); } if(returns[rid] > expectReturn){ ++pcntR; rankSumR += (j - preId + 1); } } float preDist = (pcntL == 0) ? 0.5f : (rankSumL - pcntL * (1 + pcntL) * 0.5f) / (pcntL * (0.5f * focusSize - pcntL)); float lastDist = (pcntR == 0) ? 0.5f : (rankSumR - pcntR * (1 + pcntR) * 0.5f) / (pcntR * (0.5f * focusSize - pcntR)); // cout<<focusSize<<" "<<pcntL<<" "<<pcntR<<" "<<preDist<<" "<<lastDist<<endl; discList[splitId] = max(lastDist, 0.5f) - max(preDist, 0.5f); } } void calR2Seq_(const float* xCache, const float* xAvg, const float* yCache, const float* yAvg, const int* index, size_t len, size_t sampleTime, float support, float* r2List){ cout<<"r2:"; for(size_t splitId = 0; splitId < sampleTime; ++splitId){ size_t preId = (size_t)(splitId * len / (float)sampleTime); size_t nextId = (size_t)((splitId + 1) * len / (float)sampleTime); size_t supportNextId = preId + (nextId - preId) * support * 0.5f; float SSR = 0; float varX = 0; float varY = 0; for(int j = preId; j < supportNextId; ++j){ int lid = index[j]; int rid = index[nextId - 1 - (j - preId)]; float x = xCache[lid] - xAvg[splitId]; float y = yCache[lid] - yAvg[splitId]; SSR += x * y; varX += x * x; varY += y * y; x = xCache[rid] - xAvg[splitId]; y = yCache[rid] - yAvg[splitId]; SSR += x * y; varX += x * x; varY += y * y; } float SST = sqrtf(varX * varY); r2List[splitId] = SSR / SST; cout<<r2List[splitId]<<" "; } cout<<endl; } void calAutoregressive_(const float* timeSeq, const float *data, int len, float stdScale, float &minValue, float &maxValue) { float alpha, beta; callstsq_(timeSeq, data, len, beta, alpha); float stdL = 0, stdR = 0; int cntL = 0, cntR = 0; for (int i = 0; i < len; ++i) { float err = data[i] - (i * beta + alpha); if(err >= 0){ stdR += err * err; ++cntR; }else{ stdL += err * err; ++cntL; } } stdL = sqrtf(stdL / cntL); stdR = sqrtf(stdR / cntR); float value = len * beta + alpha; minValue = value - stdL * stdScale; maxValue = value + stdR * stdScale; } void calWaveRange_(const float *data, int len, float stdScale, float &minValue, float &maxValue) { float avg = 0; for(int i = 0; i < len; ++i){ avg += data[i]; } avg /= len; float stdL = 0, stdR = 0; int cntL = 0, cntR = 0; for (int i = 0; i < len; ++i) { float err = data[i] - avg; if(err >= 0){ stdR += err * err; ++cntR; }else{ stdL += err * err; ++cntL; } } stdL = sqrtf(stdL / cntL); stdR = sqrtf(stdR / cntR); minValue = avg - stdL * stdScale; maxValue = avg + stdR * stdScale; } /* void calDiscriminationSeq_(const float* returns, const int* index, size_t len, size_t sampleTime, float support, float expectReturn, float* discList){ cout<<expectReturn<<":"; for(size_t splitId = 0; splitId < sampleTime; ++splitId){ size_t preId = (size_t)(splitId * len / (float)sampleTime); size_t nextId = (size_t)((splitId + 1) * len / (float)sampleTime); size_t supportNextId = preId + (nextId - preId) * support * 0.5f; int leftCnt = 1, rightCnt = 1; for(int j = preId; j < supportNextId; ++j){ int lid = index[j]; int rid = index[nextId - 1 - (j - preId)]; if(returns[lid] > expectReturn) ++leftCnt; if(returns[rid] > expectReturn) ++rightCnt; } discList[splitId] = rightCnt / (float)leftCnt; cout<<rightCnt<<"/"<<leftCnt<<" "; } cout<<endl; } */ #endif //ALPHATREE_BASEBI_H
true
6fbcae3d977777d77aba37469ddd5815062eb2a5
C++
shash04/General_Coding
/Companies/Microsoft/OA_questions/Min_Steps_2_Piles_Equal_Height.cpp
UTF-8
1,165
3.640625
4
[]
no_license
// Alexa is given n piles of equal or unequal heights. In one step, Alexa can remove any number of boxes // from the pile which has the maximum height and try to make it equal to the one which is just lower // than the maximum height of the stack. Determine the minimum number of steps required to make all of // the piles equal in height. // Example 1: // Input: piles = [5, 2, 1] // Output: 3 // Explanation: // Step 1: reducing 5 -> 2 [2, 2, 1] // Step 2: reducing 2 -> 1 [2, 1, 1] // Step 3: reducing 2 -> 1 [1, 1, 1] // So final number of steps required is 3. // https://leetcode.com/discuss/interview-question/364618/ #include <algorithm> int minStepToEqualPile(vector<int> arr) { if(arr.size() == 0) return 0; int retVal = 0; sort(arr.begin(), arr.end(), greater<int>()); int currHeight = arr[0]; for(int i=1; i < arr.size(); i++) { if(currHeight > arr[i]) { retVal = retVal + i; currHeight = arr[i]; } } return retVal; } int main() { vector<int> arr = {5,2,1}; cout<<minStepToEqualPile(arr)<<endl; }
true
98f93d148f9fdca6cbde6e969c73d2c9388a96b1
C++
darenlin49/ACM_Algorithm_Templates
/Math/generating_function.cpp
GB18030
4,500
3.34375
3
[]
no_license
/* ͨĸӦ---֣ HDU 1398 300ȫƽֵӲң1Ԫ4Ԫ9ԪмַƴnԪ(n <= 300) (1+x+x^2+x^3+x^4+x^5+)(1+x^4+x^8+x^12+x^16+)(1+x^9+x^18+x^27+) = a1+a2*x+a3*x^2++an*x^n+ x^nϵΪ resÿγһʽpro */ int a[17] = {1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289}; /* generating_function */ const int MAX = 400; struct generating_function{ int res[MAX]; int pro[MAX]; int mmax; //x^n --- max(n); void init(int n){ memset(res, 0, sizeof(res)); memset(pro, 0, sizeof(pro)); res[0] = 1; mmax = n; } void cal(int p); }gf; void generating_function::cal(int p){ int tmp[MAX]; memset(tmp, 0, sizeof(tmp)); for (int i = 0; i <= mmax; i ++){ for (int j = 0; j <= mmax; j += a[p]){ //ķΧԸݵǰproŻһ. if (i + j <= mmax) tmp[i+j] += res[i] * pro[j]; } } memset(res, 0, sizeof(res)); for (int i = 0; i <= mmax; i ++){ res[i] = tmp[i]; } return ; } /* generating_function */ int main(){ int n; while(scanf("%d", &n) == 1, n){ gf.init(n); for (int i = 0; i < 17; i ++){ memset(gf.pro, 0, sizeof(gf.pro)); if (a[i] > gf.mmax) break; int p = 0; while(p <= gf.mmax){ gf.pro[p] = 1; p += a[i]; } gf.cal(i); } printf("%d\n", gf.res[gf.mmax]); } return 0; } /* HDU 2069 Ӳ---⣺ܳ100 ĸΣһάʾ */ int a[5] = {1, 5, 10, 25, 50}; const int N = 300; struct generating_function{ int c1[N][101], c2[N][101]; int maxn; void init(int n){ memset(c1, 0, sizeof(c1)); memset(c2, 0, sizeof(c2)); c1[0][0] = 1; maxn = n; } void cal(int p); }ef; void generating_function::cal(int p){ int tmp[N][101]; memset(tmp, 0, sizeof(tmp)); for (int i = 0; i <= maxn; i ++){ for (int j = 0; j <= maxn; j += a[p]){ int k1 = j/a[p]; if (i + j <= maxn && c2[j][k1]) for (int k2 = 0; k1+k2 <= 100; k2 ++) tmp[i+j][k1+k2] += c1[i][k2] * c2[j][k1]; } } memset(c1, 0, sizeof(c1)); for (int i = 0; i <= maxn; i ++){ for (int k = 0; k <= 100; k ++){ c1[i][k] = tmp[i][k]; } } return ; } int main(){ int n; while(scanf("%d", &n) == 1){ ef.init(n); for (int i = 0; i < 5; i ++){ memset(ef.c2, 0, sizeof(ef.c2)); for (int j = 0; j <= n; j += a[i]){ ef.c2[j][j/a[i]] = 1; } ef.cal(i); } int res = 0; for (int k = 0; k <= 100; k ++){ res += ef.c1[n][k]; } printf("%d\n", res); } return 0; } /* ָĸ HDU 2065 ɫ (ָĸ && ̩ռ) 4ĸɣACֻܳżΡ ָɺ(1+x/1!+x^2/2!+x^3/3!)^2*(1+x^2/2!+x^4/4!+x^6/6!)^2. ǰBDȡͬĸһҪȥACֻȡż ̩չe^xx0=0n̩նʽΪ 1+x/1!+x^2/2!+x^3/3! ҲԽеҪȥe^(-x)չʽΪ1-x/1!+X^2/2!-X^3/3! Ժ߿ԻΪ(e^x+e^(-x))/2ԭʽΪ (e^x)^2 * ((e^x*e^(-x))/2)^2 õ1/4*(e^4x+2*e^2x+1) ̩չ e^4x = 1 + (4x)/1! + (4x)^2/2! + (4x)^3/3! + ... + (4x)^n/n!; e^2x = 1 + (2x)/1! + (2x)^2/2! + (2x)^3/3! + ... + (2x)^n/n!; ϵΪnϵΪ(4^n+2*2^n)/4=4^(n-1)+2^n-1; ݸ֮ */ int PowMod(int a,LL b){ int ret=1; while(b){ if(b&1) ret=(ret*a)%MOD; a=(a*a)%MOD; b>>=1; } return ret; } int main(){ int t; while(scanf("%d",&t)!=EOF&&t){ int cas=0; LL n; while(t--){ scanf("%I64d",&n); printf("Case %d: %d\n",++cas,(PowMod(4,n-1)+PowMod(2,n-1))%MOD); } printf("\n"); } return 0; }
true
9827c23d71b206f13780a1bfe2d3eb108411e590
C++
pavlovandy/ft_retro
/src/AEnemy.hpp
UTF-8
1,527
2.546875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* AEnemy.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: apavlov <apavlov@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/06 02:30:47 by apavlov #+# #+# */ /* Updated: 2019/10/06 10:48:35 by apavlov ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef AENEMY_HPP # define AENEMY_HPP #include "AMoving.hpp" #include "Player.hpp" #include "AProjectile.hpp" #include <string> #include "Ammo.hpp" class Ammo; class AProjectile; class AMoving; class Player; class AEnemy : virtual public AMoving { private: AEnemy(); int _hp; std::string _type; Ammo * _ammo; public: virtual ~AEnemy(); AEnemy( std::string type, int hp, int ammo_size ); AEnemy( AEnemy const & ); AEnemy & operator=( AEnemy const & ); void fire( Player const & ); void getDmg( void ); bool collision( AMoving & ); void draw( ); void drawBullet() ; Ammo * getAmmo(); }; #endif
true
9c23d58e8e6a838deafa170469a2de69b46ed283
C++
TrackPlatformTeam/trackPlatform-hardware
/Arduino/management/CommandManager.h
UTF-8
1,464
2.515625
3
[]
no_license
#pragma once #include <Arduino.h> #include "../peripheral/SensorManager.h" #include "../peripheral/EngineManager.h" #include "../peripheral/ServoManager.h" #include "../config/CommandsEnum.h" #include "../utils/Converter.h" /** * @brief Peripheral manager class (parse commands and execute it) * @attention First call of @getManager() method must be in setup() method */ class CommandManager { static CommandManager* manager_; CommandManager(); CommandManager(CommandManager&); ~CommandManager(); SensorManager sensors_controller; EngineManager move_controller; ServoManager servo_controller; Converter parametr_converter; ApiVersion current_api = startBasicAPI; const int param_start_pos = 2; String parse_and_execute_command_connected(String command); String parse_and_execute_command_not_connected(String command); String run_movement_manager_connected(String command); String run_sensors_manager_connected(String command); String run_servo_manager_connected(String command); String run_commumication_manager_connected(String command); String get_sensor_value(String command, SensorManagerIndex sensor_manager_index, bool is_raw); String get_sensor_all_values(SensorManagerIndex sensor_manager_index, bool is_raw); public: static const ApiVersion min_api = APIWithCRC; static const ApiVersion max_api = APIWithCRC; static CommandManager* getManager(); String parse_and_execute_command(String command); void stop_all(); };
true
1ebf733c3123c73642798a8fbc8a2c77cd390e9b
C++
arabhiar/InterviewBit
/Tree Data Structure/inorder-traversal-of-cartesian-tree.cpp
UTF-8
1,105
3.53125
4
[]
no_license
#include <bits/stdc++.h> using namespace std; #define COUNT 3 struct TreeNode { int val; TreeNode *left, *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; // Visualization of Tree void print2DUtil(TreeNode *root, int space) { if (root == NULL) return; space += COUNT; print2DUtil(root->right, space); cout << endl; for (int i = COUNT; i < space; i++) cout << " "; cout << root->val << "\n"; print2DUtil(root->left, space); } void print2D(TreeNode *root) { print2DUtil(root, 0); } TreeNode *helper(int i, int j, vector<int> A) { if (i > j) { return NULL; } int maxIdx = max_element(A.begin() + i, A.begin() + j + 1) - A.begin(); TreeNode *newNode = new TreeNode(A[maxIdx]); newNode->left = helper(i, maxIdx - 1, A); newNode->right = helper(maxIdx + 1, j, A); return newNode; } int main() { int n; cin >> n; vector<int> A(n); for (int i = 0; i < n; i++) { cin >> A[i]; } TreeNode *root = helper(0, A.size() - 1, A); cout << endl; return 0; }
true
ae3b8822051b44264c7688e459e1455686249baa
C++
0of/WebOS-Magna
/src/basedef/private/Comparer_p.h
UTF-8
3,826
2.71875
3
[ "Apache-2.0" ]
permissive
#ifndef COMPARER_P_H #define COMPARER_P_H #include "../BaseTypes.h" #include "../StaticTypeTrait.h" #include "../CompilerTimeAssert.h" //STL #include <limits> #include <cmath> namespace Magna{ namespace Core{ template< typename _Type , class _TypeTrait = DigitStaticTypeTrait<_Type> > class DigitComparer{ public: MAGNA_FORCEINLINE static bool isEqualTo( const _Type& instance, const _Type& compareOne ) { COMPILTER_TIME_ASSERT((_TypeTrait::isMatched), Shall_Matches_Integer_Type) return instance == compareOne; } MAGNA_FORCEINLINE static bool isEqualToZero( const _Type& instance ) { COMPILTER_TIME_ASSERT((_TypeTrait::isMatched), Shall_Matches_Integer_Type) return instance == 0; } MAGNA_FORCEINLINE static bool MAGNA_NOTHROW isHigherThanZero( const _Type& instance ) { COMPILTER_TIME_ASSERT((_TypeTrait::isMatched), Shall_Matches_Integer_Type) return instance > 0; } MAGNA_FORCEINLINE static bool MAGNA_NOTHROW isLowerThanZero( const _Type& instance ){ COMPILTER_TIME_ASSERT((_TypeTrait::isMatched), Shall_Matches_Integer_Type) return instance < 0; } MAGNA_FORCEINLINE static bool MAGNA_NOTHROW isHigherThan( const _Type& instance, const _Type& compareOne ){ COMPILTER_TIME_ASSERT((_TypeTrait::isMatched), Shall_Matches_Integer_Type) return instance > compareOne; } MAGNA_FORCEINLINE static bool MAGNA_NOTHROW isLowerThan( const _Type& instance, const _Type& compareOne ){ COMPILTER_TIME_ASSERT((_TypeTrait::isMatched), Shall_Matches_Integer_Type) return instance < compareOne; } }; template< typename _Type , class _TypeTrait = RealStaticTypeTrait<_Type> > class RealComparer{ public: MAGNA_FORCEINLINE static bool isEqualTo( const _Type& instance, const _Type& compareOne ) { COMPILTER_TIME_ASSERT((_TypeTrait::isMatched), Shall_Matches_Integer_Type) return isAlmostToZero( instance - compareOne ); } MAGNA_FORCEINLINE static bool isAlmostToZero( const _Type& instance ) { COMPILTER_TIME_ASSERT((_TypeTrait::isMatched), Shall_Matches_Integer_Type) return std::abs( instance ) < std::numeric_limits<_Type>::epsilon() ; } MAGNA_FORCEINLINE static bool isEqualToZero( const _Type& instance ) { return isAlmostToZero( instance ); } MAGNA_FORCEINLINE static bool isHigherThanZero( const _Type& instance ){ COMPILTER_TIME_ASSERT((_TypeTrait::isMatched), Shall_Matches_Integer_Type) return instance > std::numeric_limits<_Type>::epsilon(); } MAGNA_FORCEINLINE static bool isLowerThanZero( const _Type& instance ){ COMPILTER_TIME_ASSERT((_TypeTrait::isMatched), Shall_Matches_Integer_Type) return instance < -std::numeric_limits<_Type>::epsilon(); } MAGNA_FORCEINLINE static bool isHigherThan( const _Type& instance, const _Type& compareOne ){ COMPILTER_TIME_ASSERT((_TypeTrait::isMatched), Shall_Matches_Integer_Type) return instance - compareOne > std::numeric_limits<_Type>::epsilon(); } MAGNA_FORCEINLINE static bool MAGNA_NOTHROW isLowerThan( const _Type& instance, const _Type& compareOne ){ COMPILTER_TIME_ASSERT((_TypeTrait::isMatched), Shall_Matches_Integer_Type) return instance - compareOne < -std::numeric_limits<_Type>::epsilon(); } }; }//Core }//Magna #endif /* COMPARER_P_H */
true
6b36a5d992330d1d4e207a189ca59c3eae1e1c6b
C++
gitqwerty777/Nonogram-Solver
/dfsboard.cpp
UTF-8
7,125
2.703125
3
[]
no_license
#include "board.h" #include "dfsboard.h" #include <cstdlib> #define INF 2147483647 bool LimitFiller::getNextFillStart(){ if(fillStart.size() == 0){//this row is not tried yet, return original fs fillStart.resize(l.size()); for(int i = 0; i < l.size(); i++){ fillStart[i] = l[i].fs; } } else {//get previous fillstart if(!getNextFillStartbyFillStart()) return false; } return true; } bool LimitFiller::getNextFillStartbyFillStart(){ int limiti = 0; while(limiti < l.size()){ limiti = 0; while(limiti < l.size()){ if(l[limiti].ls > fillStart[limiti]){//add 1 and return fillStart[limiti]++; if(!isLimitLegal()){ break;//goto i = 0, readding } /*printf("("); for(int i = 0; i < l.size(); i++) printf("%d ", fillStart[i]); printf(")");*/ return true; } else {//fillstart too big, return to fs, continue adding next bit(limit) fillStart[limiti] = l[limiti].fs; limiti++; } } } //printf("row %d: cannot find next fillstart", nowr); return false; } bool LimitFiller::isLimitLegal(){ for(int i = 0; i < l.size()-1; i++) if(fillStart[i] + l[i].l >= fillStart[i+1]) return false; return true; } //DFS with heuristic void DFSBoard::DoDFS(){ //choose an answer of the line with minimum possible answer() -> use heuristic to fill board -> check other is legal or not -> if legal, next line; else, refill the current line puts("doDFS"); for(int i = 0; i < r+c; i++) isFilled[i] = false; lineOrder.clear(); lineOrder.resize(r+c); int dfsLineCount = 0; getLineWithMinBranch(dfsLineCount, lineOrder); while(!checkAnswer()){ Line nowLine = lineOrder[dfsLineCount]; /*printf("now order:\n"); for(int i = 0; i < dfsLineCount; i++) printf("%s%d ", lineOrder[i].t==ROW?"row":"col", lineOrder[i].i); puts("");*/ if(!tryFillRowWithHeuristic(nowLine)){//try all possibilities to fill the row, will filling next answer after previous called if(dfsLineCount == 0){ puts("no solution:cannot fill first row"); break; } else { //all possibilities in row nowr are failed, recover board to previous row(nowr-1) limitFillers[nowLine.index].destroy(); isFilled[nowLine.index] = false; Restore(lineOrder[--dfsLineCount]); } } else {// fill answer success, continue filling next row if(isAllSolved()) return; isFilled[nowLine.index] = true; dfsLineCount++; getLineWithMinBranch(dfsLineCount, lineOrder);//get next row index } } if(!checkAnswer()){ fprintf(stderr, "no solution: dfs failed\n"); } } void DFSBoard::getLineWithMinBranch(int dfsLineCount, vector<Line>& lineOrder){//TODO: RENAME int mini; line_type mint; long minv; bool first = true; for(int i = 0; i < r; i++){ if(solved_row[i] || isFilledByDFS(ROW, i)) continue; long v = 1; for(int j = 0; j < lim_row[i].size(); j++) if(!lim_row[i][j].isSolved()) v *= lim_row[i][j].ls-lim_row[i][j].fs+1; if(v < minv || first){ mint = ROW; minv = v; mini = i; first = false; } } for(int i = 0; i < c; i++){ if(solved_col[i] || isFilledByDFS(COL, i)) continue; long v = 1; for(int j = 0; j < lim_col[i].size(); j++) if(!lim_col[i][j].isSolved()) v *= lim_col[i][j].ls-lim_col[i][j].fs+1; if(v < minv || first){ mint = COL; minv = v; mini = i; first = false; } } if(first == true){//TODO: why first == true... //fprintf(stderr, "first = true"); checkSolve(); printBoard("first=true"); return; } //assert(first != true); //may happened in 15 $202, that solve two lines simultaneously //printf("min branch %s%d: %d possibility\n", (mint==ROW)?"row":"col", mini, minv); if(mint == ROW) lineOrder[dfsLineCount] = Line(mint, mini, mini); else lineOrder[dfsLineCount] = Line(mint, mini, r+mini); } bool DFSBoard::tryFillRowWithHeuristic(Line& nowLine){ if(nowLine.t == ROW){ limitFillers[nowLine.index].setLimit(lim_row[nowLine.i]); } else { limitFillers[nowLine.index].setLimit(lim_col[nowLine.i]); } LimitFiller& filler = limitFillers[nowLine.index]; if(!filler.getNextFillStart()) return false; bool isSuccess = false; Backup(nowLine); do{ if(tryFillRowbyFillStartHeuristic(nowLine, filler.fillStart)){//check available isSuccess = true; } else{ Restore(nowLine); } } while(!isSuccess && filler.getNextFillStart()); return isSuccess; } bool DFSBoard::tryFillRowbyFillStartHeuristic(const Line& nowLine, const vector<int>& fillStart){ conflict = false; /* fill row */ if(nowLine.t == ROW){ int nowr = nowLine.i; int limitNum = lim_row[nowr].size(); for(int i = 0; i < limitNum; i++) for(int j = fillStart[i]; j < fillStart[i]+lim_row[nowr][i].l; j++) fillGrid(nowr, j, BLACK); for(int i = 0; i < c; i++) if(b[nowr][i] == SPACE) fillGrid(nowr, i, WHITE); } else { int nowc = nowLine.i; int limitNum = lim_col[nowc].size(); for(int i = 0; i < limitNum; i++) for(int j = fillStart[i]; j < fillStart[i]+lim_col[nowc][i].l; j++) fillGrid(j,nowc, BLACK); for(int i = 0; i < r; i++) if(b[i][nowc] == SPACE) fillGrid(i, nowc, WHITE); } /* try heuristic */ while(!isAllSolved() && !conflict) if(!doHeuristicByLine()) break; if(conflict){//find contradiction when updating heuristic, restore DEBUG_PRINT("try fill: failed [%s], restore %d\n", conflictReason, nowLine.i); return false; } checkSolve();//TODO: refact if(isAllSolved()){ return checkAnswer(); } //puts("dfs with heursitic success"); return true; } void DFSBoard::checkSolve(){ for(int i = 0; i < r; i++) if(!solved_row[i]){ bool isSolved = true; for(int j = 0; j < c && isSolved; j++) if(b[i][j] == SPACE) isSolved = false; if(isSolved){ solved_row[i] = true; solvedLineNum++; } } for(int i = 0; i < c; i++) if(!solved_col[i]){ bool isSolved = true; for(int j = 0; j < r && isSolved; j++) if(b[j][i] == SPACE) isSolved = false; if(isSolved){ solved_col[i] = true; solvedLineNum++; } } } void DFSBoard::Restore(const Line& l){ //printf("restore %d\n", nowr); RestoreBoard(backupBoards[l.index]); } void DFSBoard::Backup(const Line& l){ BackupBoard(backupBoards[l.index]); } void DFSBoard::BackupBoard(Board &b){//TODO: need to add something? b.b = this->b; b.lim_row = this->lim_row; b.lim_col = this->lim_col; b.change_row = this->change_row; b.change_col = this->change_col; b.solved_row = this->solved_row; b.solved_col = this->solved_col; b.solvedLineNum = this->solvedLineNum; b.alreadySetGridNumber = this->alreadySetGridNumber; } void DFSBoard::RestoreBoard(const Board &b){ this->b = b.b; this->lim_row = b.lim_row; this->lim_col = b.lim_col; this->change_row = b.change_row; this->change_col = b.change_col; this->solved_row = b.solved_row; this->solved_col = b.solved_col; this->solvedLineNum = b.solvedLineNum; this->alreadySetGridNumber = b.alreadySetGridNumber; }
true
9754ef084165205976f60a5cc2183fc7c1e83337
C++
cyyself/OILife
/POJ/3258 - River Hopscotch.cpp
UTF-8
558
2.546875
3
[]
no_license
#include <cstdio> #include <algorithm> using namespace std; int l,n,m; int d[50005]; bool check(int x) { int last = 0; int cnt = 0; for (int i=0;i<=n && cnt <= m;i++) { if (d[i] - last < x) cnt ++; else last = d[i]; } return cnt <= m; } int main() { scanf("%d%d%d",&l,&n,&m); for (int i=0;i<n;i++) scanf("%d",&d[i]); sort(d,d+n); d[n] = l; int l = 0; int r = d[n]; int ans = -1; while (l <= r) { int mid = (l + r) / 2; if (check(mid)) { ans = mid; l = mid + 1; } else { r = mid - 1; } } printf("%d\n",ans); return 0; }
true
820724d6c7c66717134d5d9150c35a9b456c9c4d
C++
rubyAce71697/machine_learning
/nsticksrectangle/main.cpp
UTF-8
767
3.671875
4
[]
no_license
/*given n sticks of 1 unit each design a rectangle of maximum area */ #include <iostream> #include <math.h> using namespace std; int main() { int n; float area; cout<<"ENter the number of sticks"; cin>>n; if(n%2 ) { //if n is odd make it even n = n-1; cout<<"Only "<<n <<" sticks can be used"<<endl; } if(n%4== 0) { area = pow(n/4,2); } else { int sum_of_x_y = n/2; int bredth = sum_of_x_y/2; int length = sum_of_x_y/2 + 1; cout<<"sum_of_x_y: "<<sum_of_x_y<<endl; cout<<"Bredth: "<<bredth<<endl; cout<<"length: "<<length<<endl; area = length * bredth; } cout<<"The area of rectangle is: "<<area; return 0; }
true
26a932b9f61ffac6a5d0d9552e0bf3f537ed19d1
C++
wwuhn/wwuhn.github.io
/notes/notes/算法/Dijkstra.cpp
GB18030
7,369
3.609375
4
[]
no_license
#include <iostream> // Dijkstra Ͻ˹ #include <stack> // · using namespace std; //1 ݽṹ const int N = 100; // еĸڳʼ̶ const int INF = 1e7; // ʼΪ10000000ʾһ㵽һ㲻ͨ int map[N][N]; // ȨڽӾ󣬱ʾͨ; int n,m; // nʾеĸmΪм·ߵѭ int dist[N]; // ʾԴuj·Ϊdist[j]мֵ int p[N]; // ʾԴuj·ǰڵΪp[j]мֵ bool flag[N]; // flag[i]true˵iѾ뵽S;򶥵iڼV-S // Vʾȫ㣬Sǰ̰IJ· void Dijkstra(int u) { int i,j; // ѭ //2 ʼ for(i=1; i<=n; i++) // { dist[i] =map[u][i]; // ʼԴu· flag[i]=false; if(dist[i]==INF) p[i]=-1; // Դuö·Ϊ˵iԴu else p[i]=u; // ˵iԴuڣöiǰp[i]=u } dist[u] = 0; flag[u]=true; // ʼʱSֻһԪأԴu for(i=1; i<=n; i++) // { //3 ڼV-S!flag[j]ҾԴuĶt int temp = INF, t = u; for(j=1; j<=n; j++) // ڼV-SѰҾԴuĶt if(!flag[j]&&dist[j]<temp) { t=j; temp=dist[j]; } if(t==u) return ; // Ҳttδ£ѭ flag[t]= true; // 򣬽t뼯 // 4 ҵt󣬸´Դut󵽼V-StڽӵĶľ for(j=1;j<=n;j++) // ¼V-StڽӵĶ㵽Դuľ if(!flag[j]&& map[t][j]<INF) // ǰ߱ʾjV-SУ߱ʾtj if(dist[j]>(dist[t]+map[t][j])) //Դ㵽j vs Դ㾭tj· { dist[j]=dist[t]+map[t][j]; // Դ㵽j̾ p[j]=t; // jǰ } } } void findpath(int u) // Դ㵽· { int x; // ǰ stack<int>s; // ÿ<stack>һջs for(int i=1;i<=n;i++) { x=p[i]; while(x!=-1) { s.push(x); // ǰѹջ x=p[x]; } cout<<"Դ"<<u<<""<<i<<"̾Ϊ"; if(dist[i] == INF) cout << "sorry,·ɴ"<<endl; else { cout << dist[i]; cout<<"\t·Ϊ"; while(!s.empty()) { cout<<s.top()<<""; // ջԪ s.pop(); // γջ } cout<<i<<endl; } } } void printmatrix(int n) // ͼĴȨڽӾ { int i,j; cout <<"map"<<endl; cout<<"\t"; for(i=1;i<=n;++i) // б cout<<"\t"<<i; cout<<endl; for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { if(j==1) // б cout << "\t" << i; if(map[i][j]==INF) cout << "\t" << ""; else cout << "\t" << map[i][j]; if(j==n) cout<<endl; } } } void initmatrix(int m,int n) { int u,v,w; for(int i=1;i<=n;i++) // ʼͼڽӾ for(int j=1;j<=n;j++) map[i][j]=INF; // ʼڽӾΪ while(m--) { cin >> u >> v >> w; map[u][v] = map[u][v]<w?map[u][v]:w;// ڽӾ󴢴棬Сľ } } int main() { cout << "еĸ"<<endl; cin >> n; cout << "֮·ߵĸ"<<endl; cin >>m; cout << "֮·Լ룺"<<endl; initmatrix(m,n); int st; cout<<"Сڵλã"<<endl; cin>>st; printmatrix(n); Dijkstra(st); findpath(st); // stΪԴ system("pause"); return 0; } /*ʾʱȸ 5 8 1 2 2 1 3 5 2 3 2 2 4 6 3 4 7 4 3 2 3 5 1 4 5 4 1 */ /*output: еĸ 5 ֮·ߵĸ 8 ֮·Լ룺 1 2 2 1 3 5 2 3 2 2 4 6 3 4 7 4 3 2 3 5 1 4 5 4 Сڵλã 1 map 1 2 3 4 5 1 2 5 2 2 6 3 7 1 4 2 4 5 Դ11̾Ϊ0·Ϊ1 Դ12̾Ϊ2·Ϊ12 Դ13̾Ϊ4·Ϊ123 Դ14̾Ϊ8·Ϊ124 Դ15̾Ϊ5·Ϊ1235 밴. . . */ /*ʾʱȸ 5 11 1 5 12 5 1 8 1 2 16 2 1 29 5 2 32 2 4 13 4 2 27 1 3 15 3 1 21 3 4 7 4 3 19 5 */ /*output: еĸ 5 ֮·ߵĸ 11 ֮·Լ룺 1 5 12 5 1 8 1 2 16 2 1 29 5 2 32 2 4 13 4 2 27 1 3 15 3 1 21 3 4 7 4 3 19 Сڵλã 5 map 1 2 3 4 5 1 16 15 12 2 29 13 3 21 7 4 27 19 5 8 32 Դ51̾Ϊ8 ·Ϊ51 Դ52̾Ϊ24 ·Ϊ512 Դ53̾Ϊ23 ·Ϊ513 Դ54̾Ϊ30 ·Ϊ5134 Դ55̾Ϊ0 ·Ϊ5 밴. . . */
true
e268df5733da995bfcfb771ef0203780d313d782
C++
albertZhangTJ/regression_based_machine_learning_to_predict_wind_power_generation
/dimension.h
UTF-8
692
2.515625
3
[]
no_license
#ifndef DIMENSION_H #define DIMENSION_H #include <vector> #include <string> #include "structs.h" using namespace std; class dimension{ public: int exp; string name; vector<double>* params; vector<point>* data; float l_bndry; float r_bndry; dimension(string name, int exp); void on_update(vector<point> new_data); //the active learning boundary is determined using the largest absolute value for derivative //since here a minimal shift in x leads to large change in y, thus worth more of our attention vector<float> update_bndry(); double estimate(float x); ~dimension(); }; #endif
true
eb87d32ec7ba6cec8cac3403ef2c80e44db7d6ce
C++
captainwong/DSA
/include/dtl/hashtable.h
UTF-8
4,757
2.90625
3
[]
no_license
#pragma once #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #include "bitmap.h" #include "dictionary.h" #include "entry.h" #include "prime.h" #include "release.h" #include <string.h> // strlen, memset namespace dtl { /**************散列函数*************/ //! 通用散列函数模板 template <typename T> inline size_t hashCode(T t) { return static_cast<size_t>(t); } //! long long 偏特化 template <> inline size_t hashCode(long long i) { return static_cast<size_t>((i >> 32) + static_cast<int>(i)); } //! 字符串偏特化 template <> inline size_t hashCode(const char* s) { int h = 0; for (size_t n = strlen(s), i = 0; i < n; i++) { h = (h << 5) | (h >> 27); // 散列码循环左移5位 h += static_cast<int>(s[i]); // 再累加当前字符 } return static_cast<size_t>(h); // 如此所得的散列码,实际上可理解为近似的“多项式散列码” } // 对于英语单词,"循环左移5位"是实验统计得出的最佳值 //! 散列表 template <typename K, typename V> class Hashtable : public Dictionary<K, V> { friend class UniPrint; public: typedef Dictionary<K, V> DictionaryType; typedef Entry<K, V> EntryType; typedef EntryType* Bucket; typedef Bucket* Buckets; Hashtable(int c = 5) { M = primeNLT(c, 1048576); N = 0; buckets = new Bucket[M]; memset(buckets, 0, sizeof(Bucket) * M); lazyRemoval = new Bitmap(M); } ~Hashtable() { for (int i = 0; i < M; i++) { if (buckets[i]) { release(buckets[i]); } } release(buckets); release(lazyRemoval); } //! 当前词条数目 virtual int size() const override { return N; } //! 插入(禁止雷同词条,故可能失败) virtual bool put(K const& k, V const& v) override { if (buckets[probe4Hit(k)]) { return false; } // 雷同元素不必重复插入 int r = probe4Free(k); // 为新词条找个空桶(只要装填因子控制得当,必然成功) buckets[r] = new EntryType(k, v); ++N; // 插入(注意:懒惰删除标记无需复位) if (N * 2 > M) { rehash(); } // 装填因子高于50%后重散列 return true; } //! 读取 virtual V* get(K const& k) override { int r = probe4Hit(k); return buckets[r] ? &(buckets[r]->value) : nullptr; } //! 删除 virtual bool remove(K const& k) override { int r = probe4Hit(k); if (!buckets[r]) { return false; } // 对应词条不存在时,无法删除 release(buckets[r]); buckets[r] = nullptr; // //否则释放桶中词条,设置懒惰删除标记,并更新词条总数 markAsRemoved(r); --N; return true; } protected: //! 沿关键码k对应的查找链,找到词条匹配的桶(供查找和删除词条时调用) int probe4Hit(const K& k) { // 试探策略多种多样,可灵活选取;这里仅以线性试探策略为例 int r = hashCode(k) % M; // 从起始桶(按除余法确定)出发 while ((buckets[r] && (k != buckets[r]->key)) || (!buckets[r] && lazilyRemoved(r))) { r = (r + 1) % M; // 沿查找链线性试探:跳过所有冲突的桶,以及带懒惰删除标记的桶 } return r; // 调用者根据ht[r]是否为空,即可判断查找是否成功 } //! 沿关键码k对应的查找链,找到首个可用空桶 int probe4Free(const K& k) { // 试探策略多种多样,可灵活选取;这里仅以线性试探策略为例 int r = hashCode(k) % M; // 从起始桶(按除余法确定)出发 while (buckets[r]) { r = (r + 1) % M; } // 沿查找链逐桶试探,直到首个空桶(无论是否带有懒惰删除标记) return r; // 为保证空桶总能找到,装填因子及散列表长需要合理设置 } /** * @brief 重散列算法:扩充桶数组,保证装填因子在警戒线以下 * @note 装填因子过大时,采取“逐一取出再插入”的朴素策略,对桶数组扩容 * 不可简单地(通过memcpy())将原桶数组复制到新桶数组(比如前端),否则存在两个问题: * 1)会继承原有冲突; * 2)可能导致查找链在后端断裂——即便为所有扩充桶设置懒惰删除标志也无济于事 */ void rehash() { int oldM = M; Buckets oldBuckets = buckets; M = primeNLT(2 * M, 1048576); N = 0; buckets = new Bucket[M]; memset(buckets, 0, sizeof(Bucket) * M); lazyRemoval->destroy(); lazyRemoval->init(M); for (int i = 0; i < oldM; i++) { if (oldBuckets[i]) { put(oldBuckets[i]->key, oldBuckets[i]->value); } } release(oldBuckets); } bool lazilyRemoved(int r) const { return lazyRemoval->test(r); } void markAsRemoved(int r) { lazyRemoval->set(r); } private: //! 桶数组,存放词条指针 Buckets buckets; //! 桶数组容量 int M; //! 词条数量 int N; //! 懒惰删除标记 Bitmap* lazyRemoval; }; }
true
3361f12bb04530bedb58b89ef8c2b4decc2ceae9
C++
xuejingao/schoolProjects235
/project3/og/PlayList3.cpp
UTF-8
3,907
3.359375
3
[]
no_license
/* Author: JiaLe Qiu Course: CSCI-235 Fall 2018 Instructor: Tiziana Ligorio Assignment: Project 3 This is the implementation of "PlayList.h". */ #include <iostream> #include <vector> using namespace std; #include "PlayList.h" PlayList::PlayList(){ tail_ptr_ = nullptr; } //default constructor PlayList::PlayList(const Song& a_song) { Node<Song>* songNode = new Node<Song>; songNode->setItem(a_song); item_count_++; tail_ptr_ = songNode; head_ptr_ = songNode; } //parameterized constructor PlayList::PlayList(const PlayList& a_play_list_): LinkedSet(a_play_list_) { //LinkedSet<Song>:: LinkedSet(a_play_list_); item_count_ = a_play_list_.item_count_; tail_ptr_ = getPointerToLastNode(); } //copy constructor; Node<Song>* PlayList:: getPointerToLastNode() const { //traverse the chain //get to the end, which would be == nullptr Node<Song>* curPtr = head_ptr_; if (head_ptr_ == nullptr) { return curPtr; } while ((*curPtr).getNext() != nullptr) //traverse the chain until { //it gets to last node. curPtr = (*curPtr).getNext(); } //end while when the next pointer is a nullptr. return curPtr; } PlayList::~PlayList() { unloop(); clear(); } //end destructor bool PlayList:: add(const Song& new_song) { //override. ADD AT END OF CHAIN. Node<Song>* new_node_ptr = new Node<Song>;//(new_song); new_node_ptr->setItem(new_song); Node<Song>* cur_ptr = head_ptr_; if (!contains(new_song)) { //check if 'new_song' is a duplicate //cout << new_song.getTitle() << endl; if (head_ptr_ == nullptr) { tail_ptr_ = new_node_ptr; head_ptr_ = new_node_ptr; item_count_++; } else { //if not empty //while ((*cur_ptr).getNext() != nullptr) { // cur_ptr = (*cur_ptr).getNext(); //} traverse the chain until we get to one node before tail_ptr_ (*tail_ptr_).setNext(new_node_ptr); tail_ptr_ = new_node_ptr; item_count_++; //(*new_node_ptr).setNext(tail_ptr_); or "setNext(nullptr);" ??? } } else { return false; } return false; } //shall I create a last node with nullptr? since new_song replaces nullptr. Node<Song>* PlayList:: getPointerTo(const Song& target, Node<Song>*& previous_ptr) const { bool found = false; //previous_ptr = nullptr; already declared in function remove. Node<Song>* currentPtr = head_ptr_; while(!found && (currentPtr != nullptr)) { if (target == (*currentPtr).getItem()){ //==(currentPtr->getItem) found = true; } else { previous_ptr = currentPtr; currentPtr = (*currentPtr).getNext(); } } if (found == false) { previous_ptr = nullptr; currentPtr = nullptr; return currentPtr; } return currentPtr; } bool PlayList:: remove(const Song& a_song) { //override Node<Song>* previous_ptr = head_ptr_; Node<Song>* entryNodePtr = getPointerTo(a_song, previous_ptr); //problem removing first song if (contains(a_song)) { if ((head_ptr_ != nullptr) && (entryNodePtr != nullptr)) { (*previous_ptr).setNext((*entryNodePtr).getNext()); //setting previous_ptr to point to the next node of entryNodePtr. //Now, we are gonna delete entryNodePtr. delete entryNodePtr; // deletes what's stored in currentPtr's entryNodePtr = nullptr; // memory address. item_count_--; } return true; } return false; } void PlayList:: loop() { (*tail_ptr_).setNext(head_ptr_); } void PlayList:: unloop() { (*tail_ptr_).setNext(nullptr); } void PlayList::displayPlayList() { vector<Song> arr = toVector(); for(size_t i = 0; i < arr.size(); i++){ cout << "* Title: " << arr.at(i).getTitle() << " * Author: " << arr.at(i).getAuthor() << " * Album: " << arr.at(i).getAlbum() << " *" << endl; } cout << "End of playlist" << endl; } //end displayPlayList
true
123a7f10da991da129423d1a3fa9540e866186fa
C++
geranium12/Numerical-Analysis
/SuccessiveOverRelaxation/SuccessiveOverRelaxation/LES.cpp
UTF-8
1,093
2.609375
3
[]
no_license
#include "LES.h" LES::LES(ExtendedMatrix exMatrix) : mSize_(exMatrix.size()), matrix(exMatrix) { curSol_ = new float[mSize_]; prevSol_ = new float[mSize_]; state = "LinearEquationsSystem"; } int LES::findSolRelaxationMethod(int kMax, double accuracy, double option) { state = "RelaxationMethod" + std::to_string(int(10 * option)); for (int k = 0; k < kMax; ++k) { for (int i = 0; i < mSize_; ++i) { curSol_[i] = matrix[i][mSize_]; for (int j = 0; j < i; ++j) { curSol_[i] -= matrix[i][j] * curSol_[j]; } for (int j = i + 1; j < mSize_; ++j) { curSol_[i] -= matrix[i][j] * prevSol_[j]; } curSol_[i] = curSol_[i] * option / matrix[i][i] + (1 - option) * prevSol_[i]; } std::swap(prevSol_, curSol_); if (maxDiff() < accuracy) { return k; } } state += "ExceededKMax"; return -1; } float LES::maxDiff() { float mDiff = 0; for (int i = 0; i < mSize_; ++i) { if (mDiff < std::abs(prevSol_[i] - curSol_[i])) { mDiff = std::abs(prevSol_[i] - curSol_[i]); } } return mDiff; } float* LES::operator[] (int i) { return matrix[i]; }
true
f3d60960a38869c9c19656547f285c2f276634f0
C++
farzadb/Arduino_BLE_iOS_CPP
/Arduino_Bluetooth_BLE/Arduino_Bluetooth_BLE.ino
UTF-8
2,354
3.4375
3
[ "MIT" ]
permissive
#include <SoftwareSerial.h> //This is a very simple sketch for chatting with the iPhone, iPad, or Desktop //It will get a HELLO command to turn the light on or GOODBYE to turn it off. //AT commands can be sent through the IDE Monitor command. Or just data can be sent back to the phone. SoftwareSerial BLE_Serial(3, 4); // RX, TX char inData[64]; // Much larger than any expected command int i=0;//I like to put these variables here as for embedded programming it smooths things along int index=0;//This would be used as the pointer to where in the array the data stream is presently char inChar=-1;//This is a bool command=false;//This is a flag noting if a command just finished void setup() { Serial.begin(9600); Serial.println("Waiting for command..."); BLE_Serial.begin(9600);//The default baudrate for the module is 9600 pinMode(9, OUTPUT);//This for the light digitalWrite(9, LOW);//Double check that the light is off. } void loop() // run until the end of time { if(BLE_Serial.available()) //Check to see if any data has streamed into the module { byte byte_count=BLE_Serial.available();//Often one byte comes in, but sometimes more. for(i=0;i<byte_count;i++)//Handle the number of incoming bytes { inChar=BLE_Serial.read();//Read one byte if(index>63){index=0;}//Don't allow buffer overruns. if(inChar==10) //Command terminator detected { inData[index]='\0';//Close off the string command=true;//This is a command index=0;//reset } else { inData[index]=inChar;//shove the next character into the array index++; } } if(command==true && String(inData)=="HELLO")//Let's turn on the light { command=false;//Reset for the next command digitalWrite(9, HIGH);//Turn on the really bright light Serial.println(String(inData));//Write out the assembled command } else if(command==true && String(inData)=="GOODBYE")//Let's turn it off. { command=false;//Reset for the next comment digitalWrite(9, LOW);//Blessed darkness Serial.println(String(inData));//Write out the assembled command } } if(Serial.available())//When stuff is typed in the Arduino monitor window then send it up to the computer { BLE_Serial.write(Serial.read());//Read it and pass it along. } }
true
a3fad49645ef4768123266dd6dc3f294283d66dd
C++
DeMeiring/COS214-Project
/Engineering.cpp
UTF-8
1,201
2.625
3
[]
no_license
#include "Engineering.h" Engineering::~Engineering() {} Engineering::Engineering(string RNDName, bool isDept) { this->RnD_Name = RNDName; this->isDept = isDept; } string Engineering::getRnDName() { // TODO - implement Engineering::getRnDName return RnD_Name; } int Engineering::getCost() { return Cost; } int Engineering::getLevel() { return level; } Statistics* Engineering::getStats() { return stats; } // int Engineering::getTotalCost() { // } // void Engineering::addDepartment(Engineering* Dept) { // // TODO - implement Engineering::addDepartment // throw "Not yet implemented"; // } Engineering_Iterator* Engineering::createIterator(Engineering* Dept) { Engineering_Iterator* iterator = new Engineering_Iterator(Dept); return iterator; } vector<Engineering*> Engineering::getRnD() { return RnD; } bool Engineering::getIsDept() { return this->isDept; } void Engineering::setIsDept(bool isDept) { this->isDept = isDept; } int Engineering::getCompIndex() { return compIndex; } void Engineering::setCompIndex(int index) { compIndex = index; } int Engineering::getDeptIndex() { return deptIndex; } void Engineering::setDeptIndex(int index) { deptIndex = index; }
true
03fb1cc4863de3c9e95452a33eb6df1ab8dd4466
C++
haoxu686/Syntax-Parser
/State.h
UTF-8
754
2.6875
3
[]
no_license
#pragma once #include <vector> #include "Project.h" #include "Edge.h" using namespace std; class State { private: vector<set<int> *> * pvAcceptedSets; vector<set<int> *> * pvCascadeSets; vector<Project *> * pvProjects; Edge * pNextEdge; int index; public: State(int); ~State(void); void addToAcceptedSet(int, int); void addToCascadeSet(int, int); void addToAcceptedSet(int, set<int>::iterator, set<int>::iterator); set<int> * getAcceptedSetAt(int); set<int> * getCascadeSetsAt(int); void addProject(Project *); void setNextEdge(Edge *); void setIndex(int); bool equals(State *); void commit(); static bool sortMethod(Project *, Project *); Edge * nextEdge(); int getProjectCount(); Project * getProject(int); int getIndex(); };
true
ea1400647563b2d3d05061e0ca9fda486d46381b
C++
tssavita/geeksforgeeks_solutions
/easy-level/sort-an-array-of-0s-1s-and-2s.cpp
UTF-8
983
2.640625
3
[]
no_license
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } int main() { int t; cin>>t; for (int i = 0; i < t; i++) { int n; cin>>n; int arr[n]; for (int j = 0; j < n; j++) cin>>arr[j]; int low = 0, high = n-1, mid = 0; while (mid <= high) { switch(arr[mid]) { case 0: swap(&arr[low++], &arr[mid++]); break; case 1: mid++; break; case 2: swap(&arr[mid], arr[high--]); break; } } for (int j = 0; j < n; j++) cout << arr[j] << " "; cout << endl; } return 0; }
true
4bc7722f12b264e2bb869ced250ddbb665b52ae3
C++
dougnobrega/Biblioteca
/Codigo/Matematica/polyFFT.cpp
UTF-8
3,530
3
3
[]
no_license
// FFT // // Exemplos na main // // Soma O(n) & Multiplicacao O(nlogn) template<typename T> void fft(vector<T> &a, bool f, int N, vector<int> &rev){ for (int i = 0; i < N; i++) if (i < rev[i]) swap(a[i], a[rev[i]]); int l, r, m; vector<T> roots(N); for (int n = 2; n <= N; n *= 2){ T root = T::rt(f, n, N); roots[0] = 1; for (int i = 1; i < n/2; i++) roots[i] = roots[i-1]*root; for (int pos = 0; pos < N; pos += n){ l = pos+0, r = pos+n/2, m = 0; while (m < n/2){ auto t = roots[m]*a[r]; a[r] = a[l] - t; a[l] = a[l] + t; l++; r++; m++; } } } if (f) { auto invN = T(1)/N; for(int i = 0; i < N; i++) a[i] = a[i]*invN; } } template<typename T> struct poly : vector<T> { poly(const vector<int> &coef):vector<T>(coef.size()){ for (int i = 0; i < coef.size(); i++) this->at(i) = coef[i]; } poly(const vector<T> &coef):vector<T>(coef){} poly(unsigned size, T val = 0):vector<T>(size, val){} poly(){} T operator()(T x){ T ans = 0, curr_x(1); for (auto c : *this) { ans = ans+c*curr_x; curr_x = curr_x*x; } return ans; } poly<T> operator+(const poly<T> &r){ const poly<T> &l = *this; int sz = max(l.size(), r.size()); poly<T> ans(sz); for (unsigned i = 0; i < l.size(); i++) ans[i] = ans[i]+l[i]; for (unsigned i = 0; i < r.size(); i++) ans[i] = ans[i]+r[i]; return ans; } poly<T> operator-(poly<T> &r){ for (auto &it : r) it = -it; return (*this)+r; } poly<T> operator*(const poly<T> r){ const poly<T> &l = *this; int ln = l.size(), rn = r.size(); int N = ln+rn+1; int log_n = T::fft_len(N); int n = 1 << log_n; vector<int> rev(n); for (int i = 0; i < n; ++i){ rev[i] = 0; for (int j = 0; j < log_n; ++j) if (i & (1<<j)) rev[i] |= 1 << (log_n-1-j); } if (N > n) throw logic_error("resulting poly to big"); vector<T> X(n), Y(n); for (int i = 0; i < ln; i++) X[i] = l[i]; for (int i = ln; i < n; i++) X[i] = 0; for (int i = 0; i < rn; i++) Y[i] = r[i]; for (int i = rn; i < n; i++) Y[i] = 0; fft(X, false, n, rev); fft(Y, false, n, rev); for (int i = 0; i < n; i++) Y[i] = X[i]*Y[i]; fft(Y, true, n, rev); poly<T> ans(N); for (int i = 0; i < N; i++) ans[i] = Y[i]; // while (!ans.empty() && ans.back() == 0) // ans.pop_back(); return ans; } pair<poly<T>, T> briot_ruffini(T r){//for p = Q*(x - r) + R, returns (Q, R) const poly<T> &l = *this; int sz = l.size(); if (sz == 0) return {poly<T>(0), 0}; poly<T> q(sz - 1); q.back() = l.back(); for (int i = q.size()-2; i >= 0; i--){ cout << i << "~" << q.size() << endl; q[i] = q[i+1]*r + l[i+1]; } return {q, q[0]*r + l[0]}; } friend ostream& operator<<(ostream &out, const poly<T> &p){ if (p.empty()) return out; out << p.at(0); for (int i = 1; i < p.size(); i++) out << " + " << p.at(i) << "x^" << i; out << endl; return out; } }; mt19937 rng((int) chrono::steady_clock::now().time_since_epoch().count()); const int MOD = 998244353; using mint = mod_int<MOD>; int main(){ uniform_int_distribution<int> uid(0, MOD-1); int n = (1 << mint::fft_len()/2); auto rand_vec = [&](){ vector<int> rd(n); for (int &i : rd) i = uid(rng); return rd; }; poly<mint> p = rand_vec(); poly<mint> q = rand_vec(); poly<mint> sum = p+q; poly<mint> mult = p*q; for (int i = 1; i <= 5000; i++){ int x = uid(rng); auto P = p(x), Q = q(x), M = mult(x); if (P*Q != M) throw logic_error("bad implementation :("); } cout << "sucesso!" << endl; exit(0); exit(0); }
true
482e7f1f3f77fe61ac860b10debb4a8183f5286f
C++
codyjrivera/cs403
/exams/cilk/reduce.cpp
UTF-8
1,021
3.078125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <cilk/cilk.h> template <typename T> T reduce(T* array, int n, T (*op)(T, T), T id) { if (n < 1) return id; else if (n == 1) return array[0]; T* work1 = new T[n]; T* work2 = new T[n]; cilk_for (int i = 0; i < n; ++i) { work1[i] = array[i]; } for (int s = n; s > 1; s /= 2) { if (s % 2 == 1) { work1[s - 2] = op(work1[s - 2], work1[s - 1]); } cilk_for (int i = 0; i < s / 2; ++i) { work2[i] = op(work1[(2 * i)], work1[(2 * i) + 1]); } T* temp; temp = work1; work1 = work2; work2 = temp; } T val = work1[0]; delete[] work1; delete[] work2; return val; } int add(int a, int b) { return a + b; } int main(int argc, char** argv) { int s = argc - 1; int* array = new int[s]; cilk_for (int i = 0; i < s; ++i) { array[i] = atoi(argv[i + 1]); } printf("Reduction result: %d\n", reduce(array, s, add, 0)); return 1; }
true
e25fba9ffc569230c90a5d73534bf0f28129fb86
C++
MathProgrammer/LeetCode
/Contests/Weekly Contest 291/Programs/Total Appeal of A String.cpp
UTF-8
1,060
2.921875
3
[]
no_license
class Solution { public: long long appealSum(string S) { const int NO_OF_ALPHABETS = 26, NOT_FOUND = -1; long long answer = 0; vector <int> first_index(NO_OF_ALPHABETS, NOT_FOUND); vector <long long> contribution(S.size(), 0); for(int i = 0; i < S.size(); i++) { if(i == 0) { contribution[i] = 1; } else if(S[i] == S[i - 1]) { contribution[i] = contribution[i - 1] + 1; } else { if(first_index[S[i] - 'a'] == NOT_FOUND) { contribution[i] = contribution[i - 1] + i + 1; } else { contribution[i] = contribution[i - 1] + (i - first_index[S[i] - 'a']) + 1; } } first_index[S[i] - 'a'] = i + 1; answer += contribution[i]; } return answer; } };
true
5a054037b0c3a614dc782498bf37f5e7bcd273bc
C++
changzeng/BasicAlgorithm
/bytedance/robot_DOS_game.cpp
UTF-8
364
3.09375
3
[]
no_license
#include<vector> #include<iostream> #include<cmath> using namespace std; int main(){ int ans=0, building_num; cin>>building_num; vector<int> height_vec(building_num); for(int ind=0; ind<building_num; ind++){ cin>>height_vec[ind]; } for(int ind=building_num-1; ind>=0; ind--){ ans = ceil((ans+height_vec[ind])/2.0); } cout<<ans<<endl; return 0; }
true
ad00c2c0762c0ea513950603a921151bc67347ac
C++
johnerlandsson/mcv
/QCornerGuardInspector/barcodesettings.cpp
UTF-8
1,162
2.578125
3
[]
no_license
#include "barcodesettings.h" #include <QSettings> #include <QFile> #include <iostream> #include <QRegularExpression> #include <QTextStream> BarcodeSettings::BarcodeSettings() : timeout_s{ 10 }, n_error_frames{ 2 } { QSettings s; valid_barcodes_path = s.fileName(); valid_barcodes_path.remove( QRegularExpression( "[^/]*$" ) ); valid_barcodes_path.append( "valid_barcodes.txt" ); } void BarcodeSettings::load() { QSettings s; timeout_s = s.value( "BarcodeSettings/timeout_s", 10 ).toInt(); n_error_frames = s.value( "BarcodeSettings/n_error_frames" ).toInt(); QFile f( valid_barcodes_path ); if( f.open( QIODevice::ReadOnly ) ) { QTextStream ts( &f ); valid_barcodes = ts.readAll().split( '\n' ); f.close(); } } void BarcodeSettings::save() { QSettings s; s.setValue( "BarcodeSettings/timeout_s", timeout_s ); s.setValue( "BarcodeSettings/n_error_frames", n_error_frames ); QFile f( valid_barcodes_path ); if( f.open( QIODevice::WriteOnly | QIODevice::Truncate ) ) { QTextStream ts( &f ); ts << valid_barcodes.join( '\n' ); f.close(); } }
true
929b98797eff47da1eb4d6cf97342127b9761472
C++
ViKoWW/Project-Euler-
/Problem2-Even_Fibonacci_Numbers.cpp
UTF-8
987
3.9375
4
[]
no_license
#include "pch.h" #include <iostream> int start1 = 0; int start2 = 1; const int limit = 4000000; int evenSum = 0; //funktion som räknar ut fibonacci sekvensen samt identifierar om ena parametern, num2, är jämnt, isåfall läggs det till i summan evenSum. void evaluateFibonacci(int num1, int num2) { //checkar om talet är jämnt if ((num2 % 2) == 0) { evenSum += num2; // std::cout << evenSum << std::endl; } //funktionen som tar fram fibonacci sekvensen, görs genom rekursion då funktionen kallar sig själv om och om igen tills det att det större numret är större än 4 miljoner. int placeholder; placeholder = num1; num1 = num2; num2 = placeholder + num2; //std::cout << num1 << std::endl; if(num2 < limit) evaluateFibonacci(num1, num2); } int main() { //main funktionen, kör fibonacci funktionen med starttalen 0 och 1. evaluateFibonacci(start1, start2); //till slut printas den slutgiltiga summan std::cout << "The final sum is: " << evenSum; }
true
9102b7e21a5a26913c93d75fc106ca741622acff
C++
MayRiv/lab8CHMI
/lab8CHMI/calculator.cpp
UTF-8
8,322
2.546875
3
[]
no_license
#include "calculator.h" #include "ui_calculator.h" #include <math.h> #include <stdio.h> #include <iostream> #include <QDebug> #include <QFile> using namespace std; /*Calculator::Calculator(QWidget *parent) : QDialog(parent), ui(new Ui::Calculator) { a=1.0/400; n=5; ui->setupUi(this); }*/ Calculator::Calculator(QWidget *parent,int _n): QDialog(parent),ui(new Ui::Calculator) { a=1.0/400; n=_n; ui->setupUi(this); } Calculator::~Calculator() { delete ui; } void Calculator::calculate() { double h=(1.0-0.0)/(n+1); QVector<double> x(n); x[0]=0+h; for (int i=1;i<x.size();i++) x[i]+=x[i-1]+h; QVector<double> C=getC(x); h=(1.0-0.0)/(4*n+1); double argument=0; QFile file("out.txt"); file.open(QIODevice::Append | QIODevice::Text); QTextStream out(&file); for (int i=0;i<4*n+1+1;i++) { double yApproximate=0; for (int i=0;i<C.size();i++) yApproximate+=C[i]*baseFunction(i+1,argument); //printf("%lf yApp=%lf yAcc=%lf\n",(yApproximate-getAccurateValue(argument))/(yApproximate)*100,yApproximate,getAccurateValue(argument)); //std::cout << "xyy"; out <<"x= "<< argument<<" yt ="<< getAccurateValue(argument)<<" yp= "<<yApproximate<<" abs= "<<getAccurateValue(argument)-yApproximate<<" otn"<<(getAccurateValue(argument)-yApproximate)/yApproximate*100 <<"\n"; qDebug()<<"x= "<< argument<<"yt ="<< getAccurateValue(argument)<<"yp= "<<yApproximate<<"abs= "<<getAccurateValue(argument)-yApproximate<<"otn"<<(getAccurateValue(argument)-yApproximate)/yApproximate*100; arguments.push_back(argument); values.push_back(yApproximate); accurate.push_back(getAccurateValue(argument)); argument+=h; } double yApproximate=0; for (int i=0;i<C.size();i++) yApproximate+=C[i]*baseFunction(i+1,0.5); qDebug()<<"pri x=0.5 "<<"yt ="<< getAccurateValue(0.5)<<"yp= "<<yApproximate<<"abs= "<<getAccurateValue(0.5)-yApproximate<<"otn"<<(getAccurateValue(0.5)-yApproximate)/yApproximate*100; qDebug() << " "; qDebug() << " "; qDebug() << " "; out << " \n\n\n"; file.close(); } double Calculator::baseFunction(int j, double x) { return sin(j*M_PI*x); } double Calculator::derrivateBaseFunction(int j, double x) { return j*M_PI*cos(j*M_PI*x); } double Calculator::doubleDerrivateBaseFunction(int j, double x) { return -pow(j*M_PI,2.0)*sin(j*M_PI*x); } double Calculator::r(double x) { return a; } double Calculator::p(double x) { return 0; } double Calculator::q(double x) { return -1; } double Calculator::rightPartFunction(double x) { return pow(cos(M_PI*x),2)+2*a*M_PI*M_PI*cos(2*M_PI*x); } double* Calculator::methodGauss02(const double* pA, const double* pB, int n ) { static const char* methodGauss02 = "methodGauss02!"; static const char* nullPointer = "Null-pointer!"; static const char* noMemory = "No-memory!"; static const char* nEquals0 = "n = 0!"; double* X = NULL; if(!pA || !pB) printf("\n%s: %s\n", methodGauss02, nullPointer); else if(!n) printf("\n%s: %s\n", methodGauss02, nEquals0); else { double** A = NULL; //A[0] -> A[0][0] double* B = NULL; // int* ci = NULL; //current row indexes int* cj = NULL; //current column indexes if(!(A = (double**)malloc(sizeof(double*)*n)) || !(B = (double*)malloc(sizeof(double)*n)) || !(ci = (int*)malloc(sizeof(int)*n)) || !(cj = (int*)malloc(sizeof(int)*n)) || !(A[0] = (double*)malloc(sizeof(double)*n*n)) ) printf("\n%s: %s\n", methodGauss02, noMemory); else { if(!(X = (double*)malloc(sizeof(double)*n))) printf("\n%s: %s\n", methodGauss02, noMemory); else { int i; //row index int j; //column index int k; //row index int imax; //row index of maximum element int jmax; //colon index of maximum element int temp; double R; //R = A[i+1][i] / A[i][i] double S; //Si = A[i][i+1] * X[i+1] + A[i][i+2] * X[i+2] -... for(i = 1; i < n; i++) A[i] = &A[0][i*n]; for(i = 0; i < n; i++) { ci[i] = i; cj[i] = i; } //Copying pA to A and B to B for(i = 0; i < n*n; i++) A[0][i] = pA[i]; for(i = 0; i < n; i++) B[i] = pB[i]; //Making A triangle for(i = 0; i < n-1; i++) { //Seeking for maximum element imax = i; jmax = i; for(k = i; k < n; k++) for(j = i; j < n; j++) if(fabs(A[ci[k]][cj[j]]) > fabs(A[ci[imax]][cj[jmax]])) { imax = k; jmax = j; } //if imax != i then exchanging A[i] and A[imax] rows if(imax != i) { temp = ci[i]; ci[i] = ci[imax]; ci[imax] = temp; } if(jmax != i) { temp = cj[i]; cj[i] = cj[jmax]; cj[jmax] = temp; } //Making 0s in i column from i+1 row to n-1 row for(k = i+1; k < n; k++) { R = A[ci[k]][cj[i]] / A[ci[i]][cj[i]]; // for(j = i+1!!!...) for(j = i; j < n; j++) A[ci[k]][cj[j]] = A[ci[k]][cj[j]] - R * A[ci[i]][cj[j]]; B[ci[k]] = B[ci[k]] - R * B[ci[i]]; } } //Calculating X B[ci[n-1]] = B[ci[n-1]] / A[ci[n-1]][cj[n-1]]; for(k = n-2; k >= 0; k--) { S = 0; for(j = k+1; j < n; j++) S = S + A[ci[k]][cj[j]] * B[ci[j]]; B[ci[k]] = (B[ci[k]] - S) / A[ci[k]][cj[k]]; } for(i = 0; i < n; i++) X[cj[i]] = B[ci[i]]; } free(A[0]); } free(A); free(B); free(ci); free(cj); } double XTest[n]; QVector<double> XTestVector(n); for (int i=0;i<n;i++) XTestVector[i]=X[i]; return X; } QVector<double> Calculator::solveGauss(QVector<double> A, QVector<double> B)//Векторная обёртка над массивным гауссом. { double* pA=new double [A.size()]; double* pB=new double [B.size()]; for (int i=0;i<A.size();i++) pA[i]=A[i]; for (int i=0;i<B.size();i++) pB[i]=B[i]; double* pX=new double [B.size()]; pX=methodGauss02(pA,pB,B.size()); QVector<double> result(B.size()); for (int i=0;i<B.size();i++) result[i]=pX[i]; delete pA; delete pB; delete pX; return result; } QVector<double> Calculator::getC(QVector<double> x) { QVector<double> A(x.size()*x.size()); QVector<double> B(x.size()); for (int i=0;i<x.size();i++) for (int j=0;j<x.size();j++) A[i*x.size()+j]=r(x[i])*doubleDerrivateBaseFunction(j+1,x[i])+p(x[i])*derrivateBaseFunction(j+1,x[i])+q(x[i])*baseFunction(j+1,x[i]); /*A[0]=0.227222; A[1]=0.072407; A[2]=0.227200; A[3]=0.153148;*/ for (int i=0;i<x.size();i++) B[i]=rightPartFunction(x[i]); QVector<double> C= solveGauss(A,B); foreach(double coeff, C) { qDebug() << coeff; } qDebug() << " "; qDebug() << " "; qDebug() << " "; return C; } double Calculator::getAccurateValue(double x) { return (exp((x-1)/sqrt(a))+exp(-x/sqrt(a)))/(1+exp(-1/sqrt(a)))-pow(cos(M_PI*x),2); } void Calculator::setNumberOfNodes(int _n) { n=_n; arguments.clear(); values.clear(); accurate.clear(); }
true
1ce7c73251192b01b0ef9acb5e104c4e41040ff3
C++
pthom/BabylonCpp
/src/BabylonCpp/include/babylon/meshes/base_sub_mesh.h
UTF-8
1,214
2.515625
3
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
#ifndef BABYLON_MESHES_BASE_SUB_MESH_H #define BABYLON_MESHES_BASE_SUB_MESH_H #include <memory> #include <babylon/babylon_api.h> #include <babylon/babylon_common.h> namespace BABYLON { class Effect; struct MaterialDefines; using EffectPtr = std::shared_ptr<Effect>; using MaterialDefinesPtr = std::shared_ptr<MaterialDefines>; /** * @brief Base class for submeshes. */ class BABYLON_SHARED_EXPORT BaseSubMesh { public: BaseSubMesh(); ~BaseSubMesh(); /** * @brief Sets associated effect (effect used to render this submesh). * @param effect defines the effect to associate with * @param defines defines the set of defines used to compile this effect */ void setEffect(const EffectPtr& effect, const MaterialDefinesPtr& defines = nullptr); protected: /** * @brief Gets the associated effect. */ EffectPtr& get_effect(); public: /** * Hidden */ MaterialDefinesPtr _materialDefines; /** * Hidden */ EffectPtr _materialEffect; /** * Gets associated effect */ ReadOnlyProperty<BaseSubMesh, EffectPtr> effect; }; // end of class BaseSubMesh } // end of namespace BABYLON #endif // end of BABYLON_MESHES_BASE_SUB_MESH_H
true
bd41c4441953ff62ef90327c546fa86152bf0353
C++
croccanova/CS162
/Project 3 - Fantasy combat/Vampire.cpp
UTF-8
1,153
3.5
4
[]
no_license
/****************************************************** Program Name: Project3 - Fantasy Combat Author: Christian Roccanova Date: 5/8/2017 Description: Header file for the Harry Potter subclass- inherits from Creature, contains virtual attack and defense functions ******************************************************/ #include "Vampire.hpp" Vampire::Vampire() { armor = 1; strength = 18; } //Processes the attacker's turn int Vampire::attack() { attackResult = (rand() % 12) + 1; cout << "Vampire attacks with a roll of " << attackResult << "." << endl; return attackResult; } //processes the defender's turn void Vampire::defense(int atk) { int charm; charm = rand() % 2; if (charm == 1) { defenseResult = 99; cout << "Vampire used charm!" << endl; } else { defenseResult = (rand() % 6) + 1; cout << "Vampire defends with a roll of " << defenseResult << " and " << 1 << " armor." << endl; } //damage dealt after roll and armor dmg = atk - (defenseResult + 1); if (dmg < 0) { dmg = 0; } cout << "Vampire takes " << dmg << " damage." << endl; strength = strength - dmg; }
true
f47a0885d3710fed9db5ef6262aa1cfe47193e76
C++
rafarubim/Simulador-de-fluxo
/main.cpp
UTF-8
5,319
2.859375
3
[]
no_license
#include <iostream> #include <vector> #include "vectorPlus.hpp" #include "matrix.hpp" #include "numericalMethods.hpp" #include "interface.hpp" #include <thread> #include "glut.h" using namespace std; #define EVER ;; int _n = 0; matrix<double> _A; vector<double> _b; vector<double> _x0; vector<double> _x1; vector<double> _x2; void EscreverString(const char *str) { for (int i = 0; str[i] != '\0'; ++i) { glutStrokeCharacter(GLUT_STROKE_ROMAN, str[i]); } } void EscreverNum(const double num) { char buffer[100]; snprintf(buffer, 100, "%.1f", num); EscreverString(buffer); } void DesenharSistema() { glColor3f(0, 0, 0); glMatrixMode(GL_MODELVIEW); glTranslatef(-0.6, 0.7, 0); glScalef(.002, .002, 1); EscreverString("Ax = b"); glLoadIdentity(); // A glBegin(GL_LINES); glVertex2f(-0.75, 0.6); glVertex2f(-0.8, 0.6); glVertex2f(-0.8, 0.6); glVertex2f(-0.8, 0); glVertex2f(-0.8, 0); glVertex2f(-0.75, 0); glEnd(); glBegin(GL_LINES); glVertex2f(-0.25, 0.6); glVertex2f(-0.2, 0.6); glVertex2f(-0.2, 0.6); glVertex2f(-0.2, 0); glVertex2f(-0.2, 0); glVertex2f(-0.25, 0); glEnd(); for (int i = 0; i < _A.GetM(); i++) { for (int j = 0; j < _A.GetN(); j++) { glTranslatef(-0.8 + 0.05 + j*0.6/_n, 0.6 + 0.07 - (i+1)*0.6/_n, 0); glScalef(.0005, .0005, 1); EscreverNum(_A[i][j]); glLoadIdentity(); } } // x glBegin(GL_LINES); glVertex2f(-0.1, 0.6); glVertex2f(-0.15, 0.6); glVertex2f(-0.15, 0.6); glVertex2f(-0.15, 0); glVertex2f(-0.15, 0); glVertex2f(-0.1, 0); glEnd(); glBegin(GL_LINES); glVertex2f(0, 0.6); glVertex2f(0.05, 0.6); glVertex2f(0.05, 0.6); glVertex2f(0.05, 0); glVertex2f(0.05, 0); glVertex2f(0, 0); glEnd(); for (int i = 0; i < _n; i++) { glTranslatef(-0.15 + 0.05 , 0.6 + 0.07 - (i + 1)*0.6 / _n, 0); glScalef(.0005, .0005, 1); EscreverString("x"); EscreverNum(i); glLoadIdentity(); } glTranslatef(0.15, 0.2, 0); glScalef(.002, .002, 1); EscreverString("="); glLoadIdentity(); // b glBegin(GL_LINES); glVertex2f(0.5, 0.6); glVertex2f(0.45, 0.6); glVertex2f(0.45, 0.6); glVertex2f(0.45, 0); glVertex2f(0.45, 0); glVertex2f(0.5, 0); glEnd(); glBegin(GL_LINES); glVertex2f(0.6, 0.6); glVertex2f(0.65, 0.6); glVertex2f(0.65, 0.6); glVertex2f(0.65, 0); glVertex2f(0.65, 0); glVertex2f(0.6, 0); glEnd(); for (unsigned int i = 0; i < _b.size(); i++) { glTranslatef(0.45 + 0.05, 0.6 + 0.07 - (i + 1)*0.6 / _n, 0); glScalef(.0005, .0005, 1); EscreverNum(_b[i]); glLoadIdentity(); } // x Jacobi glTranslatef(-0.8, -0.3, 0); glScalef(.002, .002, 1); EscreverString("x:"); glLoadIdentity(); glTranslatef(-0.85, -0.4, 0); glScalef(.0005, .0005, 1); EscreverString("(Jacobi)"); glLoadIdentity(); glBegin(GL_LINES); glVertex2f(-0.45, -0.2); glVertex2f(-0.5, -0.2); glVertex2f(-0.5, -0.2); glVertex2f(-0.5, -0.8); glVertex2f(-0.5, -0.8); glVertex2f(-0.45, -0.8); glEnd(); glBegin(GL_LINES); glVertex2f(-0.35, -0.2); glVertex2f(-0.3, -0.2); glVertex2f(-0.3, -0.2); glVertex2f(-0.3, -0.8); glVertex2f(-0.3, -0.8); glVertex2f(-0.35, -0.8); glEnd(); for (unsigned int i = 0; i < _x1.size(); i++) { glTranslatef(-0.5 + 0.05, -0.2 + 0.07 - (i + 1)*0.6 / _n, 0); glScalef(.0005, .0005, 1); EscreverNum(_x1[i]); glLoadIdentity(); } // x Gauss Seidel glTranslatef(0, -0.3, 0); glScalef(.002, .002, 1); EscreverString("x:"); glLoadIdentity(); glTranslatef(-0.15, -0.4, 0); glScalef(.0005, .0005, 1); EscreverString("(Gauss-Seidel)"); glLoadIdentity(); glBegin(GL_LINES); glVertex2f(0.45, -0.2); glVertex2f(0.4, -0.2); glVertex2f(0.4, -0.2); glVertex2f(0.4, -0.8); glVertex2f(0.4, -0.8); glVertex2f(0.45, -0.8); glEnd(); glBegin(GL_LINES); glVertex2f(0.55, -0.2); glVertex2f(0.6, -0.2); glVertex2f(0.6, -0.2); glVertex2f(0.6, -0.8); glVertex2f(0.6, -0.8); glVertex2f(0.55, -0.8); glEnd(); for (unsigned int i = 0; i < _x2.size(); i++) { glTranslatef(0.4 + 0.05, -0.2 + 0.07 - (i + 1)*0.6 / _n, 0); glScalef(.0005, .0005, 1); EscreverNum(_x2[i]); glLoadIdentity(); } } int main() { thread thrInterface(interface::Init); // Exemplo Matriz A: { { 8,1,-1 }, { 1,-7,2 }, { 2,1,9 } } // Exemplo Vetor b: {8,-4, 12} // Exemplo Vetor x esperado: {1, 1, 1} for (EVER) { cout << "O programa resolvera o sistema Ax = b.\nComece digitando a dimensao da matriz quadrada A: "; cin >> _n; interface::AddDesenho(DesenharSistema); _A = matrix<double>(_n, _n); cout << "Digite as entradas da matriz A:\n"; for (int i = 0; i < _n; i++) { for (int j = 0; j < _n; j++) { cout << "A[" << i << "][" << j << "] = "; cin >> _A[i][j]; } } cout << "Digite agora as entradas do vetor b (dimensao " << _n << "):\n"; _b = vector<double>(_n); for (int i = 0; i < _n; i++) { cout << "b[" << i << "] = "; cin >> _b[i]; } cout << "--A:\n" << _A << endl; cout << "--b:\n" << _b << endl; _x0 = vector<double>(_n); _x1 = JacobiSolve(_A, _b, _x0, 20); cout << "--Resolucao pelos metodos numericos:\n-Jacobi -> x:\n" << _x1 << endl; _x2 = GaussSeidelSolve(_A, _b, _x0, 20); cout << "-Gauss-Seidel -> x:\n" << _x2 << endl; system("pause"); system("cls"); interface::DelDesenho(DesenharSistema); } thrInterface.join(); return 0; }
true
5a2e06c46bd417e456a4d01a8d49d77089348de7
C++
rahmatcmos/laravelstuff
/CityGisProcess/source/process/ParseCSV.cpp
UTF-8
3,807
2.625
3
[ "MIT" ]
permissive
#include <iostream> #include <istream> #include <sstream> #include <fstream> #include <string> #include <libpq-fe.h> #include <FileWatcher.h> #include <ParseCSV.h> #include <Positions.h> #include <Events.h> #include <Connections.h> #include <Monitoring.h> #include <Database.h> using namespace std; Positions p1; Events e1; Connections c1; Monitoring m1; int goodFile; void getDataCSV(std::string file) { try { // std::cout << goodFile << std::endl; checkNameCSV(file); std::ifstream csv(file.c_str()); csv.ignore(10000, '\n'); std::string line; CreateConnection(); // removeAll(); while (std::getline(csv, line)) { setDataCSV(line); } CloseConnection(); std::cout << "Program is done" << std::endl; } catch( std::exception& e ) { fprintf(stderr, "An exception has occurred: %s\n", e.what()); } } void checkNameCSV(std::string file) { if (file == "uploads/Positions.csv") { goodFile = 1; } else { if (file == "uploads/Events.csv") { goodFile = 2; } else { if (file == "uploads/Connections.csv") { goodFile = 3; } else { if(file == "uploads/Monitoring.csv") goodFile = 4; } } } } void setDataCSV(std::string line) { int follow = 1; for (int i = 0; i < 9; i++) { std::string splitter = ";"; std::string substring = line.substr(0, line.find(splitter)); if (goodFile == 1) { setPositions(substring, follow); }else { if (goodFile == 2) { setEvents(substring, follow); } else { if (goodFile == 3) { setConnections(substring, follow); } else { if (goodFile == 4) { setMonitoring(substring, follow); } } } } line.erase(0, substring.length() + 1); follow++; } if (goodFile == 1) { savePositions(p1); } else { if (goodFile == 2) { saveEvents(e1); } else { if (goodFile == 3) { saveConnections(c1); } else { if (goodFile == 4) { saveMonitoring(m1); } } } } } void setPositions(std::string line, int follow) { if (follow == 1) { p1.DateTime = line; } if (follow == 2) { p1.UnitId = line; } if (follow == 3) { p1.Rdx = line; } if (follow == 4) { p1.Rdy = line; } if (follow == 5) { p1.Speed = line; } if (follow == 6) { p1.Course = line; } if (follow == 7) { p1.NumSatellites = line; } if (follow == 8) { p1.HDOP = line; } if (follow == 9) { p1.Quality = line; } } void setEvents(std::string line, int follow) { if (follow == 1) { e1.DateTime = line; } if (follow == 2) { e1.UnitId = line; } if (follow == 3) { e1.Port = line; } if (follow == 4) { e1.Value = line; } } void setConnections(std::string line, int follow) { if (follow == 1) { c1.DateTime = line; } if (follow == 2) { c1.UnitId = line; } if (follow == 3) { c1.Port = line; } if (follow == 4) { c1.Value = line; } } void setMonitoring(std::string line, int follow) { if (follow == 1) { m1.UnitId = line; } if (follow == 2) { m1.BeginTime = line; } if (follow == 3) { m1.EndTime = line; } if (follow == 4) { m1.Type = line; } if (follow == 5) { m1.Min = line; } if (follow == 6) { m1.Max = line; } if (follow == 7) { m1.Sum = line; } } // vim:set et sw=4 ts=4: ft=cpp
true
54a4c5dbd2be1f81ff35fdced22848931307d2eb
C++
vietjtnguyen/ucla-winter09-cs174a-opengl-engine
/Vector4.h
UTF-8
7,330
3.09375
3
[]
no_license
#ifndef VECTOR4_H #define VECTOR4_H #include "Generic.h" #include "MathWrapper.h" using namespace Degrees; // Forward declarations template <class T> class Vector2; template <class T> class Vector3; template <class T> class Vector4; template <class T> class Matrix33; template <class T> class Matrix44; // Custom implementation of three-vector template <class T> class Vector4 { public: // Data union { T x; T r; T u; T width; }; union { T y; T g; T v; T height; }; union { T z; T b; T w; T depth; }; union { T a; }; // General functions // Default constructor Vector4(T x = 0, T y = 0, T z = 0, T a = 0) : x(x) , y(y) , z(z) , a(a) { } // Array constructor Vector4(T* vec) : x(vec[0]) , y(vec[1]) , z(vec[2]) , a(vec[3]) { } // Vector3 constructor Vector4(Vector3<T> vec, T a = 0) : x(vec.x) , y(vec.y) , z(vec.z) , a(a) { } // Copy constructor Vector4(const Vector4<T> &other) : x(other.x) , y(other.y) , z(other.z) , a(other.a) { } // Array typecast inline operator T*() { return &(this->x); } // Vector3 typecase inline operator Vector3<T>*() { return this; } // Vector2 typecase inline operator Vector2<T>*() { return this; } // Index operator inline T& operator [](int i) { return *(&(this->x)+i); } // Destructor ~Vector4() { } // Vector assignment operator inline Vector4<T>& operator =(const Vector4<T> &rhs) { if( this != &rhs ) { Vector4<T> temp(rhs); Core::Swap<T>(this->x, temp.x); Core::Swap<T>(this->y, temp.y); Core::Swap<T>(this->z, temp.z); Core::Swap<T>(this->a, temp.a); } return *this; } // Scalar assignment operator inline Vector4<T>& operator =(const T &rhs) { this->x = rhs; this->y = rhs; this->z = rhs; this->a = rhs; return *this; } // Set values inline void Set(T x, T y, T z, T a) { this->x = x; this->y = y; this->z = z; this->a = a; } // Negate inline Vector4<T> operator -() { return Vector4<T>( -this->x, -this->y, -this->z, -this->a ); } // Addition operators // Vector+Vector inline Vector4<T> operator +(Vector4<T> &rhs) const { return Vector4<T>( this->x+rhs.x, this->y+rhs.y, this->z+rhs.z, this->a+rhs.a); } // Vector+Scalar inline Vector4<T> operator +(T rhs) const { return Vector4<T>( this->x+rhs, this->y+rhs, this->z+rhs, this->a+rhs); } // Vector+Vector Assignment inline Vector4<T>& operator +=(Vector4<T> &rhs) { this->x += rhs.x; this->y += rhs.y; this->z += rhs.z; this->a += rhs.z; return *this; } // Vector+Scalar Assignment inline Vector4<T>& operator +=(T rhs) { this->x += rhs; this->y += rhs; this->z += rhs; this->a += rhs; return *this; } // Subtraction operators // Vector-Vector inline Vector4<T> operator -(Vector4<T> &rhs) const { return Vector4<T>( this->x-rhs.x, this->y-rhs.y, this->z-rhs.z, this->a-rhs.a); } // Vector-Scalar inline Vector4<T> operator -(T rhs) const { return Vector4<T>( this->x-rhs, this->y-rhs, this->z-rhs, this->a-rhs); } // Vector-Vector Assignment inline Vector4<T>& operator -=(Vector4<T> &rhs) { this->x -= rhs.x; this->y -= rhs.y; this->z -= rhs.z; this->a -= rhs.a; return *this; } // Vector-Scalar Assignment inline Vector4<T>& operator -=(T rhs) { this->x -= rhs; this->y -= rhs; this->z -= rhs; this->a -= rhs; return *this; } // Multiplication operators // Vector*Vector inline Vector4<T> operator *(Vector4<T> &rhs) const { return Vector4<T>( this->x*rhs.x, this->y*rhs.y, this->z*rhs.z, this->a*rhs.a); } // Vector*Scalar inline Vector4<T> operator *(T rhs) const { return Vector4<T>( this->x*rhs, this->y*rhs, this->z*rhs, this->a*rhs); } // Vector-Vector Assignment inline Vector4<T>& operator *=(Vector4<T> &rhs) { this->x *= rhs.x; this->y *= rhs.y; this->z *= rhs.z; this->a *= rhs.a; return *this; } // Vector*Scalar Assignment inline Vector4<T>& operator *=(T rhs) { this->x *= rhs; this->y *= rhs; this->z *= rhs; this->a *= rhs; return *this; } // Division operators // Vector/Vector inline Vector4<T> operator /(Vector4<T> &rhs) const { return Vector4<T>( this->x/rhs.x, this->y/rhs.y, this->z/rhs.z, this->a/rhs.a); } // Vector/Scalar inline Vector4<T> operator /(T rhs) const { return Vector4<T>( this->x/rhs, this->y/rhs, this->z/rhs, this->a/rhs); } // Vector/Vector Assignment inline Vector4<T>& operator /=(Vector4<T> &rhs) { this->x /= rhs.x; this->y /= rhs.y; this->z /= rhs.z; this->a /= rhs.a; return *this; } // Vector*Scalar Assignment inline Vector4<T>& operator /=(T rhs) { this->x /= rhs; this->y /= rhs; this->z /= rhs; this->a /= rhs; return *this; } // Comparison operators inline bool operator ==(Vector4<T> &rhs) const { return (this->x == rhs.x)&& (this->y == rhs.y)&& (this->z == rhs.z)&& (this->a == rhs.a); } inline bool operator !=(Vector4<T> &rhs) const { return !(*this == rhs); } // Vector functions // Dot product inline T Dot(Vector4<T> &rhs) const { return (this->x*rhs.x)+ (this->y*rhs.y)+ (this->z*rhs.z)+ (this->a*rhs.a); } // Projection inline Vector4<T> ProjectOnto(Vector4<T> &rhs) const { return rhs*(*this).Dot(rhs)/rhs.Dot(rhs); } // Vector length inline T Length() const { return sqrt(this->x*this->x+ this->y*this->y+ this->z*this->z+ this->a*this->a); } // Normalize vector inline void Normalize() { T length = Length(); this->x /= length; this->y /= length; this->z /= length; this->a /= length; } // Unit vector inline Vector4<T> Unit() const { Vector4<T> temp(*this); temp.Normalize(); return temp; } // Special vectors // Zero vector static inline Vector4<T> Zero() { return Vector4<T>(0, 0, 0, 0); } }; typedef Vector4<char> Vector4c; typedef Vector4<unsigned char> Vector4b; typedef Vector4<short> Vector4s; typedef Vector4<unsigned short> Vector4us; typedef Vector4<int> Vector4i; typedef Vector4<unsigned int> Vector4ui; typedef Vector4<float> Vector4f; typedef Vector4<double> Vector4d; inline Vector4f Sin(Vector4f v) { return Vector4f(Sin(v.x), Sin(v.y), Sin(v.z), Sin(v.a)); } inline Vector4d Sin(Vector4d v) { return Vector4d(Sin(v.x), Sin(v.y), Sin(v.z), Sin(v.a)); } inline Vector4f Cos(Vector4f v) { return Vector4f(Cos(v.x), Cos(v.y), Cos(v.z), Cos(v.a)); } inline Vector4d Cos(Vector4d v) { return Vector4d(Cos(v.x), Cos(v.y), Cos(v.z), Cos(v.a)); } inline Vector4f Tan(Vector4f v) { return Vector4f(Tan(v.x), Tan(v.y), Tan(v.z), Tan(v.a)); } inline Vector4d Tan(Vector4d v) { return Vector4d(Tan(v.x), Tan(v.y), Tan(v.z), Tan(v.a)); } #endif // VECTOR4_H
true
54f8e4d3b5cd8077e585f8c6ae08181581e33e11
C++
anthonywei/FxRobot
/FxRobot/FxContact.h
UTF-8
1,750
2.546875
3
[]
no_license
// -*- C++ -*- //============================================================================= /** * @file FxContact.h * * $Id: FxContact.h 2009-11-05 aotain $ * * @author anthony.wei <weishuo1999@hotmail.com> */ //============================================================================= #ifndef _FXCONTACT_H_ #define _FXCONTACT_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "FxUri.h" /* * This class is for the contact of the user * As the type of the contact, contact info */ /* * The type of the contact */ enum ContactType { Buddy, MobileBuddy, BlockedBuddy }; /* * */ class Contact { public: Contact(); Contact(Uri* pUri); Contact(Uri* pUri, char* szLocalName, ContactType eContactType); Contact(Uri* pUri, char* szLocalName, char* szNickName, ContactType eContactType); ~Contact() { if(m_Uri) { delete m_Uri; m_Uri = NULL; } } char* GetLocalName() { return m_LocalName; } void SetLocalName(char* szLocalName) { strcpy_s(m_LocalName, 256, szLocalName); } char* GetNickName() { return m_NickName; } void SetNickName(char* szNickName) { strcpy_s(m_NickName, 256, szNickName); } char* GetImpresa() { return m_Impresa; } void SetImpresa(char* szImpresa) { strcpy_s(m_Impresa, 256, szImpresa); } INT64 GetMobileNo() { return m_MobileNo; } void SetMobileNo(INT64 iMobileNo) { m_MobileNo = iMobileNo; } ContactType GetContactType() { return m_ContactType; } Uri* GetUri() { return m_Uri; } char* GetDisplayName(); private: void Init(); private: Uri* m_Uri; char m_LocalName[256]; char m_NickName[256]; char m_Impresa[256]; INT64 m_MobileNo; ContactType m_ContactType; }; #endif
true
11afa69b040cb22384720a63556f7975b3e0fc29
C++
X-DataInitiative/tick
/lib/include/tick/array_test/array_test.h
UTF-8
16,978
2.765625
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef LIB_INCLUDE_TICK_ARRAY_TEST_ARRAY_TEST_H_ #define LIB_INCLUDE_TICK_ARRAY_TEST_ARRAY_TEST_H_ // License: BSD 3 clause #include "tick/base/base.h" // // Simple tests on ArrayDouble // /** * @brief Testing test_ArrayDouble_creation : Test that we can create * ArrayDouble with different constructors, Assign value to specified index * Always returns 210 */ extern double test_constructor_ArrayDouble(ulong size); /// @brief Testing arange function extern SArrayDoublePtr test_arange(std::int64_t min, std::int64_t max); /// @brief Testing that out of bound index in an array correctly return an /// error double test_IndexError_ArrayDouble(ArrayDouble &array); /// @brief Testing that out of bound index in an array correctly return an /// error extern double test_IndexError_cols_ArrayDouble2d(ArrayDouble2d &array); //! @brief Test that we can create SparseArrayDouble with different constructor extern double test_constructor_SparseArrayDouble(); //! @brief Test that we can create SparseArrayDouble2d with different //! constructor extern double test_constructor_SparseArrayDouble2d(); //! @brief Test that we can create both sparse and non sparse arrays extern bool test_BaseArray_empty_constructor(bool flag_dense); /** * @brief Test init_to_zero method * The object sent must be modified inplace */ #define TEST_INIT_TO_ZERO(ARRAY_TYPE) \ extern void test_init_to_zero_##ARRAY_TYPE(ARRAY_TYPE &array); TEST_INIT_TO_ZERO(BaseArrayDouble); TEST_INIT_TO_ZERO(ArrayDouble); TEST_INIT_TO_ZERO(SparseArrayDouble); TEST_INIT_TO_ZERO(BaseArrayDouble2d); TEST_INIT_TO_ZERO(ArrayDouble2d); TEST_INIT_TO_ZERO(SparseArrayDouble2d); #define TEST_INIT_TO_ZERO_PTR(ARRAY_PTR_TYPE) \ extern void test_init_to_zero_##ARRAY_PTR_TYPE(ARRAY_PTR_TYPE array_ptr); TEST_INIT_TO_ZERO_PTR(SBaseArrayDoublePtr); TEST_INIT_TO_ZERO_PTR(SArrayDoublePtr); TEST_INIT_TO_ZERO_PTR(VArrayDoublePtr); TEST_INIT_TO_ZERO_PTR(SSparseArrayDoublePtr); TEST_INIT_TO_ZERO_PTR(SBaseArrayDouble2dPtr); TEST_INIT_TO_ZERO_PTR(SArrayDouble2dPtr); TEST_INIT_TO_ZERO_PTR(SSparseArrayDouble2dPtr); /** * @brief Test copy assignment method * The initial object must not be changed as it has been copied */ #define TEST_COPY(ARRAY_TYPE) \ extern void test_copy_##ARRAY_TYPE(ARRAY_TYPE &array); TEST_COPY(BaseArrayDouble); TEST_COPY(ArrayDouble); TEST_COPY(SparseArrayDouble); TEST_COPY(BaseArrayDouble2d); TEST_COPY(ArrayDouble2d); TEST_COPY(SparseArrayDouble2d); /** * @brief Test copy assignment method * The object sent must be modified inplace if it was a shared pointer on the * same array */ #define TEST_COPY_PTR(ARRAY_PTR_TYPE) \ void test_copy_##ARRAY_PTR_TYPE(ARRAY_PTR_TYPE array_ptr); TEST_COPY_PTR(SBaseArrayDoublePtr); TEST_COPY_PTR(SArrayDoublePtr); TEST_COPY_PTR(VArrayDoublePtr); TEST_COPY_PTR(SSparseArrayDoublePtr); TEST_COPY_PTR(SBaseArrayDouble2dPtr); TEST_COPY_PTR(SArrayDouble2dPtr); TEST_COPY_PTR(SSparseArrayDouble2dPtr); /** * @brief Test move assignment method * We test that data owned by a temporary array is correctly kept and not copied * when move constructor is called It must always return True \note : the * argument (constructor_array) is only used to construct the temporary array */ #define TEST_MOVE(ARRAY_TYPE) \ extern bool test_move_##ARRAY_TYPE(ARRAY_TYPE &constructor_array); TEST_MOVE(BaseArrayDouble); TEST_MOVE(ArrayDouble); TEST_MOVE(SparseArrayDouble); TEST_MOVE(BaseArrayDouble2d); TEST_MOVE(ArrayDouble2d); TEST_MOVE(SparseArrayDouble2d); /** * @brief Test value method (only available for 1d arrays) */ #define TEST_VALUE(ARRAY_TYPE) \ extern double test_value_##ARRAY_TYPE(ARRAY_TYPE &array, ulong index); TEST_VALUE(BaseArrayDouble); TEST_VALUE(ArrayDouble); TEST_VALUE(SparseArrayDouble); #define TEST_VALUE_PTR(ARRAY_PTR_TYPE) \ extern double test_value_##ARRAY_PTR_TYPE(ARRAY_PTR_TYPE array_ptr, \ ulong index); TEST_VALUE_PTR(SBaseArrayDoublePtr); TEST_VALUE_PTR(SArrayDoublePtr); TEST_VALUE_PTR(VArrayDoublePtr); TEST_VALUE_PTR(SSparseArrayDoublePtr); /** * @brief Test last method (only available for 1d arrays) */ #define TEST_LAST(ARRAY_TYPE) \ extern double test_last_##ARRAY_TYPE(ARRAY_TYPE &array); TEST_LAST(BaseArrayDouble); TEST_LAST(ArrayDouble); TEST_LAST(SparseArrayDouble); #define TEST_LAST_PTR(ARRAY_PTR_TYPE) \ extern double test_last_##ARRAY_PTR_TYPE(ARRAY_PTR_TYPE array_ptr); TEST_LAST_PTR(SBaseArrayDoublePtr); TEST_LAST_PTR(SArrayDoublePtr); TEST_LAST_PTR(VArrayDoublePtr); TEST_LAST_PTR(SSparseArrayDoublePtr); /** * @brief Test dot method (only available for 1d arrays) */ #define TEST_DOT(ARRAY_TYPE1, ARRAY_TYPE2) \ extern double test_dot_##ARRAY_TYPE1##_##ARRAY_TYPE2(ARRAY_TYPE1 &array1, \ ARRAY_TYPE2 &array2); TEST_DOT(BaseArrayDouble, BaseArrayDouble); TEST_DOT(BaseArrayDouble, ArrayDouble); TEST_DOT(BaseArrayDouble, SparseArrayDouble); TEST_DOT(ArrayDouble, BaseArrayDouble); TEST_DOT(ArrayDouble, ArrayDouble); TEST_DOT(ArrayDouble, SparseArrayDouble); TEST_DOT(SparseArrayDouble, BaseArrayDouble); TEST_DOT(SparseArrayDouble, ArrayDouble); TEST_DOT(SparseArrayDouble, SparseArrayDouble); #define TEST_DOT_PTR_1(ARRAY_PTR_TYPE1, ARRAY_TYPE2) \ extern double test_dot_##ARRAY_PTR_TYPE1##_##ARRAY_TYPE2( \ ARRAY_PTR_TYPE1 array_ptr1, ARRAY_TYPE2 &array2); TEST_DOT_PTR_1(SBaseArrayDoublePtr, BaseArrayDouble); TEST_DOT_PTR_1(SBaseArrayDoublePtr, ArrayDouble); TEST_DOT_PTR_1(SBaseArrayDoublePtr, SparseArrayDouble); TEST_DOT_PTR_1(SArrayDoublePtr, BaseArrayDouble); TEST_DOT_PTR_1(SArrayDoublePtr, ArrayDouble); TEST_DOT_PTR_1(SArrayDoublePtr, SparseArrayDouble); TEST_DOT_PTR_1(VArrayDoublePtr, BaseArrayDouble); TEST_DOT_PTR_1(VArrayDoublePtr, ArrayDouble); TEST_DOT_PTR_1(VArrayDoublePtr, SparseArrayDouble); TEST_DOT_PTR_1(SSparseArrayDoublePtr, BaseArrayDouble); TEST_DOT_PTR_1(SSparseArrayDoublePtr, ArrayDouble); TEST_DOT_PTR_1(SSparseArrayDoublePtr, SparseArrayDouble); #define TEST_DOT_PTR_2(ARRAY_TYPE1, ARRAY_PTR_TYPE2) \ extern double test_dot_##ARRAY_TYPE1##_##ARRAY_PTR_TYPE2( \ ARRAY_TYPE1 &array1, ARRAY_PTR_TYPE2 array_ptr2); TEST_DOT_PTR_2(BaseArrayDouble, SBaseArrayDoublePtr); TEST_DOT_PTR_2(BaseArrayDouble, SArrayDoublePtr); TEST_DOT_PTR_2(BaseArrayDouble, VArrayDoublePtr); TEST_DOT_PTR_2(BaseArrayDouble, SSparseArrayDoublePtr); TEST_DOT_PTR_2(ArrayDouble, SBaseArrayDoublePtr); TEST_DOT_PTR_2(ArrayDouble, SArrayDoublePtr); TEST_DOT_PTR_2(ArrayDouble, VArrayDoublePtr); TEST_DOT_PTR_2(ArrayDouble, SSparseArrayDoublePtr); TEST_DOT_PTR_2(SparseArrayDouble, SBaseArrayDoublePtr); TEST_DOT_PTR_2(SparseArrayDouble, SArrayDoublePtr); TEST_DOT_PTR_2(SparseArrayDouble, VArrayDoublePtr); TEST_DOT_PTR_2(SparseArrayDouble, SSparseArrayDoublePtr); #define TEST_DOT_PTR_PTR(ARRAY_PTR_TYPE1, ARRAY_PTR_TYPE2) \ extern double test_dot_##ARRAY_PTR_TYPE1##_##ARRAY_PTR_TYPE2( \ ARRAY_PTR_TYPE1 array_ptr1, ARRAY_PTR_TYPE2 array_ptr2); TEST_DOT_PTR_PTR(SBaseArrayDoublePtr, SBaseArrayDoublePtr); TEST_DOT_PTR_PTR(SBaseArrayDoublePtr, SArrayDoublePtr); TEST_DOT_PTR_PTR(SBaseArrayDoublePtr, VArrayDoublePtr); TEST_DOT_PTR_PTR(SBaseArrayDoublePtr, SSparseArrayDoublePtr); TEST_DOT_PTR_PTR(SArrayDoublePtr, SBaseArrayDoublePtr); TEST_DOT_PTR_PTR(SArrayDoublePtr, SArrayDoublePtr); TEST_DOT_PTR_PTR(SArrayDoublePtr, VArrayDoublePtr); TEST_DOT_PTR_PTR(SArrayDoublePtr, SSparseArrayDoublePtr); TEST_DOT_PTR_PTR(VArrayDoublePtr, SBaseArrayDoublePtr); TEST_DOT_PTR_PTR(VArrayDoublePtr, SArrayDoublePtr); TEST_DOT_PTR_PTR(VArrayDoublePtr, VArrayDoublePtr); TEST_DOT_PTR_PTR(VArrayDoublePtr, SSparseArrayDoublePtr); TEST_DOT_PTR_PTR(SSparseArrayDoublePtr, SBaseArrayDoublePtr); TEST_DOT_PTR_PTR(SSparseArrayDoublePtr, SArrayDoublePtr); TEST_DOT_PTR_PTR(SSparseArrayDoublePtr, VArrayDoublePtr); TEST_DOT_PTR_PTR(SSparseArrayDoublePtr, SSparseArrayDoublePtr); /** @brief Testing if as_array works * It should return the sum of the original array and set its data to 0 if and * only if the original array was dense */ extern double test_as_array(BaseArrayDouble &a); /** @brief Testing if as_array2d works * It should return the sum of the original array and set its data to 0 if and * only if the original array was dense */ extern double test_as_array2d(BaseArrayDouble2d &a); /** @brief Test new_ptr method * Data should not be modified as it is copied * TODO: when all typemap outs will have been encoded, this function should * return the pointer instead of its sum */ #define TEST_NEW_PTR(ARRAY_TYPE, ARRAY_PTR_RAW_TYPE, ARRAY_PTR_TYPE) \ extern double test_new_ptr_##ARRAY_PTR_TYPE(ARRAY_TYPE &array); TEST_NEW_PTR(ArrayDouble, SarrayDouble, SArrayDoublePtr); TEST_NEW_PTR(ArrayDouble, VArrayDouble, VArrayDoublePtr); TEST_NEW_PTR(SparseArrayDouble, SSparseArrayDouble, SSparseArrayDoublePtr); TEST_NEW_PTR(ArrayDouble2d, SArrayDouble2d, SArrayDouble2dPtr); TEST_NEW_PTR(SparseArrayDouble2d, SSparseArrayDouble2d, SSparseArrayDouble2dPtr); /** * @brief Test view function * \returns an array with the sum of all original arrays * It also sets data of the last two to 0 */ #define TEST_VIEW(ARRAY_TYPE) \ extern SArrayDoublePtr test_view_##ARRAY_TYPE( \ ARRAY_TYPE &array1, ARRAY_TYPE &array2, ARRAY_TYPE &array3); TEST_VIEW(BaseArrayDouble); TEST_VIEW(ArrayDouble); TEST_VIEW(SparseArrayDouble); TEST_VIEW(BaseArrayDouble2d); TEST_VIEW(ArrayDouble2d); TEST_VIEW(SparseArrayDouble2d); extern SArrayDoublePtrList1D test_slice_view1d(ArrayDouble &a, ulong start, ulong end); #define TEST_ROW_VIEW(ARRAY_TYPE, ARRAY_2D_TYPE) \ extern SArrayDoublePtrList1D test_row_view_##ARRAY_2D_TYPE(ARRAY_2D_TYPE &a, \ ulong row); TEST_ROW_VIEW(BaseArrayDouble, BaseArrayDouble2d); TEST_ROW_VIEW(ArrayDouble, ArrayDouble2d); TEST_ROW_VIEW(SparseArrayDouble, SparseArrayDouble2d); #define TEST_AS_ARRAY_PTR(ARRAY_TYPE, ARRAY_PTR_TYPE, AS_PTR_FUNC) \ extern ARRAY_PTR_TYPE test_as_array_ptr_##ARRAY_TYPE(ARRAY_TYPE &array); TEST_AS_ARRAY_PTR(ArrayDouble, SArrayDoublePtr, as_sarray_ptr); TEST_AS_ARRAY_PTR(SparseArrayDouble, SSparseArrayDoublePtr, as_ssparsearray_ptr); TEST_AS_ARRAY_PTR(ArrayDouble2d, SArrayDouble2dPtr, as_sarray2d_ptr); TEST_AS_ARRAY_PTR(SparseArrayDouble2d, SSparseArrayDouble2dPtr, as_ssparsearray2d_ptr); /** * @brief Test sum method */ #define TEST_SUM(ARRAY_TYPE) \ extern double test_sum_##ARRAY_TYPE(ARRAY_TYPE &array); TEST_SUM(BaseArrayDouble); TEST_SUM(ArrayDouble); TEST_SUM(SparseArrayDouble); TEST_SUM(BaseArrayDouble2d); TEST_SUM(ArrayDouble2d); TEST_SUM(SparseArrayDouble2d); #define TEST_SUM_PTR(ARRAY_PTR_TYPE) \ extern double test_sum_##ARRAY_PTR_TYPE(ARRAY_PTR_TYPE array_ptr); TEST_SUM_PTR(SBaseArrayDoublePtr); TEST_SUM_PTR(SArrayDoublePtr); TEST_SUM_PTR(VArrayDoublePtr); TEST_SUM_PTR(SSparseArrayDoublePtr); TEST_SUM_PTR(SBaseArrayDouble2dPtr); TEST_SUM_PTR(SArrayDouble2dPtr); TEST_SUM_PTR(SSparseArrayDouble2dPtr); /** * @brief Test min method */ #define TEST_MIN(ARRAY_TYPE) \ extern double test_min_##ARRAY_TYPE(ARRAY_TYPE &array); TEST_MIN(BaseArrayDouble); TEST_MIN(ArrayDouble); TEST_MIN(SparseArrayDouble); TEST_MIN(BaseArrayDouble2d); TEST_MIN(ArrayDouble2d); TEST_MIN(SparseArrayDouble2d); #define TEST_MIN_PTR(ARRAY_PTR_TYPE) \ extern double test_min_##ARRAY_PTR_TYPE(ARRAY_PTR_TYPE array_ptr); TEST_MIN_PTR(SBaseArrayDoublePtr); TEST_MIN_PTR(SArrayDoublePtr); TEST_MIN_PTR(VArrayDoublePtr); TEST_MIN_PTR(SSparseArrayDoublePtr); TEST_MIN_PTR(SBaseArrayDouble2dPtr); TEST_MIN_PTR(SArrayDouble2dPtr); TEST_MIN_PTR(SSparseArrayDouble2dPtr); /** * @brief Test max method */ #define TEST_MAX(ARRAY_TYPE) \ extern double test_max_##ARRAY_TYPE(ARRAY_TYPE &array); TEST_MAX(BaseArrayDouble); TEST_MAX(ArrayDouble); TEST_MAX(SparseArrayDouble); TEST_MAX(BaseArrayDouble2d); TEST_MAX(ArrayDouble2d); TEST_MAX(SparseArrayDouble2d); #define TEST_MAX_PTR(ARRAY_PTR_TYPE) \ extern double test_max_##ARRAY_PTR_TYPE(ARRAY_PTR_TYPE array_ptr); TEST_MAX_PTR(SBaseArrayDoublePtr); TEST_MAX_PTR(SArrayDoublePtr); TEST_MAX_PTR(VArrayDoublePtr); TEST_MAX_PTR(SSparseArrayDoublePtr); TEST_MAX_PTR(SBaseArrayDouble2dPtr); TEST_MAX_PTR(SArrayDouble2dPtr); TEST_MAX_PTR(SSparseArrayDouble2dPtr); /** * @brief Test norm_sq method */ #define TEST_NORM_SQ(ARRAY_TYPE) \ extern double test_norm_sq_##ARRAY_TYPE(ARRAY_TYPE &array); TEST_NORM_SQ(BaseArrayDouble); TEST_NORM_SQ(ArrayDouble); TEST_NORM_SQ(SparseArrayDouble); TEST_NORM_SQ(BaseArrayDouble2d); TEST_NORM_SQ(ArrayDouble2d); TEST_NORM_SQ(SparseArrayDouble2d); #define TEST_NORM_SQ_PTR(ARRAY_PTR_TYPE) \ extern double test_norm_sq_##ARRAY_PTR_TYPE(ARRAY_PTR_TYPE array_ptr); TEST_NORM_SQ_PTR(SBaseArrayDoublePtr); TEST_NORM_SQ_PTR(SArrayDoublePtr); TEST_NORM_SQ_PTR(VArrayDoublePtr); TEST_NORM_SQ_PTR(SSparseArrayDoublePtr); TEST_NORM_SQ_PTR(SBaseArrayDouble2dPtr); TEST_NORM_SQ_PTR(SArrayDouble2dPtr); TEST_NORM_SQ_PTR(SSparseArrayDouble2dPtr); /** * @brief Test in place multiply method (*=) * This will modify given array */ #define TEST_MULTIPLY(ARRAY_TYPE) \ extern void test_multiply_##ARRAY_TYPE(ARRAY_TYPE &array, double scalar); TEST_MULTIPLY(BaseArrayDouble); TEST_MULTIPLY(ArrayDouble); TEST_MULTIPLY(SparseArrayDouble); TEST_MULTIPLY(BaseArrayDouble2d); TEST_MULTIPLY(ArrayDouble2d); TEST_MULTIPLY(SparseArrayDouble2d); #define TEST_MULTIPLY_PTR(ARRAY_PTR_TYPE) \ extern void test_multiply_##ARRAY_PTR_TYPE(ARRAY_PTR_TYPE array_ptr, \ double scalar); TEST_MULTIPLY_PTR(SBaseArrayDoublePtr); TEST_MULTIPLY_PTR(SArrayDoublePtr); TEST_MULTIPLY_PTR(VArrayDoublePtr); TEST_MULTIPLY_PTR(SSparseArrayDoublePtr); TEST_MULTIPLY_PTR(SBaseArrayDouble2dPtr); TEST_MULTIPLY_PTR(SArrayDouble2dPtr); TEST_MULTIPLY_PTR(SSparseArrayDouble2dPtr); /** * @brief Test in place divide method (/=) * This will modify given array */ #define TEST_DIVIDE(ARRAY_TYPE) \ extern void test_divide_##ARRAY_TYPE(ARRAY_TYPE &array, double scalar); TEST_DIVIDE(BaseArrayDouble); TEST_DIVIDE(ArrayDouble); TEST_DIVIDE(SparseArrayDouble); TEST_DIVIDE(BaseArrayDouble2d); TEST_DIVIDE(ArrayDouble2d); TEST_DIVIDE(SparseArrayDouble2d); #define TEST_DIVIDE_PTR(ARRAY_PTR_TYPE) \ extern void test_divide_##ARRAY_PTR_TYPE(ARRAY_PTR_TYPE array_ptr, \ double scalar); TEST_DIVIDE_PTR(SBaseArrayDoublePtr); TEST_DIVIDE_PTR(SArrayDoublePtr); TEST_DIVIDE_PTR(VArrayDoublePtr); TEST_DIVIDE_PTR(SSparseArrayDoublePtr); TEST_DIVIDE_PTR(SBaseArrayDouble2dPtr); TEST_DIVIDE_PTR(SArrayDouble2dPtr); TEST_DIVIDE_PTR(SSparseArrayDouble2dPtr); /// @brief Testing VArrayDouble_arange_by_append : Init an empty VArray and /// append integers in order to create a range extern VArrayDoublePtr test_VArrayDouble_append1(int size); /// @brief Testing VArrayDouble_append : Creates two ranges and join each other extern VArrayDoublePtr test_VArrayDouble_append(VArrayDoublePtr va, SArrayDoublePtr sa); /// @brief Test sort method of array extern void test_sort_inplace_ArrayDouble(ArrayDouble &array, bool increasing); /// @brief Test sort function on array extern SArrayDoublePtr test_sort_ArrayDouble(ArrayDouble &array, bool increasing); /// @brief Test sort method of array keeping track of index extern void test_sort_index_inplace_ArrayDouble(ArrayDouble &array, ArrayULong &index, bool increasing); /// @brief Test sort function on array keeping track of index extern SArrayDoublePtr test_sort_index_ArrayDouble(ArrayDouble &array, ArrayULong &index, bool increasing); /// @brief Test sort method on absolute value keeping track of index extern void test_sort_abs_index_inplace_ArrayDouble(ArrayDouble &array, ArrayULong &index, bool increasing); extern void test_mult_incr_ArrayDouble(ArrayDouble &array, BaseArrayDouble &x, double a); extern void test_mult_fill_ArrayDouble(ArrayDouble &array, BaseArrayDouble &x, double a); extern void test_mult_add_mult_incr_ArrayDouble(ArrayDouble &array, BaseArrayDouble &x, double a, BaseArrayDouble &y, double b); #endif // LIB_INCLUDE_TICK_ARRAY_TEST_ARRAY_TEST_H_
true
d6306322db405700f29424765a37a36ec8e7f02b
C++
wu1274704958/gld
/include/tools/executor.h
UTF-8
2,111
3.015625
3
[]
no_license
#pragma once #include <functional> #include <vector> #include <mutex> #include <chrono> #include <cassert> namespace gld { enum class TaskType : uint8_t { NextFrame = 0x0, DelayFrame, DelayMS }; struct Task { Task(std::function<void()> func):func(func){} Task(std::function<void()> func, TaskType ty, uint64_t val) :func(func),ty(ty),val(val) {} uint64_t val = 0; std::function<void()> func; TaskType ty = TaskType::NextFrame; }; struct Executor { void delay(std::function<void()> f) { push(Task(f)); } void delay(std::function<void()> f, int ms) { auto end = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch() ).count() + ms; push(Task(f,TaskType::DelayMS,end)); } void delay_frame(std::function<void()> f, int frame) { assert(frame > 0); push(Task(f, TaskType::DelayFrame, frame)); } void push(Task t) { if (mtx.try_lock()) { que.push_back(std::move(t)); mtx.unlock(); } else { std::lock_guard<std::mutex> guard(temp_mtx); temp_que.push_back(std::move(t)); } } void do_loop() { std::lock_guard<std::mutex> guard(mtx); for (auto it = que.begin(); it != que.end();) { if (it->ty == TaskType::NextFrame) { (it->func)(); it = que.erase(it); continue; } else if (it->ty == TaskType::DelayFrame) { it->val -= 1; if (it->val == 0) { (it->func)(); it = que.erase(it); continue; } } else if (it->ty == TaskType::DelayMS) { auto now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); if (now >= it->val) { (it->func)(); it = que.erase(it); continue; } } ++it; } std::lock_guard<std::mutex> t_guard(temp_mtx); if (!temp_que.empty()) { for (auto& t : temp_que) que.push_back(std::move(t)); temp_que.clear(); } } protected: std::vector<Task> que; std::vector<Task> temp_que; std::mutex mtx,temp_mtx; }; }
true
4d6f58a3d7e7165fdcd3a13af83c49e42edc0766
C++
seleti/sid_alien_game
/game/drawable.h
UTF-8
2,112
3.328125
3
[]
no_license
#ifndef DRAWABLE__H #define DRAWABLE__H #include <SDL.h> #include <iostream> #include "vector2f.h" #include "frame.h" using std::string; // Drawable is an Abstract Base Class (ABC) that // specifies the methods that derived classes may // and must have. class Drawable { public: Drawable(const Vector2f& pos, const Vector2f& vel, const Vector2f& mxv) : position(pos), velocity(vel), maxVelocity(mxv) ,initialVelocity(vel) {} Drawable(const Drawable& s) : position(s.position), velocity(s.velocity), maxVelocity(s.maxVelocity) ,initialVelocity(s.velocity){ } virtual ~Drawable() {} virtual void draw() const = 0; virtual void update(Uint32 ticks) = 0; virtual const string& getName() const= 0; float X() const { return position[0]; } void X(float x) { position[0] = x; } float Y() const { return position[1]; } void Y(float y) { position[1] = y; } float velocityX() const { return velocity[0]; } void velocityX(float vx) { velocity[0] = vx; } float velocityY() const { return velocity[1]; } void velocityY(float vy) { velocity[1] = vy; } const Vector2f& getPosition() const { return position; } const Vector2f& getVelocity() const { return velocity; } const Vector2f& getMaxVelocity() const { return maxVelocity; } void setPosition(const Vector2f& pos) { position = pos; } void setVelocity(const Vector2f& vel) { velocity = vel; } void setMaxVelocity(const Vector2f& vel) { maxVelocity = vel; } float initVelocityX() const { return initialVelocity[0]; } float initVelocityY() const { return initialVelocity[1]; } virtual const Frame* getFrame() const=0; unsigned getPixel(Uint32 i, Uint32 j) const { Uint32 x = static_cast<Uint32>(X()); Uint32 y = static_cast<Uint32>(Y()); x = i - x; y = j - y; //x -= Viewport::getInstance()->X(); //y -= Viewport::getInstance()->Y(); Uint32 *pixels = static_cast<Uint32 *>(getFrame()->getSurface()->pixels); return pixels[ ( y * getFrame()->getWidth() ) + x ]; } private: Vector2f position; Vector2f velocity; Vector2f maxVelocity; Vector2f initialVelocity; }; #endif
true
4922c47ef8578217298acfe691f2570812d4a6d6
C++
hnlylmlzh/cs
/template/qeue_template/qeue_template/queue_template.h
UTF-8
458
3.40625
3
[]
no_license
template <class Type> class QueueItem { public: QueueItem() : item (0), next (0) { } private: Type item; QueueItem* next; }; template <class Type> class Queue { public: Queue() : front (0), back (0) { } ~Queue() { while (!is_empty()) { remove(); } } Type& remove(); void add(const Type&); bool is_empty() { return 0 == front; } private: QueueItem<Type>* front; QueueItem<Type>* back; };
true
88c5f90871e8951d67acf17d60d73ce7ffe6b56f
C++
rishabv90/High-performance-compute-project
/src/map1Proc5.cpp
UTF-8
1,460
2.59375
3
[]
no_license
#ifndef MAP1PROC5 #define MAP1PROC5 #define CHANNELS 3 // we have 3 channels corresponding to RGB __global__ void map1Proc5(float * redData, float * greenData, float * blueData, float * eroded_shadow, float * eroded_light, float * shadowRedArray, float * shadowGreenArray, float * shadowBlueArray, float * lightRedArray, float * lightGreenArray, float * lightBlueArray, int width, int height) {//this kernel does the first map in proc 5 multiplication, this kernel reduces register trafic int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; if(x < width && y < height){ int offset = y * width + x; shadowRedArray[offset] = eroded_shadow[offset] * redData[offset]; shadowGreenArray[offset] = eroded_shadow[offset] * greenData[offset]; shadowBlueArray[offset] = eroded_shadow[offset] * blueData[offset]; lightRedArray[offset] = eroded_light[offset] * redData[offset]; lightGreenArray[offset] = eroded_light[offset] * greenData[offset]; lightBlueArray[offset] = eroded_light[offset] * blueData[offset]; } } __global__ void map1Proc5V1(float * inputImage, float * eroded_shadow, float * erroded_light, float * shadowRedArray, float * shadowGreenArray, float * shadowBlueArray, float * lightRedArray, float * lightGreenArray, float * lightBlueArray, int width, int height) {//this kernel does the first map in proc 5 multiplication } #endif
true
2e788dbda5e609a5371f6b14a143ee4a624ec654
C++
doc-cloud/cpp
/container/begin-end-search.cpp
UTF-8
185
2.625
3
[]
no_license
auto begin_end_search(vector<int>const_iterator begin, vector<int>const_iterator end, int value) { for (; begin != end; ++begin) if (*begin == value) return begin; return end; }
true
9bc98d8cb27df3cc9e2a89f617f55afd67db8d84
C++
JustinWeq/Vulkan-Instanced-Quad
/Render Instanced Quad/Device.h
UTF-8
559
2.75
3
[]
no_license
#pragma once #include <vulkan.h> // Used to manage a vk device class Device { public: // defualt constructor-- construct a new instance of Device Device(); //initializes the vk device //physicalDevice- the physical device to use for this Device bool Init(VkPhysicalDevice physicalDevice); //cleans up dynamically alocated memory void destroy(); //operator for implicitly using Device as a vk device operator VkDevice(); //returns the queue family index static int GetQueueFamilyIndex(); private: //the vk device data VkDevice m_device; };
true
317ae333ed3f0e7d8205cf01e53ed58f9a3a62af
C++
tonycao/CodeSnippets
/C-CPP/Leetcode/pascals triangle ii.cpp
UTF-8
408
2.78125
3
[]
no_license
class Solution { public: vector<int> getRow(int rowIndex) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<int> array; for(int i=0; i <= rowIndex; i++){ for(int j = i-1; j >0; j--){ array[j] = array[j-1] + array[j]; } array.push_back(1); } return array; } };
true
07f6be17e261303e7a3d5b3627554d58516a51f1
C++
smilofoundation/ClaveChain
/Clave/Test/testMbedMktime.cpp
UTF-8
3,487
2.59375
3
[ "Apache-2.0" ]
permissive
#include "stdafx.h" #include "CppUnitTest.h" #include <time.h> using namespace Microsoft::VisualStudio::CppUnitTestFramework; typedef uint64_t sgx_time_t; typedef struct mbedtls_x509_time { int year, mon, day; int hour, min, sec; } mbedtls_x509_time; sgx_time_t mbedMktime(const mbedtls_x509_time *t); #define TIME_ZONE 8 #define SEC_OFFSET (TIME_ZONE * 3600) namespace TestMbedMktime { TEST_CLASS(TestMbedMktime) { public: TEST_METHOD(BaseTime) { testTime(1970, 1, 1, 0, 0, 0); } TEST_METHOD(MinMonth) { testTime(2017, 1, 15, 15, 15, 15); } TEST_METHOD(MiddleMonth) { testTime(2017, 8, 15, 15, 15, 15); } TEST_METHOD(MaxMonth) { testTime(2017, 12, 15, 15, 15, 15); } TEST_METHOD(MinDay) { testTime(2017, 8, 1, 15, 15, 15); } TEST_METHOD(MiddleDay) { testTime(2017, 8, 20, 15, 15, 15); } TEST_METHOD(MaxDay) { testTime(2017, 8, 31, 15, 15, 15); } TEST_METHOD(MinHour) { testTime(2017, 8, 20, 0, 15, 15); } TEST_METHOD(MiddleHour) { testTime(2017, 8, 20, 12, 15, 15); } TEST_METHOD(MaxHour) { testTime(2017, 8, 20, 23, 15, 15); } TEST_METHOD(MinMinute) { testTime(2017, 8, 20, 12, 0, 15); } TEST_METHOD(MiddleMinute) { testTime(2017, 8, 20, 12, 30, 15); } TEST_METHOD(MaxMinute) { testTime(2017, 8, 20, 12, 59, 15); } TEST_METHOD(MinSecond) { testTime(2017, 8, 20, 12, 0, 0); } TEST_METHOD(MiddleSecond) { testTime(2017, 8, 20, 12, 0, 30); } TEST_METHOD(MaxSecond) { testTime(2017, 8, 20, 12, 0, 59); } TEST_METHOD(LeapYearBeforeFeb) { testTime(2016, 1, 20, 12, 12, 12); } TEST_METHOD(LeapYearFeb) { testTime(2016, 2, 29, 12, 12, 12); } TEST_METHOD(LeapYearAfterFeb) { testTime(2016, 3, 2, 12, 12, 12); } TEST_METHOD(NonLeapYearBeforeFeb) { testTime(2015, 1, 10, 12, 12, 12); } TEST_METHOD(NonLeapYearFeb) { testTime(2015, 2, 28, 12, 12, 12); } TEST_METHOD(NonLeapYearAfterFeb) { testTime(2015, 3, 4, 12, 12, 12); } private: void testTime(const int& year, const int& month, const int& day, const int& hour, const int& minute, const int& second) { mbedtls_x509_time m = mbedTime(year, month, day, hour, minute, second); time_t t = mbedTimeToTimeT(m); Assert::AreNotEqual((sgx_time_t)-1, (sgx_time_t)t); sgx_time_t sgxTime = mbedMktime(&m); Assert::AreEqual((sgx_time_t)t, sgxTime); } mbedtls_x509_time mbedTime(const int& year, const int& month, const int& day, const int& hour, const int& minute, const int& second) { mbedtls_x509_time result; result.year = year; result.mon = month; result.day = day; result.hour = hour; result.min = minute; result.sec = second; return result; } time_t mbedTimeToTimeT(mbedtls_x509_time& m) { tm t; t.tm_year = m.year - 1900; t.tm_mon = m.mon - 1; t.tm_mday = m.day; t.tm_hour = m.hour; t.tm_min = m.min; t.tm_sec = m.sec; t.tm_isdst = 0; time_t result; result = mktime(&t); if (result < 0) { t.tm_hour += TIME_ZONE; result = mktime(&t); } else { result += SEC_OFFSET; } return result; } }; }
true
ca66021cce826ce9fffd3758f3a4bec28888f126
C++
akshayaggarwal/LeetCode
/Q_734.cpp
UTF-8
1,059
2.828125
3
[]
no_license
class Solution { public: bool areSentencesSimilar(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) { if(words1.size()!=words2.size()) return false; map<string,vector<string>> mymap; int i,j; vector<string> vec; for(i=0;i<pairs.size();i++) mymap[pairs[i].first].push_back(pairs[i].second); for(i=0;i<words1.size();i++){ if(words1[i]==words2[i]) continue; vec=mymap[words1[i]]; for(j=0;j<vec.size();j++){ if(words2[i]==vec[j]) break; } if(j<vec.size()) continue; vec=mymap[words2[i]]; for(j=0;j<vec.size();j++){ if(words1[i]==vec[j]) break; } if(j<vec.size()) continue; return false; } return true; } };
true
a2c7029dcfbea566d48af9bfbd95523d78755ee9
C++
11aman/c-
/inserting into array.cpp
UTF-8
500
3.234375
3
[]
no_license
#include <iostream> using namespace std; int main() { int arr[50],size,pos,num,i; cout<<"size of array:"<<endl; cin>>size; cout<<endl; cout<<"enter elements:"<<endl; for(i=0;i<size;i++) { cin>>arr[i]; } cout<<endl; cout<<"insert number:"<<endl; cin>>num; cout<<endl; cout<<"enter pos:"<<endl; cin>>pos; cout<<endl; for(i=size-1;i>=pos-1;i--) { arr[i+1] = arr[i]; } arr[pos-1] = num; size++; for(i=0;i<size;i++) { cout<<arr[i]<<" "; } return 0; }
true
99f8ed88358051884c24c8624e65710dd19aa07b
C++
koellsch/youbot_mechatroniklabor
/oberstufenlabor_mechatronik_robot/src/oberstufenlabor_mechatronik_robot/exercise04_collector_node.cpp
UTF-8
1,370
2.8125
3
[]
no_license
#include <ros/ros.h> #include "oberstufenlabor_mechatronik_robot/CollectBallsAction.h" #include <actionlib/client/simple_action_client.h> //############## MAIN ################################################################################################## int main(int argc, char* argv[]) { std::string color; int number; if(argc != 3) { std::cout << "Usage: exercise04_collector_node color number" << std::endl; return 0; } else { color = argv[1]; number = atoi(argv[2]); if(number == 1) std::cout << "Picking " << number << " " << color << " ball..." << std::endl; else std::cout << "Picking " << number << " " << color << " balls..." << std::endl; } // === ROS INITIALISATION === ros::init(argc, argv, "exercise04_collector_node"); ros::NodeHandle node; actionlib::SimpleActionClient<oberstufenlabor_mechatronik_robot::CollectBallsAction> ac("oberstufenlabor_mechatronik_robot/collect_balls", true); ROS_INFO("Waiting for action server to start."); ac.waitForServer(); oberstufenlabor_mechatronik_robot::CollectBallsGoal goal; goal.color = color; goal.number = number; ac.sendGoal(goal); //wait for the action to return ac.waitForResult(); std::cout << "Done." << std::endl; ros::shutdown(); }
true
9a3f1ce80bc78f1d96bf0aafc4c558357f1c3ee9
C++
theyimster/Class-Work
/AddressBook/addressbook.cpp
UTF-8
13,147
3.34375
3
[]
no_license
// Description: // Program allows user to use a file to keep an address book. This address book can be // manipulated by the user in different ways. These include: displaying, editing, deleting, and searching the contacts. // Program utilizes an array of structures which handles the manipulations. Also, the program heavily employs the use // of switches to format the "Menu" style interface. The program also keeps the address book up to date by saving the // contacts to an output file. // // Known Problems: // The main issues with this program involve exactness in the input from the user. I have attempted to remedy this by // explicity stating formatting in the prompts to the user, but they're still able to input bad data and would need to // use the editing function to fix it. // #include "addBook.h" // Handles File Input, Main Menu Switch, and File Saving int main(int argc, char **argv) { bool importSuccess; int conCount = NUM_CONTACTS; Contact contacts[NUM_CONTACTS+100]; // Allows for up to 100 New Contacts to be added through the program +- deleted contacts. importSuccess = getContactInfo(contacts); if (importSuccess == false) { cout << "Error importing contact information. Exiting" << endl; exit(0); } mainMenu(contacts, conCount); updateContacts(contacts,conCount); return 0; } // Handles the Main Switch which acts as a menu for the program. void mainMenu(Contact contacts[], int &conCount) { int ans, searchType, ID; string keyword; bool keepGoing = true, isEdit; do { cout << "*** Address Book Main Menu ***" << endl; cout << "(1) Display Current Contacts" << endl; cout << "(2) Add New Contact" << endl; cout << "(3) Delete Contact" << endl; cout << "(4) Edit Contact" << endl; cout << "(5) Search Current Contacts" << endl; cout << "(6) Exit and Save Contacts" << endl; cin >> ans; switch(ans) { case 1 : isEdit = false; if (conCount == 0) cout << "No contacts currently stored in Address Book." << endl; else printContacts(contacts, conCount, isEdit); break; case 2 : cin.ignore(); addContact(contacts, conCount); break; case 3 : if (conCount == 0) cout << "No contacts currently stored in Address Book." << endl; else deleteContact(contacts,ID,conCount); break; case 4 : isEdit = true; if (conCount == 0) cout << "No contacts currently stored in Address Book." << endl; else printContacts(contacts, conCount, isEdit); break; case 5 : cin.ignore(); cout << "(1) First Name" << endl; cout << "(2) Last Name" << endl; cout << "(3) Address" << endl; cout << "(4) Phone Number" << endl; cout << "Enter Search Type: "; cin >> searchType; while (searchType <=0 || searchType > 4) { cout << "Invalid Input" << endl; cin >> searchType; } cin.ignore(); cout << "Enter Keyword: "; getline(cin,keyword); searchContacts(contacts,keyword,searchType,conCount); break; case 6 : keepGoing = false; break; default : cout << "Invalid Input." << endl; break; } } while(keepGoing == true); } // Fills the Array of Structs with information given from file. // Also sets the ID of each struct to its corresponding array index. // If fails to open, returns false and closes the program. bool getContactInfo(Contact contacts[]) { ifstream inFile("contactinfo.dat"); if (!inFile.is_open()) return (false); for (int i=0;i<NUM_CONTACTS;i++) { contacts[i].ID = i; getline(inFile, contacts[i].fName); getline(inFile, contacts[i].lName); getline(inFile, contacts[i].middle); getline(inFile, contacts[i].address1); getline(inFile, contacts[i].address2); getline(inFile, contacts[i].city); getline(inFile, contacts[i].stateName); inFile >> contacts[i].zipcode; inFile.ignore(); getline(inFile, contacts[i].pNumber); getline(inFile, contacts[i].email); } inFile.close(); return(true); } // Passed the array index of a selected contact and displays its detailed contact information. void showContactInfo(Contact contacts[], int ID) { cout << endl << "Info for " << contacts[ID].fName << " " << contacts[ID].middle << " " << contacts[ID].lName << endl; cout << "Address 1 : " << contacts[ID].address1 << endl; cout << "Address 2 : " << contacts[ID].address2 << endl; cout << "City : " << contacts[ID].city << endl; cout << "State : " << contacts[ID].stateName << endl; cout << "ZipCode : " << contacts[ID].zipcode << endl; cout << "Phone number : " << contacts[ID].pNumber << endl; cout << "Email : " << contacts[ID].email << endl; cout << endl; } // Prints all current Contacts in a Last, First format void printContacts(Contact contacts[], int &conCount, bool isEdit) { for (int i=0;i<conCount;i++) { cout << "(" << i+1 << ") " << contacts[i].lName << ", " << contacts[i].fName << " " << contacts[i].middle << endl; } contactDetails(contacts, conCount, isEdit); } // Calls editContactInfo or showContactInfo based on isEdit value. void contactDetails(Contact contacts[], int &conCount, bool isEdit) { int x; if (isEdit == true) { cout << "Enter ID Number for Editing: "; cin >> x; while (x > conCount) { cout << "Please Enter Valid ID Number." << endl; cin >> x; } editContactInfo(contacts,x-1); } else { cout << "Enter ID Number for Detailed Information: "; cin >> x; while (x > conCount) { cout << "Please Enter Valid ID Number." << endl; cin >> x; } showContactInfo(contacts,x-1); } } // Fills the next empty index with information gathererd from the user. void addContact(Contact contacts[], int &conCount) { contacts[conCount].ID = conCount; cout << "Enter First Name: "; getline(cin, contacts[conCount].fName); cout << "Enter Last Name: "; getline(cin, contacts[conCount].lName); cout << "Enter Middle Initial: "; getline(cin, contacts[conCount].middle); cout << "Enter Address: "; getline(cin, contacts[conCount].address1); cout << "Enter Secondary Address (If none enter '----'): "; getline(cin, contacts[conCount].address2); cout << "Enter City: "; getline(cin, contacts[conCount].city); cout << "Enter State (Full Name): "; getline(cin, contacts[conCount].stateName); cout << "Enter Zip Code: "; cin >> contacts[conCount].zipcode; cin.ignore(); cout << "Enter Phone Number (Please enter using the format (123)456-7890): "; getline(cin, contacts[conCount].pNumber); cout << "Enter Email Address: "; getline(cin, contacts[conCount].email); conCount++; } // Called at the end of main. Loops through each index and saves to a file. void updateContacts(Contact contacts[], int &conCount) { ofstream outFile("UpdatedContacts.dat"); for (int i=0;i<conCount;i++) { outFile << contacts[i].fName << endl; outFile << contacts[i].lName << endl; outFile << contacts[i].middle << endl; outFile << contacts[i].address1 << endl; outFile << contacts[i].address2 << endl; outFile << contacts[i].city << endl; outFile << contacts[i].stateName << endl; outFile << contacts[i].zipcode << endl; outFile << contacts[i].pNumber << endl; outFile << contacts[i].email << endl; } outFile.close(); } // Displays Selected Contact's Information. Allows user to select fields and edit them until finished. void editContactInfo(Contact contacts[], int ID) { cout << "(1)First Name : " << contacts[ID].fName << endl; cout << "(2)Last Name : " << contacts[ID].lName << endl; cout << "(3)Middle Initial : " << contacts[ID].middle << endl; cout << "(4)Address 1 : " << contacts[ID].address1 << endl; cout << "(5)Address 2 : " << contacts[ID].address2 << endl; cout << "(6)City : " << contacts[ID].city << endl; cout << "(7)State : " << contacts[ID].stateName << endl; cout << "(8)ZipCode : " << contacts[ID].zipcode << endl; cout << "(9)Phone number : " << contacts[ID].pNumber << endl; cout << "(10)Email : " << contacts[ID].email << endl; int ans; bool keepEditing = true; do { cout << "Enter Field Number to Edit or Enter a 0 to Return to Main Menu: "; cin >> ans; switch(ans) { case 0 : keepEditing = false; break; case 1 : cout << "Edit First Name: "; cin >> contacts[ID].fName; break; case 2 : cout << "Edit Last Name: "; cin >> contacts[ID].lName; break; case 3 : cout << "Edit Middle Initial: "; cin >> contacts[ID].middle; break; case 4 : cout << "Edit Address 1: "; cin >> contacts[ID].address1; break; case 5 : cout << "Edit Secondary Address: "; cin >> contacts[ID].address2; break; case 6 : cout << "Edit City: "; cin >> contacts[ID].city; break; case 7 : cout << "Edit State: "; cin >> contacts[ID].stateName; break; case 8 : cout << "Edit Zip Code: "; cin >> contacts[ID].zipcode; break; case 9 : cout << "Edit Phone Number: "; cin >> contacts[ID].pNumber; break; case 10 : cout << "Edit Email: "; cin >> contacts[ID].email; break; default : cout << "Invalid Input."; break; } } while(keepEditing == true); } // Passed a keyword and a search type(Phone, Address, Last or First Name). // Prints out any contacts that match and allows their detailed information to be displayed. void searchContacts(Contact contacts[], string keyword, int searchType, int conCount) { int index = 0; cout << "Search result found: " << endl; switch (searchType) { case 1 : for (int i=0; i<conCount;i++) { if (keyword == contacts[i].fName) { cout << "(" << contacts[i].ID+1 << ") " << contacts[i].lName << ", " << contacts[i].fName << " " << contacts[i].middle << endl; index--; } else index++; } if (index == conCount) cout << "No contacts found matching keyword." << endl; else { cout << "Enter ID Number for Detailed Information: "; cin >> index; while (index > conCount || index <= 0) { cin.ignore(); cout << "Invalid ID Number. Retry. "; cin >> index; } showContactInfo(contacts,index-1); } case 2 : for (int i=0; i<conCount;i++) { if (keyword == contacts[i].lName) { cout << "(" << contacts[i].ID+1 << ") " << contacts[i].lName << ", " << contacts[i].fName << " " << contacts[i].middle << endl; index--; } else index++; } if (index == conCount) cout << "No contacts found matching keyword." << endl; else { cout << "Enter ID Number for Detailed Information: "; cin >> index; while (index > conCount || index <= 0) { cin.ignore(); cout << "Invalid ID Number. Retry. "; cin >> index; } showContactInfo(contacts,index-1); } case 3 : for (int i=0; i<conCount;i++) { if (keyword == contacts[i].address1) { cout << "(" << contacts[i].ID+1 << ") " << contacts[i].lName << ", " << contacts[i].fName << " " << contacts[i].middle << endl; index--; } else index++; } if (index == conCount) cout << "No contacts found matching keyword." << endl; else { cout << "Enter ID Number for Detailed Information: "; cin >> index; while (index > conCount || index <= 0) { cin.ignore(); cout << "Invalid ID Number. Retry. "; cin >> index; } showContactInfo(contacts,index-1); } case 4 : for (int i=0; i<conCount;i++) { if (keyword == contacts[i].pNumber) { cout << "(" << contacts[i].ID+1 << ") " << contacts[i].lName << ", " << contacts[i].fName << " " << contacts[i].middle << endl; index--; } else index++; } if (index == conCount) cout << "No contacts found matching keyword." << endl; else { cout << "Enter ID Number for Detailed Information: "; cin >> index; while (index > conCount || index <= 0) { cin.ignore(); cout << "Invalid ID Number. Retry. "; cin >> index; } showContactInfo(contacts,index-1); } } } // Deletes a contact based on user input. Calls swap to move down above indexes to replace deleted index. void deleteContact(Contact contacts[], int ID, int &conCount) { for (int i=0;i<conCount;i++) { cout << "(" << i+1 << ") " << contacts[i].lName << ", " << contacts[i].fName << " " << contacts[i].middle << endl; } int x; int y; cout << "Enter ID Number for Deletion: "; cin >> x; while (x > conCount) { cout << "Please Enter Valid ID Number." << endl; cin >> x; } ID = x-1; cout << "Are you sure you want to delete " << contacts[ID].lName << ", " << contacts[ID].fName << " " << contacts[ID].middle << " (1 for Yes, 2 for No)" << endl; cin >> y; while (y <= 0 || y > 2) { cout << "Invalid input. Please answer with 1 for Yes or 2 for No... "; cin >> y; } if (y == 1) { swap(contacts,ID,conCount); } } // Called by deleteContact void swap(Contact contacts[], int ID, int &conCount) { Contact temp[NUM_CONTACTS+10]; for (int i=0;i<conCount;i++) temp[i] = contacts[i]; for (int i = ID; i < conCount; i++) contacts[i] = temp[i+1]; conCount--; }
true
4af79d8c6810f8d97a2f7b4f1252f0be5d24a16a
C++
pawjasinski/multithreadTestStructure
/include/baseClass.h
UTF-8
279
2.53125
3
[]
no_license
#ifndef BASECLASS_H #define BASECLASS_H #include "packet.h" class Server; class BaseClass { protected: Priority prior; Server* serv; public: virtual ~BaseClass() {} virtual void update() = 0; void attach(Server* s) {serv = s;} void detach() {serv = nullptr;} }; #endif
true
1a94cf5c2cd1de1c2ec3c77f1043f5ea451c766a
C++
rusek/abb-cpp
/tests/success.cpp
UTF-8
1,201
2.890625
3
[ "MIT" ]
permissive
#include "helpers/base.h" #include <string> abb::void_block testVoid() { EXPECT_HITS(1); return abb::success().pipe([]() { HIT(); }); } abb::void_block testInt() { EXPECT_HITS(1); return abb::success(5).pipe([](int value) { REQUIRE_EQUAL(value, 5); HIT(); }); } abb::void_block testMovable() { EXPECT_HITS(1); return abb::success(std::unique_ptr<int>(new int(5))).pipe([](std::unique_ptr<int> arg) { REQUIRE_EQUAL(*arg, 5); HIT(); }); } static int refTestInt; abb::void_block testRef() { EXPECT_HITS(1); return abb::success(std::ref(refTestInt)).pipe([](int & arg) { REQUIRE_EQUAL(&arg, &refTestInt); HIT(); }); } abb::void_block testMultiArg() { EXPECT_HITS(1); return abb::success(false, 10, std::string("abc")).pipe([](bool arg1, int arg2, std::string const & arg3) { REQUIRE_EQUAL(arg1, false); REQUIRE_EQUAL(arg2, 10); REQUIRE_EQUAL(arg3, "abc"); HIT(); }); } int main() { RUN_FUNCTION(testVoid); RUN_FUNCTION(testInt); RUN_FUNCTION(testMovable); RUN_FUNCTION(testRef); RUN_FUNCTION(testMultiArg); return 0; }
true
1ee20eb7db564854b530acc25c50ff09eecf3b19
C++
nebsar/xmlRead
/deneme/readXML.cpp
UTF-8
785
2.53125
3
[]
no_license
#include "pch.h" #include "readXML.h" #include <fstream> #include<iostream> readXML::readXML() { } readXML::~readXML() { } void readXML::setFile(std::string fileName) { mfileName = fileName; } void readXML::readFile() { std::ifstream inputFile(mfileName); std::string row; if (inputFile.is_open()) { while (std::getline(inputFile, row)) { if (row.find("Time")!= std::string::npos) { stringVector.push_back(row); } if (row.find("<ns1:Body>") != std::string::npos) { std::getline(inputFile, row); stringVector.push_back(row); } } inputFile.close(); } } void readXML::writeStringtoFile() { std::ofstream myfile; myfile.open("output.txt"); for (std::string str : stringVector) { myfile << str << "\n"; } myfile.close(); }
true
02ee5b137a1625b2ccc435a44de9db94644dda64
C++
jeanpierrethach/Design-Patterns
/src/main/c++/patterns/iterator/main.cpp
UTF-8
1,976
4.03125
4
[ "MIT" ]
permissive
#include <iostream> #include <vector> class Iterator; class Aggregate { public: virtual Iterator* createIterator() = 0; }; class ConcreteAggregate : public Aggregate { private: std::vector<int> m_vector; public: ConcreteAggregate(const unsigned int size) { m_vector.reserve(size); } unsigned int size() const { return m_vector.size(); } int at(unsigned int index) { return m_vector[index]; } void add(int value) { m_vector.push_back(value); } Iterator* createIterator() override; }; class Iterator { public: virtual ~Iterator() { } virtual void begin() = 0; virtual void next() = 0; virtual bool hasNext() = 0; virtual int currentItem() = 0; }; class ConcreteIterator : public Iterator { private: ConcreteAggregate* m_aggregate; unsigned int m_index; public: ConcreteIterator(ConcreteAggregate* c_aggregate) : m_aggregate(c_aggregate), m_index(0) { } void begin() override { m_index = 0; } void next() override { m_index++; } bool hasNext() override { return m_index >= m_aggregate->size(); } int currentItem() override { return m_aggregate->at(m_index); } }; Iterator* ConcreteAggregate::createIterator() { return new ConcreteIterator(this); } int main() { ConcreteAggregate c_aggregate = ConcreteAggregate(5); c_aggregate.add(1); c_aggregate.add(2); c_aggregate.add(3); c_aggregate.add(4); c_aggregate.add(5); Iterator* it = c_aggregate.createIterator(); for ( ; !it->hasNext(); it->next()) { std::cout << it->currentItem() << std::endl; } return 0; }
true
9126e2924c5f3add0ffb6a54330aa995aa0ecba5
C++
BIGBALLON/NCTU_TCG
/FIb2584_EVAL_AI/Fib2584/Random.h
UTF-8
549
2.703125
3
[]
no_license
#ifndef __RANDOM_H__ #define __RANDOM_H__ #include <ctime> class Random { private: struct RanCtx { unsigned long long a; unsigned long long b; unsigned long long c; unsigned long long d; }; public: Random(); Random(unsigned long long seed); ~Random(); unsigned long long get_rand_num(); private: inline unsigned long long rotate_rand_num(unsigned long long x, int k) { return (x << k) | (x >> (64 - k)); } void random_init(unsigned long long seed); unsigned long long random_value(); private: RanCtx ranctx_; }; #endif
true
0866619af88b7da99cfb29d9530baf71478fe2e1
C++
Emilio007/texasholdemsim
/Texas Holdem Sim/TexasHoldEmSim/TexasHoldEmSim/player.cpp
UTF-8
16,145
2.65625
3
[]
no_license
// Player.cpp #include "player.h" using namespace std; Player::Player() { } Player::Player(double m, map<string, double>& preFlop, string Name): job(-1), fold(false), bust(false), allIn(false), raised(false), myBet(0), decision(-1), dealHighBet(0), odds(-1), raiseAmt(-1) { money = m; preFlopOdds = preFlop; name = Name; SetSkillLvl(); } // Player() void Player::AddMoney(double amt) { money += amt; } // AddMoney() double Player::GetMoney() { return money; } // GetMoney() hand Player::GetHand() { return myHand; } // GetHand() void Player:: MakeHand() { myHand.initHand(tableCards, holeCards); } void Player::AddCard(card c, int loc) { if(loc == HOLECARDS) { holeCards.push_back(c); } else if( loc == FLOP || loc == TURN || loc == RIVER) { tableCards.push_back(c); } } // AddCard() void Player::ClearCards() { myHand.clear(); tableCards.clear(); holeCards.clear(); allCards.clear(); } // ClearCard() void Player::SetPreFlopOdds(map<string, double>& oddTbl) { preFlopOdds = oddTbl; } double Player::Action(bool limitRaise, double currentHighBet, bool amHole, bool amFirstIter, int numPlay, int numLeftInRound) { possibleTurnCards.ShuffleCard(); possibleRiverCards.ShuffleCard(); dealHighBet = currentHighBet; playersLeft = numPlay; if(numLeftInRound == 1) return 0.0; cout << "Current High Bet: " << currentHighBet << "\n"; simOut << "Current High Bet: " << currentHighBet << "\n"; if(job==SMALLBLIND && amFirstIter && amHole) { if(smallBlind > money) { allIn = true; double temp = money; myBet += money; money = 0.0; cout << name << " is the small blind but not enough $$$, so allIn with" << temp << "\n"; simOut << name << " is the small blind but not enough $$$, so allIn with" << temp << "\n"; return temp; }else { money -= smallBlind; myBet += smallBlind; cout << name << " is the small blind and is forced to bet " << smallBlind << "\n"; simOut << name << " is the small blind and is forced to bet " << smallBlind << "\n"; return smallBlind; } } else if(job==BIGBLIND && amFirstIter && amHole) { if(bigBlind > money) { allIn = true; double temp = money; myBet += money; money = 0.0; cout << name << " is the big blind but not enough $$$, so allIn with" << temp << "\n"; simOut << name << " is the big blind but not enough $$$, so allIn with" << temp << "\n"; return temp; }else { money -= bigBlind; myBet += bigBlind; cout << name << " is the big blind and is forced to bet " << bigBlind << "\n"; simOut << name << " is the big blind and is forced to bet " << bigBlind << "\n"; return bigBlind; } } if(amHole) PreFlopDec(limitRaise); else PostFlopDec(limitRaise); /*---------DON'T REPLACE BELOW---------*/ switch(decision) {//now do decision case CHECK : return Check(); break; case CALL : return Call(); break; case RAISE : return Raise(raiseAmt); break; case FOLD : return Fold(); break; default: cout << "did not make a decision"; simOut << "did not make a decision"; return -1; } } // Action() bool Player::DidFold() { return fold; } // DidFold() bool Player::DidBust() { return bust; } // DidBust() bool Player::DidAllIn() { return allIn; } // DidAllIn() bool Player::DidRaised() { return raised; } // DidRaised() void Player::Reset() { bust = false; fold = false; allIn = false; myBet = 0; ClearCards(); } // Reset() void Player::ResetRaised() { raised = false; } // ResetRaised() void Player::ResetMyBet() { myBet = 0.0; } // ResetMyBet() void Player::SetBusted() { bust = true; } // SetBusted() string Player::GetName() { return name; } // GetName() double Player::GetBet() { return myBet; } // GetBet() /* Private Stuff */ void Player::CombineCards() { allCards.clear(); allCards = tableCards; allCards.push_back(holeCards[0]); allCards.push_back(holeCards[1]); } void Player::SetSB(double amnt) { smallBlind = amnt; } void Player::SetBB(double amnt) { bigBlind = amnt; } double Player::Call() { double rval = 0.0; if((dealHighBet - myBet) == 0) //you idiot, you meant check! { rval = Check(); } else if((dealHighBet - myBet) > money) //if you don't have enough money to call { allIn = true; rval = money; money = 0.0; cout << name << " went all in with " << rval << "\n"; simOut << name << " went all in with " << rval << "\n"; } else { rval = (dealHighBet - myBet); money -= rval; myBet = dealHighBet; cout << name << " called(owed) the bet of " << rval << "\n"; simOut << name << " called(owed) the bet of " << rval << "\n"; } return rval; }//Call double Player::Fold() { fold = true; cout << name << " folded -- loser!\n"; simOut << name << " folded -- loser!\n"; return 0.0; }//Fold double Player::Check() { cout << name << " checked (knock-knock)\n"; simOut << name << " checked (knock-knock)\n"; return 0.0; }//Check double Player::Raise(double amnt) { double rval = 0.0; if((dealHighBet - myBet) > money) // Not Enough $$ to raise, much less call, all in buddy { rval = Call(); } else if((dealHighBet - myBet + amnt) > money) // Don't have enough to call AND raise how much you want { allIn = true; myBet += money; rval = money; money = 0.0; cout << name << " went all in with " << rval << "\n"; simOut << name << " went all in with " << rval << "\n"; raised = true; } else { rval = (dealHighBet - myBet + amnt); money -= rval; cout << name << " called(owed) the bet of " << (dealHighBet - myBet) << " and raised " << amnt << "\n"; simOut << name << " called(owed) the bet of " << (dealHighBet - myBet) << " and raised " << amnt << "\n"; myBet += rval; raised = true; } return rval; }//Raise double Player::AllIn() { allIn = true; double temp = money; money = 0.0; return temp; } //AllIn int Player::GetJob() { return job; } // GetJob() void Player::SetJob(int theJob) { job = theJob; } // SetJob() void Player::PreFlopDec(bool limitRaise) { string lookup = holeCards[0].whatcard() + holeCards[1].whatcard(); map<string, double>::iterator it; odds = preFlopOdds.find(lookup)->second; // See excel file for magic numbers switch(playersLeft) { case 2: switch(GetSkillLvl()) { case BEGINNER: if(odds >= 41) BetHelper(limitRaise); else FoldHelper(); break; case INTERMEDIATE: if(odds >= 49) BetHelper(limitRaise); else FoldHelper(); break; case EXPERT: if(odds >= 55) BetHelper(limitRaise); else FoldHelper(); break; } break; case 3: switch(GetSkillLvl()) { case BEGINNER: if(odds >= 26.5) BetHelper(limitRaise); else FoldHelper(); break; case INTERMEDIATE: if(odds >= 31) BetHelper(limitRaise); else FoldHelper(); break; case EXPERT: if(odds >= 37) BetHelper(limitRaise); else FoldHelper(); break; } break; case 4: switch(GetSkillLvl()) { case BEGINNER: if(odds >= 19.4) BetHelper(limitRaise); else FoldHelper(); break; case INTERMEDIATE: if(odds >= 23.3) BetHelper(limitRaise); else FoldHelper(); break; case EXPERT: if(odds >= 28.0) BetHelper(limitRaise); else FoldHelper(); break; } break; case 5: switch(GetSkillLvl()) { case BEGINNER: if(odds >= 15.4) BetHelper(limitRaise); else FoldHelper(); break; case INTERMEDIATE: if(odds >= 18.7) BetHelper(limitRaise); else FoldHelper(); break; case EXPERT: if(odds >= 22.5) BetHelper(limitRaise); else FoldHelper(); break; } break; case 6: switch(GetSkillLvl()) { case BEGINNER: if(odds >= 12.7) BetHelper(limitRaise); else FoldHelper(); break; case INTERMEDIATE: if(odds >= 16) BetHelper(limitRaise); else FoldHelper(); break; case EXPERT: if(odds >= 19) BetHelper(limitRaise); else FoldHelper(); break; } break; case 7: switch(GetSkillLvl()) { case BEGINNER: if(odds >= 10.7) BetHelper(limitRaise); else FoldHelper(); break; case INTERMEDIATE: if(odds >= 13.7) BetHelper(limitRaise); else FoldHelper(); break; case EXPERT: if(odds >= 16.5) BetHelper(limitRaise); else FoldHelper(); break; } break; case 8: switch(GetSkillLvl()) { case BEGINNER: if(odds >= 9.7) BetHelper(limitRaise); else FoldHelper(); break; case INTERMEDIATE: if(odds >= 12) BetHelper(limitRaise); else FoldHelper(); break; case EXPERT: if(odds >= 14.5) BetHelper(limitRaise); else FoldHelper(); break; } break; case 9: switch(GetSkillLvl()) { case BEGINNER: if(odds >= 8.4) BetHelper(limitRaise); else FoldHelper(); break; case INTERMEDIATE: if(odds >= 11) BetHelper(limitRaise); else FoldHelper(); break; case EXPERT: if(odds >= 13) BetHelper(limitRaise); else FoldHelper(); break; } break; case 10: switch(GetSkillLvl()) { case BEGINNER: if(odds >= 7.6) BetHelper(limitRaise); else FoldHelper(); break; case INTERMEDIATE: if(odds >= 9.9) BetHelper(limitRaise); else FoldHelper(); break; case EXPERT: if(odds >= 12) BetHelper(limitRaise); else FoldHelper(); break; } break; default: break; } } // PreFlopDec() void Player::PostFlopDec(bool limitRaise) { decision = PostFlopDecHelper(); //Can't raise if limited and can't check if they owe money while((limitRaise && decision == RAISE) || (dealHighBet > myBet && decision == CHECK)) { decision = PostFlopDecHelper(); } raiseAmt = 2*bigBlind; } // PostFlopDec() int Player::PostFlopDecHelper() { //make certain things happen more than others int dec = (rand()%10); if(dec <= 3) dec = CHECK; else if(dec > 3 && dec <= 6) dec = CALL; else if(dec > 6 && dec <=8) dec = RAISE; else dec = FOLD; return dec; }//PostFlopDecHelper() void Player::SetSkillLvl() { skillLvl = rand() % 3; // 0-2 } // SetSkillLvl() int Player::GetSkillLvl() { return skillLvl; } // GetSkillLvl() void Player::SortHoleCards() { card c0 = holeCards[0]; card c1 = holeCards[1]; if(c0 < c1) { holeCards[0] = c1; holeCards[1] = c0; } } void Player::FoldHelper() { if(dealHighBet == myBet) { //cout << "FoldHelper thinks it can check.\n"; decision = CHECK; } else if(playersLeft <= 3) { //cout << "FoldHelper was going to fold, but is now calling.\n"; decision = CALL; } else { //cout << "FoldHelper thinks it can Fold.\n"; decision = FOLD; } } void Player::BetHelper(bool limitRaise) { if(dealHighBet >= 2*bigBlind || limitRaise) { //cout << "BetHelper thinks it can Call.\n"; decision = CALL; } else { //cout << "BetHelper thinks it can Raise.\n"; int mod = (rand() % 5) + 1; raiseAmt = (double)smallBlind * mod; decision = RAISE; } } ostream& operator<< (ostream& output, Player &printPlayer) { output << printPlayer.name << "\t"; output << printPlayer.skillLvl << "\t"; output << printPlayer.job << "\t"; output << printPlayer.money << "\t"; output << printPlayer.allIn << "\t"; output << printPlayer.fold << "\t"; output << printPlayer.bust << "\t"; output << "\n"; return output; }
true
8cf42be79d704e9a3ebbc5c6f59dcdf7fa009410
C++
arbainrahat/CPU-Scheduling-Algorithms-OS
/Bakery.cpp
UTF-8
1,292
2.734375
3
[]
no_license
#include(pthread.h) #include(stdio.h> #include(unistd.h> #include (assert.h> volatile int NUM_THREADS = 10; volatile int Number[10] = {0}; volatile int count_cs[10] = {0}; volatile int Entering[10] = {0}; int max() { int i = 0; int j = 0; int maxvalue = 0; for(i = 0; i < 10; i++) { if ((Number[i]) > maxvalue) { maxvalue = Number[i]; } } return maxvalue; } lock(int i) { int j; Entering[i] = 1; Number[i] = 1 + max(); Entering[i] = 0; for (j = 1; j <= NUM_THREADS; j++) { while (Entering[j]) { } /* Do nothing */ while ((Number[j] != 0) && ((Number[j] < Number[i]) || ((Number[j] == Number[i]) && (j < i)))) { } } } unlock(int i) { Number[i] = 0; } void Thread(int i) { while (1) { lock(i); count_cs[i+1] = count_cs[i+1] + 1 ; //printf("critical section of %d\n", i+1); unlock(i); } } int main() { int duration = 10000; pthread_t threads[NUM_THREADS]; int rc; long t; for(t = 0; t < NUM_THREADS; t++){ printf("In main: creating thread %ld\n", t+1); rc = pthread_create(&threads[t], NULL, Thread, (int)t); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } usleep(duration*1000); for(t=0; t < NUM_THREADS; t++) { printf("count of thread no %d is %d\n",t+1,count_cs[t+1]); } return 0; }
true
c323be0b7b518a10e8c658baa78340c2b4a19811
C++
VoreWind/CommentOrganizer
/commentparser_test.cpp
UTF-8
9,543
3.015625
3
[]
no_license
#include <QString> #include <doctest.h> #include <commentparser.h> SCENARIO("Rewriting single comments according to code style") { GIVEN("Simple single-line code enclosed in /*...*/") { QString wrong_source_code = "/*mycool test comment*/"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("Parsed source code will have comments with tags /*...*/ replaced " "by comments starting with // ") { QString right_source_code = "// Mycool test comment."; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("Simple multi-line code enclosed in /*...*/") { QString wrong_source_code = "/*mycool\n * test comment*/"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("Parsed source code will have comments with tags /*...*/ replaced " "by comments starting with // ") { QString right_source_code = "// Mycool test comment."; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("Comment enclosed in /*...*/ in the middle of valid code line") { QString wrong_source_code = "int FunShit(/*cool comment */ blah);"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("Parsed source code will have comments with tags /*...*/ removed ") { QString right_source_code = "int FunShit( blah);"; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("Comment structured like /*!...*/ ") { QString wrong_source_code = "/*!mycool test !comment*/"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("Parsed source code will have /// at the start (IDE colors them " "blue)") { QString right_source_code = "/// Mycool test !comment."; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("Doxygen styled multiline comments structured like /*! ... \n * ... " "*/ ") { QString wrong_source_code = "/*!\\param *comment1\n * \\param comment2*/"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("Parsed source code will have /// at the start (IDE colors them and " "the stars in the middle will be gone") { QString right_source_code = "/// \\param comment1.\n/// \\param comment2."; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("Doxygen styled multiline comments structured like /*! ... \n * ... " "*/ not starting with \\smth block") { QString wrong_source_code = "/*!param *comment1\n * \\param comment2*/"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("Parsed source code will have /// at the start (IDE colors them and " "the stars in the middle will be gone") { QString right_source_code = "/// Param *comment1.\n/// \\param comment2."; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("Doxygen styled multiline comments structured like /** @param... \n * " "@param... */ ") { QString wrong_source_code = "/*! @param *comment1\n * @param comment2*/"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("Parsed source code will have /// at the start (IDE colors them and " "the stars in the middle will be gone") { QString right_source_code = "/// @param comment1.\n/// @param comment2."; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("Doxygen comment with a mixture of multi-lettered and single-lettered " "tags") { QString wrong_source_code = "/*!param *comment1\n * \\param comment2 \\a thingy*/"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("The comment gets split only at multi-lined tags") { QString right_source_code = "/// Param *comment1.\n/// \\param comment2 \\a thingy."; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("extern C comment at the end of pure C block") { QString wrong_source_code = "#ifdef __cplusplus\n} /* extern \"C\" { */\n#endif"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("This text in the comments should not be affected by parser") { QString right_source_code = "#ifdef __cplusplus\n} // extern \"C\"\n #endif // __cplusplus"; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("Comment ending with some punctuation mark ") { QString wrong_source_code = "/* Fun comment; */"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("Comment wont have the dot appended") { QString right_source_code = "// Fun comment;"; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("Comment preceded by // ") { QString wrong_source_code = "\n// interesting thing\n"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("Comment has a proper capitalization and a dot at the end") { QString right_source_code = "\n// Interesting thing.\n"; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("Multiline comment preceded by // ") { QString wrong_source_code = "\n// wierd thing\n\n\n// another interesting thing\n"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("Comment has a proper capitalization and a dot at the end") { QString right_source_code = "\n// Wierd thing.\n\n\n// Another interesting thing.\n"; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("Single line of code followed by //-style comment ") { QString wrong_source_code = "\n MyNewFunction(); // its not really new\n"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("Comment has a proper capitalization and a dot at the end") { QString right_source_code = "\n MyNewFunction(); // Its not really new.\n"; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("Single line of code followed by //-style comment and containing the " "same text as the comment") { QString wrong_source_code = "\n k = THING; // THING\n"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("Comment has a proper capitalization and a dot at the end. The code " "is unaltered") { QString right_source_code = "\n k = THING; // THING.\n"; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } GIVEN("Closing bracket of extern " "C" " block with wrong formatting") { QString wrong_source_code = "#ifdef __cplusplus\n };\n #endif\n"; WHEN("Run the wrong code through comment parser") { auto parsed_source_code = CommentParser::RewriteCommentsAccordingToCodeStyle(wrong_source_code); THEN("Closing bracket has no dangling semicolons and appended by proper " "comments") { QString right_source_code = "#ifdef __cplusplus\n } // extern " "\"C\"\n #endif // __cplusplus\n"; REQUIRE(parsed_source_code.toStdString() == right_source_code.toStdString()); } } } }
true
e9f23110770e0688313e5e1cddc259a43fdf25b1
C++
EnigmaSwanAdams/CS201-HW6
/random-map.cpp
UTF-8
2,666
3.4375
3
[]
no_license
/* * Enigma Swan Adams * CS201-HW6 * 4/7/21 * * file name: random-map.cpp * main program as described in the homework assignment on blackbuard * calling the function randomMap() from main runs the full main program * */ #include <iostream> #include <iomanip> #include <string> #include <map> #include <random> #include <cmath> #include"random-map.h" #include <stdlib.h> #include <time.h> #include<stdio.h> using std::mt19937; using std::uniform_int_distribution; std::random_device r; int main(){ int first = 1; int last = 6; //uniformly distributed histagram std::map<int, int> histU; for (int n = 0; n < 10000; ++n) { ++histU[std::round(RandomBetweenU(first, last))]; } std::cout << "Uniformly distributed from " << first << " to " << last << ":\n"; std::cout << std::endl; PrintDistribution(histU); std::cout << std::endl; //normally distributed histagram std::map<int, int> histN; for (int n = 0; n < 10000; ++n) { ++histN[std::round(RandomBetweenN(first, last))]; } std::cout << "Normal distribution around " << (last - first) / 2 << ":\n"; PrintDistribution(histN); std::cout << std::endl; //histagram from rand() function std::map<int, int> hist; for (int n = 0; n < 10000; ++n) { ++hist[std::round(RandomBetween(first, last))]; } std::cout << "distribution using rand() function" << (last - first) / 2 << ":\n"; PrintDistribution(hist); /* for (size_t i = 0; i < 20; i++) { std::cout << RandomBetweenU(1, 6) << std::endl; } std::cout << "BREAK\n"; for (size_t i = 0; i < 20; i++) { std::cout << RandomBetweenN(1, 6) << std::endl; } std::cout << "BREAK\n"; srand(time(NULL)); for (size_t i = 0; i < 20; i++) { std::cout << RandomBetween(1, 6) << std::endl; } */ } int RandomBetweenU(int first, int last) { std::default_random_engine e1(r()); std::uniform_int_distribution<int> uniform_dist(first, last); return uniform_dist(e1); } int RandomBetweenN(int first, int last){ std::random_device rd{}; std::mt19937 gen{ rd() }; double mean = (last - first) / 2; double deviation = (last - first) / 2; std::normal_distribution<> d{mean,deviation}; return d(gen); } int RandomBetween(int first, int last) { return rand()%(1+last-first) + first; } void PrintDistribution(const std::map<int, int>& numbers) { for (auto p : numbers) { std::cout << std::fixed << std::setprecision(1) << std::setw(2) << p.first << ' ' << std::string(p.second / 200, '*') << '\n'; } }
true
cdd489c36389e10800c3219043cf0869ed6f6b00
C++
leeeyupeng/leeeyupeng.github.io
/project/algorithm/leetcode2021/src/lcof.12.exist.cpp
UTF-8
1,505
2.734375
3
[]
no_license
#include"leetcode.h" class Solution { private: int offset[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; int m,n; int length; vector<vector<vector<char>>> dp; vector<vector<char>> visit; bool dfs(vector<vector<char>>& board,string& word,int i,int j,int index){ if(visit[i][j] == 1){return false;} if(board[i][j] != word[index]){return false;} if(index == length-1){return true;} visit[i][j] = 1; //if(dp[i][j][index] != 0){return dp[i][j][index] == 1?true:false;} int ii,jj; int ret = false; for(int k = 0; k < 4; k ++){ ii = i + offset[k][0]; jj = j + offset[k][1]; if(ii >= 0 && ii < m && jj >= 0 && jj < n){ ret |= dfs(board,word,ii,jj,index+1); if(ret){break;} } } visit[i][j] = 0; //dp[i][j][index] = ret?1:2; return ret; } public: bool exist(vector<vector<char>>& board, string word) { this->m = board.size(); this->n = board[0].size(); this->length = word.length(); //dp = vector<vector<vector<char>>>(m,vector<vector<char>>(n,vector<char>(length,0))); visit = vector<vector<char>>(m,vector<char>(n,false)); bool ret = false; for(int i = 0; i < m; i ++){ for(int j = 0; j < n; j ++){ ret |= dfs(board,word,i,j,0); if(ret){return ret;} } } return ret; } };
true
812a7f39efccf42773c15eedb2d60a3726067e47
C++
MutantEel/Artemis-Cpp
/src/Entity.cpp
UTF-8
3,598
2.640625
3
[ "BSD-2-Clause" ]
permissive
#include <Artemis/Entity.hpp> #include <sstream> #include <Artemis/Component.hpp> #include <Artemis/World.hpp> #include <Artemis/ComponentRegistry.hpp> using namespace std; namespace artemis { Entity::Entity(World* world, int id) { this->world = world; this->entityManager = world->getEntityManager(); this->id = id; } Entity::~Entity() { world = NULL; entityManager = NULL; } void Entity::addSystemBit(bitset<BITSIZE> bit) { systemBits |= bit; } void Entity::addTypeBit(bitset<BITSIZE> bit) { typeBits |= bit; } Component* Entity::getComponent(ComponentType& type) { return entityManager->getComponent(*this, type); } ImmutableBag<Component*>& Entity::getComponents() { return entityManager->getComponents(*this); } int Entity::getId() { return id; } bitset<BITSIZE> Entity::getSystemBits() { return systemBits; } bitset<BITSIZE> Entity::getTypeBits() { return typeBits; } long int Entity::getUniqueId() { return uniqueId; } bool Entity::isActive() { return entityManager->isActive(this->getId()); } void Entity::refresh() { world->refreshEntity(*this); } void Entity::addComponent(Component* c) { entityManager->addComponent(*this, c); } void Entity::removeComponent(ComponentType& type) { entityManager->removeComponent(*this, type); } void Entity::removeSystemBit(bitset<BITSIZE> bit) { systemBits &= ~bit; } void Entity::removeTypeBit(bitset<BITSIZE> bit) { typeBits &= ~bit; } void Entity::reset() { typeBits = 0; systemBits = 0; } void Entity::setGroup(string group) { world->getGroupManager()->set(group, *this); } void Entity::setSystemBits(bitset<BITSIZE> systemBits) { this->systemBits = systemBits; } void Entity::setTag(string tag) { world->getTagManager()->subscribe(tag, *this); } Json::Value Entity::serialize() { ImmutableBag<Component*>& comps = getComponents(); Json::Value result; //save tag std::string tag = world->getTagManager()->tagForEntity(*this); if(!tag.empty()) { result["artemis_tag"] = tag; } //save group std::string group = world->getGroupManager()->getGroupOf(*this); if(!group.empty()) { result["artemis_group"] = group; } //serialize all component for(int i = 0; i < comps.getCount(); i++) { Component* c = comps.get(i); if(c && c->getTypeName()) { result[c->getTypeName()] = c->serialize(); } } return result; } void Entity::deserialize(Json::Value data) { if(data.isNull() || !data.isObject()) { return; } //get tag if(data.isMember("artemis_tag") && data["artemis_tag"].isString()) { setTag(data["artemis_tag"].asString()); } //get group if(data.isMember("artemis_group") && data["artemis_group"].isString()) { world->getGroupManager()->set(data["artemis_group"].asString(), *this); } //create components and deserialize all members Json::Value::Members members = data.getMemberNames(); for(Json::Value::Members::iterator itr = members.begin(); itr != members.end(); itr++) { Component* c = ComponentRegistry::createComponent(itr->c_str()); if(c) { c->deserialize(data[itr->c_str()]); addComponent(c); } } refresh(); } void Entity::setTypeBits(bitset<BITSIZE> typeBits) { this->typeBits = typeBits; } void Entity::setUniqueId(long int uniqueId) { this->uniqueId = uniqueId; } std::string Entity::toString() { std::ostringstream oss; oss << "Entity[" << id << "]\n"; return oss.str(); } void Entity::remove() { world->deleteEntity(*this); } };
true
279def2852cd2f0698524cebc53aa14028993f22
C++
michaeljdietz/UniverseSimulator
/UniverseSimulator/GalaxyFactory.cpp
UTF-8
1,354
2.5625
3
[]
no_license
#include "GalaxyFactory.h" #include "Random.h" #include "Game.h" #include "Galaxy.h" #include "Cluster.h" GalaxyFactory* GalaxyFactory::_instance; GalaxyFactory::GalaxyFactory(Game* game) { _game = game; } GalaxyFactory* GalaxyFactory::getInstance() { if (_instance) { return _instance; } return _instance = new GalaxyFactory(Game::getInstance()); } Galaxy* GalaxyFactory::create(Cluster* parent, std::vector<float> origin) { // TODO: Anything remaining after all children have been generated is extrastellar -- but when do we generate THAT stuff Galaxy* _galaxy = new Galaxy(_game); _galaxy->_parent = parent; _galaxy->_childCount = generateChildCount(); _galaxy->_axisCoordinateCount = floor(cbrt((float)_galaxy->_childCount)) + 1; _galaxy->_mass = generateMass(); _galaxy->_luminosity = generateLuminosity(); _galaxy->_majorRadius = generateMajorRadius(); _galaxy->_minorRadius = generateMinorRadius(); _galaxy->_temperature = generateTemperature(); return _galaxy; } long GalaxyFactory::generateChildCount() { return 0; } float GalaxyFactory::generateMass() { return 0.0f; } float GalaxyFactory::generateLuminosity() { return 0.0f; } float GalaxyFactory::generateMajorRadius() { return 0.0f; } float GalaxyFactory::generateMinorRadius() { return 0.0f; } float GalaxyFactory::generateTemperature() { return 0.0f; }
true
a5e6b5c21fbea361fba8ad45771e7a55b2af371e
C++
BreadBasket95/Infix-to-Postfix-Converter
/Stack.h
UTF-8
1,124
3.25
3
[]
no_license
/******************************************************************************* * Stack.h * * author: Rikk Anderson * date created: 9/27/2017 * last updated: 9/27/2017 * * This files defines a Stack class used for infix to postfix conversion * *******************************************************************************/ #ifndef STACK_H #define STACK_H #include <iostream> #include "Node.h" class Stack { private: Node *tos; // the head pointer of the linked list-based stack public: Stack(); // the constructor ~Stack(); // the destructor void destroy_Stack(); // removes all elements from the stack // *** methods you must implement // the item and precedence parameters are made const to // prevent and accidental modification of the parameters void push(const string &item, const int &precedence); void push(Node *node); Node* pop(); // removes and returns the top node or NULL if stack is empty Node* top() const; // returns a pointer to the top node (allows you to look at it) // returns NULL of stack is empty }; #endif
true
99f80bc49910b2679b468e7176d4e23054adb318
C++
PeachIcetea29/AlgorithmProblem
/baekjoon/2225. 합분해.cpp
UTF-8
439
2.703125
3
[]
no_license
#include <stdio.h> #define DIV 1000000000 int main() { int N, K; scanf("%d %d", &N, &K); long long d[201][201] = { 0, }; for (int i = 0; i <= N; i++) d[1][i] = 1; for (int i = 2; i <= K; i++) { for (int j = 0; j <= N; j++) { for (int k = 0; k <= j; k++) { d[i][j] += d[i - 1][k]; d[i][j] %= DIV; } } } printf("%d\n", d[K][N]); return 0; } //DP //k-1개를 사용하여 만든 수에 나머지 ?값을 붙여줌
true
88ce1d8dd7621b7f0e94c50d1b76475d47535e40
C++
rohitrtk/OpenGL
/OpenGL/src/Render/VertexBuffer.h
UTF-8
286
2.9375
3
[]
no_license
#pragma once class VertexBuffer { public: VertexBuffer(const void* data, unsigned int size); ~VertexBuffer(); void bind() const; void unbind() const; unsigned int getID() const { return this->ID; } void setID(unsigned int ID) { this->ID = ID; } private: unsigned int ID; };
true
ac361a139bafe131417757683f04fa9620800913
C++
baiumbg/assignments
/fmi/oop/homework2/prog2/Conditional.h
UTF-8
373
2.890625
3
[]
no_license
#pragma once #include "Formula.h" class Conditional : public Formula { private: Formula* condition; Formula* whenTrue; Formula* whenFalse; public: Conditional(Formula*, Formula*, Formula*); Conditional(const Conditional&); double value() const; void print(); Formula* clone() const; Conditional& operator=(const Conditional&); ~Conditional(); };
true
29b864ce7499e9dd02c7a9d5121fc703547b637b
C++
yular/CC--InterviewProblem
/LeetCode/leetcode_island-perimeter.cpp
UTF-8
876
3.0625
3
[]
no_license
/* * * Tag: Implementation * Time: O(nm) * Space: O(1) */ class Solution { public: int islandPerimeter(vector<vector<int>>& grid) { int ans = 0; if(grid.size() == 0) return ans; int n = grid.size(), m = grid[0].size(), x = 0, y = 0; for(int i = 0; i < n; ++ i){ for(int j = 0; j < m; ++ j){ if(grid[i][j] == 1){ for(int k = 0; k < 4; ++ k){ x = i + dir[k][0], y = j + dir[k][1]; if(!isInMap(x, y, n, m) || grid[x][y] == 0) ++ ans; } } } } return ans; } private: bool isInMap(int x, int y, int n, int m){ return x >= 0 && x < n && y >= 0 && y < m; } private: int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}}; };
true
95deac62ce6a7821633810c71b39794b726adbed
C++
Ritalin4Kidz/Map-Of-The-SYDE
/Map Of The SYDE/Map Of The SYDE/Player.h
UTF-8
2,954
2.6875
3
[]
no_license
#pragma once #include "SYDEstdafx.h" #include "Inventory.h" class MOTS_Player { public: MOTS_Player() {} virtual ~MOTS_Player() {} Inventory _Inventory = Inventory(); void setHealth(int newHP) { play_health = newHP; } int getHealth() { return play_health; } void setMaxHealth(int newHP) { play_max_health = newHP; } int getMaxHealth() { return play_max_health; } void setLvl(int newlvl) { play_lvl = newlvl; } int getLvl() { return play_lvl; } void setXP(int newXP) { play_xp = newXP; } int getXP() { return play_xp; } void setXPNxtLvl(int newXPNxtLvl) { play_xp_to_next_level = newXPNxtLvl; } int getXPNxtLvl() { return play_xp_to_next_level; } void setSwordDmg(int dmg) { play_sword_dmg = dmg; } int getSwordDmg() { return play_sword_dmg; } void setFireSpellUnlocked(bool unlocked) { play_fire_spell = unlocked; } bool getFireSpellUnlocked() { return play_fire_spell; } void setFireDmg(int dmg) { play_fire_dmg = dmg; } int getFireDmg() { return play_fire_dmg; } void setWaterSpellUnlocked(bool unlocked) { play_water_spell = unlocked; } bool getWaterSpellUnlocked() { return play_water_spell; } void setWaterDmg(int dmg) { play_water_dmg = dmg; } int getWaterDmg() { return play_water_dmg; } void setGrassSpellUnlocked(bool unlocked) { play_grass_spell = unlocked; } bool getGrassSpellUnlocked() { return play_grass_spell; } void setGrassDmg(int dmg) { play_grass_dmg = dmg; } int getGrassDmg() { return play_grass_dmg; } void setMoneySpellUnlocked(bool unlocked) { play_money_spell = unlocked; } bool getMoneySpellUnlocked() { return play_money_spell; } void setMoneyDmg(int dmg) { play_money_multi = dmg; } int getMoneyDmg() { return play_money_multi; } //etc values void setMoney(int coins) { player_money = coins; } void addMoney(int coins) { player_money += coins; } int getMoney() { return player_money; } void spendMoney(int coins) { player_money -= coins; } void setIcon(string _ICON) { player_icon = _ICON; } string getIcon() { return player_icon; } void setColour(ColourClass colour) { player_colour = colour; } ColourClass getColour() { return player_colour; } private: int play_health = 100; int play_max_health = 100; int play_lvl = 1; int play_xp = 0; int play_xp_to_next_level = 1000; int play_sword_dmg = 5; bool play_fire_spell = false; bool play_water_spell = false; bool play_grass_spell = false; bool play_money_spell = false; int play_fire_dmg = 5; int play_water_dmg = 5; int play_grass_dmg = 5; int play_money_multi = 2; // etc values int player_money = 0; string player_icon = "><"; ColourClass player_colour = BLACK; }; class FightWindow { public: FightWindow() {} virtual ~FightWindow() {} void AddFString(string fstring); string getFString(int index) { if (index >= _fightStrings.size()) { return ""; } return _fightStrings[index]; } void clear() { _fightStrings.clear(); } private: vector<string> _fightStrings = vector<string>(); };
true
7f9a8fd81e752f9d2b5eb1053e3e189754d8739f
C++
LingerDavid/UVA
/uva_brute_force/12325.cpp
UTF-8
1,024
3.046875
3
[]
no_license
#include<iostream> using namespace std; int N,S1,V1,S2,V2; int result; void solve(){ int M1 = N / S1, M2 = N / S2; int T = 50; int res; if(M1 > T && M2 > T){ //Volume:S2 * S1, S1 * S2 //Value:S2 * V1, S1 * V2 if(S2 * V1 < S1 * V2){ for(int i = 0;i < S2; i++){ res = i * V1 + (N - i * S1) / S2 * V2; if(result < res){ result = res; } } } else{ for(int i = 0; i < S1; i++){ res = i * V2 + (N - i * S2) / S1 * V1; if(result < res){ result = res; } } } } else if(M1 < M2){ //enumate the M2 for(int i = 0; i <= M2; i++){ res = i * V2 + (N - i * S2) / S1 * V1; if(result < res){ result = res; } } } else{ //enumate the M1 for(int i = 0; i <= M1; i++){ res = i * V1 + (N - i * S1) /S2 * V2; if(result < res){ result = res; } } } } int main(){ int k = 1; int n; cin >> n; for(int i = 0; i < n; i++){ cin >> N >> S1 >> V1 >> S2 >> V2; solve(); cout << "Case #" << (k++) << ": " << result << endl; } return 0; }
true
e27072ea0f58131e2d7e2c0c9e204f788e4861ef
C++
Z21459/OtherDemo
/SortAlgorithm/ReferenceAndPointer/StringOperator.cpp
GB18030
2,843
3.25
3
[]
no_license
#include <iostream> #include <cstring> #include <vector> using namespace std; //Ӵ ö̬滮 char * findMax(char*s1, char* s2) {//"baucbaud";"baudbaud" int len = strlen(s1) <= strlen(s2) ? strlen(s1) : strlen(s2);//ȡС int i, j, m = 0; int p, q; int length = strlen(s2); //char a[100] = { 0 }; char *a = new char[100]{0}; char *b = new char[100]{0}; *a = '\0'; *b = '\0'; //char b[100] = { 0 }; for (i = 0; i < len; i++) { for (j = 0; j < length; j++) { //strcpy_s(a, "0"); p = i;//0 0 q = j; while (s1[p] == s2[q] && s1[p] != 0)//ѭ֮ж Ҷ̵IJΪ { a[m] = s2[q];//ֵ p++; q++; m++; }// ˳ѭ ִ// //"baucbaud";"baudbaud" if (strlen(a) > strlen(b))//bһΪ ִһ֮ Ϊ aѭ֮ //ԭȵַ ¿ ԭ { //strcpy_s(b, a);//bʱŵһδŵӴ //while ((*b++ = *a++) != 0); for (int w = 0, k = 0; w < strlen(b) || k < strlen(a);) { b[w++] = a[k++]; } } m = 0; } } return b; } int strcmp1(const char*s1, const char*s2) { // int b = 0; if (s1 == nullptr || s2 == nullptr) b = -1; //while(!(b = *(unsigned char*)s1 - *(unsigned char*)s2) && *s2) { // ++s1; // ++s2; //} int i=0, j=0; for (; i < strlen(s1) || j < strlen(s2);) { if (s1[i++] != s2[j++]) { b = 1;//ͬ1 break; } } //if (b < 0) // b = -1; //else if(b>0) // b = 1; return b; } int rewen(const char*s1) { int t = 1; if (s1 == nullptr) t = -1; int i; int len = strlen(s1); for (i = 0; i < len / 2;i++) { if (s1[i] != s1[len - i-1]) { t = 0;//ǻ break; } } return t; } // char *strcpy1(char*s1, const char*s2) { if (s1 == nullptr) return nullptr; int i, j; for (i = 0,j=0; i < strlen(s2);) { s1[j++] = s2[i++]; } return s1; } // char* strcat1(char* s1, const char* s2) { if (s2 == nullptr) return nullptr; int i, k; if (s1 == nullptr) { for (i = 0, k = 0; i < strlen(s2);) { s1[k++] = s2[i++]; } } if(s1 != nullptr) { for (i = strlen(s1), k = 0; k <=strlen(s2);) { s1[i++] = s2[k++]; } } return s1; } int main3() { char p[] = "baudbaud"; char q[] = "baucbaud"; const char *a = "abo"; const char *b = "abc"; const char *w = "abdca"; char * tt = findMax(p, q);//Ӵ cout << tt; char* temp = new char[256]; *temp = '\0'; char *t = strcat1(strcat1(temp, a), b); //cout << t; delete[]temp; char* temp1 = new char[256]; strcpy1(temp1, b);//copy int z = strcmp1(a, b);//Ƚ //cout << z; delete[]temp1; int v = rewen(w); //cout << v; system("pause"); return 0; }
true
4a65bc303a931134f14579cbc061bd0b5e9655c2
C++
Hybrid-Music-Lab/Unicycle
/Source/Timeline.cpp
UTF-8
4,353
2.5625
3
[ "MIT" ]
permissive
// Copyright (c) 2019 Christoph Mann (christoph.mann@gmail.com) #include "Timeline.h" using namespace unc; using namespace lnf; // Timeline unc::Timeline::Timeline( double viewStart_, double viewLength_ ) : viewStart( viewStart_ ), viewLength( viewLength_ ) { static_assert( spacing > 1 ); // spacing is used as divisor setInterceptsMouseClicks( false, false ); // listen addAudioSettingsListener( this ); updateSampleRate(); } unc::Timeline::~Timeline() { // listen removeAudioSettingsListener( this ); } // Timeline - Component void unc::Timeline::paint( Graphics & g ) { // bg g.fillAll( greyBgNear ); // grid ruler auto gridSteps = numGridSteps(); auto gridStepping = gridSize; auto gridStart = nearestFloorOf( getViewStart(), gridStepping ); for( int i = 0; i < gridSteps; ++i ){ auto sec = gridStart + i * gridStepping; auto x = timepointToPix( sec ); // notch g.setColour( timeScaleGridNotchColour ); g.fillRect( x, 0, 1., dims::h ); } // unit ruler auto unitSteps = numUnitSteps(); auto unitStepping = calculateStepping( getViewLength(), unitSteps ); auto unitStart = nearestFloorOf( getViewStart(), unitStepping ); for( int i = 0; i < unitSteps; ++i ) { auto sec = unitStart + i * unitStepping; auto x = timepointToPix( sec ); // text String text; text.preallocateBytes( 48 ); int h = ( ( int )std::abs( sec / 3600 ) ) % 24; if( h > 0 ){ text << h << ":"; } int m = ( ( int )std::abs( sec / 60 ) ) % 60; text << m << ":"; int s = ( ( int )std::abs( sec ) ) % 60; text << s << "."; int ms = ( ( int )std::abs( sec * 1000 ) ) % 1000; text << ms; g.setColour( textColour ); g.drawText( text, x + 2, 0, spacing, dims::h, Justification::left ); // notch g.setColour( timeScaleUnitNotchColour ); g.fillRect( x, 0, 1., dims::h ); } } // Timeline - AudioSettingsListener void unc::Timeline::audioSettingsChanged( const AudioSettings& newAudioSettings ) { updateSampleRate(); } // Timeline - modify void unc::Timeline::setHorizontalView( double startInSeconds, double lengthInSeconds ) { viewStart = jlimit( 0., maximumViewLength, startInSeconds ); viewLength = jlimit( minimumViewLength, maximumViewLength, lengthInSeconds ); repaint(); sendChangeMessage(); } void unc::Timeline::setGridSize( double lengthInSeconds ) { gridSize = lengthInSeconds; repaint(); sendChangeMessage(); } void unc::Timeline::updateSampleRate() { sampleRate = getCurrentAudioSettings().sampleRate; repaint(); sendChangeMessage(); } // Timeline - access double unc::Timeline::toSeconds( int samples ) const { return samples / jmax( 1., sampleRate ); } int unc::Timeline::toSamples( double seconds ) const { return roundToIntAccurate( seconds * sampleRate ); } double unc::Timeline::pixToTimepoint( int compX ) const { auto normalized = ( double )compX / getWidth(); return viewStart + ( normalized * viewLength ); } double unc::Timeline::pixToDuration( int distX ) const { auto normalized = ( double )distX / getWidth(); return normalized * viewLength; } int unc::Timeline::timepointToPix( double seconds ) const { auto normalized = ( seconds - viewStart ) / viewLength; return normalized * getWidth(); } int unc::Timeline::durationToPix( double seconds ) const { auto normalized = seconds / viewLength; return normalized * getWidth(); } int unc::Timeline::getGridSizePix() const { return durationToPix( gridSize ); } int unc::Timeline::getGridSizeSamps() const { return toSamples( gridSize ); } double unc::Timeline::calculateStepping( double secs, int steps ) const { // which number of steps fit secs best auto f = secs / jmax( 1, steps ); // ms...s if( f < 0.001 ) return 0.001; if( f < 0.0025 ) return 0.0025; if( f < 0.005 ) return 0.005; if( f < 0.01 ) return 0.01; if( f < 0.025 ) return 0.025; if( f < 0.05 ) return 0.05; if( f < 0.1 ) return 0.1; if( f < 0.25 ) return 0.25; if( f < 0.5 ) return 0.5; // s...min if( f < 1. ) return 1; if( f < 2.5 ) return 2.5; if( f < 5.0 ) return 5.0; if( f < 10. ) return 10.; if( f < 30. ) return 30.; // mins for( int i = 1; i < 360; ++i ) { if( f < ( i * 60 ) ) { return i * 60; } } return -1.; } int unc::Timeline::numUnitSteps() const { return std::ceilf( ( float )getWidth() / spacing ); } int unc::Timeline::numGridSteps() const { return std::ceilf( ( float )getWidth() / getGridSizePix() ); }
true
a7f9fbb8dce45dc1233d56df7653991ec5d3650e
C++
jizhuoran/spatial_data_processing
/histogram_drawing/getResults.cpp
UTF-8
4,774
3.09375
3
[]
no_license
#include <iostream> #include <fstream> #include <cstring> #include <stdlib.h> #define AGE_RANGE 81 #define BINS_NUMBER 8 #define THRESHOLD_NUMBER 7 using namespace std; double estimate_eqWidth(int LEFT, int RIGHT, char * histogram_path) { unsigned int person_of_bin[BINS_NUMBER]; for (int i = 0; i < BINS_NUMBER; ++i) { person_of_bin[i] = 0; } //get the input ifstream input; input.open(histogram_path); if (input.is_open()) { for(int i = 0; i < BINS_NUMBER; ++i) { input >> person_of_bin[i]; } } else { cerr << "Can not open the file: " << histogram_path << endl; return 0.0; } input.close(); double sum = 0; int thresholds[THRESHOLD_NUMBER + 2] = {0,10,20,30,40,50,60,70,81}; int ll = -1; int rr = -1; //find the largest thresholds before LEFT for (int i = 0; i < THRESHOLD_NUMBER + 1; ++i) { if(thresholds[i+1] > LEFT) { ll = i; break; } } //find the smallest thresholds after RIGHT for (int i = 0; i < THRESHOLD_NUMBER + 2; ++i) { if(thresholds[i] > RIGHT) { rr = i; break; } } // if LEFT and RIGHT in the same interval if((ll + 1) == rr) { return 1.0 * person_of_bin[ll] * (RIGHT-LEFT+1)/(thresholds[rr] - thresholds[ll]); } // sum the interval which totally between LEFT and RIGHT for (int i = ll + 1; i < rr-1 ; ++i) { sum += person_of_bin[i]; } //add sum with right side of LEFT and its right and RIGHT and its left. sum += 1.0 * person_of_bin[ll]*(thresholds[ll+1] - LEFT) / (thresholds[ll+1] - thresholds[ll]); sum += 1.0 * person_of_bin[rr - 1]*(RIGHT - thresholds[rr-1] + 1) / (thresholds[rr] - thresholds[rr-1]); return sum; } double estimate_eqDepth(int LEFT, int RIGHT, char * histogram_path) { unsigned int thresholds[THRESHOLD_NUMBER+2]; int total = 0; for (int i = 0; i < THRESHOLD_NUMBER+2; ++i) { thresholds[i] = 0; } thresholds[THRESHOLD_NUMBER + 1] = 81; // get the input ifstream input; input.open(histogram_path); if (input.is_open()) { input>>total; for(int i = 1; i < THRESHOLD_NUMBER+1; ++i) { input >> thresholds[i]; } } else { cerr << "Can not open the file: " << histogram_path << endl; return 0.0; } input.close(); double record_per_bin = total / BINS_NUMBER; double sum = 0; int ll = -1; int rr = -1; //find the largest thresholds before LEFT for (int i = 0; i < THRESHOLD_NUMBER+1; ++i) { if(thresholds[i+1] > LEFT) { ll = i; break; } } //find the smallest thresholds after RIGHT for (int i = 0; i < THRESHOLD_NUMBER+2; ++i) { if(thresholds[i] > RIGHT) { rr = i; break; } } // if LEFT and RIGHT in the same interval if((ll + 1) == rr) { return record_per_bin * (RIGHT-LEFT+1)/(thresholds[rr] - thresholds[ll]); } // sum the interval which totally between LEFT and RIGHT sum += (rr-ll-2) * record_per_bin; //add sum with right side of LEFT and its right and RIGHT and its left. sum += record_per_bin*(thresholds[ll+1] - LEFT) / (thresholds[ll+1] - thresholds[ll]); sum += record_per_bin*(RIGHT - thresholds[rr-1] + 1) / (thresholds[rr] - thresholds[rr-1]); return sum; } int get_result(int LEFT, int RIGHT, char * dat_path) { string line, age_in_string; //person_per_age is use to store the number of records in that age unsigned int person_per_age[AGE_RANGE]; for (int i = 0; i < AGE_RANGE; ++i) { person_per_age[i] = 0; } ifstream input; input.open(dat_path); if (input.is_open()) { while (getline (input,line)){ age_in_string = strtok(&(line[0])," "); age_in_string = strtok(NULL," ");//get the second column of the data ++person_per_age[atoi(&(age_in_string[0]))];//add 1 to the corresponding elements of the array } } else { cerr << "Can not open the file: " << dat_path << endl; return 0; } input.close(); unsigned int sum = 0; for(int i = LEFT; i <= RIGHT; ++ i) { sum += person_per_age[i]; } return sum; } int main(int argc, char** argv) { if (argc != 6){ cerr << "Usage: " << argv[0] << " LEFT RIGHT WIDTH_HISTOGRAM_PATH DEPTH_HISTOGRAM_PATH DATA_PATH" << endl; /* LEFT(int): the lower bound of the interval RIGHT(int): the upper bound of the interval WIDTH_HISTOGRAM_PATH(char *): the file path of the equal-width histogram DEPTH_HISTOGRAM_PATH(char *): the file path of the equal-depth histogram DATA_PATH(char *): the file path of final_general.dat */ return -1; } cout << estimate_eqWidth(atoi(argv[1]), atoi(argv[2]), argv[3]) << endl; cout << estimate_eqDepth(atoi(argv[1]), atoi(argv[2]), argv[4]) << endl; cout << get_result(atoi(argv[1]), atoi(argv[2]), argv[5]) << endl; return 0; }
true
ccf843213caa7491b27f6bc8fc2e1e0a8574bf61
C++
AlasdairH/Batoidea
/Batoidea/src/BoundingBox.cpp
UTF-8
990
2.65625
3
[]
no_license
#include "BoundingBox.h" namespace Batoidea { bool BoundingBox::intersect(const Ray &_ray) { float tmin, tmax, tymin, tymax, tzmin, tzmax; tmin = (bounds[_ray.sign[0]].x - _ray.origin.x) * _ray.inverseDirection.x; tmax = (bounds[1 - _ray.sign[0]].x - _ray.origin.x) * _ray.inverseDirection.x; tymin = (bounds[_ray.sign[1]].y - _ray.origin.y) * _ray.inverseDirection.y; tymax = (bounds[1 - _ray.sign[1]].y - _ray.origin.y) * _ray.inverseDirection.y; if ((tmin > tymax) || (tymin > tmax)) return false; if (tymin > tmin) tmin = tymin; if (tymax < tmax) tmax = tymax; tzmin = (bounds[_ray.sign[2]].z - _ray.origin.z) * _ray.inverseDirection.z; tzmax = (bounds[1 - _ray.sign[2]].z - _ray.origin.z) * _ray.inverseDirection.z; if ((tmin > tzmax) || (tzmin > tmax)) return false; if (tzmin > tmin) tmin = tzmin; if (tzmax < tmax) tmax = tzmax; float t = tmin; if (t < 0) { t = tmax; if (t < 0) return false; } return true; } }
true
837db768df5dedebfa60ebc04cc44d9b785b3bd4
C++
AnabaenaQing/Source-Code_ShaderX_GPU-Pro_GPU-Zen
/GPU Pro5/06_Compute/Object-order Ray Tracing for Fully Dynamic Scenes/beCore/source/beValueTypes.cpp
UTF-8
2,807
2.625
3
[ "MIT", "BSD-3-Clause" ]
permissive
/*****************************************************/ /* breeze Engine Core Module (c) Tobias Zirr 2011 */ /*****************************************************/ #include "beCoreInternal/stdafx.h" #include "beCore/beValueTypes.h" #include "beCore/beTextSerializer.h" #include <lean/logging/errors.h> namespace beCore { // Constructor. ValueTypes::ValueTypes() { } // Destructor. ValueTypes::~ValueTypes() { } // Adds the given component type, returning a unique address for this type. const ValueTypeDesc& ValueTypes::AddType(const lean::property_type_info &typeInfo) { utf8_nt typeName( typeInfo.type.name() ); std::pair<typename_map::iterator, bool> it = m_typeNames.insert( std::make_pair( typeName, ValueTypeDesc(typeInfo) ) ); if (!it.second) LEAN_THROW_ERROR_CTX("Value type name collision", typeInfo.type.name()); return it.first->second; } // Removes the given component type. void ValueTypes::RemoveType(const lean::property_type_info &typeInfo) { typename_map::iterator it = m_typeNames.find( utf8_nt(typeInfo.type.name()) ); if (it != m_typeNames.end() && it->second.Info.type == typeInfo.type) m_typeNames.erase(it); } // Sets the given serializer for the given type. void ValueTypes::SetSerializer(const TextSerializer *text) { LEAN_ASSERT(text); utf8_nt typeName = text->GetType(); typename_map::iterator it = m_typeNames.find(typeName); if (it != m_typeNames.end()) it->second.Text = text; else LEAN_THROW_ERROR_CTX("Serializer type not registered", typeName.c_str()); } // Unsets the given serializer for the given type. void ValueTypes::UnsetSerializer(const TextSerializer *text) { LEAN_ASSERT(text); utf8_nt typeName = text->GetType(); typename_map::iterator it = m_typeNames.find(typeName); if (it != m_typeNames.end() && it->second.Text == text) it->second.Text = nullptr; } // Gets a component type address for the given component type name. const ValueTypeDesc* ValueTypes::GetDesc(const utf8_ntri &name) const { typename_map::const_iterator it = m_typeNames.find(utf8_nt(name)); return (it != m_typeNames.end()) ? &it->second : nullptr; } // Gets all reflectors. ValueTypes::TypeDescs ValueTypes::GetDescs() const { TypeDescs descs; descs.reserve(m_typeNames.size()); for (typename_map::const_iterator it = m_typeNames.begin(); it != m_typeNames.end(); ++it) descs.push_back(&it->second); return descs; } // Gets the component type register. ValueTypes& GetValueTypes() { static ValueTypes valueTypes; return valueTypes; } // Adds a value type. const ValueTypeDesc& AddValueType(const lean::property_type_info &type, ValueTypes &types) { return types.AddType(type); } // Adds a value type. void RemoveValueType(const lean::property_type_info &type, ValueTypes &types) { types.RemoveType(type); } } // namespace
true
77b042f556d1e2c6d6424b9b7fd5aa81fe43ee1e
C++
psj01/PersonalProjects
/The Josephus Problem/TheJosephusProblem.h
UTF-8
1,794
3.21875
3
[]
no_license
/*************************************************************************************************** The Josephus Problem The problem is known as the Josephus problem and postulates a group of soldiers of size N surrounded by an overwhelming enemy force. There is no hope for victory without reinforcements, but there is only a single horse available for escape. The soldiers agree to a pact to determine which of them is to escape and summon help. They form a circle and a number M is picked from a hat. One of their names is also picked from a hat. Beginning with the soldier whose name is picked, they begin to count clockwise around the circle. When the count reaches M, that soldier is removed from the circle, and the count begins again with the next soldier. The process continues so that each time the count reaches M, another soldier is removed from the circle. Any soldier removed from the circle is no longer counted. The last soldier remaining is to take the horse and escape. The problem is, given a number M, the ordering of the soldiers in the circle, and the soldier from whom the count begins, to determine the order in which soldiers are eliminated from the circle and which soldier escapes. ******************************************************************************************************/ #ifndef PROG5_H #define PROG5_H #include <iostream> #include <iomanip> #include <string> #include <algorithm> #include <conio.h> #include <vector> #include <algorithm> using namespace std; const int No_Items=12; // const declaration for No_Items const string Init_Val="A1"; // const declaration for Init_Val void init_vals(vector <string>& v, unsigned& N, unsigned& M); void print_vector(const vector <string>& v, const unsigned& cnt); #endif
true
fc84e9c27ac4ae548251cb24f1020870bf8ac2c0
C++
yyzYLMF/myleetcode
/33_search_in_rotated_sorted_array.cc
UTF-8
1,525
3.84375
4
[]
no_license
/* @yang 2015/3/9 Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. */ #include <iostream> #include <cstdlib> using namespace std; class Solution { public: int search(int A[], int n, int target) { int low,high,mid; low = 0; high = n-1; while(low <= high) { mid = (low+high)/2; if(A[mid] == target) return mid; else if(A[mid] > target) { if(A[low] > target) { if(A[low] > A[mid]) high = mid-1; else low = mid+1; } else high = mid-1; } else if(A[mid] < target) { if(A[high] < target) { if(A[high] < A[mid]) low = mid+1; else high = mid-1; } else low = mid+1; } } if(low > high) return -1; } }; int main() { int A[]={4,5,6,7,0,1,2}; Solution solu; int result; result = solu.search(A, 8, 0); if(result != -1) cout<<result<<" "<<A[result]<<endl; else cout<<"-1"<<endl; return 0; }
true
2abacefb5d522865e68a999f82405cb5764ffecf
C++
myhumankit/declic
/code/arduino/experimentations/detectcontractio_/detectcontractio_.ino
UTF-8
2,490
2.546875
3
[ "MIT" ]
permissive
#include <Mouse.h> #include <MHK_Button.h> VirtualButton bouton(LOW); #define HOLD_RIGHT_TIME 500 #define SEUIL 50 unsigned long start_time = 0; bool is_hold = 0; bool is_long_press = 0; bool long_press_end = 0; int seuil = 400; void setup() { // put your setup code here, to run once: Serial.begin(115200); Mouse.begin(); // bouton.begin(INPUT_PULLUP); // suppression du begin. // configure Button object // bouton.setDebounceTime(50); // duration in milliseconds: 0 to 255 (default: 0) bouton.setHoldTime(500); // duration in milliseconds: 0 to 65535 (default: 1000) bouton.setIdleTime(3000); // duration in milliseconds: 0 to 65535 (default: 1000) bouton.setMultiTime(255); // duration in milliseconds: 0 to 255 (default: 127) } void loop() { // put your main code here, to run repeatedly: int axe_x = analogRead(A1); int axe_y = analogRead(A0); if ((axe_x < (512 + SEUIL)) and (axe_x > (512 - SEUIL))) { axe_x = 512; } if ((axe_y < (512 + SEUIL)) and (axe_y > (512 - SEUIL))) { axe_y = 512; } int sensibility = analogRead(A2); int sensibility_range = map(sensibility, 0, 1023, 5, 20); int pixel_x = map(axe_x, 0, 1023, -sensibility_range, sensibility_range); int pixel_y = map(axe_y, 0, 1023, sensibility_range, -sensibility_range); //Serial.print(pixel_x); //Serial.print(" "); //Serial.println(pixel_y); Mouse.move(pixel_x, pixel_y, 0); int contraction = analogRead(A5); Serial.println(contraction); //bouton.read(); // update button state // remplacement de bouton read par boutonset. // boutonset vaut 1 si la contraction est détecté , vaut 0 sinon. if (contraction > seuil) { bouton.set (1); } else { bouton.set (0); } if (bouton.hold()) { start_time = millis(); is_hold = 1; } if (is_hold and (millis() > HOLD_RIGHT_TIME + start_time)) { Mouse.press(); is_hold = 0; is_long_press = 1; } if (bouton.released()) { if (is_hold) { if (millis() < HOLD_RIGHT_TIME + start_time) { Mouse.click(MOUSE_RIGHT); } is_hold = 0; } else { if ((not is_long_press) and (not long_press_end)) { Mouse.click(); } } long_press_end = 0; } if (bouton.pressed() and is_long_press) { is_long_press = 0; long_press_end = 1; Mouse.release(); } delay(10); }
true
393f626a5e4867d933d5d713bc04ca08f86b78c3
C++
Gaurav-71/Ballot-Box
/V_INPUT.CPP
UTF-8
2,948
2.671875
3
[]
no_license
void captains :: getinfo() { gtype("\20",15+BLINK,6,14); gotoxy(10,14);char_chk(c1,10,14); gtype(" ",0,6,14); gtype("\20",15+BLINK,6,15); gotoxy(10,15);char_chk(c2,10,15); gtype(" ",0,6,15); gtype("\20",15+BLINK,6,16); gotoxy(10,16);char_chk(c3,10,16); gtype(" ",0,6,16); } void vice_captains :: getinfo() { gtype("\20",15+BLINK,28,14); gotoxy(32,14);char_chk(v1,32,14); gtype(" ",0,28,14); gtype("\20",15+BLINK,28,15); gotoxy(32,15);char_chk(v2,32,15); gtype(" ",0,28,15); gtype("\20",15+BLINK,28,16); gotoxy(32,16);char_chk(v3,32,16); gtype(" ",0,28,16); } void captains :: count(int ) { if(ch==1) { count1++; } else if(ch==2) { count2++; } else if(ch==3) { count3++; } } void vice_captains :: count(int ) { if(ch==1) { count1++; } else if(ch==2) { count2++; } else if(ch==3) { count3++; } } void captains :: name() { int c; gotoxy(12,12);cout<<cap.c1; gotoxy(12,13);cout<<cap.c2; gotoxy(12,14);cout<<cap.c3; } void c_input_n() { ofstream ofile; ofile.open(cnames); cap.getinfo(); ofile.write((char*)&cap,sizeof(cap)); ofile.close(); } void c_disp_n() { ifstream ifile; ifile.open(cnames,ios :: trunc); ifile.read((char*)&cap,sizeof(cap)); while(!ifile.eof()) { cap.name(); ifile.read((char*)&cap,sizeof(cap)); } ifile.close(); } void captains :: input_v() { ofstream ofile; ofile.open(cvotes,ios :: trunc); ofile<<count1<<endl; ofile<<count2<<endl; ofile<<count3<<endl; ofile.close(); } void c_disp_v() { ifstream ifile; ifile.open(cvotes); while(!ifile.eof()) { ifile>>cap.count1;gotoxy(42,12);cout<<cap.count1; ifile>>cap.count2;gotoxy(42,13);cout<<cap.count2; ifile>>cap.count3;gotoxy(42,14);cout<<cap.count3; } ifile.close(); } void vice_captains :: name() { gotoxy(12,16);cout<<vcap.v1; gotoxy(12,17);cout<<vcap.v2; gotoxy(12,18);cout<<vcap.v3; } void vc_input_n() { ofstream ofile; ofile.open(vcnames,ios :: trunc); vcap.getinfo(); ofile.write((char*)&vcap,sizeof(vcap)); ofile.close(); } void vc_disp_n() { ifstream ifile; ifile.open(vcnames); ifile.read((char*)&vcap,sizeof(vcap)); while(!ifile.eof()) { vcap.name(); ifile.read((char*)&vcap,sizeof(vcap)); } ifile.close(); } void vice_captains :: input_v() { ofstream ofile; ofile.open(vcvotes,ios :: trunc); ofile<<count1<<endl; ofile<<count2<<endl; ofile<<count3<<endl; ofile.close(); } void vc_disp_v() { ifstream ifile; ifile.open(vcvotes); while(!ifile.eof()) { ifile>>vcap.count1;gotoxy(42,16);cout<<vcap.count1; ifile>>vcap.count2;gotoxy(42,17);cout<<vcap.count2; ifile>>vcap.count3;gotoxy(42,18);cout<<vcap.count3; } ifile.close(); } void details(int z) { info(z); c_input_n(); vc_input_n(); gtype(" \4 Press Enter \4 ",15,34,24); getch(); clrscr(); } void disp_result(int z) { result(z); c_disp_v(); vc_disp_v(); c_disp_n(); vc_disp_n(); }
true
d2167e112a56fff1785ff15e35290030936a161c
C++
fangyoujun/PathFinding-by-PRM
/sources/grid.cpp
UTF-8
1,451
3.140625
3
[]
no_license
#include "grid.h" Grid::Grid() { for (int x = top_left_x; x < max_x; x+=edge) { for (int y = top_left_y; y < max_y; y+=edge) { Node* node = new Node(); GridNode[x/edge][y/edge] = *node; } } } vector<Node> Grid::neighbors(const Node& node) { std::vector<Node> neighbors; signed int node_id_x = node.x() / edge; signed int node_id_y = node.y() / edge; std::vector<vector<int> > Direction = {{1,0}, //left {1,1}, //left-bottom {0,1}, //bottom {-1,1}, //right-bottom {-1,0}, //right {-1,-1}, //right-up {0,-1}, //up {1,-1}}; //left-up for (vector<int> dir : Direction) { signed int id_x = node_id_x + dir[0]; signed int id_y = node_id_y + dir[1]; if (id_x >= 0 && id_x <= num_col-1 && id_y >= 0 && id_y <= num_row-1 && GridNode[id_x][id_y].walkable) neighbors.push_back(GridNode[id_x][id_y]); } return neighbors; } int Grid::cost(Node n1, Node n2) { return std::abs(n1.center().x()-n2.center().x()) + std::abs(n1.center().y()-n2.center().y()); }
true
4e37ea2346c377b58acaa2f8cc4f86b6e561c27a
C++
js2664118/StanleyJonathan_CSCCIS5_Spring2018
/Assignments/Assignment 6/Gaddis_8thEd_Ch8_Prob2_LotteryWinner/main.cpp
UTF-8
1,180
3.109375
3
[]
no_license
/* * File: main.cpp * Author: Jonathan Stanley * Created on March 15, 2018, 12:30 PM * Purpose: This is your template for your Mac */ //System Libraries Here #include <iostream> using namespace std; //User Libraries Here //Global Constants Only, No Global Variables //Like PI, e, Gravity, or conversions //Function Prototypes Here //Program Execution Begins Here int main(int argc, char** argv) { //Declare all Variables Here int num; //Users charge account number const int SIZE=10; //Size of the array int array[SIZE]={13579,26791,26792,33445,55555,62483, 77777,79422,85647,93121}; bool found=false; //flag when the value is found int elem=0; //Element in which the value is found //Input or initialize values Here cout<<"Enter this weeks winning numbers "; cin>>num; while (!found&&elem<SIZE){ if (array[elem]==num){ found=true; cout<<"You won the lottery!!!!! "<<endl; } elem++; } if (found==false)cout<<"Your number combinations did not match the" " winning lottery numbers"<<endl; //Exit return 0; }
true
84082c49ad7d64f5e11ef9a2b631302210e997c7
C++
ZackMisso/NailString
/stringpart.h
UTF-8
400
2.75
3
[]
no_license
#pragma once class StringPart { private: int startNail; int endNail; int endSide; public: StringPart(); StringPart(int sn, int en, int es); // getter methods int getStartNail(); int getEndNail(); int getEndSide(); // setter methods void setStartNail(int param); void setEndNail(int param); void setEndSide(int param); };
true