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
87a8555bc13bb33e69606a98e1fa9064c1ee2ff7
C++
FDunbar/Atna
/Homework/partnerproj_carrie-frankie.cpp
UTF-8
1,151
3.453125
3
[]
no_license
//Frankyln Dunbar & Carrie Navio #include <iostream> #include <cstdio> using namespace std; char morse [][10] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".--.-",".-.-", "---." }; //character sequence of morse code char text[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'W', 'Z'}; //character sequence of morse letters char *translatetomorse(char text []) {} char *translatetotext(char morse []) {} int main() { cout << "Input 1 for text to morse, Input 2 for morse to text" << endl; int choice; cin>>choice; char message[1000]; cout << "Input your message por favor" << endl; gets(message); char *answer; switch(choice){ case 1: answer = translatetomorse(message); break; case 2 : answer = translatetotext(message); break; default : cout<< "Enter something else man" << endl; } return 0; }
true
d4a2523791fcf8b1f40d3800e148c1b69890fef3
C++
boris-ns/DiscreteCosineTransform
/DiscreteCosineTransform/Utils.h
UTF-8
580
2.96875
3
[]
no_license
#pragma once #include "Transform.h" /* Resizes (creates NxN) matrices. */ void ResizeMatrix(Matrix& matrix, size_t size); /* Prints matrix to the console. */ void PrintMatrix(const Matrix& matrix); /* Fills up matrix w/ random elements. */ void CreateMatrixWithRandomElements(Matrix& mat); /* Writes matrix to file. */ void WriteMatrixToFile(const Matrix& matrix, const std::string& path); /* Loads matrix from file. */ void LoadMatrixFromFile(Matrix& matrix, const std::string& path); /* Compares two matrices. */ bool CompareMatrices(const Matrix& m1, const Matrix& m2);
true
28c09a345ca10c07162b10bb360da5bdf8587d4c
C++
harshchan/compi-coding-snippets
/array_merge.cpp
UTF-8
566
2.671875
3
[]
no_license
#include<iostream> #include<conio.h> #include<stdlib.h> #include <bits/stdc++.h> // #include<unordered_set> using namespace std; main() { set <int> S; vector<int> Inter; int A[]={1, 2, 3, 4, 5}; int B[]={1,2,3,6,7}; int siz=S.size(); int i; for(i=0;i<5;i++) { S.insert(A[i]); if(siz==S.size()) { Inter.push_back(A[i]); } else siz=S.size(); } for(i=0;i<5;i++) { S.insert(B[i]); if(siz==S.size()) { Inter.push_back(B[i]); } else siz=S.size(); } cout<<S.size()<<" "<<Inter.size(); return 0; }
true
f6a4c4dcf2ca1b605600ee41c7b1949506ebc544
C++
eelfgnc/Object-Oriented-Programming1-Lab.
/Lab 03/Random Number Generator/RandomNumberGenerator.cpp
UTF-8
4,694
3.5625
4
[]
no_license
#include "RandomNumberGenerator.h" #include <time.h> #include<cmath> #include <iostream> using namespace std; RandomNumberGenerator::RandomNumberGenerator() { srand(time(NULL)); } RandomNumberGenerator::~RandomNumberGenerator() { } int RandomNumberGenerator::getRandomInteger(int lowerBound, int upperBound) { return lowerBound + rand() % (upperBound - lowerBound + 1); } /** * \brief Kullanicinin girdigi maksimum ve minimum sayilar arasindan uretilen rastgele float sayinin hassasitini ayarlayan fonksiyon * \brief Float sayilar uretebilmek icin oncelikle maksimum ve minimum sayilarimizi pow(10,precision+1) ile carpariz ve rand fonksiyonunun buldugu tam sayiyi pow(10,precision+1) ile bolerek ondalikli bir sayi elde ederiz. * \param lowerBound: Uretilecek float sayinin minimum degeri * \param upperBound: Uretilecek float sayinin maksimum degeri * \param precision: Virgulden sonra kac basamak oldugu gosteren deger */ float RandomNumberGenerator::getRandomFloat(float lowerBound, float upperBound, Precision precision) { int min, max; float random; if (precision == Precision::ONE) { min = lowerBound * pow(10, precision + 1); max = upperBound * pow(10, precision + 1); random = min + rand() % (max - min + 1); return (float)random / pow(10, precision + 1); } else if (precision == Precision::TWO) { min = lowerBound * pow(10, precision + 1); max = upperBound * pow(10, precision + 1); random = min + rand() % (max - min + 1); return (float)random / pow(10, precision + 1); } else if (precision == Precision::THREE) { min = lowerBound * pow(10, precision + 1); max = upperBound * pow(10, precision + 1); random = min + rand() / (max - min + 1); return (float)random / pow(10, precision + 1); } else if (precision == Precision::FOUR) { min = lowerBound * pow(10, precision + 1); max = upperBound * pow(10, precision + 1); random = min + rand() % (max - min + 1); return (float)random / pow(10, precision + 1); } } /** * \brief Kullanicinin girdigi maksimum ve minimum sayilar arasindan uretilen rastgele double sayinin hassasitini ayarlayan fonksiyon * \brief Double sayilar uretebilmek icin oncelikle maksimum ve minimum sayilarimizi pow(10,precision+1) ile carpariz ve rand fonksiyonunun buldugu sayiyi pow(10,precision+1) ile bolerek elde ederiz. * \param lowerBound: Uretilecek double sayinin minimum degeri * \param upperBound: Uretilecek double sayinin maksimum degeri * \param precision: Virgulden sonra kac basamak oldugu gosteren deger */ double RandomNumberGenerator::getRandomDouble(double lowerBound, double upperBound, Precision precision) { int min, max; double random; if (precision == Precision::ONE) { min = lowerBound * pow(10,precision+1); max = upperBound * pow(10, precision + 1); random = min + rand() % (max - min + 1); return (double)random / pow(10, precision + 1); } else if (precision == Precision::TWO) { min = lowerBound * pow(10, precision + 1); max = upperBound * pow(10, precision + 1); random = min + rand() % (max - min + 1); return (double)random / pow(10, precision + 1); } else if (precision == Precision::THREE) { min = lowerBound * pow(10, precision + 1); max = upperBound * pow(10, precision + 1); random = min + rand() / (max - min + 1); return (double)random / pow(10, precision + 1); } else if (precision == Precision::FOUR) { min = lowerBound * pow(10, precision + 1); max = upperBound * pow(10, precision + 1); random = min + rand() % (max - min + 1); return (double)random / pow(10, precision + 1); } } /** * \brief Kullanicinin girdigi parametre degerlerine gore rastgele buyuk harf, kucuk harf veya rakam ureten fonksiyon * \brief Eger kullanici buyuk harf isterse buyuk harflerin asci koduna bakarsak 65 ve 90 arasinda degistigini gozlemleriz.Rand fonskiyonunu kullanirken kullandigimiz sayi araligi bu sayilar olur. * \brief Kucuk harflerin asci tablosundaki degerleri ise 97 ve 122 sayilari arasinda degisir.Yine rand fonksiyonunun sayi araligi bu sayilar olur. * \brief Kullanici CharacterType olarak DIGIT isterse kullaniciya sadece rastgele elde edilen rakamlar gonderilir. * \param characterType: Kullanicinin istedigi random sayi turu (Buyuk harfler, Kucuk harfler, Rakamlar) */ char RandomNumberGenerator::getRandomCharacter(CharacterType characterType) { if (characterType == CharacterType::UPPER_LETTER) { return 65 + rand() % (90 - 65 + 1); } else if (characterType == CharacterType::LOWER_LETTER ) { return 97 + rand() % (122 - 97 + 1); } else if (characterType == CharacterType::DIGIT) { return rand() % 10; } }
true
8a96e66f8d8272495b44bffbe79661681ce10623
C++
vxp768/coding_practice
/sliding_window/max_sum_subarray_size_K.cpp
UTF-8
1,234
4.1875
4
[]
no_license
/* Given an array of integers and a number k, find maximum sum of a subarray of size k. Input : arr[] = {100, 200, 300, 400} k = 2 Output : 700 */ // Returns maximum sum in a subarray of size k. int maxSum(int arr[], int n, int k) { // k must be greater if (n < k) { cout << "Invalid"; return -1; } // Compute sum of first window of size k int res = 0; for (int i=0; i<k; i++) res += arr[i]; // Compute sums of remaining windows by removing first element of previous // window and adding last element of current window. int curr_sum = res; for (int i=k; i<n; i++) { curr_sum += arr[i] - arr[i-k]; res = max(res, curr_sum); } return res; } /* * Given an integer array nums, find the contiguous subarray (containing at least one number) * which has the largest sum and return its sum. * Window is not defined */ class Solution { public: int maxSubArray(vector<int>& nums) { int sum = nums[0]; int max_sum = sum; for(int i=1; i<nums.size(); i++){ sum = max(sum + nums[i], nums[i]); max_sum = max(max_sum, sum); } return max_sum; } };
true
b5c0b1ba71d39401b45f7cf4df39a857b65fc044
C++
clintgeek/churchStageLightController
/helperFunctions.ino
UTF-8
2,364
2.609375
3
[ "MIT" ]
permissive
void welcomeMessage() { screenPrinter("First Methodist", "Mansfield"); powerOnSelfTest(); } String findModeName(int mode) { return String(modes[mode]); } void dispalyRgbVals(int rgbVals[3]) { lcd.setCursor(0,1); lcd.print(" "); lcd.setCursor(0,1); lcd.print("R" + String(rgbVals[0])); lcd.setCursor(6,1); lcd.print("G" + String(rgbVals[1])); lcd.setCursor(12,1); lcd.print("B" + String(rgbVals[2])); } void displayMode() { displayMode(solidColor); } void displayMode(int rgbVals[3]) { if (mode < 1) { screenPrinter("LEFT or RIGHT", "to select mode"); } else { screenPrinter(findModeName(mode),""); dispalyRgbVals(rgbVals); } } void displayPotentialMode() { potentialModeStart = currentMillis; screenPrinter("Press SELECT for:", findModeName(potentialMode)); } void screenPrinter(String line1, String line2) { debugPrinter("LCD Updated", 1); lcd.clear(); lcd.print(line1); lcd.setCursor(0,1); lcd.print(line2); } void backlightDimmer() { bool shouldDim = ((currentMillis - backlightStart) > backlightTimeout); if (shouldDim) { analogWrite(LCDLED, 10); } } void backlightOn() { backlightStart = currentMillis; analogWrite(LCDLED, 255); } bool continueMode (int checkMode) { if (checkMode == mode && potentialMode == 255) { return true; } else { return false; } } void threadSafeDelay(int min, int max) { int totalDelay = random(min, max); threadSafeDelay(totalDelay); } void threadSafeDelay(int duration) { for (int delayCounter = 0; delayCounter < duration; delayCounter++) { loop(); delay(1); } } void debugPrinter(String title, int blankLines) { if (debug) { Serial.println(title); for (int i=0; i < blankLines; i++) { Serial.println(); } } } void debugPrinter(String title, int value, int blankLines) { if (debug) { Serial.print(title); Serial.println(value); for (int i=0; i < blankLines; i++) { Serial.println(); } } } void debugPrinter(String title, char* value, int blankLines) { if (debug) { Serial.print(title); int x = 0; while (true) { if (value[x] == '\n') { Serial.println(); break; } else { Serial.print(value[x]); x++; } } for (int i=0; i < blankLines; i++) { Serial.println(); } } }
true
4b6d54e8f8d3cc5f46ae07e9745b16746cbc4916
C++
nabetani/qiita-scribbles
/2019.03/memptr/hoge.cpp
UTF-8
726
3.078125
3
[ "Apache-2.0" ]
permissive
#include <cstddef> #include <ctime> #include <iostream> void show_sec(){ auto timer = std::time(NULL); auto local = localtime(&timer); std::cout << local->tm_sec << std::endl; } void show_min(){ auto timer = std::time(NULL); auto local = localtime(&timer); std::cout << local->tm_min << std::endl; } void show_xxx( int tm::*member ){ auto timer = std::time(NULL); auto local = localtime(&timer); std::cout << local->*member << std::endl; } void use_show_xxx(void){ show_xxx(&tm::tm_sec); } int main(int argc, char const * argv[]) { use_show_xxx(); if ( 1<argc && argv[1][0]=='1' ){ show_sec(); show_xxx(&tm::tm_sec); } else { show_min(); show_xxx(&tm::tm_min); } return 0; }
true
1f079f79928b6b40fed240862cd4643a60b3a8eb
C++
J-eno/Coursework
/435 - Computer Graphics/Proj3-SimpleRasterizer/geometry.cpp
UTF-8
5,381
3.09375
3
[]
no_license
//Implementation for Geometry Classes #include "geometry.h" Geometry::Geometry() { //Empty because abstract } Geometry::~Geometry() { //also empty because we won't manually delete these } void Geometry::SetColor(double r, double g, double b) { m_color << r,g,b; } Eigen::Vector3d Geometry::GetColor() { return m_color; } double Geometry::GetT() { return m_tValue; } void Geometry::setMaterials(double kd, double ks, double e, double kt, double it) { m_kd = kd; m_ks = ks; m_e = e; m_kt = kt; m_it = it; } //============================================ //Polygon Class //============================================ Polygon::Polygon() { //it's here } Polygon::Polygon(double r, double g, double b, double numVertices, bool Phong) { m_phong = Phong; Init(r,g,b,numVertices); } void Polygon::Init(double r, double g, double b, double numVertices) { SetColor(r,g,b); if(numVertices > 3) { m_isConcave = true; } } //reset polygon data void Polygon::Clear() { m_vertices.clear(); m_isConcave = false; } //Turn polygon with more than 3 points into triangles vector<Polygon> Polygon::Triangularize() { int i = 1; while(i <= m_vertices.size() - 2) { Polygon *newTri = new Polygon(m_color[0], m_color[1], m_color[2], 3, m_phong); newTri->setMaterials(m_kd, m_ks, m_e, m_kt, m_it); newTri->AddVertex(m_vertices[0]); newTri->AddVertex(m_vertices[i]); newTri->AddVertex(m_vertices[i+1]); if(!m_normals.empty()) { newTri->AddNormal(m_normals[0]); newTri->AddNormal(m_normals[i]); newTri->AddNormal(m_normals[i+1]); } newTri->SetNormal(); for(int i = 0; i < 3; i++) { newTri->m_normals.push_back(newTri->m_normal); } newTris.push_back(*newTri); i++; } return newTris; } void Polygon::AddVertex(Eigen::Vector3d vertex) { m_vertices.push_back(vertex); } void Polygon::AddScreenVertex(Eigen::Vector4d vertex) { m_screenVertices.push_back(vertex); } void Polygon::AddNormal(Eigen::Vector3d normal) { m_normals.push_back(normal); } void Polygon::SetNormal() { Eigen::Vector3d v0 = m_vertices[0]; Eigen::Vector3d v1 = m_vertices[1]; Eigen::Vector3d v2 = m_vertices[2]; //normal = cross product of two edges m_normal = (v1 - v0).cross(v2 - v0); m_normal.normalize(); //cout << "Normal " << m_normal << endl; } void Polygon::SetPhongNormal(double alpha, double beta, double gamma) { Eigen::Vector3d n0 = m_normals[0]; Eigen::Vector3d n1 = m_normals[1]; Eigen::Vector3d n2 = m_normals[2]; m_normal = alpha*n0 + beta*n1 + gamma*n2; m_normal.normalize(); } double Polygon::cross2d(Eigen::Vector2d x, Eigen::Vector2d y) { return x[0]*y[1]-x[1]*y[0]; } Eigen::Vector2d Polygon::project(Eigen::Vector3d x, int projectDir) { switch (projectDir) { case 0: return Eigen::Vector2d(x[1],x[2]); case 1: return Eigen::Vector2d(x[0],x[2]); case 2: return Eigen::Vector2d(x[0],x[1]); } return Eigen::Vector2d(1.0, 1.0); } //=============================================================== // LIGHT CLASS //=============================================================== Light::Light() { } Light::Light(Eigen::Vector3d position, Eigen::Vector3d color) { m_position = position; m_color = color; } //=============================================================== // SPHERE CLASS //=============================================================== /* Sphere:: Sphere() { } Sphere::Sphere(double r, double g, double b, double x, double y, double z, double radius) { Init(r,g,b,x,y,z,radius); } void Sphere::Init(double r, double g, double b, double x, double y, double z, double radius) { SetColor(r,g,b); SetCenter(x,y,z); SetRadius(radius); } void Sphere::Clear() { } void Sphere::SetCenter(double x, double y, double z) { m_center << x, y, z; } Eigen::Vector3d Sphere::GetCenter() { return m_center; } void Sphere::SetRadius(double radius) { m_radius = radius; } double Sphere::GetRadius() { return m_radius; } bool Sphere::Intersect(Ray ray, double tMin, double tMax, HitRecord &hr) { //a(t)^2 + b(t) + c = 0 //a = ray.directionDOTray.direction //b = 2ray.directionDOTray.origin - center //c = (origin-centerDOTorigin-center) - radius squared double a = 1; double b = (2*ray.GetDirection()).dot(ray.GetEye() - m_center); double c = (ray.GetEye() - m_center).dot(ray.GetEye() - m_center) - (m_radius*m_radius); double discriminant = b*b - 4*a*c; if(discriminant < 0) { return false; } double t0; double t1; if(discriminant == 0) { t0 = -(b/2*a); t1 = -(b/2*a); } else { t0 = (-b-sqrt(discriminant))/(2*a); t1 = (-b+sqrt(discriminant))/(2*a); } //If neither t is in our t-range (behind camera) return false if((t0 < tMin || t0 > tMax) && (t1 < tMin || t1 > tMax)) { return false; } //If t0 is in range but t1 is out of range, use t0 if((t0 >= tMin && t0 <= tMax) && (t1 < tMin || t1 > tMax)) { m_tValue = t0; } //If t1 is in range but t0 is out of range, use t1 if((t1 >= tMin && t1 <= tMax) && (t0 < tMin || t0 > tMax)) { m_tValue = t1; } //If both, use smallest if((t0 >= tMin && t0 <= tMax) && (t1 >= tMin || t1 <= tMax)) { m_tValue = fmin(t0,t1); } return true; } */
true
e724ffe8827b9bbb3b4ecf9722754a25efd5032e
C++
ArvinZJC/BUAAHND_G2T1_C-
/L3/L3_3.cpp
UTF-8
664
4.09375
4
[]
no_license
// L3.pdf, P42, program that shows the level of an integer grade #include <iostream> using namespace std; int main() { int grade; cout << "Enter an integer grade between 0 and 100: "; cin >> grade; // loop until a proper integer grade is entered while (grade < 0 || grade > 100) { cout << "Error! Please enter again: "; cin >> grade; } // end while cout << endl; switch (grade / 10) { case 10: case 9: cout << "A" << endl; break; case 8: cout << "B" << endl; break; case 7: cout << "C" << endl; break; case 6: cout << "D" << endl; break; default: cout << "F" << endl; } // end switch-case return 0; } // end main
true
54f357aa16b292adb53b71b5f7235577ac454cef
C++
gianricardo/smart
/src/ExprLib/dd_front.h
UTF-8
15,306
2.84375
3
[ "Apache-2.0" ]
permissive
#ifndef DD_FRONT_H #define DD_FRONT_H #include "exprman.h" class shared_state; // ****************************************************************** // * * // * sv_encoder class * // * * // ****************************************************************** /** Abstract class for building decision diagrams. Allows for a generic "encoding" of model state variables into decision diagram variables, and construction of DDs without knowing library details. This should work with CUDD, our library, or pretty much anything. */ class sv_encoder : public shared_object { public: /// Error codes, thrown as exceptions enum error { /// Bad parameter somewhere. Invalid_Edge, #ifdef DEVELOPMENT_CODE /// Output parameter should not be modified. Shared_Output_Edge, #endif /// Library returned an out of memory error. Out_Of_Memory, /// Operation failed because this encodes the empty set Empty_Set, /// Generic failure. Failed }; /** Produce a "human-readable" name for an error. @param e The engine error. @return A string constant. */ static const char* getNameOfError(error e); public: /// Simple constructor. sv_encoder(); protected: /// Virtual destructor. virtual ~sv_encoder(); public: // Required for shared_object: virtual bool Print(OutputStream &s, int width) const; virtual bool Equals(const shared_object *o) const; /** For debugging, display the current node information. @param s Output stream to write to @param e Edge pointer @throws An error, as appropriate */ virtual void dumpNode(OutputStream &s, shared_object* e) const = 0; /** For debugging, and displaying the internal representation. Display the graph rooted at the given node. */ virtual void showNodeGraph(OutputStream &s, shared_object* e) const = 0; /** For debugging, display the current "forest". Might not be supported for all backends. @param s Output stream to write to. */ virtual void dumpForest(OutputStream &s) const = 0; /** Does the forest separate primed from unprimed vars? This affects numbering. If false, then primed and unprimed vars are mixed together. If there are NO primed variables, then TBD: does it matter? */ virtual bool arePrimedVarsSeparate() const = 0; /** Get the number of variables in the decision diagram forest. If arePrimedVarsSeparate() returns true, then this returns the number of primed variables, which is assumed to equal the number of unprimed variables. */ virtual int getNumDDVars() const = 0; /** Build a blank "edge" for this encoder. Can be used later for any parameter that needs an edge. @param e If nonzero, the new edge will be copied from \a e. @return An empty wrapper. */ virtual shared_object* makeEdge(const shared_object* e) = 0; /** Is this a valid edge for this encoder? @param e An edge, should have been created by makeEdge(). @return true iff it is a valid edge */ virtual bool isValidEdge(const shared_object* e) const = 0; /** Copy one edge to another. @param src Source edge. @param dest Destination edge. @throws Appropriate error code. */ virtual void copyEdge(const shared_object* src, shared_object* dest) const = 0; /** Build the "symbolic" representation for a given boolean constant. @param t Boolean constant @param answer An edge for storing the result, should have been created by makeEdge(). @throws Appropriate error code. */ virtual void buildSymbolicConst(bool t, shared_object* answer) = 0; /** Build the "symbolic" representation for a given boolean constant. @param t Integer constant @param answer An edge for storing the result, should have been created by makeEdge(). @throws Appropriate error code. */ virtual void buildSymbolicConst(long t, shared_object* answer) = 0; /** Build the "symbolic" representation for a given boolean constant. @param t Real constant @param answer An edge for storing the result, should have been created by makeEdge(). @throws Appropriate error code. */ virtual void buildSymbolicConst(double t, shared_object* answer) = 0; /** Build the "symbolic" representation for f(sv), where sv is a state variable (possibly "primed"), and f is an expression depending on sv. @param sv A model state variable @param primed Do we want the primed or unprimed version? @param f Expression to evaluate on sv; if 0, we assume the identity function. @param answer An edge for storing the result, should have been created by makeEdge(). @throws Appropriate error code. */ virtual void buildSymbolicSV(const symbol* sv, bool primed, expr* f, shared_object* answer) = 0; /** Convert a state to a "minterm" (path in DD). Depends on choice of "variable encoding". @param s A model state. @param mt An array of dimension (#levels+1), minterm will be written here. @throws Appropriate error code. */ virtual void state2minterm(const shared_state* s, int* mt) const = 0; /** Convert a "minterm" (path in DD) to a state. Inverse operation of \a state2minterm(). Used to convert from state representation to DD representation, which of course depends on the choice of "encoding". @param mt Minterm. Array of dimension (#levels+1) of (unprimed) variable assignments. @param s Output: corresponding state. Must be allocated already. @throws Appropriate error code. */ virtual void minterm2state(const int* mt, shared_state *s) const = 0; /** Find the "first" element in a set. @param set The set we care about. @return The first minterm in the set, or 0 on error or if this is the empty set. */ virtual const int* firstMinterm(shared_object* set) const = 0; /** Find the "next" element in a set. \a firstMinterm() must be called before calling this method. Behavior is undefined if the set has been changed since calling \a firstMinterm(). @param set The set we care about. @return The first minterm in the set, or 0 on error or if there are no more minterms. */ virtual const int* nextMinterm(shared_object* set) const = 0; /** Convert a set of "minterms" to a set, encoded as a DD. @param mts Minterms to add. Array of arrays of dimension (#levels+1) of (unprimed) variable assignments. @param n Number of minterms. @param ans Set of minterms encoded as a DD. @throws Appropriate error code. */ virtual void createMinterms(const int* const* mts, int n, shared_object* ans) = 0; /** Convert a set of "minterms" to a set of edges, encoded as a DD. @param from From states. Array of arrays of dimension (#levels+1) of unprimed variable assignments. @param to To states. Array of arrays of dimension (#levels+1) of primed variable assignments. @param n Number of minterms. @param ans Set of edges encoded as a DD. @throws Appropriate error code. */ virtual void createMinterms(const int* const* from, const int* const* to, int n, shared_object* ans) = 0; /** Convert a set of "minterms" and values to a matrix, encoded as a DD. @param from From states. Array of arrays of dimension (#levels+1) of unprimed variable assignments. @param to To states. Array of arrays of dimension (#levels+1) of primed variable assignments. @param values Array of values. @param n Number of minterms. @param ans Set of edges encoded as a DD. @throws Appropriate error code. */ virtual void createMinterms(const int* const* from, const int* const* to, const float* values, int n, shared_object* ans) = 0; /** Build a unary operation on a DD node. @param op Unary operation requested. @param opnd Operand, as a wrapper around a DD node. @param ans An edge for storing the result, should have been created by makeEdge(). Can be the same pointer as \a opnd. @throws Appropriate error code. */ virtual void buildUnary(exprman::unary_opcode op, const shared_object* opnd, shared_object* ans) = 0; /** Build a binary operation on DD nodes. @param left Left operand. @param op Binary operation requested. @param right Right operand. @param ans An edge for storing the result, should have been created by makeEdge(). Can be the same pointer as \a left or \a right. @throws Appropriate error code. */ virtual void buildBinary(const shared_object* left, exprman::binary_opcode op, const shared_object* right, shared_object* ans) = 0; /** Build an associative operation on two DD nodes. @param left Left operand. @param flip Should the operator be inverted. @param op Associative operator. @param right Right operand. @param ans An edge for storing the result, should have been created by makeEdge(). Can be the same pointer as \a left or \a right. @throws Appropriate error code. */ virtual void buildAssoc(const shared_object* left, bool flip, exprman::assoc_opcode op, const shared_object* right, shared_object* ans) = 0; /** Determine the cardinality of a DD node. Normally that means the number of minterms that lead to a non-default function value. If the DD node represents a set, then it gives the cardinality of the set. @param x Set to determine. @param card Output: set cardinality; will be negative on overflow. @throws Appropriate error code. */ virtual void getCardinality(const shared_object* x, long &card) = 0; /** Determine the (approximate) cardinality of a DD node. @param x Set to determine. @param card Output: set cardinality; will be INF on overflow. @throws Appropriate error code. */ virtual void getCardinality(const shared_object* x, double &card) = 0; /** Determine the cardinality of a DD node. @param x Set to determine. @param card Output: set cardinality, as a bigint. @throws Appropriate error code. */ virtual void getCardinality(const shared_object* x, result &card) = 0; /** Determine if a DD node represents the empty set. @param x Set to determine @param empty Output: true iff set x is empty @throws Appropriate error code */ virtual void isEmpty(const shared_object* x, bool &empty) = 0; /** Pre-image operator. For a given set of states x and edges E, return the set of states with an edge to a state in x. @param x Target states; within this forest. @param E Set of edges; must be "compatible" with this forest. @param ans Output: source states; within this forest. @throws Appropriate error code. */ virtual void preImage(const shared_object* x, const shared_object* E, shared_object* ans) = 0; /** Post-image operator. For a given set of states x and edges E, return the set of states that can be reached by following an edge from a state in x. @param x Source states; within this forest. @param E Set of edges; must be "compatible" with this forest. @param ans Output: target states; within this forest. @throws Appropriate error code. */ virtual void postImage(const shared_object* x, const shared_object* E, shared_object* ans) = 0; /** Backward reachability operator. Reflexive and transitive closure of the Pre-image operator. @param x Target states; within this forest. @param E Set of edges; must be "compatible" with this forest. @param ans Output: source states; within this forest. @throws Appropriate error code. */ virtual void preImageStar(const shared_object* x, const shared_object* E, shared_object* ans) = 0; /** Forward reachability operator. Reflexive and transitive closure of the Post-image operator. @param x Source states; within this forest. @param E Set of edges; must be "compatible" with this forest. @param ans Output: target states; within this forest. @throws Appropriate error code. */ virtual void postImageStar(const shared_object* x, const shared_object* E, shared_object* ans) = 0; /** Restrict first element in a relation. @param E Set of edges (e, e'); within this forest. @param rows Set of desired "rows"; must be "compatible" with this forest. @param ans Output: new set of edges equal to E & (rows X all); within this forest. @throws Appropriate error code. */ virtual void selectRows(const shared_object* E, const shared_object* rows, shared_object* ans) = 0; /** Restrict second element in a relation. @param E Set of edges (e, e'); within this forest. @param cols Set of desired "columns"; must be "compatible" with this forest. @param ans Output: new set of edges equal to E & (all X cols); within this forest. @throws Appropriate error code. */ virtual void selectCols(const shared_object* E, const shared_object* cols, shared_object* ans) = 0; /// Report stats virtual void reportStats(OutputStream &out) = 0; }; #endif
true
ba8cf8818cb6d3e7786889f2759d97ff3ffe3598
C++
Falmouth-Games-Academy/comp270-worksheet-D
/comp270-worksheet-D/Matrix2D.cpp
UTF-8
809
3.5625
4
[]
no_license
#include "stdafx.h" #include "Matrix2D.h" // Sets this matrix to represent a rotation and a translation, // so as to move a point in world space (rotation is performed first). void Matrix2D::setTransform(Point2D translation, float rotation) { Matrix2D transMat; transMat.m_[0][2] = translation.x; transMat.m_[1][2] = translation.y; Matrix2D rotMat; rotMat.m_[0][0] = rotMat.m_[1][1] = cos(rotation); rotMat.m_[1][0] = sin(rotation); rotMat.m_[0][1] = -rotMat.m_[1][0]; *this = transMat * rotMat; } // Multiplies the components of a point/vector void Matrix2D::multiply(float & x, float & y, float & w) const { float x_ = m_[0][0] * x + m_[0][1] * y + m_[0][2] * w, y_ = m_[1][0] * x + m_[1][1] * y + m_[1][2] * w, w_ = m_[2][0] * x + m_[2][1] * y + m_[2][2] * w; x = x_; y = y_; w = w_; }
true
7193e9a4bd8fae9f6fcda3088abdbbda82015fc1
C++
ErenO/Piscine-CPP
/d03/ex01/main.cpp
UTF-8
2,589
2.5625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: eozdek <eozdek@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/10/05 08:56:28 by eozdek #+# #+# */ /* Updated: 2017/10/05 11:27:07 by eozdek ### ########.fr */ /* */ /* ************************************************************************** */ #include <iostream> #include "FragTrap.hpp" #include "ScavTrap.hpp" int main() { FragTrap *a = new FragTrap("a"); FragTrap *b = new FragTrap("b"); std::cout << "FragTrap" << std::endl; a->rangedAttack("b"); b->rangedAttack("a"); a->takeDamage(30); std::cout << "Hit points " << a->getHitPts() << std::endl; a->takeDamage(30); std::cout << "Hit points " << a->getHitPts() << std::endl; a->takeDamage(30); std::cout << "Hit points " << a->getHitPts() << std::endl; a->takeDamage(30); std::cout << "Hit points " << a->getHitPts() << std::endl; a->takeDamage(30); std::cout << "Hit points " << a->getHitPts() << std::endl; b->meleeAttack("a"); a->vaulthunter_dot_exe("a"); a->vaulthunter_dot_exe("a"); a->beRepaired(20); std::cout << "Hit points " << a->getHitPts() << std::endl; delete(a); delete(b); std::cout << "ScavTrap" << std::endl; ScavTrap *c = new ScavTrap("c"); ScavTrap *d = new ScavTrap("d"); c->rangedAttack("d"); d->rangedAttack("b"); c->takeDamage(30); std::cout << "Hit points " << c->getHitPts() << std::endl; c->takeDamage(30); std::cout << "Hit points " << c->getHitPts() << std::endl; c->takeDamage(30); std::cout << "Hit points " << c->getHitPts() << std::endl; c->takeDamage(30); std::cout << "Hit points " << c->getHitPts() << std::endl; c->takeDamage(30); std::cout << "Hit points " << c->getHitPts() << std::endl; d->meleeAttack("c"); c->challengeNewcomer("d"); c->challengeNewcomer("d"); c->beRepaired(20); std::cout << "Hit points " << c->getHitPts() << std::endl; delete(c); delete(d); return (0); }
true
3f73d26de9d7ba932be943e1da1c13b74901389b
C++
admiswalker/i-am-learning-coding
/AtCoder/abc_109/main_b.cpp
UTF-8
1,570
2.546875
3
[]
no_license
//#define _GLIBCXX_DEBUG #include <bits/stdc++.h> using namespace std; typedef int64_t int64; typedef uint32_t uint; typedef uint64_t uint64; //--- template <typename T> inline void print(const T& rhs){ std::cout<<" = "<<rhs<<std::endl; } template <typename T> inline void print(const std::vector<T>& rhs){ std::cout<<" = [ "; for(uint i=0; i<rhs.size(); ++i){ std::cout<<rhs[i]<<' '; } std::cout<<"]"<<std::endl; } template <typename T> inline void print(const std::vector<std::vector<T>>& rhs){ std::cout<<" = "<<std::endl; std::cout<<"[[ "; for(uint p=0; p<rhs.size(); ++p){ if(p!=0){ std::cout<<" [ "; } for(uint q=0; q<rhs[p].size(); ++q){ std::cout<<rhs[p][q]<<' '; } if(p!=rhs.size()-1){ std::cout<<"]"<<std::endl; } } std::cout<<"]]"<<std::endl; } #define printn(var) {printf("%s", #var);print(var);} #define printn_all(var) {printf("%s(%d): ", __func__, __LINE__);printf("%s", #var);print(var);} //--- int main(){ // ios_base::sync_with_stdio(false); // cin.tie(NULL); unordered_map<string, int> ht; int N; cin >> N; vector<string> vS(N); for(int i=0; i<N; ++i){ cin >> vS[i]; } string s_prev=""; for(int i=0; i<N; ++i){ string s=vS[i]; if(i!=0 && s[0] != s_prev[s_prev.size()-1]){ cout << "No" << endl; return 0; } auto itr = ht.find( s ); if(itr!=ht.end()){ cout << "No" << endl; return 0; } ht.insert({s, 1}); s_prev = s; } cout << "Yes" << endl; return 0; }
true
7459d4c4b3c7c92915ccb42cfae8968e2a6af9f6
C++
rbiegelmeyer/esp8266_example_WPS
/esp8266_example_WPS.ino
UTF-8
1,508
2.78125
3
[]
no_license
// Test for ESP8266 WPS connection. #include <ESP8266WiFi.h> void setup() { Serial.begin(115200); pinMode(12, INPUT_PULLUP); pinMode(14, INPUT_PULLUP); } void connectWPS(){ // WPS works in STA (Station mode) only. WiFi.mode(WIFI_STA); delay(100); // Called to check if SSID and password has already been stored by previous WPS call. // The SSID and password are stored in flash memory and will survive a full power cycle. // Calling ("",""), i.e. with blank string parameters, appears to use these stored values. WiFi.begin("",""); // Long delay required especially soon after power on. delay(3000); // Check if WiFi is already connected and if not, begin the WPS process. if (WiFi.status() != WL_CONNECTED) { Serial.println("\nAttempting connection ..."); WiFi.beginWPSConfig(); // Another long delay required. delay(5000); if (WiFi.status() == WL_CONNECTED) { Serial.println("Connected!"); Serial.println(WiFi.localIP()); Serial.println(WiFi.SSID()); Serial.println(WiFi.macAddress()); } else { Serial.println("Connection failed!"); } } else { Serial.println("\nConnection already established."); } } void teste(){ WiFi.begin("Qualquer coisa","CoisaQualquer"); delay(1000); Serial.println("Connection lost!"); } void loop() { // put your main code here, to run repeatedly: if (!digitalRead(12)) connectWPS(); else if (!digitalRead(14)) teste(); }
true
79229bd701e2e5037574b702faa636c24538b2b1
C++
icgw/practice
/LeetCode/C++/0268._Missing_Number/example.cpp
UTF-8
281
2.65625
3
[ "MIT" ]
permissive
#include <iostream> #include "solution.hpp" void run_example() { Solution s; vector<int> nums1 { 3, 0, 1 }; std::cout << s.missingNumber(nums1) << std::endl; vector<int> nums2 { 9, 6, 4, 2, 3, 5, 7, 0, 1 }; std::cout << s.missingNumber(nums2) << std::endl; }
true
4deeb1d606052dfc9daeedb00dfb6f5f65cf9c28
C++
MarkOates/hexagon
/tests/Hexagon/AdvancedCodeEditor/SelectionTest.cpp
UTF-8
8,646
2.921875
3
[]
no_license
#include <gtest/gtest.h> #include <Hexagon/AdvancedCodeEditor/Selection.hpp> #include <Hexagon/Testing/Comparison/Hexagon/AdvancedCodeEditor/Selection.hpp> #define EXPECT_THROW_WITH_MESSAGE(code, raised_exception_type, expected_exception_message) \ try { code; FAIL() << "Expected " # raised_exception_type; } \ catch ( raised_exception_type const &err ) { EXPECT_EQ(std::string(expected_exception_message), err.what()); } \ catch (...) { FAIL() << "Expected " # raised_exception_type; } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, can_be_created_without_blowing_up) { Hexagon::AdvancedCodeEditor::Selection selection; } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, selection__is_a_constructor_arg_and_has_a_getter) { std::vector<CodeRange> code_ranges = { CodeRange{4, 5, 10, 6} }; Hexagon::AdvancedCodeEditor::Selection selection(code_ranges); EXPECT_EQ(code_ranges, selection.get_code_ranges()); } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, find_next_from__with_no_code_ranges__returns_the_cursor_location_that_was_passed_location) { std::vector<CodeRange> empty_code_ranges = {}; Hexagon::AdvancedCodeEditor::Selection selection(empty_code_ranges); EXPECT_EQ(CodePoint(32, 87), selection.find_next_from(32, 87)); } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, find_next_from__finds_the_next_selection) { std::vector<CodeRange> code_ranges = { CodeRange{2, 0, 3, 0}, CodeRange{3, 8, 4, 8}, CodeRange{9, 19, 10, 19}, }; Hexagon::AdvancedCodeEditor::Selection selection(code_ranges); EXPECT_EQ(CodePoint(2, 0), selection.find_next_from(0, 0)); // on the same line EXPECT_EQ(CodePoint(3, 8), selection.find_next_from(4, 0)); // on a subsequent line } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, find_next_from__when_at_an_existing_selections_start__finds_the_next_selection) { std::vector<CodeRange> code_ranges = { CodeRange{2, 0, 3, 0}, CodeRange{3, 8, 4, 8}, CodeRange{9, 19, 10, 19}, }; Hexagon::AdvancedCodeEditor::Selection selection(code_ranges); EXPECT_EQ(CodePoint(3, 8), selection.find_next_from(2, 0)); // on the same line EXPECT_EQ(CodePoint(9, 19), selection.find_next_from(3, 8)); // on a subsequent line } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, find_next_from__when_beyond_the_last_selection__does_nothing) { std::vector<CodeRange> code_ranges = { CodeRange{2, 0, 3, 0}, CodeRange{3, 8, 4, 8}, CodeRange{9, 19, 10, 19}, }; Hexagon::AdvancedCodeEditor::Selection selection(code_ranges); EXPECT_EQ(CodePoint(10, 19), selection.find_next_from(10, 19)); // on the same line } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, find_previous_from__with_no_code_ranges__returns_the_cursor_location_that_was_passed_location) { std::vector<CodeRange> empty_code_ranges = {}; Hexagon::AdvancedCodeEditor::Selection selection(empty_code_ranges); EXPECT_EQ(CodePoint(32, 87), selection.find_previous_from(32, 87)); } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, find_previous_from__finds_the_previous_selection) { std::vector<CodeRange> code_ranges = { CodeRange{2, 0, 3, 0}, CodeRange{3, 8, 4, 8}, CodeRange{9, 19, 10, 19}, }; Hexagon::AdvancedCodeEditor::Selection selection(code_ranges); EXPECT_EQ(CodePoint(2, 0), selection.find_previous_from(4, 0)); // on the same line EXPECT_EQ(CodePoint(2, 0), selection.find_previous_from(4, 7)); // on a subsequent line } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, find_previous_from__when_at_an_existing_selection_start__finds_the_previous_selection) { std::vector<CodeRange> code_ranges = { CodeRange{2, 0, 3, 0}, CodeRange{3, 8, 4, 8}, CodeRange{9, 19, 10, 19}, }; Hexagon::AdvancedCodeEditor::Selection selection(code_ranges); EXPECT_EQ(CodePoint(2, 0), selection.find_previous_from(3, 8)); // on the same line EXPECT_EQ(CodePoint(3, 8), selection.find_previous_from(9, 19)); // on a subsequent line } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, find_previous_from__when_before_the_first_selection__does_nothing) { std::vector<CodeRange> code_ranges = { CodeRange{2, 1, 3, 1}, CodeRange{3, 8, 4, 8}, CodeRange{9, 19, 10, 19}, }; Hexagon::AdvancedCodeEditor::Selection selection(code_ranges); EXPECT_EQ(CodePoint(1, 0), selection.find_previous_from(1, 0)); // on the previous line EXPECT_EQ(CodePoint(1, 1), selection.find_previous_from(1, 1)); // on the same line } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, push_down_from__will_move_code_points_down_that_are_at_or_below_a_starting_line) { std::vector<CodeRange> code_ranges = { CodeRange(2, 1, 3, 1), CodeRange(3, 8, 4, 8), CodeRange(9, 19, 10, 19), CodeRange(9, 20, 10, 20), CodeRange(9, 99, 10, 99), }; Hexagon::AdvancedCodeEditor::Selection selection(code_ranges); selection.push_down_from(19, 3); std::vector<CodeRange> expected_moved_code_ranges = { CodeRange(2, 1, 3, 1), CodeRange(3, 8, 4, 8), CodeRange(9, 19+3, 10, 19+3), CodeRange(9, 20+3, 10, 20+3), CodeRange(9, 99+3, 10, 99+3), }; EXPECT_EQ(expected_moved_code_ranges, selection.get_code_ranges()); } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, push_down_from__when_num_lines_to_push_down__is_negative__will_throw_an_error) { // TODO } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, pull_up_from__when_num_lines_to_pull_up_is_negative__will_throw_an_error) { // TODO } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, pull_up_from__will_move_code_points_up_that_are_at_or_below_a_starting_line) { std::vector<CodeRange> code_ranges = { CodeRange(2, 1, 3, 1), CodeRange(3, 8, 4, 8), CodeRange(9, 19, 10, 19), CodeRange(9, 20, 10, 20), CodeRange(9, 99, 10, 99), }; Hexagon::AdvancedCodeEditor::Selection selection(code_ranges); selection.pull_up_from(19, 3); std::vector<CodeRange> expected_moved_code_ranges = { CodeRange(2, 1, 3, 1), CodeRange(3, 8, 4, 8), CodeRange(9, 19-3, 10, 19-3), CodeRange(9, 20-3, 10, 20-3), CodeRange(9, 99-3, 10, 99-3), }; EXPECT_EQ(expected_moved_code_ranges, selection.get_code_ranges()); } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, pull_up_from__when_num_lines_to_pull_up_is_greater_than_the_number_of_available_lines_to_pull_up_will_error) { Hexagon::AdvancedCodeEditor::Selection selection; std::string expected_message = "Selection::pull_up_from: error: guard \"(num_lines_to_pull_up <= " "starting_on_line)\" not met"; EXPECT_THROW_WITH_MESSAGE(selection.pull_up_from(0, 1), std::runtime_error, expected_message); EXPECT_THROW_WITH_MESSAGE(selection.pull_up_from(10, 11), std::runtime_error, expected_message); EXPECT_THROW_WITH_MESSAGE(selection.pull_up_from(1, 999), std::runtime_error, expected_message); } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, clear_select_lines__will_remove_ranges_that_intersect_with_the_line_indices) { std::vector<CodeRange> code_ranges = { CodeRange(2, 1, 3, 1), CodeRange(3, 8, 4, 8), CodeRange(9, 19, 10, 19), CodeRange(9, 20, 10, 20), CodeRange(9, 99, 10, 99), CodeRange(9, 108, 10, 110), CodeRange(9, 118, 10, 120), CodeRange(9, 128, 10, 130), }; Hexagon::AdvancedCodeEditor::Selection selection(code_ranges); std::vector<int> line_indices_to_clear = { 8, 20, 108, 119, 130 }; selection.clear_select_lines(line_indices_to_clear); std::vector<CodeRange> expected_result_code_ranges = { CodeRange(2, 1, 3, 1), CodeRange(9, 19, 10, 19), CodeRange(9, 99, 10, 99), }; Hexagon::AdvancedCodeEditor::Selection expected_result_selection(expected_result_code_ranges); EXPECT_EQ(expected_result_selection, selection); } TEST(Hexagon_AdvancedCodeEditor_SelectionTest, clear_select_lines__will_ignore_line_indices_that_do_not_intersect_with_code_ranges) { std::vector<CodeRange> code_ranges = { CodeRange(2, 1, 3, 1), CodeRange(3, 8, 4, 8), CodeRange(9, 19, 10, 19), CodeRange(9, 20, 10, 20), CodeRange(9, 99, 10, 99), CodeRange(9, 108, 10, 110), CodeRange(9, 118, 10, 120), CodeRange(9, 128, 10, 130), }; Hexagon::AdvancedCodeEditor::Selection selection(code_ranges); std::vector<int> line_indices_to_clear = { 0, 7, 9, 18, 21, 50, 98, 107, 111, 117, 121, 127, 131, 999 }; selection.clear_select_lines(line_indices_to_clear); EXPECT_EQ(code_ranges, selection.get_code_ranges()); }
true
b30272c5e9d67f2f60710ef656ad24337dd41916
C++
sogaberusu/ShootingGame
/Game/Background.cpp
SHIFT_JIS
915
2.59375
3
[]
no_license
#include "stdafx.h" #include "Background.h" Background::Background(CVector3 pos, CQuaternion rot,int mapNo) { //Rei}bv[h if (mapNo == enContainer) { m_model.Init(L"Assets/modelData/Background.cmo"); } //eXg}bv[h if (mapNo == enTestMap) { m_model.Init(L"Assets/modelData/TestMap.cmo"); } m_phyStaticObject.CreateMeshObject(m_model, pos, rot); m_position = pos; m_rotation = rot; //nʂVhEV[o[ɂB m_model.SetShadowReciever(true); } Background::~Background() { } void Background::Update() { //XV m_model.UpdateWorldMatrix(m_position, m_rotation, CVector3::One()); //VhELX^[o^B g_graphicsEngine->GetShadowMap()->RegistShadowCaster(&m_model); } void Background::Draw(Camera& camera) { //` m_model.Draw(camera.GetViewMatrix(), camera.GetProjectionMatrix(),enNormalDraw); }
true
5e685d7616b1998d33d10a742d0f7f7c9083c448
C++
vazj/osockets
/inc/imp/addrinfo.h
UTF-8
3,001
2.59375
3
[]
no_license
/*********************************************************** * osockets ***********************************************************/ /** * @file addrinfo.h * @brief AddrInfo class definition * @author Kamil Wiatrowski * @date 30-Apr-2011 */ #ifndef ADDRINFO_H #define ADDRINFO_H #include "imp/osocketsdef.h" #include "imp/addrinfobase.h" #include "address.h" #include "socketexception.h" namespace osocket { /** * @brief Wrapper for struct addrinfo */ class AddrInfo : public AddrInfoBaseIf { public: /** * @brief Constructor * @param target_ address for which addrinfo should be obtained * @param hints_ hints for addrinfo */ AddrInfo(const Address& target_, const AddrInfoBase& hints_) throw(SocketException); /** * @brief Destructor */ virtual ~AddrInfo(); /** * @brief get family * @return (e.g. AF_INET) */ virtual _Int getFamily() const; /** * @brief get socket type * @return socktype (e.g. SOCK_STREAM) */ virtual _Int getSockType() const; /** * @brief get flags * @return flags (e.g. AI_PASSIVE) */ virtual _Int getFlags() const; /** * @brief get protocol * @return protocol (0 (auto) or IPPROTO_TCP, IPPROTO_UDP) */ virtual _Int getProtocol() const; /** * @brief get sockaddr lenght * @return lenght of sockaddr */ socklen_t getAddrLen() const; /** * @brief get canonname * @return canonname of host or NULL */ const _Char* getCanonName() const; /** * @brief get sockaddr * @return pointer to sockaddr struct */ const struct sockaddr* getSockAddr() const; /** * @brief check if addrinfo is filled * @return true if addrinfo is NULL and object can't be used */ _SBool empty() const; /** * @brief move to next node of addrinfo * @return own pointer */ AddrInfo* next(); /** * @brief back to first node of addrinfo */ void begin(); protected: private: /** * @brief Copy constructor */ AddrInfo(const AddrInfo& other_); /** * @brief Assignment operator */ AddrInfo& operator=(const AddrInfo& rhs_); /** @brief addrinfo with address info data */ struct addrinfo *m_pAddrInfo; /** @brief first addrinfo structure (needed for freeaddrinfo) */ struct addrinfo *m_pAddrRoot; static const char* CLASS_NAME; }; } // namespace osocket #endif // ADDRINFO_H
true
b652c4609d0df46a7a3ed0e130ff5380d7484e6f
C++
abufarhad/Programming
/C++ Practice/complex number add.cpp
UTF-8
635
3.625
4
[]
no_license
#include <bits/stdc++.h> using namespace std; class Complex { public: Complex(int r1, int c1, int r2, int c2) { complex<double> a(r1,c1); complex<double> b(r2,c2); cout << "Sum of these two numbers can be described by: " << a+b << endl; } }; int main() { double a, b, c, d; cout << "Enter the real part of 1st number: "; cin >> a; cout << "Enter the imaginary part of 1st number: "; cin >> b; cout << "Enter the real part of 2nd number: "; cin >> c; cout << "Enter the imaginary part of 2nd number: "; cin >> d; Complex object(a, b, c, d); return 0; }
true
fe73b369af2e9e87efdbfbfb860aecda09bc4681
C++
Kanazawanaoaki/atcoder_memo
/abc/abc155/abc155b.cpp
UTF-8
381
2.765625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int ans=0; int tmp; for (int i = 0; i < n; i++) { cin >> tmp; if ((tmp % 2 ==0 )&& !((tmp %3 ==0) || (tmp %5 == 0))){ ans += 1; } } if (ans >0){ cout << "DENIED" << endl; } else { cout << "APPROVED" << endl; } }
true
1a266d4f8f629e278829bb7936bab8f4e0f10d42
C++
leizhichengg/CppPrimer
/Chapter 07/7.3/7.3.cpp
UTF-8
556
3.078125
3
[]
no_license
#include<iostream> #include<string> #include "Sales_data.h" using namespace std; int main() { Sales_data total; if (cin >> total.name >> total.num >> total.rev) { Sales_data trans; while (cin>>trans.name>>trans.num>>trans.rev) { if (total.isbn() == trans.isbn()) total.combine(trans); else { cout << total.name <<" "<< total.num <<" "<< total.rev << endl; total = trans; } } cout << total.name <<" "<< total.num <<" "<< total.rev << endl; } else cerr << "No data?!" << endl; return 0; }
true
a3fc84d04424c884e4a45dff4a65f55e914d4a9b
C++
camilabga/milker_robot
/Integration Tests/state_machine(inicial)/testes/maquina_estados.cpp
UTF-8
1,165
2.703125
3
[]
no_license
#include <iostream> #include "I2C/I2C.h" using namespace std; int main(){ //Variaveis I2C: I2C arduino; // //Variaveis Máquina_Estado: int estadoAtual = 1, estadoAnterior; bool fim_geral = false; // while(!fim_geral){ switch(estadoAtual){ case 1: //Segue Parede: //Teste: arduino.out[0] = 'V'; arduino.out[1] = 'D'; arduino.out[2] = 'C'; if(!arduino.tradeData()){ cout << "Erro ao enviar! " << endl; return -1; } cout << "Enviado.. " << "Confirmacao: " << arduino.in << endl; usleep(100000); // if(!arduino.sendData()){ // cout << "Erro ao enviar! " << endl; // return -1; // } // // // if(!arduino.getData()){ // cout << "Erro ao receber! " << endl; // return -1; // } arduino.out[0] = 'D'; arduino.out[1] = 'E'; arduino.out[2] = 'U'; if(!arduino.tradeData()){ cout << "Erro ao enviar! " << endl; return -1; } //Teste cout << "Enviado.. " << "Confirmacao: " << arduino.in << endl; //TEste usleep(100000); break; case 2: //Procura Copo: break; default: //Erro: break; } } return 0; }
true
d39434f2e9f341982696a8818f0efa15bbcbb503
C++
zhengszh/Leetcode
/189.cpp
UTF-8
960
3.140625
3
[]
no_license
#include <cstdio> #include <vector> using namespace std; class Solution { public: void rotate(vector<int>& nums, int k) { int n = nums.size(); int time = k % n; int moveTime = 0; int a = 0; int b = time; int temp1 = nums[a]; while (moveTime != n) { for (int i = 0; i < nums.size(); ++i) printf("%d ", nums[i]); printf("\n"); int temp2 = nums[b]; nums[b] = temp1; int temppos = b; if (b > n - time - 1) { b = b - n + time; } else { b = b + time; } a = temppos; temp1 = temp2; moveTime++; } } }; int main() { int a[10] = {1,2,3,4,5,6,7}; vector<int> v(a, a + 6); Solution s; s.rotate(v, 2); for (int i = 0; i < v.size(); ++i) printf("%d ", v[i]); printf("\n"); return 0; }
true
37c12493ef550407d62daaf5d805f06bf7b6d653
C++
SamuelYiyuanTu/ComputationalFinanceP1
/compFinance/compFinance/main.cpp
UTF-8
8,929
3.34375
3
[]
no_license
// // main.cpp // compFinance // // Created by Samuel Tu on 1/13/18. // Copyright © 2018 Samuel_Tu. All rights reserved. // MGMTMFE405.2@gmail.com // #include <iostream> #include <vector> #include <cmath> #include <random> #include <numeric> #include <fstream> #include <ctime> #define PI 3.14159265 using namespace std; /** * Usage * This C++ code implements project 1 for the computational finance class. * The output includes all the mean, standard deviation and time calculated. * For histogram plotting, I have code to output the random variables generated * to several files and plot the histogram with R. The location where the files are * located is my local directory. Therefore, if you want to see the files when running * code, please change the addresses in the code accordingly. **/ // generate uniform random variables from 0 -> m vector<long> uniform(int seed, int size, int m, int a, int b){ vector<long> array(size); array[0] = seed; for (int i = 1; i < size; i++) { array[i] = (a * array[i-1] + b) % m; } return array; } // output File function void outputFile (vector<double> v, string s) { ofstream outputFile; outputFile.open(s); for (int i = 0; i < v.size(); i++) { //cout << v[i] << endl; outputFile << v[i] << "\n"; } outputFile.close(); } // calculate mean double mean (vector<double> v) { double sum = 0.0; for (int i = 0; i < v.size(); i++) { sum += v[i]; } return sum/v.size(); } // calculate standard deviation double sd(vector<double> v, double mean) { double sum = 0.0; for (int i = 0; i < v.size(); i++) { sum += (v[i] - mean) * (v[i] - mean); } return sqrt(sum/(v.size() - 1)); } // general output function to print void calculation (vector<double> vb) { double avg = mean(vb); double std = sd(vb, avg); cout << "The Empirical mean = " << avg << endl; cout << "The Empirical std = " << std << endl; } // Question 1 vector<double> q1 (int flag, int size) { // set parameters int a = (int)pow(7.0, 5.0); int b = 0; int m = (int)pow(2, 31) - 1; //int size = 10000; int seed = 1; // generate uniform random using LGM vector<long> v = uniform(seed, size, m, a, b); // generate uniform from 0 -> 1 by dividing vector<double> vb(size); for (int i = 0; i < size; i++) { vb[i] = (double)v[i]/(double)m; } // since I will call this function in multiple places, where I might not want to print the following // I have a flag variable to control where to print. if (flag == 1) { cout << "************* Question 1 ***********" << endl; calculation(vb); // generating uniform random using buildin function vector<double> buildinUni(size); for (int i = 0; i < size; i++) { buildinUni[i] = ((double) rand() / (RAND_MAX)); } double buildinAvg = mean(buildinUni); double buildinStd = sd(buildinUni, buildinAvg); cout << "Mean using buildin = " << buildinAvg << endl; cout << "std using buildin = " << buildinStd << endl; // The empirical mean and std are very close to the ones that generates using buildin function. } return vb; // two ways of calculating mean and std. I am just testing those. //double sum = accumulate(vb.begin(), vb.end(), 0.0); //double avg2 = sum / vb.size(); //double sq_sum = std::inner_product(vb.begin(), vb.end(), vb.begin(), 0.0); //double stdev = sqrt(sq_sum / v.size() - avg2 * avg2); } // Question 2 void q2 () { cout << endl << "************* Question 2 ***********" << endl; vector<double> v = q1(0, 10000); // generate 10,000 uniform using (a) vector<double> result; for (int i = 0; i < v.size(); i++) { if (v[i] >= 0 && v[i] < 0.3) { result.push_back(-1); } else if (v[i] >= 0.3 && v[i] < 0.65) { result.push_back(0); } else if (v[i] >= 0.65 && v[i] < 0.85) { result.push_back(1); } else { result.push_back(2); } } // for loop // address to create csv file string address = "/Users/samueltu/Desktop/Winter_2018/405_ComputFin/Week1/q2.csv"; outputFile(result, address); calculation(result); } // getting sum to sum up bernulli double sum (vector<double> v) { double sum = 0; for (int i = 0; i < v.size(); i++) { sum += v[i]; } return sum; } // Question 3 void q3 () { cout << endl << "************* Question 3 ***********" << endl; int n = 44; double p = 0.64; int size = 1000; int count = 0; vector<double> result; vector<double> tmp = q1(0, n * size); // sum up bernulli for (int i = 0; i < size * n; i += 44) { vector<double> res; for (int j = i; j < i+n; j++) { if (tmp[j] < p) { res.push_back(1); } else { res.push_back(0); } } // inner for loop double temp_num = sum(res); result.push_back(temp_num); res.clear(); // compute probability if (temp_num >= 40.0) { count++; } } // outter for loop // outputting files string address = "/Users/samueltu/Desktop/Winter_2018/405_ComputFin/Week1/q3.csv"; outputFile(result, address); // probability that P(X >= 40) = 0 // Theoretical value is 4.823664e-05, which is approx to 0 double prob = (double)count/(double)size; cout << "count = " << count << endl; cout << "probability that P(X >= 40) = " << prob << endl; } // Question 4 void q4 () { cout << endl << "************* Question 4 ***********" << endl; // (a) int size = 10000; vector<double> v = q1(0, size); double lamda = 1.5; int count1 = 0; int count2 = 0; vector<double> res; // constructing vector and counting probabilities for two conditions. for (int i = 0; i < v.size(); i++) { double temp = -lamda * log(v[i]); res.push_back(temp); if (temp >= 1) { count1++; } if (temp >= 4) { count2++; } } // for loop string address = "/Users/samueltu/Desktop/Winter_2018/405_ComputFin/Week1/q4.csv"; outputFile(res, address); // (b) calculate propability double prob1 = (double)count1/(double) size; double prob2 = (double)count2/(double) size; cout << "P(X >= 1) = " << prob1 << endl; cout << "P(X >= 4) = " << prob2 << endl; // (c) calculate mean and std calculation(res); } // Question 5 void q5 () { cout << endl << "************* Question 5 ***********" << endl; clock_t t1, t2; // (a) int size = 50000; // number of random variables // generate more for the pm method. choose 0.3 because the probability for failure are pi/4 // therefore, I chose 0.3 > 0.21 (1-pi/4) to ensure there is enough number to pick. vector<double> v1 = q1(0, size * (1 + 0.3)); // (b) Box-Muller Method vector<double> res_bm; // get 2 consecutive uniform random as U1 and U2 t1 = clock(); for (int i = 0; i < size; i += 2) { double z1 = sqrt(-2*log(v1[i])) * cos(2*PI*v1[i+1]); double z2 = sqrt(-2*log(v1[i])) * sin(2*PI*v1[i+1]); res_bm.push_back(z1); res_bm.push_back(z2); } t1 = clock() - t1; // (c) mean and sd cout << "Box-Muller Method:" << endl; calculation(res_bm); // (d) Polar-Marsaglia Method vector<double> res_pm; int size2 = (int)v1.size(); t2 = clock(); for (int i = 0; i < size2; i += 2) { // break when it reach "size" number of variables. if (res_pm.size() == size) break; double v_1 = 2 * v1[i] - 1; double v_2 = 2 * v1[i+1] - 1; double w = v_1 * v_1 + v_2 * v_2; if (w <= 1) { double z_1 = v_1 * sqrt((-2*log(w))/w); double z_2 = v_2 * sqrt((-2*log(w))/w); res_pm.push_back(z_1); res_pm.push_back(z_2); } } t2 = clock() - t2; // (e) mean and std cout << endl; cout << "Polar-Marsaglia Method:" << endl; calculation(res_pm); // (f) cout << endl; cout << "size = " << size << endl; cout << "Box-Muller time: " << ((float)t1/CLOCKS_PER_SEC) * 1000 << " ms" << endl; cout << "Polar-Marsaglia time: " << ((float)t2/CLOCKS_PER_SEC) * 1000 << " ms" << endl; // box-muller is slower because the sin and cos calculation. } int main(int argc, const char * argv[]) { /* Project 1*/ q1(1, 10000); // Question 1 q2(); // Question 2 q3(); // Question 3 q4(); // Question 4 q5(); // Question 5 return 0; }
true
e819af11674e5010f0242dcece6ba929f22b0813
C++
YYang30/LintcodeSol
/Linked_List_Cycle.cpp
UTF-8
812
2.65625
3
[]
no_license
// // main.cpp // Yang_Sol // // Created by YangYang on 16/4/20. // Copyright © 2016年 YangYang. All rights reserved. // #include <iostream> #include <cstring> #include <vector> #include <algorithm> #include <cmath> #include <map> using namespace std; class ListNode{ public: int val; ListNode *next; ListNode(int val){ this->val = val; this->next = NULL; } // ~ListNode(){} }; //判断链表是否有环: 快慢指针法 class Solution{ public: bool hasCycle(ListNode *head){ if(head == NULL) return false; ListNode *fast = head->next; ListNode *slow = head; while(fast !=NULL && fast->next !=NULL){ if(slow == fast) return true; slow = slow->next; fast = fast->next->next; } return false; } }; int main(){ // do sth return 0; }
true
6c7038223b292447ba3f65636850b5b7f4e2f699
C++
murphymadeleine21/Connect-4-Game
/Board.h
UTF-8
2,125
3.453125
3
[]
no_license
// // Board.hpp // Connect 4 // // Created by Madeleine Murphy on 6/15/19. // Copyright © 2019 Madeleine Murphy. All rights reserved. // #ifndef Board_h #define Board_h #include "Color.h" #include <stdio.h> class Board { public: Board(); //Construct an empty Board 6rowsx7cols, 21 checkers for each player (R for Red, B for Black) int checkersToPlay(Color c) const; //return the number of checkers that are available to play for the indicated color. int checkersCol(int column) const; //Return the number of checkers in the indicated column, or −1 if the column number is invalid. bool full(int column) const; //return if the column is full int checkersRow(int row) const; //return number of checkers in the indicated row, or -1 if invalid int colorCheckersCol(int column, Color c) const; //return number of indicated color's checkers in a column, or -1 if invalid int colorCheckersRow(int row, Color c) const; //return number of indicated color's checkers in a row, or -1 if invalid int checkersInPlayC(Color c) const; //Return the total number of checkers in play for the indicated color. int checkersInPlay() const; //return the total number of checkers in play in the game int totalCheckers() const; //Return the total number of checkers in the game for both players char checkerInPos(int row, int col) const; //return the character at that Grid bool drop(Color c, int column); //If the column indicated by (column) is full or invalid, or if the player has no checkers left to play, this function returns false without changing anything. Otherwise, it will return true after dropping the checker: the checker is placed into the top most empty row space in the column. The indicated color's number of checkers available for play will decrease by 1. The parameter endRow is set to the row the checker was placed in. private: char m_grid[6][7]; int m_redToPlay; int m_blackToPlay; int m_totalCheckers; int m_checkersInPlay; int m_redInPlay; int m_blackInPlay; }; #endif /* Board_h */
true
dcf410ff70881cb0b83fdf317a846526cde0f162
C++
hamsham/LightMath
/include/lightsky/math/scalar_utils.h
UTF-8
22,293
3.15625
3
[ "BSD-2-Clause" ]
permissive
/* * File: math/scalar_utils.h * Author: Miles Lacey * * Created on March 6, 2014, 10:04 PM */ #ifndef LS_MATH_SCALAR_UTILS_H #define LS_MATH_SCALAR_UTILS_H #include <climits> // CHAR_BIT #include <limits> // std::numeric_limits #include "lightsky/setup/Arch.h" #include "lightsky/setup/Types.h" #include "lightsky/math/Types.h" namespace ls { namespace math { /** * @brief Calculate the greatest common divisor between two integers. * * @param a * @param b * * @return The greatest common divisor between a & b. */ template <typename scalar_t> constexpr scalar_t gcd(scalar_t a, scalar_t b) noexcept; /** * @brief min * Get the minimum of two single numbers. * * This function can be run at compile-time. * * @param a * * @param b * * @return The smallest of the two parameters a and b. */ template <typename scalar_t> constexpr scalar_t min(scalar_t a, scalar_t b) noexcept; /** * @brief min * Get the minimum of two or more numbers. * * This function can be run at compile-time. * * @param a * * @param b * * @param nums * * @return The smallest number of the input parameters. */ template <typename scalar_t, typename... scalars_t> constexpr scalar_t min(const scalar_t& a, const scalar_t& b, const scalars_t&... nums) noexcept; /** * @brief mix * Perform a linear interpolation of x between the two scalars a, b. * * @param a * * @param b * * @return The linear "mix" of a and b. */ template <typename scalar_t> constexpr scalar_t mix(scalar_t a, scalar_t b, scalar_t percent) noexcept; /** * @brief max * Get the maximum of two single numbers. * This function can be run at compile-time. * * @param a * * @param b * * @return The largest number of the two parameters a and b. */ template <typename scalar_t> constexpr scalar_t max(scalar_t a, scalar_t b) noexcept; /** * @brief max * Get the maximum of two or more numbers. * * This function can be run at compile-time. * * @param a * * @param b * * @param nums * * @return The largest number of the input parameters. */ template <typename scalar_t, typename... scalars_t> constexpr scalar_t max(const scalar_t& a, const scalar_t& b, const scalars_t&... nums) noexcept; /** * @brief clamp * Bind a number to within a certain range. * * @param n * A number that should be constrained to be within a specific range. * * @param minVal * The minimum allowable value that 'n' can be. * * @param maxVal * The maximum allowable value that 'n' can be. * * @return a number, such that minVal <= n <= maxVal */ template <typename scalar_t> constexpr scalar_t clamp(scalar_t n, scalar_t minVal, scalar_t maxVal) noexcept; /** * @brief Clamp a number between 0 and 1. * * @param n * A single scalar value. * * @return The input value, clamped between the range of (0, 1), inclusive. */ template <typename scalar_t> constexpr scalar_t saturate(const scalar_t n) noexcept; /** * @brief Retrieve the nearest integer less than or equal to the input float. * * @param n * A floating-point number. * * @return A value equal to the nearest integer that is less than or equal to * the input parameter. */ template <typename floating_t> constexpr floating_t floor(const floating_t n) noexcept; /** * @brief Retrieve the nearest integer less than or equal to the input float. * This overload assumes compile-time knowledge of the range of numbers that a * float should reside within. * * @param n * A floating-point number. * * @return A value equal to the nearest integer that is less than or equal to * the input parameter. */ template <typename floating_t, typename int_t, int_t range> constexpr int_t ranged_floor(const floating_t n) noexcept; /** * @brief Retrieve the nearest integer greater than or equal to the input * float. * * @param n * A floating-point number. * * @return A value equal to the nearest integer that is greater than or equal * to the input parameter. */ template <typename floating_t> constexpr floating_t ceil(const floating_t n) noexcept; /** * @brief Retrieve the nearest integer greater than or equal to the input * float. This overload assumes compile-time knowledge of the range of numbers * that a float should reside within. * * @param n * A floating-point number. * * @return A value equal to the nearest integer that is less than or equal to * the input parameter. */ template <typename floating_t, typename int_t, int_t range> constexpr int_t ranged_ceil(const floating_t n) noexcept; /** * @brief Calculate the nearest integer closest to the input parameter. * * @param n * A floating-point number. * * @return A value equal to the nearest integer to the input parameter. */ template <typename floating_t> constexpr floating_t round(const floating_t n) noexcept; /** * @brief fract * Compute the fractional part of a floating-point number. * * @param n * A floating-point number. * * @return The fractional part of the input float. This is calculated as * "x - floor(x)". */ template <typename floating_t> constexpr floating_t fract(const floating_t n) noexcept; /** * @brief fmod * Compute remainder of the division of one floating-point number by another. * * @param n1 * The dividend. * * @param n2 * The divisor. * * @return The remainder of the division between n1 / n2. */ template <typename floating_t> constexpr floating_t fmod(const floating_t n1, const floating_t n2) noexcept; /** * @brief fmod_1 * Compute remainder of the division of one floating-point number by 1. * * @param n * The dividend. * * @return The remainder of the division between n1 / 1.0. */ template <typename floating_t> constexpr floating_t fmod_1(const floating_t n) noexcept; /** * @brief step * Generate a step function by comparing two values. * * step() generates a step function by comparing x to edge. For the return * value, 0.0 is returned if x < edge, and 1.0 is returned otherwise. * * @param edge * Specifies the location of the edge of the step function. * * @param x * Specify the value to be used to generate the step function. * * @return A step function between two values. */ template <typename floating_t> constexpr floating_t step(floating_t edge, floating_t x) noexcept; /** * @brief smoothstep * Perform a smooth interpolation of a number along the sub-sequence [a, b]. * * @param a * A number within the same sub-sequence that x lies on. * * @param b * A number within the same sub-sequence that x lies on. * * @return The smooth linear interpolation of x in between the interval a and b. */ template <typename floating_t> constexpr floating_t smoothstep(floating_t a, floating_t b, floating_t x) noexcept; /** * @brief smootherstep * Perform a second-order smooth interpolation of a number along the * sub-sequence [a, b]. * * @param a * A number within the same sub-sequence that x lies on. * * @param b * A number within the same sub-sequence that x lies on. * * @return The smoother linear interpolation of x in between the interval a and * b. */ template <typename floating_t> constexpr floating_t smootherstep(floating_t a, floating_t b, floating_t x) noexcept; /** * @brief fastSqrt * Perform a square root on a single number without using the standard library. * This method uses IEEE floating point arithmetic. Use only if the input * argument uses this format. * * @param a number whose square root should be obtained. * * @return The square root of the input number. */ template <typename scalar_t> inline scalar_t fast_sqrt(typename setup::EnableIf<setup::IsIntegral<scalar_t>::value, scalar_t>::type) noexcept; template <typename scalar_t> inline scalar_t fast_sqrt(scalar_t) noexcept; /** * @brief fastInvSqrt * Get the inverse square root of a number. * This method uses IEEE floating point arithmetic. Use only if the input * argument uses this format. * * @param a number whose square root should be obtained. * * @return The inverse square root (1/sqrt(x)) of the input number. */ template <typename scalar_t> inline scalar_t inversesqrt(scalar_t) noexcept; /** * @brief Convert a number from degrees to radians. This function can be run at * compile-time. * * @param the value of an angle, in degrees. * * @return the value of an angle, in radians. */ template <typename scalar_t> constexpr scalar_t radians(scalar_t degrees) noexcept; /** * @brief Convert a number from radians to degrees. This function can be run at * compile-time. * * @param the value of an angle, in radians. * * @return the value of an angle, in degrees. */ template <typename scalar_t> constexpr scalar_t degrees(scalar_t radians) noexcept; /** * @brief Compute the modulus of num%denom only when necessary. * * This method only works with positive integers. * * @param num * Numerator * * @param denom * Denominator * * @return num % denom */ template <typename integral_t> constexpr integral_t fast_mod(const integral_t num, const integral_t denom) noexcept; /** * @brief log2 * Calculate the log-base2 of a number * * @param a number * * @return the log-base2 of a number, using IEEE floating point arithmetic */ template <typename scalar_t> inline scalar_t log2(scalar_t n) noexcept; /** * @brief log2 * Calculate the log-base2 of a number * * @param a number * * @return the log-base2 of a number, using IEEE floating point arithmetic */ template <> inline float log2<float>(float) noexcept; /** * @brief log * Calculate the natural log of a number * * @param a number * * @return ln(x), using IEEE floating point arithmetic */ template <typename scalar_t> inline scalar_t log(scalar_t) noexcept; /** * @brief log10 * Calculate the log-base2 of a number * * @param a number * * @return the log-base-10 of a number, using IEEE floating point arithmetic */ template <typename scalar_t> inline scalar_t log10(scalar_t) noexcept; /** * @brief log10 * Calculate the log-base2 of a number * * @param a number * * @return the log-base-10 of a number, using IEEE floating point arithmetic */ template <> inline float log10<float>(float) noexcept; /** * @brief logN * Calculate the log-base2 of a number * * @param baseN * The base of the logarithm. * * @param a number * * @return the log-baseN of a number, using IEEE floating point arithmetic */ template <typename scalar_t> inline scalar_t logN(scalar_t baseN, scalar_t) noexcept; /** * @brief next_pow2 * Find the next (greater) power of two that is closest to the value of a number * * @param An unsigned integral type * * @return The current or next greatest power of two. */ inline uint8_t next_pow2(uint8_t) noexcept; inline uint16_t next_pow2(uint16_t) noexcept; inline uint32_t next_pow2(uint32_t) noexcept; inline uint64_t next_pow2(uint64_t) noexcept; /** * @brief next_pow2 * Find the next (greater) power of two that is closest to the value of a number * * @param A signed integral type * * @return The current or next greatest power of two. */ inline int8_t next_pow2(int8_t) noexcept; inline int16_t next_pow2(int16_t) noexcept; inline int32_t next_pow2(int32_t) noexcept; inline int64_t next_pow2(int64_t) noexcept; /** * @brief prev_pow2 * Find the previous (lesser) power of two that is closest to the value of a number * * @param An unsigned integral type * * @return The previous power of two. */ inline uint8_t prev_pow2(uint8_t) noexcept; inline uint16_t prev_pow2(uint16_t) noexcept; inline uint32_t prev_pow2(uint32_t) noexcept; inline uint64_t prev_pow2(uint64_t) noexcept; /** * @brief prev_pow2 * Find the previous (lesser) power of two that is closest to the value of a * number. * * @param A signed integral type * * @return The previous power of two. */ inline int8_t prev_pow2(int8_t) noexcept; inline int16_t prev_pow2(int16_t) noexcept; inline int32_t prev_pow2(int32_t) noexcept; inline int64_t prev_pow2(int64_t) noexcept; /** * @brief nearest_pow2 * Find the closest power of two to a number. This may either be greater than * or less than the input number. * * @param A signed integral type * * @return The current or closest power of two to a number. */ template <typename data_t> inline data_t nearest_pow2(typename setup::EnableIf<setup::IsIntegral<data_t>::value, data_t>::type) noexcept; /** * @brief is_pow2 * Determine if a number is a power of two or not. * * @param A number who's value should be evaluated. * * @return True if the number is a poiwer of two, false if the number is not a * power of two. */ template <typename data_t> constexpr bool is_pow2(typename setup::EnableIf<setup::IsIntegral<data_t>::value, data_t>::type n) noexcept; /** * @brief factorial * Retrieve the factorial of a number * * @param A number who's factorial is to be calculated. * * @return The factorial of a given number. */ template <typename scalar_t> constexpr scalar_t factorial(scalar_t) noexcept; /** * @brief pow * Evaluate a number to a given power. * * This function's implmentation will be defined at compile-time for integers * and floats. * * @param x * * @param y * * @return x^y */ template <typename scalar_t> constexpr scalar_t pow( typename setup::EnableIf<setup::IsIntegral<scalar_t>::value, scalar_t>::type x, typename setup::EnableIf<setup::IsIntegral<scalar_t>::value, scalar_t>::type y) noexcept; template <typename scalar_t> inline scalar_t pow(scalar_t x, scalar_t y) noexcept; /** * @brief exp * Evaluate the exponentiation of e^x. * * @param x * The power X to which e will be raised by. * * @return E, raised to the power x. */ template <typename scalar_t> inline scalar_t exp(scalar_t x) noexcept; /** * @brief exp2 * Evaluate the exponentiation of 2^x. * * @param x * The power X to which 2 will be raised by. * * @return 2, raised to the power x. */ template <typename scalar_t> inline scalar_t exp2(scalar_t x) noexcept; /** * @brief cos * Evaluate the cosine of an angle at compile-time. * * @param An angle, in radians, who's cosine value is to be calculated. * * @return The cosine of a given angle. */ template <typename scalar_t> constexpr scalar_t cos(typename setup::EnableIf<!setup::IsFloat<scalar_t>::value, scalar_t>::type x) noexcept; template <typename scalar_t> constexpr scalar_t cos(scalar_t x) noexcept; /** * @brief sin * Evaluate the sine of an angle at compile-time. * * @param An angle, in radians, who's sine value is to be calculated. * * @return The sine of a given angle. */ template <typename scalar_t> constexpr scalar_t sin(typename setup::EnableIf<!setup::IsFloat<scalar_t>::value, scalar_t>::type x) noexcept; template <typename scalar_t> constexpr scalar_t sin(scalar_t x) noexcept; /** * @brief tan * Evaluate the tangent of an angle at compile-time. * * @param An angle, in radians, who's tangent value is to be calculated. * * @return The tangent of a given angle. */ template <typename scalar_t> constexpr scalar_t tan(scalar_t) noexcept; /** * @brief atan2 * Evaluate the arc-tangent of two cartesian lengths. * * @param y * The length of the y-axis. * * @param x * The length of the x-axis. * * @return The arc-tangent of two lengths. */ template <typename scalar_t> inline scalar_t atan2(scalar_t y, scalar_t x) noexcept; /** * @brief atan * Evaluate the arc-tangent of y/x. * * @param n * The value of y/x * * @return The arc-tangent of two lengths. */ template <typename scalar_t> inline scalar_t atan(scalar_t n) noexcept; /** * @brief acos * Evaluate the arc-cosine of an angle at compile-time. * * @param An angle, in radians, who's arc-cosine value is to be calculated. * * @return The arc-cosine of a given angle. */ template <typename scalar_t> inline scalar_t acos(scalar_t) noexcept; /** * @brief asin * Evaluate the arc-sine of an angle at compile-time. * * @param An angle, in radians, who's arc-sine value is to be calculated. * * @return The arc-sine of a given angle. */ template <typename scalar_t> inline scalar_t asin(scalar_t) noexcept; /** * @brief rcp * Evaluate the reciprocal of a decimal scalar. * * @note This function does not check for division-by-zero. * * @param The value to be evaluated. * * @return A reciprocal estimate of the input number. */ template <typename scalar_t> constexpr scalar_t rcp(const scalar_t&) noexcept; /** * @brief sum * Evaluate the sum of a series of numbers at compile-time. * * @param A set of numbers who's values are to be added together. * * @return The sum of a set of numbers. */ template <typename scalar_t> constexpr scalar_t sum(const scalar_t&) noexcept; /** * @brief sum * Evaluate the sum of a series of numbers at compile-time. * * @param A set of numbers who's values are to be added together. * * @return The sum of a set of numbers. */ template <typename scalar_t, typename... scalars_t> constexpr scalar_t sum(const scalar_t& num, const scalars_t&... nums) noexcept; /** * @brief reciprocal sum * Evaluate the reciprocal of a sum. * * @param A set of numbers who's values are to be added together. * * @return The inverse of a sequence sum. */ template <typename scalar_t> constexpr scalar_t sum_inv(const scalar_t&) noexcept; /** * @brief reciprocal sum * Evaluate the reciprocal of a sum. * * @param A set of numbers who's values are to be added together. * * @return The inverse of a sequence sum. */ template <typename scalar_t, typename... scalars_t> constexpr scalar_t sum_inv(const scalar_t& num, const scalars_t&... nums) noexcept; /** * @brief average * Evaluate the average of a series of numbers at compile-time. * * @param A set of numbers who's values are to be averaged. * * @return The average of a set of numbers. */ template <typename scalar_t> constexpr scalar_t average() noexcept; /** * @brief average * Evaluate the average of a series of numbers at compile-time. * * @param A set of numbers who's values are to be averaged. * * @return The average of a set of numbers. */ template <typename scalar_t, typename... scalars_t> constexpr scalar_t average(const scalar_t& num, const scalars_t&... nums) noexcept; /** * @brief Count the number of bits in an integer. * * @param num * A number containing a string of set bits. * * @return A count of all the set bits in an integer. */ constexpr unsigned count_set_bits(const unsigned long long num) noexcept; /** * @brief Count the number of bits in an integer. * * This version of the bit-count algorithm casts the input type into the * largest possible integral data type available (currently unsigned long * long). This means that negative values may return a very large value on a * two's complement machine. * * This also means that passing a value of -1 into the function will return the * maximum allowable number of bits available for storage on the current CPU. * * @param num * A number containing a string of set bits. * * @return A count of all the set bits in an integer. */ template <typename scalar_t> constexpr unsigned count_set_bits(const scalar_t num) noexcept; /** * @brief Scale a number from one data type with a range of values to another * data type with a range of values. * * @param num * A number which will be linearly scaled from one numerical range to another. * * @param oldMin * The minimum value of the input number's current range of valid values. * * @param oldMax * The maximum value of the input number's current range of valid values. * * @param newMin * The minimum number by which the input number should be scaled to represent. * * @param newMax * The maximum number by which the input number should be scaled to represent. * * @return The input number, linearly scaled from one numerical range to * another. */ template <typename in_type, typename out_type> constexpr out_type scale_to_range( const in_type num, const out_type oldMin = std::numeric_limits<in_type>::min(), const out_type oldMax = std::numeric_limits<in_type>::max(), const out_type newMin = std::numeric_limits<out_type>::min(), const out_type newMax = std::numeric_limits<out_type>::max() ) noexcept; /** * @brief Retrieve the sign bits of a scalar type. * * @param x * The number to be queried. * * @returns 1 if the sign bit is set, 0 if x is greater than, or equal to zero. */ template <typename data_t> constexpr int sign_mask(typename setup::EnableIf<setup::IsUnsigned<data_t>::value, data_t>::type) noexcept; template <typename data_t> constexpr int sign_mask(data_t x) noexcept; /** * @brief Determine if the sign-bit is set. * * @param x * The number to be queried. * * @returns 1 if the sign bit is set, 0 if x is greater than, or equal to zero. */ template <typename data_t> constexpr data_t sign(typename setup::EnableIf<setup::IsIntegral<data_t>::value, data_t>::type) noexcept; template <typename data_t> constexpr data_t sign(data_t x) noexcept; /** * @brief Retrieve the absolute value of a number * * @param x * * @return A number without the sign bit set. */ template <typename data_t> constexpr data_t abs(typename setup::EnableIf<setup::IsIntegral<data_t>::value, data_t>::type) noexcept; template <typename data_t> constexpr data_t abs(data_t x) noexcept; /** * @brief Perform a fused multiply-and-add calculation * * @param x * An initial operand. * * @param m * A number which will be multiplied against 'x'. * * @param a * The final operand which will be added to 'x*m'. * * @return (x*m)+a */ template <typename data_t> constexpr data_t fmadd(data_t x, data_t m, data_t a) noexcept; /** * @brief Perform a fused multiply-and-subtract calculation * * @param x * An initial operand. * * @param m * A number which will be multiplied against 'x'. * * @param a * The final operand which will be subtracted from 'x*m'. * * @return (x*m)-a */ template <typename data_t> constexpr data_t fmsub(data_t x, data_t m, data_t a) noexcept; } // end math namespace } // end ls namespace #include "lightsky/math/generic/scalar_utils_impl.h" #ifdef LS_ARCH_X86 #include "lightsky/math/x86/scalarf_utils_impl.h" #elif defined(LS_ARM_NEON) #include "lightsky/math/arm/scalarf_utils_impl.h" #endif #endif /* LS_MATH_SCALAR_UTILS_H */
true
dec81ba0cbe2a03dc2c39ef9d79fb3a17d2aa5fd
C++
ljesuscastrog/DaftPunkHelmet
/ArduinoBlueTooth/ArduinoBlueTooth.ino
UTF-8
1,984
2.796875
3
[]
no_license
#include <SoftwareSerial.h> #include <ArduinoJson.h> #include <Adafruit_NeoPixel.h> #define PIN 6 #define NUMPIXELS 60 SoftwareSerial BT1(4, 2); String colors[6]; Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); long color[3] = { 0,0,0 }; void setup() { Serial.begin(9600); BT1.begin(9600); pinMode(13, OUTPUT); pixels.begin(); Serial.println("Comenzado"); } void loop() { String receivedData = GetBTLine(); if (receivedData != "") { Serial.println(receivedData); StaticJsonBuffer < 200 > jsonBuffer; JsonObject & root = jsonBuffer.parseObject(receivedData); // Test if parsing succeeds. if (!root.success()) { return; } for (int i = 0; i < 6; i++) { String colorStr = root["colors"][i]; Serial.println(colorStr); RetrieveColor(colorStr); for (int j = i * 10; j < (i + 1) * 10; j++) { // Serial.print(j); // Serial.print(" "); pixels.setPixelColor(j, pixels.Color(color[0], color[1], color[2])); // Moderately bright green color. pixels.show(); // This sends the updated pixel color to the hardware. } Serial.println(""); } } } String GetBTLine() { String str = ""; if (BT1.available()) { char c = BT1.read(); while (c != '\n') //Hasta que el caracter sea intro { str = str + c; c = BT1.read(); } return (str); } } String GetLine() { String S = ""; if (Serial.available()) { char c = Serial.read(); ; while (c != '\n') //Hasta que el caracter sea intro { S = S + c; delay(25); c = Serial.read(); } return (S + '\n'); } } String GetCharArray(char str) { String ramdomString(str); return ramdomString; } void RetrieveColor(String hexadecimal) { long colors[3]; if (hexadecimal.startsWith("#")) { long number = (long)strtol(&hexadecimal[1], NULL, 16); // Split them up into r, g, b values color[0] = number >> 16; color[1] = number >> 8 & 0xFF; color[2] = number & 0xFF; } }
true
a7633382cf251bc4b508239580a80880398aeedc
C++
gsscsd/Code_Training
/leetcode/Easy/9.回文数.cpp
UTF-8
993
3.953125
4
[]
no_license
/** 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 你能不将整数转为字符串来解决这个问题吗? */ /** 解题思路 */ #include <iostream> #include <vector> #include <string> using namespace std; class Solution { public: // 采用反转整数的方式,100ms bool isPalindrome(int x) { if(x < 0) return false; int temp = x; int reverse = 0; while(temp != 0) { reverse = reverse * 10 + (temp % 10); temp /= 10; } return !(reverse - x); } // 采用字符串的方式 204ms bool isPalindrome_(int x) { string s = to_string(x); int len = s.length(); for(int i = 0;i < len;i++) { if(s[i] != s[len - i - 1]) { return false; } } return true; } }; int main() { return 0; }
true
2977e7f5db6c6f6901643f60ab8684c00cbc6513
C++
avyavkumar/coding-solutions
/leetcode_merge_intervals.cpp
UTF-8
1,408
3.140625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; bool sortingFunc(Interval a, Interval b) { if ( b.start != a.start) return b.start > a.start; else return b.end > a.end; } class Solution { public: vector<Interval> merge(vector<Interval>& intervals) { sort(intervals.begin(), intervals.end(), sortingFunc); std::vector<Interval> finalResult; if (intervals.size() == 0) return finalResult; int startIndex = 0, endIndex = 0; int endTime = intervals[0].end; int startTime = intervals[0].start; for (int i = 1; i < intervals.size(); i++) { if (intervals[i].end >= endTime && intervals[i].start <= endTime) { endIndex = i; endTime = intervals[i].end; } if (intervals[i].start >= startTime && intervals[i].end <= endTime) continue; else { Interval temp(intervals[startIndex].start,intervals[endIndex].end); finalResult.push_back(temp); startIndex = i; endIndex = i; startTime = intervals[i].start; endTime = intervals[i].end; } } Interval temp(startTime,endTime); finalResult.push_back(temp); return finalResult; } };
true
758f3d0f63fc12d57c7de1c0639b012df2ca1a2b
C++
bhuman/BHumanCodeRelease
/Src/Libs/ImageProcessing/CNS/CameraModelOpenCV.h
UTF-8
8,339
2.796875
3
[ "BSD-2-Clause" ]
permissive
#pragma once #include "ImageProcessing/SIMD.h" #include <Eigen/Geometry> #include <Eigen/SVD> #include <vector> #include <iostream> //! Simple camera model class /* Camera model class using the model also used in OpenCV: http://opencv.willowgarage.com/documentation/camera_calibration_and_3d_reconstruction.html This can been seen as stripped-down version of sensor-model. Some of the functions were taken from sensor-model. */ class CameraModelOpenCV { public: //! Create empty camera model CameraModelOpenCV(); //! Constructor with all coefficients CameraModelOpenCV(const Eigen::Isometry3d& camera2World, double width, double height, double scale_x, double scale_y, double offset_x, double offset_y, double k1 = 0, double k2 = 0, double p1 = 0, double p2 = 0); //! Project ball in world coordinates into image plane bool worldBall2ImageCircleClipped(const Eigen::Vector3d& p_world, double worldRadius, double& x, double& y, double& r) const; //! Reconstruct ball in world coordinates from image coordinates and known ball radius (in world) void imageCircle2WorldBall(double x, double y, double radius, double worldRadius, Eigen::Vector3d& pBall) const; //! Construct ray that leads to the image position in camera coordinates void image2CameraRay(double x, double y, Eigen::Vector3d& p, Eigen::Vector3d& v) const; //! Construct ray that leads to the image position in world coordinates void image2WorldRay(double x, double y, Eigen::Vector3d& p, Eigen::Vector3d& v) const; //! Simple projection into image space from world coordinates void world2Image(const Eigen::Vector3d& p_world, double& x, double& y) const; //! Simple projection into image space from world coordinates (with clipping indication) bool world2ImageClipped(const Eigen::Vector3d& v, double& x, double& y) const; //! Simple projection into image space from camera coordinates void camera2Image(const Eigen::Vector3d& p_cam, double& x, double& y) const; //! Simple projection into image space from camera coordinates (with clipping indication) bool camera2ImageClipped(const Eigen::Vector3d& p_cam, double& x, double& y) const; //! Apply radial distortion at x, y void distort(double& xDist, double& yDist, double x, double y) const; /*! Overloaded function */ void distort(double& x, double& y) const {distort(x, y, x, y); } //! Apply distortion at x, y and compute the Jacobian void distort(double& xDist, double& yDist, Eigen::Matrix2d& jac, double x, double y) const; //! Radial part of the distortion model double rPrimeOfR(double r) const {return r * (1 + k1 * r * r + k2 * r * r * r * r);} //! Inverse of \c rPrimeOfR /*! Uses linear interpolation on the pre-calculated table \c rOfRPrimeTab. If \c rPrime>rPrimeMax \c Nan is returned. */ double rOfRPrime(double rPrime) const {return rOfRPrime2Factor(rPrime * rPrime) * rPrime;} enum {DEFAULT_REFINEMENT_CTR = 1}; //! Computes undistorted image coordinates according to distortion parameters /*! There is no analytical solution, so an approximate formula is used. The result is refined by a \c refinementCtr step of Newton's method. */ void undistort(double& xUndist, double& yUndist, double x, double y, int refinementCtr = DEFAULT_REFINEMENT_CTR) const; //! Overloaded function void undistort(double& x, double& y, int refinementCtr = DEFAULT_REFINEMENT_CTR) const {undistort(x, y, x, y, refinementCtr);}; //! Set frame of camera in world coordinates void setCamera2World(const Eigen::Isometry3d& cam2world); //! Computes the table used for undistortion /*! Computes also both rMax and rMaxPrime. And sets \c isDistorted */ void computeRTab(); //! Return frame of camera in world coordinates Eigen::Isometry3d getCamera2World() const; //! Extends v1 to an orthonormal system [v1 v2 v3] void smOrthogonalVector(const Eigen::Vector3d& v1, Eigen::Vector3d& v2, Eigen::Vector3d& v3) const; Eigen::Vector3d getOrthoVec(Eigen::Vector3d v) const; //! Camera pose in world coordinates Eigen::Isometry3d camera2World; //! Pinhole camera parameters double width, height, scale_x, scale_y, offset_x, offset_y; //! distortion camera parameters (see openCV) double k1, k2, p1, p2; //! If in distortion r<rMax the distortion function is unique (similar for undistortion) double rMax, rMaxPrime; //! See \c rOfRPrimeTab double rPrime2Step; //! Precomputed table for computing \c rOfRPrimeFactor fast /*! \c rPrimeToR[i]=rOfRPrimeFactor(i*rPrime2Step). Values are available up to \c rMaxPrime*rMaxPrime. */ std::vector<double> rOfRPrime2FactorTab; //! Whether this camera has distortion or not (coefficient as in the default constructor) bool isDistorted; //! auxiliary function for radial undistortion /*! If rPrime = rPrimeOfR(r), then \c rOfRPrimeFactor(rPrime*rPrime)*rPrime=r */ double rOfRPrime2Factor(double rPrime2) const; //! Scales the calibration, corresponding to a scaled image void scale(double factor) { scale_x *= factor; scale_y *= factor; offset_x *= factor; offset_y *= factor; width *= factor; height *= factor; } //! Returns a rotation that moves the image center by \c dX,dY /*! Precisely, p(cameraRotation(dX,dY)*Vector3d(0,0,1)) \approx p(Vector3d(0,0,1))+(dX,dY) */ Eigen::Isometry3d cameraRotation(double dX, double dY) const { Eigen::Vector3d axis(-dY / scale_y, dX / scale_x, 0); double angle = axis.norm(); if(angle == 0) angle = 1E-9; return Eigen::Isometry3d(Eigen::AngleAxisd(angle, axis / angle)); } //! Computes a coefficient, how much at undistorted (xU,yU) the distortion deviates from a flat mapping /*! The result is defined as max_{small dX,dY} |distort(xU+dX,yU+dY)-distort(xU,yU)|/|(dX, dY)| */ double distortionAt(double xU, double yU) const; //! Computes the maximum \c distortionAt in the image double computeWorstDistortion() const; //! Returns whether \c x,y is in the image. bool isInImage(double x, double y) const {return 0 <= x && x < width && 0 <= y && y < height;} //! Returns a rotation of the camera that moves \c (xOld,yOld) to \c xNew,yNew /*! A point which maps to \c xOld,yOld in the old camera frame maps to \c xNew,yNew in the new camera frame and the result returned is the rotation from new to old camera frame that achieves it. Being a rotation this holds for all points in space. Several rotations have this property. Among them the one is chosen that has the smallest rotation angle. */ Eigen::Isometry3d rotationNewCamera2OldCamera(double xOld, double yOld, double xNew, double yNew) const; //! Computes a camera that is in the middle and has averaged parameters static CameraModelOpenCV average(const CameraModelOpenCV& camA, const CameraModelOpenCV& camB); EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; //! Define input streaming std::istream& operator>>(std::istream& i, CameraModelOpenCV& c); //! Define output streaming std::ostream& operator<<(std::ostream& o, const CameraModelOpenCV& c); //! Returns the smallest rotation X, such that v1=X*v0 inline Eigen::Isometry3d fromTo(const Eigen::Vector3d& v0, const Eigen::Vector3d& v1) { double n0 = v0.norm(), n1 = v1.norm(); if(n0 == 0 || n1 == 0) return Eigen::Isometry3d::Identity(); Eigen::Vector3d axis = v0.cross(v1); double len = axis.norm(), angle = atan2(len, v0.dot(v1)); if(len == 0) return Eigen::Isometry3d::Identity(); return Eigen::Isometry3d(Eigen::AngleAxisd(angle, axis / len)); } //! Finds the closest Isometry3d to a given affine transformation /*! The purpose of this function is to restore the orthonormality of the rotation part of the matrix. Call this function after loading Isometries and once in a while when numerical errors can accumulate. */ inline Eigen::Isometry3d normalize(const Eigen::Isometry3d& a2b) { Eigen::Isometry3d result(a2b); result.linear() = a2b.rotation(); return result; } //! Interpolates between two isometry \c a and \c b /*! \c alpha=0 returns a, \c alpha=1 returns b, the orientation part uses spherical interpolation, the translation part is linear. */ Eigen::Isometry3d slerp(const Eigen::Isometry3d& a, const Eigen::Isometry3d& b, double alpha);
true
99494810e4647b75a0ce277b9b75f95bca851ac7
C++
twobob/FinalProject
/SourceCode/Prototypes/SpaceColonisation/SpaceColonisation/Node.cpp
UTF-8
2,281
3.359375
3
[ "BSL-1.0", "Zlib", "MIT" ]
permissive
#include <iostream> #include "Node.h" #include "Vec2.h" #include "Utility.h" #include "Edge.h" Node::Node(int newX, int newY) { pos = new Vec2(newX, newY); } Node::Node(Vec2* newPos) { pos = newPos; } Node::~Node() {} void Node::Branch(std::vector<Node*> nodes, std::vector<Edge*> edges) { // Shortest = null Node* shortest = nullptr; float minDist = 75; // For every node... for (auto neighbour : nodes) { if (neighbour->start) { continue; } // If shortest is null if (shortest == nullptr) { // If neighbour doesn't have a parent if (neighbour->parent == nullptr) { // And is within the minDistance... if (Utility::DistanceBetween(neighbour->getPos(), pos) < minDist) { // And it doesn't create a road intersection... bool intersection = false; // For each road for (auto edge : edges) { if (Utility::Intersect(neighbour->getPos(), pos, edge->child->getPos(), edge->parent->getPos())) { // std::cout << "Intersection found whilst assigning shortest. Breaking." << std::endl; intersection = true; break; } } // If no intersection... if (!intersection) { // It becomes the shortest shortest = neighbour; } } } } // Else else { // If neighbour doesn't already have a parent if (neighbour->parent == nullptr) { // If neighbour is closer than shortset if (Utility::DistanceBetween(neighbour->getPos(), pos) < Utility::DistanceBetween(shortest->getPos(), pos)) { // If this connection doesn't create an road intersection... bool intersection = false; // For each road for (auto edge : edges) { if (Utility::Intersect(neighbour->getPos(), pos, edge->child->getPos(), edge->parent->getPos())) { // std::cout << "Intersection found. Breaking." << std::endl; intersection = true; break; } } // If no intersection... if (!intersection) { // neighbour is our new shortest shortest = neighbour; } } } } } // If shortest still isn't null if (shortest != nullptr) { // Add shortest to our children children.push_back(shortest); // Shortest's parent is this shortest->parent = this; } }
true
fbedd7826cd843e02d76081608781f24cfb2ad3a
C++
OneWhiteSpirit/gamedev_courses
/hello_libs/hello_bins/src/main.cpp
UTF-8
933
3.4375
3
[]
no_license
#include <iostream> #include <cstdlib> #include <hello_libs.hpp> int main() { int n = 2, m = 2; std::cout << "Find largest element in matrix." << std::endl; std::cout << std::endl; //std::cout << "Enteratrix size NxM." << std::endl; //std::cout << "N: "; std::cin >> n; //std::cout << std::endl; //std::cout << "M: "; std::cin >> m; //std::cout << std::endl; //std::cout << "Enter matrix elements: " << std::endl; std::cout << "Matrix " << n << "x" << m << std::endl; int *a = new int[n*m]; a[0] = 2; a[1] = 12; a[2] = 44; a[3] = 15; /*for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { std::cin >> a[i*m + j]; } std::cout << std::endl; }*/ bool is_good = matrix_largest_elem(reinterpret_cast<int*>(a), n , m); int result = is_good ? EXIT_SUCCESS : EXIT_FAILURE; return result; }
true
a4a4d83f6abde2e1efd5199a809ad41f159242e1
C++
jwhuseu/ACM
/数据结构/二叉树/Uva 10562 Undraw the Trees (看图写树)(递归的思想).cpp
GB18030
2,553
3.328125
3
[]
no_license
//Ŀӣhttps://vjudge.net/contest/169966#problem/Q //Ŀ: ǽתűʾÿó'-',|'ͿոַʾÿҶӽһ"|",Ȼһ"-",ǡӽڵϷ //˼·Ҫǿǰ(DFS),ҪǴ ⣬ȻDFS #include <iostream> #include <string.h> #include <string> #include <stdio.h> const int maxn = 200 + 10; using namespace std; char s[maxn][maxn]; int n; void DFS(int r, int c) { printf("%c(", s[r][c]); if (r + 1 < n && s[r + 1][c] == '|') { int i = c; while (s[r + 2][i - 1] == '-'&& i - 1 >= 0)i--; //ҵ"-"ߵǸ while (s[r + 2][i] == '-' && s[r + 3][i] != '\0') { if (!isspace(s[r + 3][i]))DFS(r + 3, i); i++;//ݹÿһ } } printf(")"); //ݵʱǵ ) } int main() { //freopen("in.txt", "r", stdin); int T; scanf("%d", &T); getchar(); //ȡֺ Ҫȡַַ һҪһ while (T--) { n = 0; while (gets(s[n])) { if (s[n++][0] == '#') { n--; break; } } printf("(");// if (n) { for (int i = 0; i < strlen(s[0]); i++) { if (!isspace(s[0][i])) { DFS(0, i); break; } //ֻһ } } printf(")\n"); // } return 0; } //ѵ(Ҫ IJͬ )Ϥfgets(char *s,int n,sstream)÷ #include <iostream> #include <string.h> #include <string> #include <stdio.h> const int maxn = 200 + 10; using namespace std; char s[maxn][maxn]; int n; void DFS(int r, int c) { printf("%c(", s[r][c]); if (r + 1 < n && s[r + 1][c] == '|') { int i = c; while (s[r + 2][i - 1] == '-'&& i - 1 >= 0)i--; while (s[r + 2][i] == '-' && s[r + 3][i] != '\0') { if (!isspace(s[r + 3][i]))DFS(r + 3, i); i++; } } printf(")"); } int main() { //freopen("in.txt", "r", stdin); int T; fgets(s[0], maxn, stdin); //ļstreamжȡmaxn-1ַ/һУһвmaxn-1sַ//:http://blog.csdn.net/jackin2/article/details/5573771 sscanf(s[0], "%d", &T); while (T--) { n = 0; for (;;) { fgets(s[n], maxn, stdin); if (s[n][0] == '#')break; n++; } printf("("); if (n) { for (int i = 0; i < strlen(s[0]); i++) { if (!isspace(s[0][i])) { DFS(0, i); break; } } } printf(")\n"); } return 0; } /* : 2 A | -------- B C D | | ----- - E F G # e | ---- f g # */
true
dfaad4f25109f8e011759c217a97dda9d50dcfff
C++
JasonKappes/Kap-Engine
/Editor/Object Selection Strategy Pattern/ActiveObject.h
UTF-8
1,653
2.578125
3
[]
no_license
#ifndef _activeobject #define _activeobject #include "SelectedObject.h" class Serializable; class PositionUI; class RotationUI; class EmptyUI; class ScaleUI; class GroupUI; //This manages the overall behavior for selected objects class ActiveObject : public SelectedObject { public: ActiveObject(); ActiveObject(const ActiveObject&) = delete; ActiveObject operator=(const ActiveObject&) = delete; ~ActiveObject(); //Calls the forward movement behavior of the current indicator virtual void ForwardAdjustment() override; //Calls the right movement behavior of the current indicator virtual void RightAdjustment() override; //Calls the left movement behavior of the current indicator virtual void LeftAdjustment() override; //Calls the backward movement behavior of the current indicator virtual void BackwardAdjustment() override; //Sends world information for the selected object to the selected indicators virtual void ShowSelection() override; //Selects the current indicator group (pos/scale/rot) based on adjustment type virtual void SetAdjustmentType(SelectedObject::adjustment) override; //Switches to a topdown view of the selected object virtual void SnapToObject() override; //Duplicates the selected object (duplicate object can be selected, moved, and is saved) virtual void Duplicate() override; //Deletes this object (won't display during any future runs) virtual void Erase() override; //Calls the indicator group to render its indicators virtual void DrawUI() override; private: PositionUI* position_ui; RotationUI* rotation_ui; ScaleUI* scale_ui; }; #endif _activeobject #pragma once
true
cbd79d1477c592fb960c5ba7239a4e4c9fda5534
C++
belkacemlahouel/IA41_Pogo
/Interface_cpp/boardgui.cpp
UTF-8
4,655
2.796875
3
[]
no_license
#include "boardgui.h" BoardGUI::BoardGUI(QWidget* parent):QWidget(parent) { /* Creation des cases et de leur version graphique */ this->boardGUI = new CaseGUI*[3]; for (int i = 0; i < 3; ++i) boardGUI[i] = new CaseGUI[3]; for(int i=0;i<3;i++) { for(int j=0;j<3;j++){ this->boardGUI[i][j] = CaseGUI(j+1 +(i*3),parent); } } /* Ajout de l'image sur les cases, et positionnement */ QPixmap case_pixmap; if(!case_pixmap.load(":/new/images/case150px.png")){ qWarning("Failed to load case.png"); } list<PawnLabel*>::iterator it; for(int i=0;i<3;i++) { for(int j=0;j<3;j++){ int x = i*this->boardGUI[i][j].getCaseSize()+i*10+10; int y = j*this->boardGUI[i][j].getCaseSize()+j*10+10; this->boardGUI[i][j].setParent(parent); this->boardGUI[i][j].setPixmap(case_pixmap); this->boardGUI[i][j].move(x,y); } } /* Création de tous les pions version GUI, et ajout au plateau */ this->insertPawnLabel(0,0,new PawnLabel(parent,true)); this->insertPawnLabel(0,0,new PawnLabel(parent,true)); this->insertPawnLabel(1,0,new PawnLabel(parent,true)); this->insertPawnLabel(1,0,new PawnLabel(parent,true)); this->insertPawnLabel(2,0,new PawnLabel(parent,true)); this->insertPawnLabel(2,0,new PawnLabel(parent,true)); this->insertPawnLabel(0,2,new PawnLabel(parent,false)); this->insertPawnLabel(0,2,new PawnLabel(parent,false)); this->insertPawnLabel(1,2,new PawnLabel(parent,false)); this->insertPawnLabel(1,2,new PawnLabel(parent,false)); this->insertPawnLabel(2,2,new PawnLabel(parent,false)); this->insertPawnLabel(2,2,new PawnLabel(parent,false)); /* Connexion des pawnsLabels au plateau GUI */ for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { for(it = this->boardGUI[i][j].pawnListGUI.begin();it != this->boardGUI[i][j].pawnListGUI.end() ; it++) { PawnLabel *temp = *it; connect(temp,SIGNAL(deselectOthers(PawnLabel*)),this,SLOT(deselectPawnsLabels(PawnLabel*))); } } } } /* Idem que insertPawn, mais GRAPHIQUEMENT */ void BoardGUI::insertPawnLabel(int i, int j, PawnLabel *p) { CaseGUI* c= &(this->boardGUI[i][j]); int x = c->x() + c->getCaseSize()/2 - 25; int y = c->y() + c->getCaseSize() - 15 - c->pawnListGUI.size()*10; c->pawnListGUI.push_back(p); p->move(x,y); } void BoardGUI::insertPawnLabel(CaseGUI* c, PawnLabel *p) { int x = c->x() + c->getCaseSize()/2 - 25; int y = c->y() + c->getCaseSize() - 15 - c->pawnListGUI.size()*10; c->pawnListGUI.push_back(p); p->move(x,y); } void BoardGUI::removePawn(CaseGUI* c, PawnLabel *p) { c->pawnListGUI.remove(p); } // Se déclenche a la fin de Board::movePawns. void BoardGUI::movePawnLabels(Case* oldCase,Case* dest) { PawnLabel* toMove; list<PawnLabel*>::iterator it; list<PawnLabel*>::iterator toMove_iterator; CaseGUI* oldCaseGUI; CaseGUI* destGUI; /* On recherche les versions GUI des cases oldCase et dest */ for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { if(boardGUI[i][j].getCaseNum() == oldCase->getCaseNum()) { oldCaseGUI = &boardGUI[i][j]; } } } for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { if(boardGUI[i][j].getCaseNum() == dest->getCaseNum()) { destGUI = &boardGUI[i][j]; } } } for (it=oldCaseGUI->pawnListGUI.begin(); it != oldCaseGUI->pawnListGUI.end(); ++it) { if((*it)->getSelected() == 1) { toMove_iterator = it; } } while(toMove_iterator != oldCaseGUI->pawnListGUI.end()) { toMove = *toMove_iterator; insertPawnLabel(destGUI,toMove); toMove_iterator = oldCaseGUI->pawnListGUI.erase(toMove_iterator); toMove->setSelected(0); } } void BoardGUI::deselectPawnsLabels(PawnLabel *p) { list<PawnLabel*>::iterator it; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { for(it = this->boardGUI[i][j].pawnListGUI.begin();it != this->boardGUI[i][j].pawnListGUI.end() ; it++) { PawnLabel *temp = *it; if(temp != p) { temp->setSelected(false); } } } } } BoardGUI& BoardGUI::operator =(const BoardGUI& b){ this->boardGUI = b.boardGUI; return *this; }
true
1c6320f64ba6ba498e693ec04dbf319c74d67bdd
C++
ShankarBirTamang/Learning_Cplusplus
/ch6_streamComputationForConsole/Q9.cpp
UTF-8
2,409
4
4
[]
no_license
/* Write a program to store and retrieve the information of patient. (Patient ID,name, address, age and type )in hospital management system. */ #include<iostream> #include<fstream> using namespace std; class patient{ int patientID; char name[40]; char address[30]; int age; char ptype[30]; public: void getdata(){ cout<<"\nEnter Patient ID: "; cin>>patientID; cout<<"Enter Patient name: "; cin>>name; cout<<"Enter Address: "; cin>>address; cout<<"Enter age: "; cin>>age; cout<<"Enter patient's type: "; cin>>ptype; } void showdata(){ cout<<"\nPatient ID: "<<patientID<<endl; cout<<"Paitent Name: "<<name<<endl; cout<<"Patient Address: "<<address<<endl; cout<<"Age: "<<age<<endl; cout<<"Patient's type: "<<ptype<<endl; } void inputRecord(); void displayRecord(); }; void patient::inputRecord(){ patient pat; fstream file; file.open("patient.txt",ios::in|ios::out|ios::app|ios::binary); char ch; do{ pat.getdata(); file.write((char*)&pat,sizeof(pat)); cout<<"Do you want to add another patient's information: (y/n)? "; cin>>ch; }while(ch=='y'|ch=='Y'); file.close(); } void patient::displayRecord(){ patient pat; fstream file; file.open("patient.txt",ios::in|ios::out|ios::binary); file.seekg(0); file.read((char*)&pat,sizeof(pat)); cout<<"\nPatient's information."<<endl; cout<<"-----------------------"; while(!file.eof()){ pat.showdata(); file.read((char*)&pat,sizeof(pat)); } file.close(); } int main() { patient p; int n; while(1){ cout<<"\nSelect any number: "<<endl; cout<<"-------------------"<<endl; cout<<"1.Input Record"<<endl; cout<<"2.Display Record"<<endl; cout<<"3.Exit"<<endl; cout<<"==> "; cin>>n; switch (n) { case 1: p.inputRecord(); break; case 2: p.displayRecord(); break; case 3: exit(0); break; default: cout<<"Enter number between 1 and 3 only."<<endl; break; } } return 0; }
true
3b4f3c360cefe6003cebbbe2c94d3ffd85bc8ef2
C++
Yonaioana/POO_TEMA3
/Farmacie.cpp
UTF-8
9,639
3.1875
3
[]
no_license
#include "Farmacie.h" /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ ///Functii membru ale clasei Farmacie Farmacie::Farmacie(int id): m_id(id)//partea default { /// std::cout<<"Construiesc o farmacie cu urmatorul id: "<<id<<std::endl; } ////copy constructor -> folosit pt initializarea obiectelor noi Farmacie::Farmacie(const Farmacie &f): m_id(f.m_id) { /// std::cout<<"Am apelat copy constructor pt Farmacie"<<std::endl; } ///operator= -> am folosit pentru a inlocui continutul unui obiect Farmacie& Farmacie::operator= (const Farmacie &f) { /// self-assignment guard if (this == &f) return *this; // do the copy m_id = f.m_id; // can handle self-assignment // return the existing object /// std::cout<<"Am apelat operator= pt Farmacie"<<std::endl; return *this; } ///destructor Farmacie::~Farmacie() { /// std::cout<<"Distrug farmacia cu urmatorul id: "<<m_id<<std::endl; } ///functie virtuala de afisare in supraclasa void Farmacie::print() { std::cout<<"Farmacie (clasa de baza) cu id-ul: "<<m_id<<std::endl; } ///setter, getter void Farmacie::SetIdFarmacie(int id) { m_id = id; } int Farmacie::GetIdFarmacie() const { return m_id; } std::ostream& operator<< (std::ostream &out, const Farmacie &f) { out<<"Farmacia are id-ul: "<<f.m_id<<std::endl; return out; } std::istream& operator>> (std::istream &in, Farmacie &f) { std::cout<<"Introduceti id-ul farmaciei:"<<std::endl; in >> f.m_id; return in; } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ ///Functii membru ale clasei FarmacieFizica FarmacieFizica::FarmacieFizica(int id) { Farmacie::SetIdFarmacie(id); m_nrAngajati = 0; m_denumire = ""; m_profit = 0; std::cout<<"Construiesc farmacia fizica cu id-ul: "<<id<<std::endl; } ///constructor cu parametri FarmacieFizica::FarmacieFizica(int id, const std::string &denumire, int nrAngajati, int profit):m_denumire(denumire), m_nrAngajati(nrAngajati), m_profit(profit) { Farmacie::SetIdFarmacie(id); /// std::cout<<"Construiesc farmacia fizica cu id-ul "<<id<<" si numele "<<denumire<<std::endl; } ///copy constructor FarmacieFizica::FarmacieFizica(const FarmacieFizica &f) { Farmacie::m_id = f.m_id; m_denumire = f.m_denumire; m_nrAngajati = f.m_nrAngajati; m_profit = f.m_profit; std::cout<<"Am apelat copy constructor pt FarmacieFizica"<<std::endl; } ///operator= FarmacieFizica& FarmacieFizica::operator= (const FarmacieFizica &f) { // self-assignment guard if (this == &f) return *this; // do the copy Farmacie::m_id = f.m_id; // can handle self-assignment m_denumire = f.m_denumire; m_nrAngajati = f.m_nrAngajati; m_profit = f.m_profit; // return the existing object std::cout<<"Am apelat assignment constructor pt FarmacieFizica"<<std::endl; return *this; } ///destructor FarmacieFizica::~FarmacieFizica() { /// std::cout<<"Distrug farmacia fizica cu id-ul: "<<m_id<<std::endl; } ///setter, getter void FarmacieFizica::SetDenumire(const std::string &denumire) { m_denumire = denumire; } void FarmacieFizica::SetNumarAngajati(int nrAngajati) { m_nrAngajati = nrAngajati; } void FarmacieFizica::SetProfit (int profit) { m_profit = profit; } int FarmacieFizica::GetNumarAngajati() const { return m_nrAngajati; } int FarmacieFizica::GetProfit() const { return m_profit; } const std::string& FarmacieFizica::GetDenumire() const { return m_denumire; } ///supraincarcare >>,<< std::ostream& operator<< (std::ostream &out, const FarmacieFizica &f) { out<<"Farmacia fizica are:"<<std::endl; out<<"-id-ul: "<<f.GetIdFarmacie()<<std::endl; out<<"-deunumirea: "<<f.m_denumire<<std::endl; out<<"-numarul de angajati:"<<f.m_nrAngajati<<std::endl; out<<"-profitul:"<<f.m_profit<<std::endl; return out; } std::istream& operator>> (std::istream &in, FarmacieFizica &f) { std::cout<<"Introduceti pentru farmacia fizica urmatoarele:"<<std::endl; std::cout<<"Id-ul:"<<std::endl; int id; in>>id; f.SetIdFarmacie(id); std::cout<<"Denumirea:"<<std::endl; in>>f.m_denumire; std::cout<<"Numarul de angajati:"<<std::endl; in>>f.m_nrAngajati; std::cout<<"Profitul:"<<std::endl; in>>f.m_profit; std::cout<<std::endl; return in; } ///functie virtuala de afisare void FarmacieFizica::print() { std::cout<<"Farmacie fizica (clasa derivata)"<<std::endl; std::cout<<*this; } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ ///Functii membru ale clasei FarmacieOnline ///default constructor FarmacieOnline::FarmacieOnline(int id) { Farmacie::m_id = id; m_web = ""; m_nrVizitatori = 0; m_discount = 0; m_dateFarmacie = make_tuple(m_web, m_nrVizitatori, m_discount); std::cout<<"Construiesc farmacia online cu id-ul: "<<Farmacie::m_id<<std::endl; } ///constructor cu parametrii FarmacieOnline::FarmacieOnline(int id, std::string web, int nrVizitatori, int discount):m_web(web), m_nrVizitatori(nrVizitatori), m_discount(discount) { Farmacie::m_id = id; m_dateFarmacie = make_tuple(web, nrVizitatori, discount); //m_info.push_back(m_dateFarmacie); std::cout<<"Construiesc farmacia online cu id-ul "<<Farmacie::m_id<<"si adresa web "<<web<<std::endl; } ///copy constructor FarmacieOnline::FarmacieOnline(const FarmacieOnline &f) { Farmacie::m_id = f.m_id; m_web = f.m_web; m_nrVizitatori = f.m_nrVizitatori; m_discount = f.m_discount; m_dateFarmacie = make_tuple(f.m_web, f.m_nrVizitatori, f.m_discount); //m_info.push_back(m_dateFarmacie); std::cout<<"Am apelat copy constructor pt FarmacieOnline"<<std::endl; } ///operator= FarmacieOnline& FarmacieOnline::operator= (const FarmacieOnline &f) { // self-assignment guard if (this == &f) return *this; //do the copy Farmacie::m_id = f.m_id; // can handle self-assignment m_web = f.m_web; m_nrVizitatori = f.m_nrVizitatori; m_discount = f.m_discount; m_dateFarmacie = make_tuple(f.m_web, f.m_nrVizitatori, f.m_discount); //do the copy in the data structure for (unsigned int i = 0; i<m_info.size(); i++) if (m_info[i] == f.m_dateFarmacie) { m_info[i] = f.m_dateFarmacie; break; } // return the existing object std::cout<<"Am apelat operator= pentru FarmacieOnline"<<std::endl; return *this; } ///destructor FarmacieOnline::~FarmacieOnline() { //Stergem obiectul si din vector! std::cout<<"Distrugem farmacia online cu id-ul:"<<Farmacie::m_id<<std::endl; m_info.erase(std::find(m_info.begin(), m_info.end(), this->m_dateFarmacie)); } ///functie care afiseaza toate farmaciile online void FarmacieOnline::ShowAllFarmaciiOnline() { std::cout<<"Lista tuturor farmaciilor online"<<std::endl; for (m_vec::const_iterator i = m_info.begin(); i != m_info.end(); i++) { std::cout<<"Adresa web este: "<<std::get<0>(*i)<<std::endl; std::cout<<"Numarul de vizitatori este: "<<std::get<1>(*i)<<std::endl; std::cout<<"Discount-ul este: "<<std::get<2>(*i)<<std::endl; std::cout<<std::endl; } } ///functie care adauga o farmacie in vector void FarmacieOnline::addFarmacieOnline(FarmacieOnline &f) { m_info.push_back(f.m_dateFarmacie); } ///supraincarcare operatori bool operator== (const FarmacieOnline &f1, const FarmacieOnline &f2) { if (f1.GetIdFarmacie()==f2.GetIdFarmacie() && f1.m_dateFarmacie == f2.m_dateFarmacie) return true; return false; } std::ostream& operator<< (std::ostream &out, const FarmacieOnline &f) { out<<"Farmacia online are:"<<std::endl; out<<"-id-ul: "<<f.GetIdFarmacie()<<std::endl; out<<"-adresa web: "<<f.m_web<<std::endl; out<<"-numarul de vizitatori:"<<f.m_nrVizitatori<<std::endl; out<<"-discout-ul:"<<f.m_discount<<std::endl; return out; } std::istream& operator>> (std::istream &in, FarmacieOnline &f) { std::cout<<"Introduceti pentru farmacia online urmatoarele:"<<std::endl; std::cout<<"Id-ul:"<<std::endl; int id; in>>id; f.SetIdFarmacie(id); std::cout<<"Adresa web:"<<std::endl; in>>f.m_web; std::cout<<"Numarul de vizitatori:"<<std::endl; in>>f.m_nrVizitatori; std::cout<<"Discount-ul:"<<std::endl; in>>f.m_discount; f.m_dateFarmacie = make_tuple(f.m_web, f.m_nrVizitatori, f.m_discount); return in; } ///functie de afisare void FarmacieOnline::print() { std::cout<<"Farmacie online (clasa derivata)"<<std::endl; std::cout<<*this; } ///instantierea vectorului std::vector<std::tuple<std::string,int,int>> FarmacieOnline::m_info;
true
a20b1d712b67b5dac87ec8d3e186d3d2f72db7ad
C++
rexxar-tc/IoDriver
/Firmware/EEPROMHandler.hpp
UTF-8
1,599
2.875
3
[]
no_license
#ifndef _IODRIVER_EEPROMHANDLER #define _IODRIVER_EEPROMHANDLER #include <EEPROM.h> #include <iodriver.hpp> #ifndef EEPROM1_SIZE # error IoDriver::EEPROMHandler needs to know the size of the primary EEPROM! #endif #ifdef HAS_SECONDARY_EEPROM # ifndef EEPROM2_SIZE # error IoDriver::EEPROMHandler needs to know the size of the secondary EEPROM! # endif #endif // Note: VIRTUAL_START must be less than VIRTUAL_END. // Example sizes assume a virtual size of 200. #ifdef EEPROM_H_VIRTUAL_SIZE # ifndef NEGATIVE_VIRTUAL_INDICES # ifndef HAS_SECONDARY_EEPROM # define EEPROM_H_VIRTUAL_START EEPROM1_SIZE // e.g. 1024 # else # define EEPROM_H_VIRTUAL_START EEPROM1_SIZE+EEPROM2_SIZE // e.g. 2048 # endif # else # define EEPROM_H_VIRTUAL_START -100-EEPROM_H_VIRTUAL_SIZE // e.g. -300 /* Note: address -1 is reserved for "404 not found" return values, * so we can't have a virtual array with indices, say, -200 to -1. * However, values such as -201 to -2 are inconvenient. So, we offset * by 100 instead of 1 to have something cleaner like -300 to -99. */ # endif # define EEPROM_H_VIRTUAL_END EEPROM_H_VIRTUAL_START+EEPROM_H_VIRTUAL_SIZE-1 // e.g. 1223, 2247, -101 #endif namespace IoDriver { class EEPROMHandler { public: uint8_t read( int ); void write( int, uint8_t ); private: #ifdef EEPROM_H_VIRTUAL_SIZE int address_to_virtual_index( int ); uint8_t virtual_eeprom[EEPROM_H_VIRTUAL_SIZE]; #endif }; } extern IoDriver::EEPROMHandler EEPROM_H; #endif // _IODRIVER_EEPROMHANDLER
true
65257246668b88e79dfe2830c463fbfac1b475df
C++
myabu-dev/AtCoder
/ABC/129/aa.cpp
UTF-8
1,405
2.859375
3
[]
no_license
// // Created by yuu on 2019-06-17. // // // Created by yuu on 2019-06-09. // #include <iostream> #include <string> #include <algorithm> #include <vector> #include <map> #include <utility> #include <math.h> #include <stack> #include <queue> using namespace std; bool compare_by_b(pair<string, int> a, pair<string, int> b) { if(a.second != b.second){ return a.second > b.second; }else{ return a.first > b.first; } } int main(void){ int N,K; map<string, int> name_sum; cin>>N>>K; for (int i = 0; i < N; ++i) { string day; string name; int price; int quantity; cin>>day>>name>>price>>quantity; if(name_sum.count(name) == 0){ name_sum[name] = price * quantity; }else{ name_sum[name] += price * quantity; } } vector<pair<string, int>> ans; for (int i = 0; i < K; ++i) { int max_value = -1; string max_name; for (const auto& [key, value] : name_sum){ if(max_value < value){ max_name = key; max_value = value; } } name_sum[max_name] = -1; ans.push_back(make_pair(max_name,max_value)); } sort(ans.begin(), ans.end(), compare_by_b); for (int i = 0; i < K; ++i) { cout<<ans[i].first<<" "<<ans[i].second<<endl; } return 0; }
true
aab084e80c30b8b1fda103fe52cb1fed30ce3861
C++
Armstrm6/Lab-03-Class-Ownership-and-Memory
/main.cpp
UTF-8
11,948
3.40625
3
[]
no_license
#include "SomeThing.h" #include <iostream> #include <string> #include <list> #include <algorithm> #include <random> #include <time.h> int main(){ std::cout<<"The rules are:"<< std::endl<<"1. Each player must end their turn with 5 or fewer cards in their hand."<< std::endl<<"2. At the start of their turn, they must draw a card from the top of the community pile of cards"<< std::endl<<"3. The player then tries to make a stack from their hand in order from 1 to 13 during their turn."<< std::endl<<"4. During their turn, the player may draw additional cards from the top of the pile so long as the total cards in their hand don’t exceed 6."<< std::endl<<"5. When the player cannot place any more cards in their stack and they have 6 cards in their hand, they must discard 1 card to the bottom of the community pile and then player goes."<< std::endl<<"6. A player may choose to discard all of their cards to the bottom of the community pile and start with 5 new cards at the beginning of their turn. This action ends their turn without them getting a chance to draw a 6th card or discard any cards to their stack."<< std::endl<<"7. The game is played with a standard playing card deck (Ace = 1, Jack = 11, Queen =12, King = 13). The suits are not important for the purposes of determining rule 3 (i.e. a 4 of any suit can go on top of a 3 of any suit)."<< std::endl<<"8. Moves: P=Play Card, N=New Set"; Deck New_deck; int DEBUGVAL = 0; if(DEBUGVAL == 0){ New_deck.shuffleDeck(); } Player player1; Player player2; Player player3; int player_to_start = 1; int coin= 0; char move; int c; int sizeOfHand; char draw; std::string name; Card* card; for( int i=0; i<5; i++){ player1.addToHand(New_deck.removeCard()); } for( int i=0; i<5; i++){ player2.addToHand(New_deck.removeCard()); } for( int i=0; i<5; i++){ player3.addToHand(New_deck.removeCard()); } while (coin == 0){ std::cout<<"Player : "<<player_to_start<<" : Your turn begins..."<<std::endl; //Uses switching and cases to sort through the different players (1->3) switch (player_to_start){ case 1: std::cout << "Player 1, START!" << std::endl << std::endl; player1.showHand(); player1.showStack(); std::cout << std::endl; while(move != 'D'){ std::cout<<"What is your move (P / N): "<<std::endl; std::cin>>move; //play if(move == 'P'){ while((player1.getHandSize()>5)||(move!='N')){ if(player1.getHandSize() <= 5){ std::cout<<"Would you like to draw a card? Y/N?"<<std::endl; std::cin>>draw; if(draw == 'Y'){ std::cout<<"Picking up card"<<std::endl; player1.addToHand(New_deck.removeCard()); } } player1.showHand(); std::cout<<"What card do you want to play? "<<std::endl; std::cin >> c; card = player1.removeFromHand(c); if(player1.addToStack(card)==true){//Added a true statement, not sure if it already checks for it or not std::cout << "Nice Play!" << std::endl; if(c==13){ coin=1; } }else{ std::cout << "Oof! Not quite! Try again!" << std::endl; player1.addToHand(card); } std::cout<<"Do you have more cards to play? (Y/N)"<<std::endl; std::cin>>move; if(move == 'N'){ if(player1.getHandSize() == 6){ player1.showHand(); std::cout << "Your hand is at 6 cards, please choose a card to discard back to the community pile:" << std::endl; std::cin>>c; New_deck.addCard(player1.removeFromHand(c)); } break; } } break; //break as it shoudl end the player's turn } //New hand if(move == 'N'){ sizeOfHand = player1.getHandSize(); for(int i = 0; i < sizeOfHand; i++){ New_deck.addCard(player1.nukeHand()); } for(int i=0; i<5; i++){ player1.addToHand(New_deck.removeCard()); } std::cout<<"Player 1 Turn Ended."<<std::endl; break; } } case 2: std::cout << "Player 2, START!" << std::endl << std::endl; player2.showHand(); player2.showStack(); std::cout << std::endl; while(move != 'D'){ std::cout<<"What is your move (P / N): "<<std::endl; std::cin>>move; //play if(move == 'P'){ while((player2.getHandSize()>5)||(move!='N')){ if(player2.getHandSize() <= 5){ std::cout<<"Would you like to draw a card? Y/N?"<<std::endl; std::cin>>draw; if(draw == 'Y'){ std::cout<<"Picking up card"<<std::endl; player2.addToHand(New_deck.removeCard()); } } player2.showHand(); player2.showStack(); std::cout << std::endl; std::cout<<"What card do you want to play? "<<std::endl; std::cin >> c; card = player2.removeFromHand(c); if(player2.addToStack(card)){ std::cout << "Nice Play!" << std::endl; if(c==13){ coin=2; } }else{ std::cout << "Oof! Not quite! Try again!" << std::endl; player2.addToHand(card); } std::cout<<"Do you have more cards to play? (Y/N)"<<std::endl; std::cin>>move; if(move == 'N'){ if(player2.getHandSize() == 6){ player2.showHand(); std::cout << "Your hand is at 6 cards, please choose a card to discard back to the community pile:" << std::endl; std::cin>>c; New_deck.addCard(player2.removeFromHand(c)); } break; } } break; //break as it shoudl end the player's turn } //New hand if(move == 'N'){ sizeOfHand = player2.getHandSize(); for(int i = 0; i < sizeOfHand; i++){ New_deck.addCard(player2.nukeHand()); } for(int i=0; i<5; i++){ player2.addToHand(New_deck.removeCard()); } std::cout<<"Player 2 Turn Ended."<<std::endl; break; } } case 3: std::cout << "Player 3, START!" << std::endl << std::endl; player3.showHand(); player3.showStack(); std::cout << std::endl; while(move != 'D'){ std::cout<<"What is your move (P / N): "<<std::endl; std::cin>>move; //play if(move == 'P'){ while((player3.getHandSize()>5)||(move!='N')){ if(player3.getHandSize() <= 5){ std::cout<<"Would you like to draw a card? Y/N?"<<std::endl; std::cin>>draw; if(draw == 'Y'){ std::cout<<"Picking up card"<<std::endl; player3.addToHand(New_deck.removeCard()); } } player3.showHand(); player3.showStack(); std::cout << std::endl; std::cout<<"What card do you want to play? "<<std::endl; std::cin >> c; card = player3.removeFromHand(c); if(player3.addToStack(card)){ std::cout << "Nice Play!" << std::endl; if(c==13){ coin=3; } } else{ std::cout << "Oof! Not quite! Try again!" << std::endl; player3.addToHand(card); } std::cout<<"Do you have more cards to play? (Y/N)"<<std::endl; std::cin>>move; } if(move == 'N'){ if(player3.getHandSize() == 6){ player3.showHand(); std::cout << "Your hand is at 6 cards, please choose a card to discard back to the community pile:" << std::endl; std::cin>>c; New_deck.addCard(player3.removeFromHand(c)); } break; } break; //break as it shoudl end the player's turn } //New hand if(move == 'N'){ sizeOfHand = player3.getHandSize(); for(int i = 0; i < sizeOfHand; i++){ New_deck.addCard(player3.nukeHand()); } for(int i=0; i<5; i++){ player3.addToHand(New_deck.removeCard()); } std::cout<<"Player 3 Turn Ended."<<std::endl; break; } } } } player_to_start++; if(player_to_start>3){ player_to_start=1; } if(coin == 1){ std::cout<<"CONGRATS PLAYER 1 ON WINNING!"<<std::endl; } if(coin == 2){ std::cout<<"CONGRATS PLAYER 2 ON WINNING!!"<<std::endl; } if(coin == 3){ std::cout<<"CONGRATS PLAYER 3 ON WINNING!!!"<<std::endl; } return 0; }
true
150777c93f8ae5df19481409703e7ceb5ed11d9d
C++
nandakobs/kobs.cpp
/CFB Cursos/22. Funções - Parte 1.cpp
ISO-8859-1
1,178
3.671875
4
[]
no_license
#include <iostream> using namespace std; //temos que prototipar/apresentar a funo primeiro e embaixo escreve-las void texto(); void soma(int n1, int n2); int soma2(int n1, int n2); void tr(string tra[4]); int main(){//main uma funo string transp[4]=("carro","moto","barco","aviao"); int res; res=soma2(175,25); cout << "Valor de res: " << res << "\n"; // o mesmo que cout << "Valor de res: " << soma2(175,25) << "\n"; tr(transp); texto(); //chamando a funo soma(15,5); /*for(int i=0; i<10; i++){ //aqui escrevemos texto 10 vezes texto(); }*/ return 0; } //escreva o cdigo das funes dps do principal //a funo s ser executada quando ela for chamada no main //funo void no retorna nenhum valor void texto(){ cout << "\nCanal Fessor Bruno\n"; } void soma(int n1, int n2){ cout << "soma dos valores: " << n1+n2 << "\n"; } //qualquer outra funo escrita aqui temos q dar o valor a ser retornado int soma2(int n1, int n2){ return n1+n2; } void tr(string tra[4]){ for(int i=0; i<4; i++){ cout << tra[i] << "\n"; } }
true
eabc0c5a6c02d1a150e5ef237448b24c0db684aa
C++
jflygare/ctci
/src/main/resources/chapter01/Question02.h
UTF-8
925
4.34375
4
[]
no_license
#include <iostream> static inline void reverse(char* str) { // str is just a pointer to the starting location of an array of bytes (char) in memory // Can only iterate through the array until we see a null terminator '\0' // <string.h> provides utilities for working with strings (null terminated char arrays) std::cout << "The input string = [" << str << "]" << std::endl; int i = 0; while (str[i] != '\0') { i++; } std::cout << "The string is [" << i << "] chars" << std::endl; // Swap the values in place, in memory // Only need to iterate through half the array since letters are trading int j = 0; int k = i - 1; // For readability char tmp = '\0'; while (j < k) { std::cout << "Swapping [" << str[j] << "] with [" << str[k] << "]" << std::endl; tmp = str[j]; str[j] = str[k]; str[k] = tmp; j++; k--; } std::cout << "The string is now = [" << str << "]" << std::endl; }
true
229f9a3a09701c23f378b53d9cef26527d9aa461
C++
218643/PAMSI
/0905/inc/priorityqueue.hh
UTF-8
3,303
3.53125
4
[]
no_license
#pragma once #include "ipriorityqueue.hh" template <typename E> class PQNode; template <typename E> class PriorityQueue; /*! * \brief Klasa węzła kolejki. * * Zawiera element węzła oraz wskaźnik na następny węzeł. */ template <typename E> class PQNode { friend class PriorityQueue<E>; // przyznajemy dostep do wezla klasie Queue private: E elem; /*!< Element kolejki */ int value; /*!< Wartosc elementu */ PQNode<E>* next; /*!< Wskaźnik na kolejny węzeł */ }; /*! * \brief Klasa kolejki. * * Zawiera metody umożliwiające operacje na kolejce. */ template <typename E> class PriorityQueue : public IPriorityQueue<E> { private: PQNode<E>* front; /*!< Wskaźnik na początek kolejki */ PQNode<E>* end; /*!< Wskaźnik na koniec kolejki */ int queue_size=0; /*!< Rozmiar kolejki */ public: PriorityQueue() { front = NULL; // inicjalizacja NULLami poczatku i konca end = NULL; }; ~PriorityQueue() {}; /** * Funkcja dodająca element do kolejki * * */ void add(const E& elem, const int& value); /** * Funkcja usuwająca element z kolejki * Wyrzuca wyjątek EmptyQueueException jeśli kolejka jest pusta. * * */ E remove(); /** * Funkcja zwracająca rozmiar kolejki * * */ int size(); /** * Funkcja wyświetlająca kolejkę * * */ void show_queue(); // pokazuje kolejke }; template <typename E> void PriorityQueue<E>::add(const E& elem, const int& value) { PQNode<E>* v = new PQNode<E>; PQNode<E>* tmp = new PQNode<E>; PQNode<E>* tmp_2 = new PQNode<E>; v->elem=elem; v->value=value; v->next=NULL; PQNode<E>* e = end; PQNode<E>* f = front; if(size()!=0) { // sprawdzamy czy nie jest pusta while(f->next) { if(f->value>=value) break; tmp_2=f; f=f->next; } if(f->next!=NULL) { if(f!=front) { tmp_2->next=v; tmp=f; v->next=tmp; queue_size++; // zwiekszamy rozmiar kolejki o 1 } else { v->next=f; front=v; } } else if(f->next==NULL && size()==1) { if(v->value>f->value) { f->next=v; end=v; queue_size++; } else { v->next=f; front=v; queue_size++; } } else { e->next=v; end=v; queue_size++; // zwiekszamy rozmiar kolejki o 1 } } else { front=v; // ustawiamy nowy poczatek i nowy koniec end=v; queue_size++; // zwiekszamy rozmiar kolejki o 1 } } template <typename E> E PriorityQueue<E>::remove() { /* Wyrzuca wyjątek gdy kolejka jest pusta */ if(size()!=0) { PQNode<E>* old=front; front=old->next; queue_size--; // zmniejszamy rozmiar kolejki o 1 return old->elem; // zwracamy pierwszy element delete old; } else { std::string EmptyQueueException = "Kolejka jest pusta!"; throw EmptyQueueException; // metoda wyrzuca wyjatek jesli kolejka pusta } } template <typename E> int PriorityQueue<E>::size() { return queue_size; } template <typename E> void PriorityQueue<E>::show_queue() { PQNode<E>* tmp = front; if(tmp!=NULL) { std::cout<<"Elementy kolejki:"<<std::endl; std::cout<<tmp->elem<<std::endl; while(tmp->next) { // wyswietlamy elementy tmp=tmp->next; std::cout<<tmp->elem<<std::endl; } } else std::cout<<"Kolejka jest pusta!"<<std::endl; }
true
e1c80d4b7c60eafe69ecbda461a82edd34c06d25
C++
mschristiansen/hbs
/firmware/src/Display.cpp
UTF-8
1,402
2.921875
3
[]
no_license
/* Functions for initialising and updating the display. */ #include <SPI.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include "HBS.h" #define OLED_RESET 4 Adafruit_SSD1306 display(OLED_RESET); #if (SSD1306_LCDHEIGHT != 32) #error("Height incorrect, please fix Adafruit_SSD1306.h!"); #endif void displayInit() { // initialize with the I2C addr 0x3C (for the 128x32) display.begin(SSD1306_SWITCHCAPVCC, 0x3C); } void displayUpdate(const struct state d) { // Display text in size 1 giving four rows of text. display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(0,0); display.clearDisplay(); // First row. display.print(d.selected == HEAT ? "*" : " "); display.print(" Temp: "); display.print(d.actualTemp, 1); display.print("/"); display.println(d.setTemp, 1); // Second row. display.print(d.selected == PUMP ? "*" : " "); display.print(" Pump: "); display.println( d.pump ? "on" : "off" ); // Third row. display.print(d.selected == HEATER ? "*" : " "); display.print(" Heater: "); if (d.heater == OFF) display.println("off"); else { display.print(d.heat / 2.55, 0); display.println("%"); } // Fourth row. display.print(d.selected == BUZZER ? "*" : " "); display.print(" Buzzer: "); display.println( d.buzzer ? "on" : "off" ); // Update display. display.display(); }
true
0ec2864b9420a942bfc5bf661a591bd567ec55c0
C++
ccard/Indoor_Localization_server
/Localization_CodeRedizine/DBImage.h
UTF-8
882
2.578125
3
[]
no_license
#pragma once #include "ImageContainer.h" class DBImage : public ImageContainer { public: DBImage(): ImageContainer(){} DBImage(string img_file,Mat descriptor, vector<KeyPoint> kps): ImageContainer(img_file,descriptor, kps){} DBImage(const DBImage &o): ImageContainer(o){} void makeMask(int maskType = ImageContainer::CIRCLE, int side_radius = 9, int side2 = 16); /** * Intializes the orb object based on the parameters * * @param: the parm object containing the orb pramaters */ void initDescriptor(); /** * Calculates the orb descriptor of the image */ bool calcDescriptor(); /** * returns the size of the drawable image * * @return: the size of the displayable image */ Size imageSize(); /** * Determines if the ImageContainer has an image to display */ bool hasImage(); bool loadImage(){return false;} void getMat(Mat &mat){ }; };
true
9ab1654e5bd1c91983ca13cc3fb311ff5a16ceeb
C++
Hieromon/AutoConnect
/examples/Credential/Credential.ino
UTF-8
5,135
2.625
3
[ "MIT" ]
permissive
/* Credential.ino, AutoConnect for ESP8266. https://github.com/Hieromon/AutoConnect Copyright 2018, Hieromon Ikasamo. Licensed under The MIT License. https://opensource.org/licenses/MIT An example sketch for an Arduino library for ESP8266 WLAN configuration via the Web interface. This sketch provides a conservation measures utility for saved credentials in EEPROM. By accessing the root path, you can see the list of currently saved credentials via the browser. Enter an entry number of the credential, that entry will be deleted from EEPROM. This sketch uses PageBuilder to support handling of operation pages. */ #if defined(ARDUINO_ARCH_ESP8266) #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #elif defined(ARDUINO_ARCH_ESP32) #include <WiFi.h> #include <WebServer.h> #endif #include <AutoConnect.h> #include <AutoConnectCredential.h> #include <PageBuilder.h> #if defined(ARDUINO_ARCH_ESP8266) ESP8266WebServer Server; #elif defined(ARDUINO_ARCH_ESP32) WebServer Server; #endif AutoConnect Portal(Server); String viewCredential(PageArgument&); String delCredential(PageArgument&); // Specified the offset if the user data exists. // The following two lines define the boundalyOffset value to be supplied to // AutoConnectConfig respectively. It may be necessary to adjust the value // accordingly to the actual situation. #define CREDENTIAL_OFFSET 0 //#define CREDENTIAL_OFFSET 64 /** * An HTML for the operation page. * In PageBuilder, the token {{SSID}} contained in an HTML template below is * replaced by the actual SSID due to the action of the token handler's * 'viewCredential' function. * The number of the entry to be deleted is passed to the function in the * POST method. */ static const char PROGMEM html[] = R"*lit( <!DOCTYPE html> <html> <head> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"> <style> html { font-family:Helvetica,Arial,sans-serif; -ms-text-size-adjust:100%; -webkit-text-size-adjust:100%; } .menu > a:link { position: absolute; display: inline-block; right: 12px; padding: 0 6px; text-decoration: none; } </style> </head> <body> <div class="menu">{{AUTOCONNECT_MENU}}</div> <form action="/del" method="POST"> <ol> {{SSID}} </ol> <p>Enter deleting entry:</p> <input type="number" min="1" name="num"> <input type="submit"> </form> </body> </html> )*lit"; static const char PROGMEM autoconnectMenu[] = { AUTOCONNECT_LINK(BAR_24) }; // URL path as '/' PageElement elmList(html, {{ "SSID", viewCredential }, { "AUTOCONNECT_MENU", [](PageArgument& args) { return String(FPSTR(autoconnectMenu));} } }); PageBuilder rootPage("/", { elmList }); // URL path as '/del' PageElement elmDel("{{DEL}}", {{ "DEL", delCredential }}); PageBuilder delPage("/del", { elmDel }); // Retrieve the credential entries from EEPROM, Build the SSID line // with the <li> tag. String viewCredential(PageArgument& args) { AutoConnectCredential ac(CREDENTIAL_OFFSET); station_config_t entry; String content = ""; uint8_t count = ac.entries(); // Get number of entries. for (int8_t i = 0; i < count; i++) { // Loads all entries. ac.load(i, &entry); // Build a SSID line of an HTML. content += String("<li>") + String((char *)entry.ssid) + String("</li>"); } // Returns the '<li>SSID</li>' container. return content; } // Delete a credential entry, the entry to be deleted is passed in the // request parameter 'num'. String delCredential(PageArgument& args) { AutoConnectCredential ac(CREDENTIAL_OFFSET); if (args.hasArg("num")) { int8_t e = args.arg("num").toInt(); Serial.printf("Request deletion #%d\n", e); if (e > 0) { station_config_t entry; // If the input number is valid, delete that entry. int8_t de = ac.load(e - 1, &entry); // A base of entry num is 0. if (de > 0) { Serial.printf("Delete for %s ", (char *)entry.ssid); Serial.printf("%s\n", ac.del((char *)entry.ssid) ? "completed" : "failed"); // Returns the redirect response. The page is reloaded and its contents // are updated to the state after deletion. It returns 302 response // from inside this token handler. Server.sendHeader("Location", String("http://") + Server.client().localIP().toString() + String("/")); Server.send(302, "text/plain", ""); Server.client().flush(); Server.client().stop(); // Cancel automatic submission by PageBuilder. delPage.cancel(); } } } return ""; } void setup() { delay(1000); Serial.begin(115200); Serial.println(); rootPage.insert(Server); // Instead of Server.on("/", ...); delPage.insert(Server); // Instead of Server.on("/del", ...); // Set an address of the credential area. AutoConnectConfig Config; Config.boundaryOffset = CREDENTIAL_OFFSET; Portal.config(Config); // Start if (Portal.begin()) { Serial.println("WiFi connected: " + WiFi.localIP().toString()); } } void loop() { Portal.handleClient(); }
true
fe856f7e91b97b496638ce76a1abe36cf93dfa1b
C++
young2866/BJ
/BJ10987/BJ10987/10987.cpp
UTF-8
309
3.125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int moum(string N) { int ANS = 0; for (int i = 0; i < N.length(); i++) { if (N[i] == 'a' || N[i] == 'e' || N[i] == 'i' || N[i] == 'o' || N[i] == 'u') ANS++; } return ANS; } int main() { string N; cin >> N; cout << moum(N) << "\n"; return 0; }
true
e63e85c580a5d329453fa6ee7cc2cfd418a3d5bd
C++
KadeWalter/Pointer_And_Reference_Stuff
/main.cpp
UTF-8
1,455
4.3125
4
[]
no_license
#include <stdio.h> #include <iostream> using namespace std; void Swap(int &first, int &second) { int temp = first; first = second; second = temp; } int main() { // POINTER STUFF cout << "Pointer stuffs: " << endl << endl; int var = 10; int *ptr = &var; cout << "Working with pointers: " << endl; cout << "Value of ptr = " << *ptr << endl; cout << "Address of ptr = " << ptr << endl; *ptr = 20; cout << "Changed *ptr = 20." << endl; cout << "Value of ptr = " << *ptr << endl; cout << "Address of ptr = " << ptr << endl; cout << endl; cout << "Working with pointer and arrays:" << endl; int arr[3] = { 10, 20, 30 }; int *arrptr = arr; cout << "*arrptr = arr" << endl; for (int i = 0; i < 3; i++) { cout << *arrptr << endl; arrptr++; } cin.ignore(); cout << endl << endl << endl; // REFERENCE STUFF cout << "Reference stuffs: " << endl << endl; int a = 10; cout << "a created. a = 10. a = " << a << endl; int &ref = a; cout << "&ref created. &ref = a. ref = " << ref << endl; ref = 20; cout << "ref = 20." << endl; cout << "ref = " << ref << ", a = " << a << endl; a = 30; cout << "a = 30." << endl; cout << "ref = " << ref << ", a = " << a << endl << endl; cout << "Swap method:" << endl; int x = 1; int y = 2; cout << "x and y created. x = " << x << ", y = " << y << endl; cout << "Calling swap method..." << endl; Swap(x, y); cout << "After swap, x = " << x << ", y = " << y << endl; cin.ignore(); }
true
ea371a70c0109cb346eed218bc84744c2bd61331
C++
texane/maths
/lemnisca/main.cc
UTF-8
858
3.34375
3
[]
no_license
#include <cstdio> #include <cmath> static inline double dtor(double d) { return ((2.f * M_PI) / 360.f) * d; } static inline double rtod(double r) { return (360.f / (2.f * M_PI)) * r; } static inline double polar_to_cartesian (double r, double rho, double& x, double &y) { x = ::cos(rho) * r; y = ::sin(rho) * r; } int main(int ac, char** av) { static const double step = dtor(0.01f); static const double a = 100.f; static const double aa = a * a; // cos(2x) > 0.f <=> 135.f < x < 225.f for (double rho = dtor(135.f) + step; rho < dtor(225.f); rho += step) { const double cos2rho = ::cos(2.f * rho); const double r = ::sqrt(aa * cos2rho); double x, y; polar_to_cartesian(r, rho, x, y); ::printf("%lf %lf\n", x, y); // polar_to_cartesian(-r, rho, x, y); ::printf("%lf %lf\n", -x, -y); } return 0; }
true
dbc58e09e1a39e85890017e3dcaddb967e04f269
C++
zee7985/Competitive-Programming
/Stack_and_Queue/snq_nextGreatrONLeftSide.cpp
UTF-8
559
3.265625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; void nextGreterOnLeftSide(vector<int> arr) { stack<int> st; for (int i = 0; i < arr.size(); i++) { while (st.size() != 0 && st.top() <= arr[i]) { st.pop(); } if (st.size() == 0) cout<<arr[i] <<" -> " <<-1<<" "<<"\n"; else cout<<arr[i] <<" -> " <<st.top()<<" "<<"\n"; st.push(arr[i]); } } int main(){ vector<int> arr = { 6, 2, 5, 4, 5, 1, 6 }; nextGreterOnLeftSide(arr); }
true
6e46935f742533aedf7be243f24d9ffdb60c1d58
C++
enburk/cppplay
/include/cpp_data_binding.h
UTF-8
906
3.46875
3
[]
no_license
// https://en.cppreference.com/w/cpp/language/structured_binding // Case 1: binding an array int a[2] = {1,2}; auto [x,y] = a; // creates e[2], copies a into e, then x refers to e[0], y refers to e[1] auto& [xr, yr] = a; // xr refers to a[0], yr refers to a[1] // Case 2: binding a tuple-like type float x{}; char y{}; int z{}; std::tuple<float&,char&&,int> tpl(x,std::move(y),z); const auto& [a,b,c] = tpl; // a names a structured binding that refers to x; decltype(a) is float& // b names a structured binding that refers to y; decltype(b) is char&& // c names a structured binding that refers to the 3rd element of tpl; decltype(c) is const int // Case 3: binding to data members struct S { int x1 : 2; volatile double y1; }; S f(); const auto [x, y] = f(); // x is a const int lvalue identifying the 2-bit bit field // y is a const volatile double lvalue
true
a06769208b70f112f7242c32d9f7243341a1068f
C++
lukeinchina/study
/algorithm/hash/dynimic_hash.hpp
UTF-8
944
2.875
3
[]
no_license
#pragma once #include <stdlib.h> #include "hash_func.h" template<typename ElemType> class DHash { public: DHash(long init_size = 16):_ratio(3.0) { _curr_table_size = init_size < 16 ? 16 : init_size; _list_size = 1024; /* init table size */ _table_list = (ElemType **)calloc(sizeof(ElemType *) * _list_size); assert(NULL != _table_list); /* first hash talbe */ _table_list[0] = (ElemType *)malloc(_init_size * sizeof(ElemType)); _elem_count = 0; _expanding = false; } ~DHash(void); int Insert(const ElemType &e); int Delete(const ElemType &e); void Clear(void); private: void Destroy(void); private: long _elem_count; const double _ratio; long _curr_table_size; ElemType **_table_list; long _list_size; bool _expanding; };
true
16330411610551c012955201f69b9cea16328aa0
C++
tanle8/lbd_eos
/1-intro_to_eos/stl.cpp
UTF-8
1,332
3.859375
4
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <boost/lambda/lambda.hpp> using namespace std; void printVector(vector<int> vectorOfNumbers) { for(auto number : vectorOfNumbers) { cout << number << " "; } cout << endl; } int main () { // 1. Loop over an vector using for loop. vector<int> vectorOfNumbers = {1, 2, 3, 4}; // //for (int i = 0; i < vectorOfNumbers.size(); i++) { // cout << vectorOfNumbers[i] << " "; //} //cout << endl; // 2. Loop over a vector using for each. vectorOfNumbers.push_back(1000); //for (auto number : vectorOfNumbers) { // cout << number << " "; //} //cout << endl; // 3. Loop over an vector using for_each, with this way, we can specify the chunk we want. for_each(vectorOfNumbers.begin(), vectorOfNumbers.end(), cout << boost::lambda::_1 << " "); cout << endl; //for_each( vectorOfNumbers.begin() + 1, vectorOfNumbers.end(), [](int number) { cout << number << " "; }); //cout << endl; //vectorOfNumbers.pop_back(); //for_each( vectorOfNumbers.begin(), vectorOfNumbers.end(), [](int number) { cout << number << " "; }); //cout << endl; //cout << vectorOfNumbers.front() << endl; //cout << vectorOfNumbers.at(0) << endl; // //try { // vectorOfNumbers.at(100); //} catch ( std::out_of_range& ex ) { // cerr << ex.what() << endl; //} }
true
fa3c2b3f6b8ca82231c1a9e18f019b223aa4970e
C++
tianyu-z/CPP_Programming_for_MFE
/7.3/7.3/TestSTLAlgo.cpp
UTF-8
989
3.6875
4
[]
no_license
//Purpose: The test file of STLAlgorithem //Author: Tianyu Zhang //Date: 07/03/18 #include <algorithm> #include <vector> #include <iostream> #include "FunctionObj.cpp" using namespace std; int LessThanLimit(double input) // A global function to check the input is less than a certain value. { const double limit = 20.0; return input < limit; } void main() { // Create a vector with 20 elements. vector<double> v1; for (int i = 0; i < 20; i++) { v1.push_back(i + 0.1); } // Adopt the global function to get the number of elements less than a certain value. int result1 = count_if(v1.begin(), v1.end(), LessThanLimit); cout << "The number of elements that are less than 20 is " << result1 << endl; // Adopt the function object to get the number of elements less than a certain value. double limit = 20.0; int result2 = count_if(v1.begin(), v1.end(), FunctionObj<double>(limit)); cout << "The number of elements that are less than " << limit << " is " << result2 << endl; }
true
4dca11ac1bc061510f93b8aa2e4151a2151e25f2
C++
samlewis02/Nextion_weather
/sendStatus.ino
UTF-8
795
2.734375
3
[]
no_license
void sendStatus(String s) { String stat = " Status: " + s; nexSerial.print("t1.txt="); // This is sent to the nextion display to set what object name (before the dot) and what atribute (after the dot) are you going to change. nexSerial.print("\""); // Since we are sending text, and not a number, we need to send double quote before and after the actual text. nexSerial.print(stat); // This is the value you want to send to that object and atribute mentioned before. nexSerial.print("\""); // Since we are sending text, and not a number, we need to send double quote before and after the actual text. nexSerial.write(0xff); // We always have to send this three lines after each command sent to the nextion display. nexSerial.write(0xff); nexSerial.write(0xff); }
true
6ba2d620c0d02dcf898316dbc988442de3ca03f9
C++
TP1997/MNIST-Network
/main.cpp
UTF-8
13,553
2.703125
3
[]
no_license
#include <iostream> #include <fstream> #include <numeric> #include <cstdlib> #include <ctime> #include <algorithm> #include "network.h" #include "mnistdata.h" using namespace std; /** NOT USED FUNCTIONS */ //Debugging: bool tryParse(string &input, int &output); void toTxtFile(const char *fname, const vector<double> &buffer); /** USED FUNCTIONS */ //Printing: void printVectorImage(const VectorXd &vec, const unsigned int rows, const unsigned int cols); void printVectorLabelConverted(const VectorXd &vec); //Helpers: void bytewiseReverseInt(uint32_t &n); unsigned char* getSingleMnistImageData(unsigned const char *buffer, int idx, const unsigned int imgSize); VectorXd toDoubleVector(unsigned char *buffer, const unsigned int bufferSize); double getVectorLabelConverted(const VectorXd &vec); //Initalization: unsigned char* mnistImageReader(const char *path, unsigned int &rows, unsigned int &cols, unsigned int &noOfImages); unsigned char *mnistLabelReader(const char *path); vector<VectorXd> parseImageData(unsigned char *buffer, const unsigned int imgSize, const unsigned int noOfImages); vector<VectorXd> parseLabelData(unsigned char *buffer, const unsigned int nOfElements); vector<double> parseLabelData2(unsigned char *buffer, const unsigned int nOfElements); //Training: vector<unsigned int> pickRandomIdices(const unsigned int cnt, const unsigned int upperRange); MatrixXd crtRndmMinibatch(vector<VectorXd> &data, vector<unsigned int> &idx, const unsigned int imgSize); MatrixXd crtOutputVectors(vector<VectorXd> &data, vector<unsigned int> &idx); /** GLOBALS */ //Training-set, 60 000 examples. const char* TRAINING_SET_IMAGE_FILE = "mnist/training_set/train-images.idx3-ubyte"; //Training-set images. const char* TRAINING_SET_LABEL_FILE = "mnist/training_set/train-labels.idx1-ubyte"; //Training-set labels. //Test-set, 10 000 examples. const char* TEST_SET_IMAGE_FILE = "mnist/test_set/t10k-images.idx3-ubyte"; //Test-set images. const char* TEST_SET_LABEL_FILE = "mnist/test_set/t10k-labels.idx1-ubyte"; //Test-set labels. /************************************************************/ /***************** MAIN FUNCTION START **********************/ int main() { // VARIABLE INITALIZATION. unsigned int rows, cols; //Image dimensions unsigned int trnCount, tstCount=0; //Number of images in the set. //Load training set. unsigned char *trnData = mnistImageReader(TRAINING_SET_IMAGE_FILE, rows, cols, trnCount); unsigned char *trnLabel = mnistLabelReader(TRAINING_SET_LABEL_FILE); //Load test set. unsigned char *tstData = mnistImageReader(TEST_SET_IMAGE_FILE, rows, cols, tstCount); unsigned char *tstLabel = mnistLabelReader(TEST_SET_LABEL_FILE); //Parse & convert training data. vector<VectorXd> imageTrnData = parseImageData(trnData, rows*cols, trnCount); vector<VectorXd> labelTrnData = parseLabelData(trnLabel, trnCount); //Parse & convert test data. vector<VectorXd> imageTstData = parseImageData(tstData, rows*cols, tstCount); vector<double> labelTstData = parseLabelData2(tstLabel, tstCount); //Create training set. MnistData<VectorXd> trainingData(imageTrnData, labelTrnData); //Create test set. MnistData<double> testData(imageTstData, labelTstData); //Create network. // NETWORK TRAINING unsigned int epochs = 1; //Number of training ephocs. unsigned int mbSize = 10; //Size of SGD training batch. double eta = 3.0; //Network's learning rate. vector<double> NN_accuracy; //Get accuracy results while training. Network network(3, 784, 30, 10); //Create network with 3 layers with sizes of 784, 30, 10. //network.SGD_debug(imageTrainData, labelTrainData, mbSize, epochs, eta, imageTestData, labelTestData, NN_accuracy); //toTxtFile("accuracy.txt", NN_accuracy); network.train(trainingData, mbSize, epochs, eta); //New unsigned int rec=network.evaluate(testData); cout << rec << "/" << tstCount << endl; // NETWORK TESTSPACE bool quit=false; string input; int idx=0; VectorXd outputVec(10); cout << "Type index in range [0, " << tstCount-1 << "]. Quit by typing some rubbish." << endl; getline(cin, input); quit=tryParse(input, idx); while(!quit){ printVectorImage(testData.getImg(idx), rows, cols); outputVec=network.recDigit(testData.getImg(idx)); cout << "Correct value: " << testData.getLbl(idx) << endl; cout << "Network recognized as: " << getVectorLabelConverted(outputVec) << endl; //cout << "Networks output as vector:\n" << outputVec << endl; cout << "Type index in range [0, " << tstCount-1 << "]. Quit by typing some rubbish." << endl; getline(cin, input); quit=tryParse(input, idx); } cout << "End..." << endl; return 0; } /************************************************************/ /**************** FUNCTION DECLARATIONS (USED) **************/ /** Read image data stored in binary file. * @param *path Filepath to binary file. * @param rows Reference. * @param cols Reference. * @param noOfImagesReference. * @return buffer Whole image data set stored in byte array. */ unsigned char* mnistImageReader(const char *path, unsigned int &rows, unsigned int &cols, unsigned int &nOfImages){ unsigned char *buffer; uint32_t magicNumber=0; ifstream inputFile(path, ios_base::binary); if(inputFile.is_open()){ //Magic number. inputFile.read((char*)&magicNumber, sizeof(magicNumber)); bytewiseReverseInt(magicNumber); //Number of images. inputFile.read((char*)&nOfImages, sizeof(nOfImages)); bytewiseReverseInt(nOfImages); //Number of pixel rows in image. inputFile.read((char*)&rows, sizeof(rows)); bytewiseReverseInt(rows); //Number of pixel columns in image. inputFile.read((char*)&cols, sizeof(cols)); bytewiseReverseInt(cols); //Allocate space for image-data-buffer. buffer=new unsigned char[nOfImages*rows*cols]; //Read image data to buffer. inputFile.read((char*)&buffer[0], (nOfImages*rows*cols)*sizeof(char)); inputFile.close(); return buffer; } else{ cout << "Can't open the file." << endl; return nullptr; } } /** Read label data from binary file * @param path Filepath to binary file. * @return buffer Whole label data set stored in byte array. */ unsigned char *mnistLabelReader(const char *path){ unsigned char *buffer; uint32_t magicNumber=0; uint32_t noOfItems=0; ifstream inputFile(path, ios_base::binary); if(inputFile.is_open()){ //Magic number. inputFile.read((char*)&magicNumber, sizeof(magicNumber)); bytewiseReverseInt(magicNumber); //Number of items. inputFile.read((char*)&noOfItems, sizeof(noOfItems)); bytewiseReverseInt(noOfItems); //Allocate space for label-data-buffer. buffer=new unsigned char[noOfItems]; //Read label data to buffer. inputFile.read((char*)&buffer[0], (noOfItems)*sizeof(char)); inputFile.close(); return buffer; } else{ cout << "Can't open the file." << endl; return nullptr; } } /** Parse MNIST-image-data and convert it to network's input format. * @param buffer Mnist image data. * @return images, Set of Mnist-images in vector format. */ vector<VectorXd> parseImageData(unsigned char *buffer, const unsigned int imgSize, const unsigned int nOfImages){ vector<VectorXd> images; images.reserve(nOfImages); for(unsigned int n=0; n<nOfImages; n++){ unsigned char *imgData=getSingleMnistImageData(buffer, n, imgSize); images.push_back(toDoubleVector(imgData, imgSize)); } return images; } /** Parse Mnist-label-data and convert it to network's input format. * @param buffer, Mnist label data. * @param nOfElements, Number of individual elements in label data. * @return labels, Set of Mnist-labels in vector format. */ vector<VectorXd> parseLabelData(unsigned char *buffer, const unsigned int nOfElements){ vector<VectorXd> labels(nOfElements); unsigned int n=0; for_each( labels.begin(), labels.end(), [&](VectorXd &v){v.resize(10); v(int(buffer[n++]))=1.0;} ); //for_each( labels.begin(), labels.end(), [&](VectorXd &v){v.resize(10); v.setOnes(10); v*=0.01; v(int(buffer[n++]))=0.99f;} ); return labels; } /** * */ vector<double> parseLabelData2(unsigned char *buffer, const unsigned int nOfElements){ vector<double> labels(nOfElements); unsigned int i=0; for_each( labels.begin(), labels.end(), [&](double &d){d=(double)buffer[i++];} ); return labels; } /** Pick random indices in range [0, upperRange-1]. * @param cnt, Number of indeces generated. * @param upperRange * @return indices, Array of random indices. */ vector<unsigned int> pickRandomIdices(const unsigned int cnt, const unsigned int upperRange){ vector<unsigned int> indices(cnt); srand(rndmSeed()); for_each( indices.begin(), indices.end(), [&upperRange](unsigned int &i){i=(rand()%upperRange);} ); return indices; } /** Function for creating random mini-batch. * @param data, Mnist-image-data in network-input-format. * @param idx, Vector of randomly picked index values. * @param imgSize, Size of single Mnist-image (number of pixels). * @return batch, Mini-batch stored in matrix-form. Each column represents data of single Mnist-image. */ MatrixXd crtRndmMinibatch(vector<VectorXd> &data, vector<unsigned int> &idx, const unsigned int imgSize){ MatrixXd batch(imgSize, idx.size()); for(unsigned int n=0; n<idx.size(); n++){ batch.col(n)=data[idx[n]]; } return batch; } /** Function for creating correct network outputs based on created minibatch. * @param data, Mnist-label-data in network-input-format. * @param idx, Vector of randomly picked index values (same values used in crtRndmMinibatch). * @return labels, Labels stored in matrix-form, Each column reperesents data of single (correct) output. */ MatrixXd crtOutputVectors(vector<VectorXd> &data, vector<unsigned int> &idx){ MatrixXd labels(10, idx.size()); for(unsigned int n=0; n<idx.size(); n++){ labels.col(n)=data[idx[n]]; } return labels; } /** Reverse 32-bit unsigned integer bytewise * @param &n, Integer to be reversed. */ void bytewiseReverseInt(uint32_t &n){ n=((n>>16)&0x0000ffff) | ((n<<16)&0xffff0000); n=((n>>8)&0x00ff00ff) | ((n<<8)&0xff00ff00); } /** Get data of single image from image-byte array. * @param buffer, Pointer to buffer which holds the overall image data. * @param idx, Starting index of image. * @param imgSize, Size of single image. * @return bufferCopy, Image data stored in byte array. */ unsigned char* getSingleMnistImageData(unsigned const char *buffer, int idx, const unsigned int imgSize){ unsigned char *bufferCopy=new unsigned char[imgSize]; memcpy(bufferCopy, &buffer[idx*imgSize], imgSize+1); return bufferCopy; } /** Function that converts char-to-double and normalize value to range [0,1]. * @param buffer, Array that holds the convertable data. * @param buferSize, Size of convertable bufer. * @return vec, double vector that holds converted values. */ VectorXd toDoubleVector(unsigned char *buffer, const unsigned int bufferSize){ VectorXd vec(bufferSize); unsigned int n=0; for_each( vec.data(), vec.data()+vec.size(), [&](double &d){d=buffer[n++]/255.0;} );//*(0.99/255.0)+0.01 return vec; } /** Function for printing (Test/Training) image. * @param vec, Image's data in vector-format. * @param rows, Image's height (pixels). * @param cols, Image's width (pixels). */ void printVectorImage(const VectorXd &vec, const unsigned int rows, const unsigned int cols){ double minE=vec.minCoeff(); for(unsigned int n=0; n<vec.rows(); n++){ printf("%c%s", (vec(n)==minE? '.':'#'), ((n+1)%rows==0)?( ((n+1)%(rows*cols)==0)? "\n\n" : "\n" ) : " "); } } /** Function for printing vector-format label in numeric format. * @param vec, Label data in vector format. */ void printVectorLabelConverted(const VectorXd &vec){ unsigned int maxIdx; vec.maxCoeff(&maxIdx); cout << maxIdx << endl; } /* * * */ double getVectorLabelConverted(const VectorXd &vec){ unsigned int maxIdx; vec.maxCoeff(&maxIdx); return maxIdx; } /** DEBUGGING * */ bool tryParse(string &input, int &output){ try{ output=stoi(input); } catch(std::invalid_argument &e){ return true; } return false; } void toTxtFile(const char *fname, const vector<double> &buffer){ ofstream file(fname); for(double d : buffer){ file << d << "\n"; } file.close(); }
true
cbf3c95869fa8215a3279bf6ed71cf83efc61efa
C++
9prady9/arrayfire-benchmarks
/src/indexing.cpp
UTF-8
4,998
2.5625
3
[]
no_license
#include <arrayfire_benchmark.h> #include <arrayfire.h> #include <vector> #include <functional> #include <iostream> using af::array; using af::randu; using af::sum; using af::dim4; using af::seq; using af::span; using af::deviceGC; using af::deviceMemInfo; using std::vector; using std::pair; void indexingBench(benchmark::State& state, af_dtype type) { int dim = state.range(0); dim4 dims(state.range(2), state.range(3), state.range(4), state.range(5)); dim4 odims(state.range(2), state.range(3), state.range(4), state.range(5)); dims[dim] = state.range(1); //std::cout << dims << std::endl; //std::cout << odims << std::endl; { array a = randu(dims, type); array out = randu(odims, type); switch(dim) { case 0: out(seq(state.range(1)), span, span, span) = a; break; case 1: out(span, seq(state.range(1)), span, span) = a; break; case 2: out(span, span, seq(state.range(1)), span) = a; break; case 3: out(span, span, span, seq(state.range(1))) = a; break; } size_t alloc_bytes, alloc_buffers, lock_bytes, lock_buffers; deviceMemInfo(&alloc_bytes, &alloc_buffers, &lock_bytes, &lock_buffers); for(auto _ : state) { switch(dim) { case 0: out(seq(state.range(1)), span, span, span) = a; break; case 1: out(span, seq(state.range(1)), span, span) = a; break; case 2: out(span, span, seq(state.range(1)), span) = a; break; case 3: out(span, span, span, seq(state.range(1))) = a; break; } out.eval(); af::sync(); } size_t alloc_bytes2, alloc_buffers2, lock_bytes2, lock_buffers2; deviceMemInfo(&alloc_bytes2, &alloc_buffers2, &lock_bytes2, &lock_buffers2); state.counters["alloc_bytes"] = alloc_bytes2 - alloc_bytes; state.counters["alloc_buffers"] = alloc_buffers2 - alloc_buffers; state.counters["bytes"] = a.bytes(); } deviceGC(); //af::printMemInfo(); } void indexingBench2(benchmark::State& state, af_dtype type) { int dim = state.range(0); dim4 dims(state.range(2), state.range(3), state.range(4), state.range(5)); dim4 odims(state.range(2), state.range(3), state.range(4), state.range(5)); dims[dim] = state.range(1); //std::cout << dims << std::endl; //std::cout << odims << std::endl; { array a = randu(dims, type); array out = randu(odims, type); switch(dim) { case 0: a = out(seq(state.range(1)), span, span, span); break; case 1: a = out(span, seq(state.range(1)), span, span); break; case 2: a = out(span, span, seq(state.range(1)), span); break; case 3: a = out(span, span, span, seq(state.range(1))); break; } size_t alloc_bytes, alloc_buffers, lock_bytes, lock_buffers; deviceMemInfo(&alloc_bytes, &alloc_buffers, &lock_bytes, &lock_buffers); for(auto _ : state) { switch(dim) { case 0: a = out(seq(state.range(1)), span, span, span); break; case 1: a = out(span, seq(state.range(1)), span, span); break; case 2: a = out(span, span, seq(state.range(1)), span); break; case 3: a = out(span, span, span, seq(state.range(1))); break; } out.eval(); af::sync(); } size_t alloc_bytes2, alloc_buffers2, lock_bytes2, lock_buffers2; deviceMemInfo(&alloc_bytes2, &alloc_buffers2, &lock_bytes2, &lock_buffers2); state.counters["alloc_bytes"] = alloc_bytes2 - alloc_bytes; state.counters["alloc_buffers"] = alloc_buffers2 - alloc_buffers; state.counters["bytes"] = a.bytes(); } deviceGC(); //af::printMemInfo(); } void CustomArgs(benchmark::internal::Benchmark* b) { vector<pair<int, int>> sizes = { {1, 1<<26}, {1, 1<<26}, {1, 1}, {1, 1} }; pair<int, int> elements = {1, 1<<8}; int max = 1<<28; //printf("el: %d %d\n", elements.first, elements.second); vector<dim_t> d(4, 1); for(int dim = 0; dim < 4; dim++) { for(d[3] = sizes[3].first; d[3] <= sizes[3].second; d[3]*=8) { for(d[2] = sizes[2].first; d[2] <= sizes[2].second; d[2]*=8) { for(d[1] = sizes[1].first; d[1] <= sizes[1].second; d[1]*=8) { for(d[0] = sizes[0].first; d[0] <= sizes[0].second; d[0]*=8) { for(int el = elements.first; el <= d[dim]; el*=8) { if((d[0]*d[1]*d[2]*d[3]) < max) { b->Args({dim, el, d[0], d[1], d[2], d[3]}); //printf("elements: %d %d %d %d = %d\n", d[0],d[1],d[2],d[3], d[0]*d[1]*d[2]*d[3]); } } } } } } } } int main(int argc, char** argv) { vector<af_dtype> types = {f32, f64}; benchmark::Initialize(&argc, argv); af::benchmark::RegisterBenchmark("indexing", types, indexingBench) ->Apply(CustomArgs) ->ArgNames({"dim", "elements", "dim0", "dim1", "dim2", "dim3"}); //af::benchmark::AFJSONReporter jsonr; // benchmark::RunSpecifiedBenchmarks(&r, &jsonr); af::benchmark::AFReporter r; benchmark::RunSpecifiedBenchmarks(&r); }
true
5f5be99455f7bba4f195f95054eedfdf53bb9154
C++
cjleighton/Leighton_CSCI2270_FinalProject
/UserData.h
UTF-8
1,384
2.6875
3
[]
no_license
#ifndef USERDATA_H #define USERDATA_H #include <iostream> #include <vector> using namespace std; struct textVector //vector of this type stores userText { string word; int usages; }; struct User { string username; string password; User *parent; User *leftChild; User *rightChild; }; class UserData { public: UserData(); ~UserData(); void importer(); void exporter(User *x); void interface(string); //for listUsers and exporter string login(string,string); //user and pass bool addUser(string,string); //user and pass void listUsers(User*); bool changePass(string,string); //old pass and new pass void deleteAccount(); //doesn't need argument, uses sessionUser void loadText(string); void commonWords(); void avgWordLength(); void sortText(); User* searcher(string); protected: private: User *root; string sessionUser; string sessionPassword; string userText; vector<textVector> text; //user text stored here for analysis vector<textVector> textTemp; //copy of 'text', but for editing in commonWords vector<string> textAlpha; //copy of 'text', but for alphabetization int vectorSize; //size of textVector string exportLine; }; #endif // USERDATA_H
true
ed98d8112a9feaae9a4eb989e0e019ebd3c40039
C++
kratt/precomputed-radiance-transfer
/Src/Vector2.cpp
ISO-8859-3
5,752
3.46875
3
[]
no_license
//Author: Sren Pirk //Date: 22.01.2013 #include "Vector2.h" Vector2::Vector2() : x(0.0), y(0.0) { } Vector2::Vector2(float x, float y) { this->x = x; this->y = y; } Vector2::Vector2(const Vector2 &v) { this->x = v.x; this->y = v.y; } Vector2::Vector2(const float *v) { this->x = v[0]; this->y = v[1]; } Vector2::~Vector2() { } float Vector2::length() { float length = 0.0f; length = sqrtf((this->x * this->x) + (this->y * this->y)); return length; } float Vector2::dot(const Vector2 &vec) { float dot = 0.0f; dot = (this->x * vec.x) + (this->y * vec.y); return dot; } float Vector2::angle(Vector2 &vec) { float d = this->dot(vec); float a = this->length(); float b = vec.length(); float s = d / (a*b); float angle = (float)acos((double)s); return angle; } float Vector2::cross(const Vector2 &vec) { return (this->x * vec.y - this->y * vec.x); } void Vector2::normalize() { float len = this->length(); if(len > 0.0f) { this->x = this->x / len; this->y = this->y / len; } } Vector2 Vector2::normalized() { float len = this->length(); Vector2 normalized; if(len > 0.0) { normalized.x = this->x / len; normalized.y = this->y / len; } return normalized; } void Vector2::set(float x, float y) { this->x = x; this->y = y; } void Vector2::set(float *vec) { this->x = vec[0]; this->y = vec[1]; } Vector2 &Vector2::get() { return *this; } void Vector2::print() { printf("x: %f, y: %f\n", x, y); } Vector2 &Vector2::operator =(const Vector2 &a) { this->x = a.x; this->y = a.y; return *this; } Vector2 &Vector2::operator +=(const Vector2 &a) { this->x += a.x; this->y += a.y; return *this; } Vector2 &Vector2::operator +=(float s) { this->x += s; this->y += s; return *this; } Vector2 &Vector2::operator -=(const Vector2 &a) { this->x -= a.x; this->y -= a.y; return *this; } Vector2 &Vector2::operator -=(float s) { this->x -= s; this->y -= s; return *this; } Vector2 &Vector2::operator *=(const Vector2 &a) { this->x *= a.x; this->y *= a.y; return *this; } Vector2 &Vector2::operator *=(float s) { this->x *= s; this->y *= s; return *this; } Vector2 &Vector2::operator /=(const Vector2 &a) { this->x /= a.x; this->y /= a.y; return *this; } Vector2 &Vector2::operator /=(float s) { this->x /= s; this->y /= s; return *this; } //----------------------------------------------------------------------------------------------- Vector2 operator +(const Vector2 &a, const Vector2 &b) { Vector2 r; r.x = a.x + b.x; r.y = a.y + b.y; return r; } Vector2 operator +(const Vector2 &a, float s) { Vector2 r; r.x = a.x + s; r.y = a.y + s; return r; } Vector2 operator +(float s, const Vector2 &a) { Vector2 r; r.x = a.x + s; r.y = a.y + s; return r; } Vector2 operator -(const Vector2 &a, const Vector2 &b) { Vector2 r; r.x = a.x - b.x; r.y = a.y - b.y; return r; } Vector2 operator -(const Vector2 &a, float s) { Vector2 r; r.x = a.x - s; r.y = a.y - s; return r; } Vector2 operator -(const Vector2 &a) { Vector2 r; r.x = -a.x; r.y = -a.y; return r; } Vector2 operator *(const Vector2 &a, float s) { Vector2 r; r.x = a.x * s; r.y = a.y * s; return r; } Vector2 operator *(const Vector2 &a, const Vector2 &b) { Vector2 r; r.x = a.x * b.x; r.y = a.y * b.y; return r; } Vector2 operator /(const Vector2 &a, float s) { Vector2 r; r.x = a.x / s; r.y = a.y / s; return r; } Vector2 operator /(const Vector2 &a, const Vector2 &b) { Vector2 r; r.x = a.x / b.x; r.y = a.y / b.y; return r; } //----------------------------------------------------------------------------------------------- bool operator == (const Vector2 &a, const Vector2 &b) { return(a.x == b.x && a.y == b.y); } bool operator != (const Vector2 &a, const Vector2 &b) { return(a.x != b.x || a.y != b.y); } bool operator <= (const Vector2 &a, const Vector2 &b) { return(a.x <= b.x && a.y <= b.y); } bool operator < (const Vector2 &a, const Vector2 &b) { return(a.x < b.x && a.y < b.y); } bool operator >= (const Vector2 &a, const Vector2 &b) { return(a.x >= b.x && a.y >= b.y); } bool operator > (const Vector2 &a, const Vector2 &b) { return(a.x > b.x && a.y > b.y); } //----------------------------------------------------------------------------------------------- Vector2 Vector2::mulMatrix(float *matrix) { Vector2 result; result.x = matrix[0] * this->x + matrix[1] * this->y; result.y = matrix[2] * this->x + matrix[3] * this->y; return result; } float cross(const Vector2 &a, const Vector2 &b) { return (a.x * b.y - a.y * b.x); } Vector2 normalize(Vector2 &v) { float len = v.length(); Vector2 normalized; if(len > 0.0) { normalized.x = v.x / len; normalized.y = v.y / len; } return normalized; } float dot(const Vector2 &a, const Vector2 &b) { float dot = 0.0f; dot = (a.x * b.x) + (a.y * b.y); return dot; } float length(const Vector2 &v) { float length = 0.0f; length = sqrtf((v.x * v.x) + (v.y * v.y)); return length; } Vector2 operator *(float s, const Vector2 &v) { return (v * s); }
true
3f232d350ecae5c54b4f8acb0a883357bc630876
C++
JinnyJingLuo/Expanse
/Paradis_Hydrogen/ParadisJHU06012020/ParadisJHU06012020/ezmath/Line.h
UTF-8
1,083
2.859375
3
[]
no_license
// EZMath library by Ahmed M. Hussein // July 2009 // Feel free to use and distribute, but please cite or acknowledge, thanks. #ifndef LINE_H_ #define LINE_H_ #include "Vector.h" using namespace EZ; namespace GeometrySystem { class Line { public: Line(); Line(const Line& oLine); Line(const Vector& oDirection,const Point& oPoint); Line(const Point& oPoint1,const Point& oPoint2); ~Line(); Line& operator=(const Line& oLine); void Set(const Vector& oDirection,const Point& oPoint); void Set(const Point& oPoint1,const Point& oPoint2); void SetDirection(const Vector& oDirection); void SetPoint(const Point& oPoint); Vector GetDirection() const; Point GetPoint() const; bool IsPointOnLine(const Point& oPoint) const; void ReverseDirection(); Point GetPointProjection(const Point& oPoint) const; bool GetNearestPoints(const Line& oLine,Point& oPoint1,Point& oPoint2) const; bool GetIntersectionPoint(const Line& oLine,Point& oPoint,const double& dTolerance = 1E-6) const; private: protected: Vector m_oDirection; Point m_oPoint; }; } #endif
true
071d0a47a6e10c30edb92b4e81e1731809031c27
C++
TsovakPalakian/C
/day7/homework/homework/print.h
UTF-8
1,016
2.8125
3
[]
no_license
template<typename T> void print_array(T *p, char data_type[]); template<typename T> void print_array(T *p, int to, char data_type[]); template<typename T> void print_array(T *p, int from, int to, char data_type[]); template<typename T> void print_bidimansional_array(T *p, char data_type[], int column_count, int line_count); template<typename T> void print_array(T *p, char data_type[]) { for (int i = 0; i < N; ++i) { printf(data_type, *p++); } } template<typename T> void print_array(T *p, int to, char data_type[]) { for (int i = 0; i < to; ++i) { printf(data_type, i, *p++); } } template<typename T> void print_array(T *p, int from, int to, char data_type[]) { for (int i = from; i < to; ++i) { printf(data_type, *(p + from)); } } template<typename T> void print_bidimansional_array(T *p, char data_type[], int column_count, int line_count) { for (int i = 0; i < column_count; ++i) { for (int j = 0; j < line_count; ++j) { printf(data_type, i, j, *(*(p + i) + j)); } printf("\n"); } }
true
786307542a662e96ebd8f3628cc01447aaeaba6c
C++
Rikijaz/Pac-Man
/Pac-Man/src/Blinky.cpp
UTF-8
1,747
2.84375
3
[]
no_license
// Blinky.cpp : Defines the Blinky class's functions #include "Blinky.h" Blinky::Blinky() : Ghost(BLINKY_VEL_){} Blinky::Blinky(Data & data, int pos_x, int pos_y) : Ghost(BLINKY_VEL_) { // Get player spritesheet if (!data.GetSprites("Blinky", sprite_sheet_)) { std::cout << "Failed to retrieve textures from my_data_!\n"; } else { // Initialize the offsets pos_.x_ = pos_x; pos_.y_ = pos_y; double tile_pos_x = static_cast<double>(pos_.x_) / GLOBALS::TILE_WIDTH; double tile_pos_y = static_cast<double>(pos_.y_) / GLOBALS::TILE_HEIGHT; tile_pos_.x_ = static_cast<int>(std::ceil(tile_pos_x)); tile_pos_.y_ = static_cast<int>(std::ceil(tile_pos_y)); // Initialize the collision box dimensions cbox_.w = sprite_sheet_.at(0)->GetWidth(); cbox_.h = sprite_sheet_.at(0)->GetHeight(); cbox_.x = pos_.x_; cbox_.y = pos_.y_; // Initialize the velocity vel_x_ = 0; vel_y_ = 0; // Initialize animation frame regulators frame_offset_ = 0; frame_ = 0; time_to_update_ = 100; time_elapsed_ = 0; is_moving_ = false; // Initialize direction is_facing_right_ = false; is_facing_down_ = false; is_facing_left_ = false; is_facing_up_ = false; std::cout << "Blinky has loaded successfully!\n"; } } Blinky::~Blinky() { } void Blinky::Update(Level & level, int elapsed_time) { //std::cout << "Blinky\n"; GetPlayerPos(level); if (PlayerIsInScope()) { Pursue(level); //std::cout << "Blinky is pursuing.\n"; } else { Wander(level); //std::cout << "Blinky is wandering.\n"; } Move(level); SetAnimation(elapsed_time); } void Blinky::UpdateMapPos(Level & level) { level.SetCharacterPos(BLINKY_CHAR_KEY, pos_); level.SetCharacterTilePos(BLINKY_CHAR_KEY, tile_pos_.x_, tile_pos_.y_); }
true
f63a0aaa2de86edca242db00af552d22fc9333cf
C++
snrkr/Grade-calculator
/gradecalculate.cpp
UTF-8
3,890
3.984375
4
[]
no_license
// ****************************************************************** // // This program computes student grades. For each student, two // quiz grades (graded on a 10 point basis), one midterm exam grade // and one final exam grade (each on a 100 point basis) are read // in. The final numeric grade is computed weighing the final // exam 50%, the midterm 25%, and the quizzes 25%. The numeric // grade and corresponding letter grade are output. // // ****************************************************************** #include <iostream> #include <cstdlib> #include <fstream> #include <cassert> using namespace std; struct StudentRecord { int quiz1, quiz2, midtermExam, finalExam; double courseAverage; char letterGrade; }; void inputRecord (StudentRecord& record); char letterGrade (double numericGrade); void outputRecord (StudentRecord record); void computeAverage (StudentRecord& record); int main() { StudentRecord student; inputRecord(student); computeAverage(student); outputRecord(student); return 0; } void inputRecord (StudentRecord& record) { int readNum; fstream inputStream; inputStream.open("score.txt"); if (!inputStream.is_open()) { cerr << "Error file opening" << endl; exit(1); } inputStream >> readNum; record.quiz1 = readNum; assert(0 <= record.quiz1 && record.quiz1 <= 10); inputStream >> readNum; record.quiz2 = readNum; assert(0 <= record.quiz2 && record.quiz2 <= 10); inputStream >> readNum; record.midtermExam = readNum; inputStream >> readNum; record.finalExam = readNum; inputStream.close(); } char letterGrade (double numericGrade) { char letter; if (numericGrade < 60) letter = 'F'; else if (numericGrade < 70) letter = 'D'; else if (numericGrade < 80) letter = 'C'; else if (numericGrade < 90) letter = 'B'; else letter = 'A'; return letter; } void outputRecord (StudentRecord record) { ofstream outputStream; outputStream.open("output.txt"); if (!outputStream.is_open()) { cerr << "Error file writing" << endl; exit(1); } outputStream << "Quiz Scores: " << record.quiz1 << " " << record.quiz2 << endl; outputStream << "Midterm Exam Score: " << record.midtermExam << endl; outputStream << "Final Exam Score: " << record.finalExam << endl; outputStream << endl; outputStream << "Course Average: " << record.courseAverage << endl; outputStream << "Final Letter Grade: " << record.letterGrade << endl; cout << "Quiz Scores: " << record.quiz1 << " " << record.quiz2 << endl; cout << "Midterm Exam Score: " << record.midtermExam << endl; cout << "Final Exam Score: " << record.finalExam << endl; cout << endl; cout << "Course Average: " << record.courseAverage << endl; cout << "Final Letter Grade: " << record.letterGrade << endl; cout << "Successfully written on the text file" << endl; outputStream.close(); } void computeAverage (StudentRecord& record) { const double EXAM_WT = 0.5; const double MIDTERM_WT = 0.25; const double QUIZ_WT = 0.25; double quiz1Percent, quiz2Percent; // // Convert the 10 point quizzes to a percent, then find the average // quiz1Percent = 10 * record.quiz1; quiz2Percent = 10 * record.quiz2; double quizAvg = (quiz1Percent + quiz2Percent) / 2.0; // // Compute the weighted average to get the numeric course grade // record.courseAverage = quizAvg * QUIZ_WT + record.midtermExam * MIDTERM_WT + record.finalExam * EXAM_WT; // // Call the letterGrade function to find the corresponding letter grade record.letterGrade = letterGrade (record.courseAverage); }
true
0ec66199b2a3e75b8cbd6e76a69fa18539e43ab1
C++
mengchun0120/interview
/src/line_reflection.cpp
UTF-8
2,888
3.59375
4
[]
no_license
/* Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points. Example 1: Input [[1,1],[-1,1]] Output true Example 2: Input [[1,1],[-1,-1]] Output false Follow up: Could you do better than O(n^2)? */ #include <cassert> #include <vector> #include <unordered_map> #include <functional> using namespace std; struct Point { int x; int y; }; struct HashKey { double dist; int y; bool operator==(const HashKey& k) const { return dist == k.dist && y == k.y; } }; struct MyHash { static hash<int> intHash; static hash<double> doubleHash; size_t operator()(const HashKey& k) const { return doubleHash(k.dist) ^ intHash(k.y); } }; hash<int> MyHash::intHash; hash<double> MyHash::doubleHash; struct ReflectionRecord { int leftCount, rightCount; ReflectionRecord() : leftCount(0) , rightCount(0) {} }; typedef unordered_map<HashKey, ReflectionRecord, MyHash> ReflectionMap; bool lineReflection(double& line, const vector<Point> points) { unsigned int maxIdx, minIdx; maxIdx = 0; minIdx = 0; for(unsigned int i = 1; i < points.size(); ++i) { if(points[i].x > points[maxIdx].x) { maxIdx = i; } if(points[i].x < points[minIdx].x) { minIdx = i; } } if(points[minIdx].y != points[maxIdx].y) return false; double mid = (double)(points[minIdx].x + points[maxIdx].x) / 2.0; ReflectionMap reflectMap; for(unsigned int i = 0; i < points.size(); ++i) { double dist = points[i].x - mid; if(dist == 0.0) continue; double absDist = dist > 0.0 ? dist : -dist; HashKey key{absDist, points[i].y}; ReflectionRecord& r = reflectMap[key]; if(dist < 0.0) { ++(r.leftCount); } else { ++(r.rightCount); } } for(auto it = reflectMap.begin(); it != reflectMap.end(); ++it) { if(it->second.leftCount != it->second.rightCount) return false; } line = mid; return true; } int main() { vector<Point> points1{{-1,1},{1,1}}; double line1; bool r1 = lineReflection(line1, points1); assert(r1 && line1 == 0.0); vector<Point> points2{{-1,1},{1,2}}; double line2; bool r2 = lineReflection(line2, points2); assert(!r2); vector<Point> points3{{-1,1},{1,1},{-5,10},{8,7},{-8,7},{5,10},{100,20}, {-100,20},{101,30},{102,40},{-101,30},{-102,40}}; double line3; bool r3 = lineReflection(line3, points3); assert(r3 && line3 == 0.0); vector<Point> points4{{-1,1},{1,1},{-5,10},{8,7},{-8,7},{5,10},{100,20}, {-100,20},{101,30},{102,40},{-101,30},{-101,40}}; double line4; bool r4 = lineReflection(line4, points4); assert(!r4); }
true
437d304b7245efc7fec1f98bcbb2312efc0f5ef2
C++
ouru2006/Intro-Computer-Graphics
/305ass1/aabb.h
UTF-8
1,283
3
3
[]
no_license
#ifndef AABB_H #define AABB_H #include "hitable.h" inline float ffmin(float a, float b){ return a<b? a:b; } inline float ffmax(float a, float b){ return a>b? a:b; } class aabb{ public: aabb(){} aabb(const vec3& a, const vec3& b){ _min=a; _max=b; } vec3 min() const {return _min;} vec3 max() const{return _max;} bool hit(const ray& r, float tmin, float tmax)const; vec3 _min; vec3 _max; }; inline bool aabb::hit(const ray &r, float tmin, float tmax) const{ for(int a = 0; a<3;a++){ float invD=1.0f/r.direction()[a]; float t0 = (min()[a]-r.origin()[a])*invD; float t1 = (max()[a]-r.origin()[a])*invD; if(invD < 0.0f) std::swap(t0,t1); tmin = t0> tmin?t0:tmin; tmax = t1<tmax? t1:tmax; if(tmax <= tmin) return false; } return true; } aabb surrounding_box(aabb box0,aabb box1){ vec3 small(fmin(box0.min().x(),box1.min().x()), fmin(box0.min().y(),box1.min().y()), fmin(box0.min().z(),box1.min().z())); vec3 big(fmin(box0.max().x(),box1.max().x()), fmin(box0.max().y(),box1.max().y()), fmin(box0.max().z(),box1.max().z())); return aabb(small,big); } #endif // AABB_H
true
daf1edaca0c3690616eb22fb3e17d4682f377225
C++
Phitherek/oop
/Objects/Object.cpp
UTF-8
372
2.953125
3
[]
no_license
#include <iostream> #include <cstdlib> #include <string> #include "Object.h" using namespace std; Object::Object() { _desc = ""; } Object::~Object() { _desc = ""; } Object& Object::setDesc(string desc) { _desc = desc; return *this; } string Object::getDesc() { return _desc; } void Object::draw() { cout << "Object::draw(): " << endl << "desc: " << _desc << endl; }
true
7d856aa7726f72a5f9746198e76e35321f553a17
C++
simonhoff/Oving11
/replace.cpp
UTF-8
345
2.75
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include "replace.h" using namespace std; void replace(vector<string> &strVec, string str, string replacement){ vector<string>::iterator i; for (i = strVec.begin(); i != strVec.end(); i++){ if (*i == str){ strVec.erase(i); strVec.insert(i, replacement); } } }
true
2e0a319ae67005767f0eea5000eda6666d9004af
C++
SteveYuOWO/algorithm
/advanced/1105.Spiral Matrix.cpp
UTF-8
1,391
2.640625
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int N; int main() { scanf("%d", &N); vector<int> v(N); for(int i = 0; i < N; i++) scanf("%d", &v[i]); sort(v.begin(), v.end(), greater<int>()); int col, row; for(int i = 1; i * i <= N; i++) if(N % i == 0) col = i; row = N / col; vector<vector<int>> ans(row); for(int i = 0; i < row; i++) ans[i].resize(col, -1); int x = 0, y = 0, dir = 0, i = 0;// 0 右边 1 下面 2 左面 3 上面 if(y + 1 >= col || ans[x][y + 1] != -1) dir = (dir + 1) % 4; // 开始方向可能朝下 while(true) { if(i == v.size()) break; if(dir == 0) { ans[x][y++] = v[i++]; if(y + 1 >= col || ans[x][y + 1] != -1) dir = (dir + 1) % 4; } else if(dir == 1) { ans[x++][y] = v[i++]; if(x + 1 >= row || ans[x + 1][y] != -1) dir = (dir + 1) % 4; } else if(dir == 2) { ans[x][y--] = v[i++]; if(y - 1 < 0 || ans[x][y - 1] != -1) dir = (dir + 1) % 4; } else { ans[x--][y] = v[i++]; if(x - 1 < 0 || ans[x - 1][y] != -1) dir = (dir + 1) % 4; } } for(int i = 0; i < row; i++) { printf("%d", ans[i][0]); for(int j = 1; j < col; j++) printf(" %d", ans[i][j]); putchar('\n'); } return 0; }
true
427ad8652a3f61148ff50d81454c88e36ab26102
C++
chrisyrniu/ECE6122-Hwk3
/Problem3/Problem3.cpp
UTF-8
1,752
3.296875
3
[]
no_license
/* Author: <Yaru Niu> Class: ECE6122 Last Date Modified: <2019-10-06> Description: Solution to Problem 3 of Homework 3 */ #include <iostream> #include <fstream> #include <string> #include <vector> #include <omp.h> #include <time.h> using namespace std; // Main int main(int argc, char* argv[]){ fstream input; int number; int flag1 = 0; int flag2 = 0; int flag3 = 0; int rows; int **triangle; int *maxSum; // Read the file, and store the data of the triangle into a dynamic 2D array const char* filepath = argv[1]; input.open(filepath, ios::in); if (!input){ cout << "Unable to open file"; } while(input >> number){ if (flag1 == 0){ rows = number; triangle = new int*[rows]; for (int i = 0; i < rows; ++i){ triangle[i] = new int[i + 1]; } flag1 = flag1 + 1; } else{ triangle[flag2][flag3] = number; if (flag2 == flag3){ flag3 = 0; flag2 = flag2 + 1; } else{ flag3 = flag3 + 1; } } } input.close(); //Muti-thread (one) #pragma omp parallel num_threads(1) { // Dynamic programming: get the maximum sum from the bottom to top // Initialize the maxSum array with the bottom number of the triangle maxSum = triangle[rows - 1]; for (int m = rows - 2; m >= 0; --m){ for (int n = 0; n <= m; ++n) maxSum[n] = max(maxSum[n], maxSum[n + 1]) + triangle[m][n]; } cout << maxSum[0] << endl; ofstream output; output.open("output3.txt"); output << maxSum[0]; } }
true
f9d9d097521cf7f4d4f09f97a2668dd19dc89c8e
C++
layslahelmer/SISTSUPERV.TRAB1
/Circuito.h
UTF-8
414
2.609375
3
[]
no_license
class Circuito { public: Circuito(float r1 = 0.0, float r2 = 0.0, float v = 0.0); Circuito(bool serieOuParalelo); ~Circuito(); float ResistenciaEquivalente(float r1, float r2, bool serieOuParalelo); float CorrenteTotal(float r1, float r2, bool serieOuParalelo); float PotenciaTotal(float r1, float r2, float v, bool serieOuParalelo); float r1; float r2; float v; bool serieOuParalelo; };
true
fe20c4d8f5dcbcbbdc532f2c83e71fddb9ccd54b
C++
Chris-SG/MazeNavigator
/tree_search/include/DepthFirstSearch.h
UTF-8
364
2.546875
3
[]
no_license
#pragma once #include "ITreeSearch.h" /// <summary> /// DepthFirstSearch is a search algorithm in which a node is followed /// all the way to the end before following another node's path /// </summary> class DepthFirstSearch : public TreeSearch { private: public: DepthFirstSearch(); ~DepthFirstSearch(); virtual std::vector<SearchNode*> Solve(Grid2D* map); };
true
de0170cc6b780070a4d474a6d05de00b71e67234
C++
DaftMat/Daft-Engine
/src/Core/Materials/SettingManager.inl
UTF-8
3,299
2.703125
3
[ "MIT" ]
permissive
#include <Core/Utils/Logger.hpp> #include "SettingManager.hpp" namespace daft::core { template <typename T> const std::vector<SettingManager::Setting<T>>& SettingManager::settings() const { if constexpr (std::is_same_v<T, int>) return m_ints; else if constexpr (std::is_same_v<T, bool>) return m_bools; else if constexpr (std::is_same_v<T, float>) return m_floats; else if constexpr (std::is_same_v<T, double>) return m_doubles; else if constexpr (std::is_same_v<T, glm::vec2>) return m_vec2s; else if constexpr (std::is_same_v<T, glm::vec3>) return m_vec3s; else if constexpr (std::is_same_v<T, glm::vec4>) return m_vec4s; else if constexpr (std::is_same_v<T, glm::mat2>) return m_mat2s; else if constexpr (std::is_same_v<T, glm::mat3>) return m_mat3s; else if constexpr (std::is_same_v<T, glm::mat4>) return m_mat4s; std::stringstream ss; ss << "invalid setting type, returning empty list..."; core::Logger::info(std::move(ss)); return std::vector<Setting<T>>{}; } template <typename T> std::vector<SettingManager::Setting<T>>& SettingManager::settings() { return const_cast<std::vector<Setting<T>>&>(static_cast<const SettingManager&>(*this).settings<T>()); } template <typename T> void SettingManager::add(std::string name, T value) noexcept { if constexpr (std::is_same_v<T, int>) m_ints.emplace_back(std::move_if_noexcept(name), value); else if constexpr (std::is_same_v<T, bool>) m_bools.emplace_back(std::move_if_noexcept(name), value); else if constexpr (std::is_same_v<T, float>) m_floats.emplace_back(std::move_if_noexcept(name), value); else if constexpr (std::is_same_v<T, double>) m_doubles.emplace_back(std::move_if_noexcept(name), value); else if constexpr (std::is_same_v<T, glm::vec2>) m_vec2s.emplace_back(std::move_if_noexcept(name), value); else if constexpr (std::is_same_v<T, glm::vec3>) m_vec3s.emplace_back(std::move_if_noexcept(name), value); else if constexpr (std::is_same_v<T, glm::vec4>) m_vec4s.emplace_back(std::move_if_noexcept(name), value); else if constexpr (std::is_same_v<T, glm::mat2>) m_mat2s.emplace_back(std::move_if_noexcept(name), value); else if constexpr (std::is_same_v<T, glm::mat3>) m_mat3s.emplace_back(std::move_if_noexcept(name), value); else if constexpr (std::is_same_v<T, glm::mat4>) m_mat4s.emplace_back(std::move_if_noexcept(name), value); else { std::stringstream ss; ss << "invalid setting type, nothing has been done."; core::Logger::info(std::move(ss)); } } template <typename T> auto SettingManager::getIt(std::string name) const { return std::find(settings<T>().begin(), settings<T>().end(), Setting<T>(std::move(name))); } template <typename T> auto SettingManager::getIt(std::string name) { std::string iname = std::move(name); return const_cast<decltype(getIt<T>(iname))&>(static_cast<const SettingManager&>(*this).getIt<T>(iname)); } template <typename T> T& SettingManager::get(std::string name) { return const_cast<T&>(static_cast<const SettingManager&>(*this).get<T>(std::move(name))); } } // namespace daft::core
true
a23389d76fc15b1d05e0e941fbdd5175950745f9
C++
antrad/If_Quake_2_Was_2D
/Game/Game/World.cpp
UTF-8
6,416
2.609375
3
[ "WTFPL" ]
permissive
#include "..\..\Engine\Engine\Advanced2D.h" using namespace Advanced2D; #include "World.h" #include <ios> #include <sstream> Sprite* World::addSprite_basic(int type, double x, double y, double w, double h, int my_layer, int render_type, std::string texture_path, int frame) { //FIND TEXTURE Texture *my_texture = NULL; my_texture = g_engine->texture_manager->findTexture(texture_path); if (my_texture==NULL) { g_engine->gui->messagebox_add("ERROR",texture_path + " not found !",10); return NULL; } //CREATE SPRITE Sprite *sprite_temp = new Sprite(); sprite_temp->setImage(my_texture); sprite_temp->setFrameColumns(my_texture->tile_columns); sprite_temp->setFrameCurrent(frame); sprite_temp->setRenderType(render_type); sprite_temp->setType(type); sprite_temp->setPosition(x,y); sprite_temp->setSize(w,h); g_engine->addSprite(sprite_temp,my_layer); return sprite_temp; }//addSprite_basic() Sprite* World::addSprite_string(int my_class, int type, int id, int state, std::string line, std::string third_line) { std::string line2 = line ; double x, y, w, h; int my_layer,collidable; int render_type; double scale_x,scale_y; double rotation; std::string texture_path; int frame,frame_relx,frame_rely; int energy; double scroll_x,scroll_y,scroll_step_x,scroll_step_y; double offset_mx,offset_my; int flip_h,flip_v; double vel_x,vel_y; int alpha,red,green,blue; //std::string command; std::stringstream stream(line); if (stream >>x>>y>>w>>h >>my_layer>>collidable>>render_type >>scale_x>>scale_y>>rotation >>texture_path >>frame>>frame_relx>>frame_rely >>scroll_x>>scroll_y>>scroll_step_x>>scroll_step_y>>offset_mx>>offset_my>>flip_h>>flip_v >>vel_x>>vel_y>>energy >>alpha>>red>>green>>blue) { Sprite *block = new Sprite(); block->setClass(my_class); block->setType(type); block->setID(id); block->setState(state); block->setText(third_line); /////find texture Texture *my_texture = NULL; my_texture = g_engine->texture_manager->findTexture(texture_path); if(my_texture==NULL) { my_texture = g_engine->gui->default_t; block->setColor_Texture(0xFFFF00F6); //g_engine->gui->messagebox_add("ERROR ADDING TILE SPRITE","Missing texture " + texture_path + ".",100); //return NULL; } //image block->setImage(my_texture); block->setFrameColumns(my_texture->tile_columns); block->setFrameCurrent(frame); block->setFrameRelX(frame_relx); block->setFrameRelY(frame_rely); // //render type block->setRenderType(render_type); block->setOffsetMX(offset_mx); block->setOffsetMY(offset_my); block->setScrollX(scroll_x); block->setScrollY(scroll_y); block->setScrollStepX(scroll_step_x); block->setScrollStepY(scroll_step_y); block->setSize((int)w,(int)h); block->setScale(scale_x,scale_y); if(third_line=="fitscreen") { block->setScale( (float)g_engine->getScreenWidth()/block->getImage()->getWidth(), (float)g_engine->getScreenHeight()/block->getImage()->getHeight()); block->setSize( (float)g_engine->getScreenWidth(), (float)g_engine->getScreenHeight()); } if(third_line=="fitscreen_tiled") { block->setSize((float)g_engine->getScreenWidth(),(float)g_engine->getScreenHeight()); block->setRenderType(TILE); } else if(third_line[0]=='&') { //srusit ce se ako je state prevelik ili -999 !!! if(g_engine->save_to_map) { g_engine->game_maps[g_engine->map_current]->player_spawn[state].setX(x); g_engine->game_maps[g_engine->map_current]->player_spawn[state].setY(y); } } block->setRotation(rotation); // block->flip_h = flip_h; block->flip_v = flip_v; block->setVelocity(vel_x,vel_y); block->setPosition(x,y); block->setColor_Texture(D3DCOLOR_ARGB(alpha,red,green,blue)); block->setCollidable(collidable); if (block->getCollidable()) g_engine->coll_manager->setColl_box(block); g_engine->addSprite(block,my_layer); if(block->getID()==ITEM) { block->rel_posx = block->getY()-8; block->rel_posy = block->getY()+8; block->setVelocityY(0.3); } if(block->getClass()==SOUND) { if(block->getID()==SOUND_POINT) { block->rel_posx = g_engine->stringtoint(block->getArg(block->arg_list.size()-1));//domet zvuka zadnji argument } //block->sound = g_engine->audio->FindSound(block->getText()); } return block; } else { g_engine->gui->messagebox_add("ERROR ADDING TILE SPRITE","Line not readable.",10); g_engine->log_text.push_back(line2); return NULL; } } Sprite* World::addTileScroller(int my_class, int type, int id, int state, std::string line, std::vector <string> textures, std::string third_line) { std::string line_error = line ; int texture_num; double x,y; int my_layer,collidable; double scroll_x,scroll_y,scroll_step_x,scroll_step_y; int alpha,red,green,blue; std::stringstream stream; stream << line; if (stream >>texture_num >>x>>y >>my_layer>>collidable >>scroll_x>>scroll_y>>scroll_step_x>>scroll_step_y >>alpha>>red>>green>>blue) { Sprite *block = new Sprite(); for(unsigned int i=0;i<textures.size();i++)//set textures { Texture *my_texture = NULL; my_texture = g_engine->texture_manager->findTexture(textures[i]); if(my_texture==NULL) { my_texture = g_engine->gui->default_t; block->setColor_Texture(0xFFFF00F6); //ERROR something } else { block->texture_vector.push_back(my_texture); block->setSize( block->getWidth() + my_texture->getWidth(), my_texture->getHeight()); } } if(block->texture_vector.empty()) { delete block; return NULL; } block->setRenderType(TILESCROLLER_X); block->setClass(my_class); block->setType(type); block->setID(id); block->setState(state); block->setPosition(x,y); block->setScrollX(scroll_x); block->setScrollY(scroll_y); block->setScrollStepX(scroll_step_x); block->setScrollStepY(scroll_step_y); block->setCollidable(collidable); if (block->getCollidable()) g_engine->coll_manager->setColl_box(block); block->setColor_Texture(D3DCOLOR_ARGB(alpha,red,green,blue)); block->setText(third_line); g_engine->addSprite(block,my_layer); return block; } else { g_engine->gui->messagebox_add("ERROR ADDING SPRITE","Line not readable.",10); g_engine->log_text.push_back(line_error); return NULL; } }//addTileScroller()
true
d7571e233afc035062a6e175643271ad923da338
C++
TausifIqbal/CPcode
/c++ sol/CSES/Graph Algorithms/download_speed.cpp
UTF-8
1,275
2.609375
3
[]
no_license
#include <iostream> #include <cstdio> #include <algorithm> #include <string.h> using namespace std; #define endl '\n' const int maxn = 500; int n, m; long graph[maxn][maxn]; long maxflow(){ long total = 0; long maxflow, maxloc; long flow[maxn], par[maxn]; bool visited[maxn]; while(true){ memset(flow, 0, sizeof(flow)); memset(par, -1, sizeof(par)); memset(visited, 0, sizeof(visited)); flow[0] = 1000000007; while(true){ maxflow = 0, maxloc = -1; for(int i = 0; i < n; i++){ if(!visited[i] && flow[i] > maxflow){ maxflow = flow[i]; maxloc = i; } } if(maxloc == -1 || maxloc == n - 1) break; visited[maxloc] = 1; for(int i = 0; i < n; i++){ if(flow[i] < min(maxflow, graph[maxloc][i])){ flow[i] = min(maxflow, graph[maxloc][i]); par[i] = maxloc; } } } if(maxloc == -1) break; total += maxflow; int cur = n - 1; while(cur != 0){ int nx = par[cur]; graph[nx][cur] -= maxflow; graph[cur][nx] += maxflow; cur = nx; } } return total; } int main(){ ios::sync_with_stdio(false); cin.tie(NULL); cin >> n >> m; for(int i = 0; i < m; i++){ int a, b, c; cin >> a >> b >> c; a--, b--; graph[a][b] += c; } cout << maxflow() << endl; return 0; }
true
47504089369ca3da6de53e4524470fe9a29016c8
C++
AsafZalcman/The-Pong-Game
/Menu.h
UTF-8
668
2.6875
3
[]
no_license
#pragma once #include "Game.h" #include <conio.h> using namespace std; class Menu { Game pong; bool firstGame = true; Game::GameStatus gameStatus = Game::GameStatus::OFF; public: enum {UserVsUser = '1', UserVsPc = '2', PcVsPc = '3' ,RESUME_GAME = '4',RETURNFROMINST = '5', INSTRUCTIONS = '8', EXIT = '9' }; void run(); void setGameStatus(Game::GameStatus status) { gameStatus = status; } void setFirstGameOff() { firstGame = false; } char getChose() const; void printInstructions() const; void printPong() const; void printGameOver() const; void countDown() const; void chosePcLevel(char userChoise, int& levelL, int& levelR); void printMenu() const; };
true
8bb495439491c28896f62323f418d369f600bf84
C++
xuxiandi/DOMQ
/framework/base/thread/thread.cpp
UTF-8
771
2.671875
3
[]
no_license
#include <base/thread/thread.h> #include <pthread.h> namespace base { Thread::~Thread() { Stop(); } int Thread::Start() { if ( _alive ) return -1; pthread_attr_t attr; if ( pthread_attr_init(&attr) != 0 ) return -1; if ( pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) != 0 ) return -1; if (pthread_create(&_threadHandle, &attr, &Thread::ThreadFunc, this) == -1) return -1; _alive = true; return 0; } void Thread::Stop() { if ( _alive ) { pthread_cancel(_threadHandle); _alive = false; } } void Thread::Wait() { if ( _alive ) { pthread_join(_threadHandle, NULL); _alive = false; } } void* Thread::ThreadFunc(void* p) { Thread* thread = (Thread*)p; thread->Run(); thread->_alive = false; return NULL; } }
true
d2b88c117755c76fef41eccd864f80a4b9732b18
C++
lssxfy123/C-study
/stl_test53/test.cpp
GB18030
2,111
3.421875
3
[]
no_license
// Copyright 2017.|| // author|| // shared ptrʵSTL Reference #include <algorithm> #include <deque> #include <iostream> #include <memory> #include <set> #include "../include/print.hpp" #include "../include/buckets.hpp" using namespace std; class Item { public: Item(const string& name, float price = 0) : name_(name), price_(price) {} string name() const { return name_; } void set_name(const string& name) { name_ = name; } float price() const { return price_; } void set_price(float p) { price_ = p; } private: string name_; float price_; }; template<typename Coll> void PrintItems(const string& msg, const Coll& coll) { cout << msg << endl; for (const auto& elem : coll) { cout << ' ' << elem->name() << ":" << elem->price() << endl; } } int main(int argc, char* argv[]) { typedef shared_ptr<Item> ItemPtr; // ʹshared_ptrΪSTLʵReference set<ItemPtr> allItems; deque<ItemPtr> bestsellers; bestsellers = {ItemPtr(new Item("Kong Yize", 20.10f)), ItemPtr(new Item("A Midsummer Night's Dream", 14.99f)), ItemPtr(new Item("The Maltese Falcon", 9.88f))}; allItems = {ItemPtr(new Item("Water", 0.44f)), ItemPtr(new Item("Pizza", 2.22f))}; allItems.insert(bestsellers.begin(), bestsellers.end()); PrintItems("bestsellers: ", bestsellers); PrintItems("all: ", allItems); cout << endl; cout << "double price of bestsellers" << endl; for_each(bestsellers.begin(), bestsellers.end(), [](shared_ptr<Item>& elem) { elem->set_price(elem->price() * 2); }); cout << "replace second bestseller by first item with name Pizza" << endl; bestsellers[1] = *(find_if(allItems.begin(), allItems.end(), [](shared_ptr<Item> elem) { return elem->name() == "Pizza"; })); bestsellers[0]->set_price(44.77f); PrintItems("bestsellers: ", bestsellers); PrintItems("all: ", allItems); return 0; }
true
683f9d5c73a59447be88d7f4be9af4ed17381caf
C++
imulan/procon
/lib/RollingHash.cpp
UTF-8
1,140
2.953125
3
[]
no_license
struct RollingHash{ static const int MD = 3; static const vector<ll> hash_base, hash_mod; int n; vector<ll> hs[MD], pw[MD]; RollingHash(){} RollingHash(const string &s){ n = s.size(); rep(i,MD){ hs[i].assign(n+1,0); pw[i].assign(n+1,0); hs[i][0] = 0; pw[i][0] = 1; rep(j,n){ pw[i][j+1] = pw[i][j]*hash_base[i] % hash_mod[i]; hs[i][j+1] = (hs[i][j]*hash_base[i]+s[j]) % hash_mod[i]; } } } // 1-index ll hash_value(int l, int r, int i){ return ((hs[i][r] - hs[i][l]*pw[i][r-l])%hash_mod[i]+hash_mod[i])%hash_mod[i]; } bool match(int l1, int r1, int l2, int r2){ bool ret = true; rep(i,MD) ret &= (hash_value(l1-1,r1,i) == hash_value(l2-1,r2,i)); return ret; } vector<ll> calc(int l, int r){ vector<ll> ret(MD); rep(i,MD) ret[i]=hash_value(l-1,r,i); return ret; } }; const vector<ll> RollingHash::hash_base{1009,1021,1013}; const vector<ll> RollingHash::hash_mod{1000000009,1000000007,1000000021};
true
3114c6300fa3b4b539378e2de80ed4a70aa5c44f
C++
momsspaghettti/coursera-c-plus-plus-modern-development
/Brown/first_week/first_week/priority_collection.h
WINDOWS-1251
3,469
3.28125
3
[]
no_license
#pragma once #include <algorithm> #include <iterator> #include <set> #include <utility> #include <vector> template <typename T> class PriorityCollection { public: using Id = size_t; // // Id Add(T object); // [range_begin, range_end) // , // [ids_begin, ...) template <typename ObjInputIt, typename IdOutputIt> void Add(ObjInputIt range_begin, ObjInputIt range_end, IdOutputIt ids_begin); // , - // bool IsValid(Id id) const; // const T& Get(Id id) const; // 1 void Promote(Id id); // std::pair<const T&, int> GetMax() const; // GetMax, std::pair<T, int> PopMax(); private: std::set<std::pair<int, size_t>> priority_set_; std::vector<T> data_; std::vector<int> checker_; }; template <typename T> typename PriorityCollection<T>::Id PriorityCollection<T>::Add(T object) { Id id = data_.size(); data_.push_back(std::move(object)); checker_.push_back(0); priority_set_.insert({ 0, id }); return id; } template <typename T> template <typename ObjInputIt, typename IdOutputIt> void PriorityCollection<T>::Add(ObjInputIt range_begin, ObjInputIt range_end, IdOutputIt ids_begin) { for (; range_begin != range_end;) { *(ids_begin++) = Add(std::move(*(range_begin++))); } } template <typename T> bool PriorityCollection<T>::IsValid(Id id) const { return id < data_.size() && checker_.at(id) != -1; } template <typename T> const T& PriorityCollection<T>::Get(Id id) const { return data_.at(id); } template <typename T> void PriorityCollection<T>::Promote(Id id) { const auto iter = priority_set_.find({checker_.at(id), id}); priority_set_.erase(iter); ++checker_[id]; priority_set_.insert({ checker_.at(id), id }); } template <typename T> std::pair<const T&, int> PriorityCollection<T>::GetMax() const { auto max_pair = *std::prev(priority_set_.end()); return { data_.at(max_pair.second), max_pair.first }; } template <typename T> std::pair<T, int> PriorityCollection<T>::PopMax() { auto max_pair = *std::prev(priority_set_.end()); priority_set_.erase(std::prev(priority_set_.end())); checker_[max_pair.second] = -1; auto result = std::make_pair(std::move(data_.at(max_pair.second)), std::move(max_pair.first)); return result; } class StringNonCopyable : public std::string { public: using std::string::string; // StringNonCopyable(const StringNonCopyable&) = delete; StringNonCopyable(StringNonCopyable&&) = default; StringNonCopyable& operator=(const StringNonCopyable&) = delete; StringNonCopyable& operator=(StringNonCopyable&&) = default; }; void TestPriorityCollection();
true
bd61fddf20786fb0457ed6daead8b5ceee6c1a6d
C++
OhmPopy/eepp
/include/eepp/system/safedatapointer.hpp
UTF-8
545
2.546875
3
[ "MIT" ]
permissive
#ifndef EE_SYSTEM_SAFEDATAPOINTER #define EE_SYSTEM_SAFEDATAPOINTER #include <eepp/config.hpp> namespace EE { namespace System { /** @brief Keep a pointer and release it in the SafeDataPointer destructor */ class EE_API SafeDataPointer { public: SafeDataPointer(); SafeDataPointer( Uint32 size ); SafeDataPointer( Uint8 * data, Uint32 size ); /** @brief The destructor deletes the buffer */ ~SafeDataPointer(); void clear(); /** Pointer to the buffer */ Uint8 * data; /** Buffer size */ Uint32 size; }; }} #endif
true
0b16074f19c08cd5d27262aba0db50babb4e742d
C++
SilvioWeging/kASA
/stxxl/tests/common/test_log2.cpp
UTF-8
3,354
2.53125
3
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/*************************************************************************** * tests/common/test_log2.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de> * Copyright (C) 2013 Timo Bingmann <tb@panthema.net> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <iostream> #include <cmath> #include <cassert> #include <stxxl/bits/config.h> #include <stxxl/bits/common/tmeta.h> #include <stxxl/bits/common/utils.h> #include <stxxl/bits/verbose.h> using stxxl::LOG2; using stxxl::unsigned_type; template <unsigned_type i> void log_i(unsigned_type floorv, unsigned_type ceilv) { std::cout << i << "\t" << (i < 1000000 ? "\t" : "") << stxxl::LOG2_floor<i>::value << "\t" << stxxl::LOG2<i>::floor << "\t" << stxxl::LOG2<i>::ceil << std::endl; std::cout << "\t\t" << stxxl::ilog2_floor(i) << "\t" << stxxl::ilog2_floor(i) << "\t" << stxxl::ilog2_ceil(i) << std::endl; STXXL_CHECK(stxxl::LOG2_floor<i>::value == stxxl::ilog2_floor(i)); STXXL_CHECK(stxxl::LOG2<i>::floor == stxxl::ilog2_floor(i)); STXXL_CHECK(stxxl::LOG2<i>::ceil == stxxl::ilog2_ceil(i)); if (i <= 1) { STXXL_CHECK(stxxl::LOG2_floor<i>::value == 0); STXXL_CHECK(stxxl::LOG2<i>::floor == 0); STXXL_CHECK(stxxl::LOG2<i>::ceil == 0); } else if (i == 2) { STXXL_CHECK(stxxl::LOG2_floor<i>::value == 1); STXXL_CHECK(stxxl::LOG2<i>::floor == 1); STXXL_CHECK(stxxl::LOG2<i>::ceil == 1); } else { STXXL_CHECK(stxxl::LOG2_floor<i>::value == floorv); STXXL_CHECK(stxxl::LOG2<i>::floor == floorv); STXXL_CHECK(stxxl::LOG2<i>::ceil == ceilv); #if 0 // not many compiler have log2l() if (i <= ((stxxl::uint64)(1) << 59)) // does not work for higher powers { STXXL_CHECK(stxxl::LOG2_floor<i>::value == (unsigned_type)floorl(log2l(i))); STXXL_CHECK(stxxl::LOG2<i>::floor == (unsigned_type)floorl(log2l(i))); STXXL_CHECK(stxxl::LOG2<i>::ceil == (unsigned_type)ceill(log2l(i))); } #endif } std::cout << "\n"; } template <unsigned_type i> void log_ipm1(unsigned_type p) { log_i<i - 1>(p - 1, p); log_i<i>(p, p); log_i<i + 1>(p, p + 1); std::cout << std::endl; } int main() { std::cout << "i\t\tLOG2<i>\tLOG2<i>\tLOG2<i>" << std::endl; std::cout << "\t\t\tfloor\tceil" << std::endl; log_ipm1<1 << 0>(0); log_ipm1<1 << 1>(1); log_ipm1<1 << 2>(2); log_ipm1<1 << 3>(3); log_ipm1<1 << 4>(4); log_ipm1<1 << 5>(5); log_ipm1<1 << 6>(6); log_ipm1<1 << 7>(7); log_ipm1<1 << 8>(8); log_ipm1<1 << 9>(9); log_ipm1<1 << 10>(10); log_ipm1<1 << 11>(11); log_ipm1<1 << 12>(12); log_ipm1<1 << 16>(16); log_ipm1<1 << 24>(24); log_ipm1<1 << 30>(30); log_ipm1<1UL << 31>(31); #if __WORDSIZE == 64 log_ipm1<1UL << 32>(32); log_ipm1<1UL << 33>(33); log_ipm1<1UL << 48>(48); log_ipm1<1UL << 50>(50); log_ipm1<1UL << 55>(55); log_ipm1<1UL << 63>(63); #endif }
true
bbeafaaa01700600bdffd2981f1885abb167972e
C++
Nargisgod/Proect
/ramdevice.h
UTF-8
373
2.640625
3
[]
no_license
#ifndef RAMDEVICE_H #define RAMDEVICE_H #include "busdevice.h" class RAMDevice : public BusDevice { Q_OBJECT public: RAMDevice(int width); uint8_t read8(uint32_t address) override; void write8(uint32_t address, uint8_t value) override; const uint8_t *getBuffer(uint32_t address) const; private: QVector<uint8_t> _data; }; #endif // RAMDEVICE_H
true
121fa5f1211ab7a9ad2a068c93a53f82735dae04
C++
peterhyun1234/Algorithm_Pgrms
/using_cpp/Binary_search/징검다리.cpp
UTF-8
809
3.03125
3
[]
no_license
#include <string> #include <vector> #include <algorithm> using namespace std; int solution(int distance, vector<int> rocks, int n) { int answer = 0; int degree_of_rocks = rocks.size(); sort(rocks.begin(), rocks.end()); int left = 0; int right = distance; while (left <= right) { int mid = (left + right) / 2; int compared_rock_position = 0; int removed_stone_num = 0; for (int j = 0; j < degree_of_rocks; j++) { if (rocks[j] - compared_rock_position < mid) removed_stone_num++; else compared_rock_position = rocks[j]; } if (removed_stone_num > n) right = mid - 1; else left = mid + 1; } answer = right; return answer; }
true
73f16d6d892384855e8a1939a1e23e0db27c2a47
C++
Zinc-30/math6380
/project3/rank.cpp
UTF-8
16,394
2.65625
3
[]
no_license
// // rank.cpp // xcodeProject1 // // Created by Jinxing on 13/5/2017. // Copyright © 2017 Jinxing. All rights reserved. // #include <iostream> #include <math.h> #include <string> #include <map> #include <fstream> #include <sstream> #include <vector> #include <algorithm> #include <random> using namespace std; #define MAXSTRING 100 #define CELL_SIZE 990 map<string, int> drug_dict; map<string, int> cell_dict; typedef double real; real lr = 1e-3; real weight_scale = 1e-3; int batch_size = 1000; int epoch = 1000; int drug_size = 265, gene_size = 1250, class_size = 3; vector<int> cell_feature[CELL_SIZE]; int train_data_nums = 0; int test_data_nums = 0; int print_epo = 1; /* Model parameters: drugW, the embedding matrix of drugs drugb, the bias vector of drugs affineW, affineb, the affine layer, convert the rank scores to softmax scores cell_embed, temp vector to store the embedding of cell */ real *drugW, *drugb, *affineW, *affineb; // gradients of parameters real *grad_drugW, *grad_drugb, *grad_affineW, *grad_affineb; struct DataPair{ int sample_id; int cell_id; int drug1_id; int drug2_id; int y; }; vector<DataPair> train_pairs; vector<DataPair> test_pairs; void ReadDrugDict(char* filename) { ifstream infile(filename); if (infile.is_open()){ string tmp_drug; int idx = 0; while (infile >> tmp_drug){ drug_dict[tmp_drug] = idx; idx++; } infile.close(); } else{ printf("ERROR: failed to read the file in ReadDrugDict\n"); exit(1); } } void ReadCellDict(char* filename) { ifstream infile(filename); if (infile.is_open()){ string tmp_cell; int idx = 0; while (infile >> tmp_cell){ cell_dict[tmp_cell] = idx; idx++; } infile.close(); } else{ printf("ERROR: failed to read the file in ReadDrugDict\n"); exit(1); } } // Read the features of the drug void ReadCellFeature(char* filename) { ifstream infile(filename); if (infile.is_open()){ int cnt = 0; string line; while(getline(infile,line)){ istringstream iss(line); int tmp; while(iss >> tmp) cell_feature[cnt].push_back(tmp); cnt++; } infile.close(); } else{ printf("ERROR: failed to read the file of cell features\n"); exit(1); } } // Load the training pairs void ReadTrainPairs(char* filename) { ifstream infile(filename); if (infile.is_open()){ string line; while (getline(infile, line)){ istringstream iss(line); DataPair tmp; iss >> tmp.sample_id; tmp.sample_id += 1; string cell_name, drug1_name, drug2_name; iss >> cell_name; iss >> drug1_name; iss >> drug2_name; tmp.cell_id = cell_dict[cell_name]; tmp.drug1_id = drug_dict[drug1_name]; tmp.drug2_id = drug_dict[drug2_name]; float y = 0; iss >> y; tmp.y = int(y); train_pairs.push_back(tmp); } infile.close(); train_data_nums = (int) train_pairs.size(); } else{ printf("ERROR: failed to read the file of training pairs\n"); exit(1); } } // Load the testing pairs void ReadTestPairs(char* filename) { ifstream infile(filename); if (infile.is_open()){ string line; while (getline(infile, line)){ istringstream iss(line); DataPair tmp; tmp.y = 0; // intialize the unknow value to 0 iss >> tmp.sample_id; tmp.sample_id += 1; string cell_name, drug1_name, drug2_name; iss >> cell_name; iss >> drug1_name; iss >> drug2_name; tmp.cell_id = cell_dict[cell_name]; tmp.drug1_id = drug_dict[drug1_name]; tmp.drug2_id = drug_dict[drug2_name]; test_pairs.push_back(tmp); } infile.close(); test_data_nums = int(test_pairs.size()); } else{ printf("ERROR: failed to read the file of testing pairs\n"); exit(1); } } void ClearGradients() { for (int i = 0; i < drug_size * gene_size; i++) grad_drugW[i] = 0; for (int i = 0; i < drug_size; i++) grad_drugb[i] = 0; for (int i = 0; i < class_size; i++) grad_affineW[i] = 0; for (int i = 0; i < class_size; i++) grad_affineb[i] = 0; } void UpdateParameters() { for (int i = 0; i < drug_size * gene_size; i++) drugW[i] += - lr * grad_drugW[i]; for (int i = 0; i < drug_size; i++) drugb[i] += -lr * grad_drugb[i]; for (int i = 0; i < class_size; i++) affineW[i] += -lr * grad_affineW[i]; for (int i = 0; i < class_size; i++) affineb[i] += -lr * grad_affineb[i]; } struct Result{ int pred_y; real loss; }; // Predict the drug sensitivity rank for each data sample // Only backpropagate the gradients during the training period Result TrainPredictOneData(DataPair cur_pair, bool train) { Result result; // forward pass int tmp_cell_id = cur_pair.cell_id; int tmp_gene_num = (int) cell_feature[tmp_cell_id].size(); int tmp_drug1_id = cur_pair.drug1_id; int tmp_drug2_id = cur_pair.drug2_id; // computhe the score s = b1 - b2 + <x, beta_1 - beta_2> real s = drugb[tmp_drug1_id] - drugb[tmp_drug2_id]; for (int k = 0; k < tmp_gene_num; k++){ int gene_id = cell_feature[tmp_cell_id][k]; s += drugW[tmp_drug1_id * gene_size + gene_id] - drugW[tmp_drug2_id * gene_size + gene_id]; } // transform the score s to target labels probability by affine - softmax layers real prob[3]; real maxp = 0; int maxid = 0; for (int k = 0; k < 3; k++){ prob[k] = s * affineW[k] + affineb[k]; if (prob[k] > maxp){ maxp = prob[k]; maxid = k; } } // transform by softmax function real sum = 0; for (int k = 0; k < 3; k++){ prob[k] -= maxp; prob[k] = exp(prob[k]); sum += prob[k]; } for (int k = 0; k < 3; k++) prob[k] /= sum; result.pred_y = maxid; result.loss = 0; if (train){ int tmp_y = cur_pair.y; result.loss = -log(prob[tmp_y+1]); // backpropagate the gradients real dx[3]; for (int k = 0; k < 3; k++) dx[k] = prob[k]; dx[tmp_y+1] -= 1; for (int k = 0; k < 3; k++){ grad_affineW[k] += dx[k] * s; grad_affineb[k] += dx[k]; } real ds = 0; for (int k = 0; k < 3; k++) ds += dx[k] * affineW[k]; grad_drugb[tmp_drug1_id] += ds; grad_drugb[tmp_drug2_id] += -ds; for (int k = 0; k < tmp_gene_num; k++){ int gene_id = cell_feature[tmp_cell_id][k]; grad_drugW[tmp_drug1_id * gene_size + gene_id] += ds; grad_drugW[tmp_drug2_id * gene_size + gene_id] += -ds; } } return result; } // partition the training data into training set and validation set void Train() { // random shuffle the training data random_shuffle(train_pairs.begin(), train_pairs.end()); int sample_train_size = train_data_nums / 5 * 4; real loss = 0, train_acc = 0, val_acc = 0; for (int iter = 0; iter < epoch; iter++){ // train and update parameters for (int i = 0; i < sample_train_size; i = i + batch_size){ real batch_loss = 0; ClearGradients(); for (int j = i; j < i + batch_size && j < sample_train_size; j++){ Result result = TrainPredictOneData(train_pairs[j], true); batch_loss += result.loss; } // printf("batch loss %.4f\n",batch_loss); // update parameters by SGD UpdateParameters(); loss += batch_loss; } loss /= sample_train_size / batch_size; // train accuracy for (int i = 0; i < sample_train_size; i++){ Result result = TrainPredictOneData(train_pairs[i], false); if (result.pred_y == train_pairs[i].y + 1) train_acc += 1.0 / sample_train_size; } // validation accuracy for (int i = sample_train_size; i < train_data_nums; i++){ Result result = TrainPredictOneData(train_pairs[i], false); if (result.pred_y == train_pairs[i].y + 1) val_acc += 1.0 / (train_data_nums - sample_train_size); } // print average loos and training accuracy if ((iter % print_epo) == 0){ printf("==========> epoch %d loss %.4f train-acc %.4f val-acc %.4f\n", iter, loss / print_epo, train_acc / print_epo, val_acc / print_epo); loss = 0; train_acc = 0; val_acc = 0; } } } // use the whole dataset for training void Train2() { // random shuffle the training data random_shuffle(train_pairs.begin(), train_pairs.end()); real loss = 0, train_acc = 0; for (int iter = 0; iter < epoch; iter++){ // train and update parameters for (int i = 0; i < train_data_nums; i = i + batch_size){ real batch_loss = 0; ClearGradients(); for (int j = i; j < i + batch_size && j < train_data_nums; j++){ Result result = TrainPredictOneData(train_pairs[j], true); batch_loss += result.loss; } // printf("batch loss %.4f\n",batch_loss); // update parameters by SGD UpdateParameters(); loss += batch_loss; } loss /= train_data_nums / batch_size; // train accuracy for (int i = 0; i < train_data_nums; i++){ Result result = TrainPredictOneData(train_pairs[i], false); if (result.pred_y == train_pairs[i].y + 1) train_acc += 1.0 / train_data_nums; } // print average loos and training accuracy if ((iter % print_epo) == 0){ printf("==========> epoch %d loss %.4f train-acc %.4f\n", iter, loss / print_epo, train_acc / print_epo); loss = 0; train_acc = 0; } } } void Test(char *test_predict_file) { // predict the drug pairs in test file ofstream ofile(test_predict_file); ofile << "SampleID,ComparisonValue" << endl; for (int i = 0; i < test_data_nums; i++){ Result result = TrainPredictOneData(test_pairs[i], false); test_pairs[i].y = result.pred_y; ofile << test_pairs[i].sample_id << "," << test_pairs[i].y - 1 << endl; } ofile.close(); } void normal_initialize(real *array, int asize) { unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator (seed); std::normal_distribution<double> distribution (0.0,1.0); for (int i = 0; i < asize; i++) array[i] = weight_scale * distribution(generator); } void SaveParameters(char* parameter_file) { ofstream ofile(parameter_file); ofile << "drugW" << endl; ofile << drugW[0]; int i = 0; for (i = 1; i < drug_size * gene_size; i++) ofile << " " << drugW[i]; ofile << endl; ofile << "drugb" << endl; ofile << drugb[0]; for (i = 1; i < drug_size; i++) ofile << " " << drugb[i]; ofile << endl; ofile << "affineW" << endl; ofile << affineW[0]; for (i = 1; i < class_size; i++) ofile << " " << affineW[i]; ofile << endl; ofile << "affineb" << endl; ofile << affineb[0]; for (i = 1; i < class_size; i++) ofile << " " << affineb[i]; ofile << endl; ofile.close(); } void ReadParameters(char *parameter_file) { ifstream infile(parameter_file); if (infile.is_open()){ string name; string line; int i = 0; getline(infile,name); getline(infile,line); istringstream iss(line); for (i = 0; i < drug_size * gene_size; i++) iss >> drugW[i]; getline(infile,name); getline(infile,line); iss.str(line); for (i = 0; i < drug_size; i++) iss >> drugb[i]; getline(infile,name); getline(infile,line); iss.str(line); for (i = 0; i < class_size; i++) iss >> affineW[i]; getline(infile,name); getline(infile,line); iss.str(line); for (i = 0; i < class_size; i++) iss >> affineb[i]; infile.close(); } else{ printf("ERROR: failed to read the parameter file\n"); exit(1); } } void InitParameters() { drugW = (real *)calloc(drug_size * gene_size, sizeof(real)); drugb = (real *)calloc(drug_size, sizeof(real)); affineW = (real *)calloc(class_size, sizeof(real)); affineb = (real *)calloc(class_size, sizeof(real)); normal_initialize(drugW, drug_size * gene_size); normal_initialize(affineW, class_size); grad_drugW = (real *)calloc(drug_size * gene_size, sizeof(real)); grad_drugb = (real *)calloc(drug_size, sizeof(real)); grad_affineW = (real *)calloc(class_size, sizeof(real)); grad_affineb = (real *)calloc(class_size, sizeof(real)); } void DestroyParameters() { free(drugW); free(drugb); free(affineW); free(affineb); free(grad_drugW); free(grad_drugb); free(grad_affineW); free(grad_affineb); } int ArgPos(char *str, int argc, char **argv) { int a; for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) { if (a == argc - 1) { printf("Argument missing for %s\n", str); exit(1); } return a; } return -1; } int main(int argc, char**argv) { char drug_list_file[MAXSTRING], cell_list_file[MAXSTRING], cell_feature_file[MAXSTRING]; char train_pairs_file[MAXSTRING], test_pairs_file[MAXSTRING], test_predict_file[MAXSTRING]; char parameter_file[MAXSTRING] = "parameters.txt"; int i = 0; if (argc == 1) { printf("Drug sensitivity rank prediction \n\n"); printf("Options:\n"); printf("Parameters for training:\n"); printf("\t-druglist <file>\n"); printf("\t\tUse <file> to build a dictionary of drug names\n"); printf("\t-celllist <file>\n"); printf("\t\tUse <file> to build a dictionary of cell names\n"); printf("\t-cellfeature <file>\n"); printf("\t\tUse <file> to get gene features for each cell\n"); printf("\t-trainpairs <file>\n"); printf("\t\tUse <file> to get the training pairs\n"); printf("\t-testpairs <file>\n"); printf("\t\tUse <file> to get the testing pairs\n"); printf("\t-testpredict <file>\n"); printf("\t\tUse <file> to store the predict results\n"); printf("\nExamples:\n"); printf("./rank -druglist druglist.txt -celllist celllist.txt -cellfeature cellfeature.txt -trainpairs trainpair.txt -testpairs testpair.txt -testpredict test_predict.csv \n\n"); return 0; } drug_list_file[0] = 0; cell_list_file[0] = 0; cell_feature_file[0] = 0; train_pairs_file[0] = 0; test_pairs_file[0] = 0; test_predict_file[0] = 0; if ((i = ArgPos((char *)"-druglist", argc, argv)) > 0) strcpy(drug_list_file, argv[i + 1]); if ((i = ArgPos((char *)"-celllist", argc, argv)) > 0) strcpy(cell_list_file, argv[i + 1]); if ((i = ArgPos((char *)"-cellfeature", argc, argv)) > 0) strcpy(cell_feature_file, argv[i + 1]); if ((i = ArgPos((char *)"-trainpairs", argc, argv)) > 0) strcpy(train_pairs_file, argv[i + 1]); if ((i = ArgPos((char *)"-testpairs", argc, argv)) > 0) strcpy(test_pairs_file, argv[i + 1]); if ((i = ArgPos((char *)"-testpairs", argc, argv)) > 0) strcpy(test_pairs_file, argv[i + 1]); if ((i = ArgPos((char *)"-testpredict", argc, argv)) > 0) strcpy(test_predict_file, argv[i + 1]); ReadDrugDict(drug_list_file); ReadCellDict(cell_list_file); ReadCellFeature(cell_feature_file); ReadTrainPairs(train_pairs_file); ReadTestPairs(test_pairs_file); InitParameters(); Train2(); Test(test_predict_file); SaveParameters(parameter_file); DestroyParameters(); return 0; }
true
7c9b4373fcd26dbc8105b6bed632729e6940f604
C++
pkroy0185/C-plus-plus-programs1
/8.cpp
UTF-8
1,136
2.9375
3
[]
no_license
/* Draw below pattern OOOOOOOOOOOOOOOOO OOOOOO*****OOOOOO OOOO*********OOOO OOO***********OOO OO*************OO OO*************OO OO*************OO OOO***********OOO OOOO*********OOOO OOOOOO*****OOOOOO OOOOOOOOOOOOOOOOO */ #include<iostream> using namespace std; void PrintPattern() { int i,j; cout<<"\tFigure 8."<<endl<<endl; for(i=1;i<=11;i++) { for(j=1;j<=17;j++) { if(i>1 && i<11) { if(j>2 && j<16) { if(j>6 && j<12) cout<<"*"; else if((i>4 && i<8)&&((j>2 && j<7)||(j>11 && j<16))) cout<<"*"; else if((i==3 || i==9)&&((j>4 && j<7)||(j>11 && j<14))) cout<<"*"; else if((i==4 || i==8)&&((j>3 && j<7)||(j>11 && j<15))) cout<<"*"; else cout<<"O"; } else cout<<"O"; } else cout<<"O"; } cout<<endl; } } int main() { PrintPattern(); return 0; }
true
7815b1ef8d44ff583a7760f15a7babc4df7da0c4
C++
maximejen/Arcade-EPI-2017-2018
/core/PlayerScore.hpp
UTF-8
807
2.546875
3
[]
no_license
/* ** EPITECH PROJECT, 2018 ** cpp_arcade ** File description: ** ${Description} */ #ifndef CPP_ARCADE_PLAYERNAME_HPP #define CPP_ARCADE_PLAYERNAME_HPP #include <iostream> #include <ios> #include <string> #include "Keys.hpp" #include "../libs/src/IGraphicLib.hpp" #include <chrono> #include <map> #include <fstream> namespace Arcade { class PlayerScore { public: PlayerScore(); bool setPlayerName(IGraphicLib &); std::string getPlayerName() const; bool writeScoreInFile(); void setScore(int score); private: bool endescape(Keys curKey); std::string playerName; void addNewLetter(Keys); bool endEntry(Keys curKey); std::chrono::steady_clock::time_point timer; std::map<int, std::string> score; void openScore(); int curScore; }; } #endif //CPP_ARCADE_PLAYERNAME_HPP
true
3700b711b3d32baee58f9e50f8870ac94e86b235
C++
juniway/lint
/algorithms/sort/heapsort/heap_sort.cpp
UTF-8
2,504
3.46875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int leftChild(int i) { return 2 * i + 1; } int rightChild(int i) { return 2 * i + 2; } void maxHeapify(vector<int>& a, int i, int n) { int parent = i, left = leftChild(i), right = rightChild(i); if (left < n && a[left] > a[parent]) { parent = left; } if (right < n && a[right] > a[parent]) { parent = right; } if (parent != i) { swap(a[i], a[parent]); maxHeapify(a, parent, n); } } void percolateDown(vector<int>& a, int i, int size) { int min, left = leftChild(i), right = rightChild(i); while (left < size) { min = left; if (right < size && a[left] < a[right]) min = right; if (a[min] > a[i]) { swap(a[min], a[i]); i = min; left = leftChild(i); right = rightChild(i); } else { break; } } } void bubbleUp(vector<int>& a, int x) { a.push_back(x); int i = a.size() - 1; int parent = i / 2; while (i > 0 && a[i] > parent) { swap(a[i], a[parent]); i = parent; parent = i / 2; } } void PercolateDown(vector<int>& num, int index, int size) { int min; while (index * 2 + 1 < size) { min = index * 2 + 1; if (index * 2 + 2 < size) { if (num[min] < num[index * 2 + 2]) { min = index * 2 + 2; } } if (num[min] <= num[index]) { break; } else { swap(num[index], num[min]); index = min; } } } void buildMaxHeap(vector<int>& a) { for(int i = a.size() / 2 - 1 ; i >= 0; i--) { // cout << i << ":" << a[i] << endl; // maxHeapify(a, i, a.size()); PercolateDown(a, i, a.size()); } } void heapSort(vector<int>& a) { buildMaxHeap(a); int i = a.size() - 1; while(i > 0) { swap(a[0], a[i]); i--; cout << i + 1 << endl; maxHeapify(a, 0, i+1); } cout << endl; } void testBuild() { // vector<int> a {16, 14, 10, 8, 7, 9, 3, 2, 4}; // vector<int> a {9, 8, 3, 7, 16, 14, 2, 10, 4}; vector<int> a {4, 6, 3, 5, 2, 1}; buildMaxHeap(a); heapSort(a); for(auto x: a) { cout << x << " "; } cout << endl; // bubbleUp(a, 17); // for(auto x: a) { // cout << x << " "; // } // cout << endl; } int main(int argc, char *argv[]) { testBuild(); return 0; }
true
605093942e7d2dd5c4664faee1ccceda2c177c9b
C++
IsaacLaw12/RayTracer
/src/OctTree.h
UTF-8
1,581
2.515625
3
[]
no_license
#ifndef OctTree_INCLUDED #define OctTree_INCLUDED #include <string> #include <iostream> #include <vector> #include <set> #include <memory> #include <limits> // Needs to link Eigen in the makefile with g++ -I/path/to/Eigen #include <Eigen> #include <Core> class Model; #include "BoundingBox.h" #include "Model.h" #include "Ray.h" class OctTree : public BoundingBox { public: OctTree(Eigen::MatrixXd& verts, Eigen::MatrixXi& faces, int recursionLimit); OctTree(OctTree* parent_bb, int recursionLimit, Eigen::Vector3d min, Eigen::Vector3d max); Eigen::Vector3d get_vertex(int index); std::vector<int> get_contained_faces(); std::set<int> intersected_faces(Ray& ray); private: void find_contained_faces(std::set<int> &parent_faces); double max(double a, double b, double c); double min(double a, double b, double c); bool triangle_intersects(Eigen::Vector3d& v0, Eigen::Vector3d& v1, Eigen::Vector3d& v2); bool axis_test(const Eigen::Vector3d& axis, const Eigen::Vector3d& e, const Eigen::Vector3d& v0, const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, const Eigen::Vector3d& u0, const Eigen::Vector3d& u1, const Eigen::Vector3d& u2); void find_corners(); void subdivide_box(); void calculate_bounding(); Eigen::MatrixXd& Vertices; Eigen::MatrixXi& Faces; std::vector<std::unique_ptr<OctTree>> contained_boxes; std::set<int> contained_faces; Eigen::Vector3d center = Eigen::Vector3d(); int recursion_limit; }; #endif
true
33a762dd5e9591eda01926fa4582f9e152f3770f
C++
fqurishi/OpenGLCplusplus
/showcase/src/Camera.cpp
UTF-8
2,941
2.890625
3
[]
no_license
#include <cmath> #include <vector> #include <iostream> #include <glm\gtc\matrix_transform.hpp> #include "Camera.h" #include <glm\gtc\type_ptr.hpp> #include <GL\glew.h> using namespace std; Camera::Camera(float x, float y, float z) { init(); location = glm::vec4(x, y, z, 1); updateView(); } void Camera::init() { u = glm::vec4(1, 0, 0, 0); v = glm::vec4(0, 1, 0, 0); n = glm::vec4(0, 0, 1, 0); m = glm::mat4(u, v, n, (glm::vec4(0, 0, 0, 1))); } void Camera::moveCameraLeft(float x) { c = u; glm::vec4 compute = glm::normalize(c) * x; location = location - compute; updateView(); } void Camera::moveCameraRight(float x) { c = u; glm::vec4 compute = glm::normalize(c) * x; location = location + compute; updateView(); } void Camera::moveCameraUp(float y) { c = v; glm::vec4 compute = glm::normalize(c) * y; location = location + compute; updateView(); } void Camera::moveCameraDown(float y) { c = v; glm::vec4 compute = glm::normalize(c) * y; location = location - compute; updateView(); } void Camera::moveCameraForward(float z) { c = n; glm::vec4 compute = glm::normalize(c) * z; location = location - compute; location.y = 0; updateView(); } void Camera::moveCameraBackward(float z) { c = n; glm::vec4 compute = glm::normalize(c) * z; location = location + compute; location.y = 0; updateView(); } void Camera::panLeft(float a) { pan = pan + a; updateView(); } void Camera::panRight(float a) { pan = pan - a; updateView(); } void Camera::pitchUp(float a) { pitch = pitch + a; updateView(); } void Camera::pitchDown(float a) { pitch = pitch + a; updateView(); } float Camera::getX() { return location.x; } float Camera::getY() { return location.y; } float Camera::getZ() { return location.z; } glm::mat4 Camera::getMatrix() { return m; } void Camera::updateView() { glm::vec4 newLocation = glm::vec4(location); float cosPitch = (float)cos(pitch); float sinPitch = (float)sin(pitch); float cosPan = (float)cos(pan); float sinPan = (float)sin(pan); u = glm::vec4(cosPan, 0, -sinPan, 0); v = glm::vec4(sinPan * sinPitch, cosPitch, cosPan * sinPitch, 0); n = glm::vec4(sinPan * cosPitch, -sinPitch, cosPitch * cosPan, 0); float matArray []= { u.x, v.x, n.x, 0, u.y, v.y, n.y, 0, u.z, v.z, n.z, 0, -(glm::dot(u, newLocation)), -(glm::dot(v, newLocation)), -(glm::dot(n, newLocation)), 1}; m = glm::make_mat4(matArray); } void Camera::mouseMovement(double xoffset, double yoffset, GLboolean constrainPitch) { xoffset *= 0.005; yoffset *= 0.005; pan -= xoffset; pitch += yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (pitch > 1.45f) pitch = 1.45f; if (pitch < -1.45f) pitch = -1.45f; } // update values updateView(); }
true
ec77ac6477ac84884277785d32b52789270befac
C++
rajesh-gole/Company-Preparation
/Basics Questions/0.8 Sort element by frequency.cpp
UTF-8
1,235
3.6875
4
[]
no_license
#include<bits/stdc++.h> using namespace std; void ArraySort(int a[],int m) { map<int, int> mp; for(int i=0;i<m;i++) mp[a[i]]++; vector<pair<int , int>> v; for(auto p : mp){ int x = p.first; int y = p.second; v.push_back({y, -x}); } sort(v.rbegin(), v.rend()); // sort frequency in decreasing order vector<int> ans; for(auto p : v){ int x = p.first; int y = p.second; //cout << x << " " << y << endl; while(x-->0) // same as x-- cout<<-y<<" "; } } int main() { int a1[]={2,3,2,4,5,12,2,3,3,3,12}; // Output : 3, 3, 3, 3, 2, 2, 2, 12, 12, 4, 5 int m=sizeof(a1)/sizeof(a1[0]); ArraySort(a1,m); } // print the elements of an array in the decreasing frequency and if 2 numbers have same frequency then print the one which came first. /* Step1: store the elements in map Step2: store the freq,ele into vector using pair Step3: sort freq in decreasing order Step4: print the ele as per their freq '-' is must else 5 come first the 4 will come */
true
ee1e7d252f202d025d306ed4c7094fcdde3269af
C++
HidemiANDO/dpro_arduino
/Arduino/sketch_may28a/sketch_may28a.ino
UTF-8
486
2.53125
3
[]
no_license
#include <Servo.h> int SERVO1_SOCKET = 6; int SERVO2_SOCKET = 5; int SERVO3_SOCKET = 3; Servo servo1; Servo servo2; Servo servo3; void setup() { // put your setup code here, to run once: servo1.attach( SERVO1_SOCKET ); servo2.attach( SERVO2_SOCKET ); servo3.attach( SERVO3_SOCKET ); set_servo(); } void set_servo(){ servo1.write(20); servo2.write(-60); servo3.write(0); } void loop() { // put your main code here, to run repeatedly: //set_servo(); }
true
3a7d9f5f9db0bdccc6924790c46c2610979b6efc
C++
nohupped/just_another_repository
/SampleFind/DirEnt/library.cpp
UTF-8
1,179
3.015625
3
[]
no_license
#include "library.h" #include <dirent.h> #include <iostream> #include <string.h> #include <stdlib.h> #include <stdio.h> using namespace std; void getDirs(char* path) { DIR *dir_p = NULL; dirent *dir_ent = NULL; dir_p = opendir(path); while ((dir_ent = readdir(dir_p)) != NULL) { char* absolute_path = get_absolute_path(path, dir_ent->d_name); //get_absolute_path(path, dir_ent->d_name); if ((absolute_path != NULL) && (dir_ent->d_type == DT_DIR)) { printf("%s\n", absolute_path); getDirs(absolute_path); free(absolute_path); } } closedir(dir_p); } char* get_absolute_path(char* path, char* dname) { if (!(strcmp(dname, ".")) || !(strcmp(dname, "..")) ){ return NULL; } if ((strcmp(path, "/"))) { char *newpath = (char*) malloc(strlen(path)+2+strlen(dname)); strcpy(newpath, path); strcat(newpath, "/"); strcat(newpath, dname); return newpath; } else { char *newpath = (char*) malloc(strlen(path)+1+strlen(dname)); strcpy(newpath, path); strcat(newpath, dname); return newpath; } }
true
820f72de1bb6e5b1a491d975e4d21bcefac541dd
C++
sonyshot/LetsBuildSomething
/LetsBuildSomething/TetrisPiece.h
UTF-8
893
2.8125
3
[]
no_license
#pragma once #ifndef TETRISPIECE_H #define TETRISPIECE_H #include "SFML\Graphics.hpp" #include <array> enum PieceType { PIECE1, PIECE2, PIECE3, PIECE4, PIECE5, PIECE6, PIECE7 }; class TetrisPiece :public sf::Drawable, public sf::Transformable{ sf::VertexArray m_vertices; PieceType m_pieceType; int m_blockSize = 20; int m_rows = 0; int m_cols = 0; std::array<int, 8> m_blockPositions; sf::Color randomColor(); void draw(sf::RenderTarget& target, sf::RenderStates states) const; public: TetrisPiece(PieceType, int); ~TetrisPiece(); sf::Color m_color = randomColor(); sf::Vertex operator[](int index); std::array<int, 8> getBlockPositions(); void rotatePiece(); //i'm pretty sure this is a bad way to do this... int rotateGrowth(); void createPiece(PieceType); PieceType getPieceType(); }; #endif // !TETRISPIECE_H /* Clean up color access, fix rotation */
true
74d221113ff82adb6a89a00f41c597d30d00b7d9
C++
kadragon/acmicpc
/01000/01427.cpp
UTF-8
370
2.53125
3
[]
no_license
// // Created by kangdonguk on 2020/03/06. // // https://www.acmicpc.net/problem/1427 // 소트인사이드 #include <stdio.h> int a[10]; int main() { int n; scanf("%d", &n); while (n > 0) { a[n % 10]++; n /= 10; } for (int i = 9; i >= 0; i--) for (int j = 0; j < a[i]; j++) printf("%d", i); return 0; }
true
11182bcfba95fba83cdbbd0d2109fb4309c947e0
C++
2505552499/C-Workstation
/Leetcode/240.搜索二维矩阵-ii.cpp
UTF-8
1,637
3.015625
3
[]
no_license
/* * @lc app=leetcode.cn id=240 lang=cpp * * [240] 搜索二维矩阵 II */ // @lc code=start class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { // int m = matrix.size(); // int n = matrix[0].size(); // int k =0; // int flag; // for(;k < m - 1 && k < n - 1; k++){ // if(matrix[k][k] <= target && matrix[k + 1][k + 1] > target){ // flag = k; // break; // } // else flag = min(n - 1, m - 1); // } // if(m == 1){ // for(int i = 0;i< n;i++){ // if(matrix[0][i] == target) return true; // } // return false; // } // for(int i = 0;i <= flag;i++){ // for(int j = flag;j<n;j++){ // if(matrix[i][j] == target){ // return true; // } // } // } // for(int i = flag;i < m;i++){ // for(int j = 0;j<= flag;j++){ // if(matrix[i][j] == target){ // return true; // } // } // } // return false; int m = matrix.size(), n = m? matrix[0].size():0,r = 0,c = n - 1; while(r < m && c >= 0){ if(matrix[r][c] == target){ return true; } matrix[r][c] > target ? c-- : r++; } return false; } }; // 1 3 5 7 9 // 2 4 6 8 12 // 11 13 15 17 19 // 12 14 16 18 20 // 21 22 23 24 25 // 5 6 10 14 // 6 10 13 18 // 10 13 18 19 // @lc code=end
true
3d1417f53280c2ad99fe94fffeea2a0be6a22b40
C++
Trilaterus/HPEngineCubed
/NanDaiYoCode/RandomResource.h
UTF-8
265
2.859375
3
[]
no_license
/* A namespace of helper functions to generate random types such as ints, floats and bools. */ #pragma once #include <random> namespace RandomResource { int generateInt(int iMin, int iMax); float generateFloat(float fMin, float fMax); bool generateBool(); }
true
e2a22f4e962a4266d4cfb19b484591ac3970e89d
C++
aushani/summer
/cc/app/model_based/object_state.h
UTF-8
718
2.53125
3
[]
no_license
#pragma once #include <Eigen/Core> namespace app { namespace model_based { class ObjectState { public: ObjectState(double x, double y, double a, const std::string &cn); const Eigen::Vector2d& GetPos() const; double GetTheta() const; const std::string& GetClassname() const; double GetRange() const; double GetCosTheta() const; double GetSinTheta() const; double GetBearing() const; bool operator<(const ObjectState &os) const; private: double kResPos_ = 0.001; double kResAngle_ = 0.001; Eigen::Vector2d pos_; double theta_; std::string classname_; double bearing_; double range_; double cos_theta_; double sin_theta_; }; } // namespace model_based } // namespace app
true
243dc59ea72c817f02d008c994d17fdc664a125a
C++
amjabb/C-Data-Structures
/Hashing/quadraticHash.cpp
UTF-8
2,987
3.265625
3
[]
no_license
// // quadraticHash.cpp // search // // Created by Amir Jabbari on 11/15/15. // Copyright © 2015 Amir Jabbari. All rights reserved. // #include "quadraticHash.hpp" #include <cstdlib> #include <iostream> #include <string> #include <sstream> using namespace std; quadHash::quadHash(int size) { for(int i = 0; i < tableSize; i++) HashTable[i] = new stock(); for(int i = 0; i < size; i++) { int r = rand()%100 +1; stringstream st; st << "A" << i; string result = st.str(); int index = hash(result); int mult = 1; while (StatusTable[index] == 1) { if(index == size) index = 0; index += (mult*mult)%tableSize; mult++; } StatusTable[index] = 1; HashTable[index] = new stock(result,r); } } void quadHash::AddItem(string sname, int sprice) { int index = hash(sname); while (StatusTable[index] == 1) { if(index == tableSize) index = 0; index = index+1; } StatusTable[index] = 1; HashTable[index]->stockInit(sname,sprice); } int quadHash::NumberOfItemsInIndex(int index) { int count = 0; if(HashTable[index]->getName() == "empty") { return count; } else { count++; stock* Ptr = HashTable[index]; } return count; } void quadHash::printTable() { int number; for(int i = 0; i < tableSize; i++) { if (HashTable[i]->getName() == "empty") { cout << "index = " << i << endl; cout << "Empty" << endl; cout << 0 << endl; } else{ cout << "index = " << i << endl; cout << HashTable[i]->getName() << endl; cout << HashTable[i]->getPrice() << endl; } } } void quadHash::printItemsInIndex(int index) { stock* Ptr = HashTable[index]; for(int i = 0; i < tableSize; i++) { if(Ptr->getName() == "empty") { cout << "index = " << index << " is empty"; } else { cout << "index " << index << " contains the following item\n"; } } } void quadHash::search(string sname) { int index = hash(sname); bool foundName = false; int number = 1; stock* Ptr = HashTable[index]; for ( int i = 0; i < tableSize; i++) { if (sname == HashTable[index]->getName()) { foundName = true; break; } else { index += (number*number)%tableSize; } } if(foundName == true) { cout << "Stock Price = " << HashTable[index]->getPrice()<< endl; cout << "Location = " << index << endl; } } int quadHash::hash(string key) { int hash = 0; int index; for(int i = 0; i < key.length(); i++) { hash = (hash + (int)key[i]) * 8; } index = hash % tableSize; return index; }
true
939f0a87208dd105cde5c314d5e18b533b1c70f3
C++
jorshi/VoiceToMidiController
/Source/PitchDetection.cpp
UTF-8
4,587
2.734375
3
[]
no_license
/* ============================================================================== PitchDetection.cpp Created: 22 Mar 2017 11:41:06am Author: Jordie Shier ============================================================================== */ #include "PitchDetection.h" PitchDetection::PitchDetection(int bufferSize) : readPos_(0) { // Assumming that the length passed in will be a multiple of 2 // Allocate half the buffer size length for the yin data sample buffer yinData_.setSize(1, bufferSize/2); inputBuffer_.setSize(1, bufferSize); // YIN default tolerance was 0.15 tolerance_ = 0.15; // Detected pitch buffer detectedF0_.resize(maxFreqSmoothing); std::fill(detectedF0_.begin(), detectedF0_.end(), -1.0); f0Pointer_ = 0; } PitchDetection::~PitchDetection() { } void PitchDetection::runDetection(const float *samples, int numSamples) { int samplesRead = 0; float* input = inputBuffer_.getWritePointer(0); // Fill the input buffer. When enough samples are in the buffer, run // pitch detection while (samplesRead < numSamples) { // Accumulated enough samples to perform pitch if (readPos_ >= inputBuffer_.getNumSamples()) { readPos_ = 0; updatePitch(); } else { // Copy samples into the input buffer input[readPos_] = samples[samplesRead]; readPos_++; samplesRead++; } } } float PitchDetection::getSmoothedPitch(int smoothingFactor) const { // Max smoothing range as defined in the parameters smoothingFactor = std::min(smoothingFactor, (int)maxFreqSmoothing); // Return the current detected pitch if the smoothing factor is small if (smoothingFactor < 2) { return getCurrentPitch(); } int avgNum = 0; float sum = 0.0f; float pitch; float smoothed; // Calculate moving average, only consider non-zero pitch calculations for (int i = 0; i < smoothingFactor; ++i) { pitch = detectedF0_[negativeAwareModulo(f0Pointer_ - i, detectedF0_.size())]; if (pitch > 0) { sum += pitch; avgNum++; } } // Return the smoothed pitch if one was found smoothed = sum / avgNum; if (smoothed > 0) { return smoothed; } else { return -1.0f; } } float PitchDetection::quadIntMin(int position) { float s0, s1, s2; const float* data = yinData_.getReadPointer(0); // TODO: remove this -- the origin algorithm did some more checks // on the posistion, but I think it is safe to assume that position // received here will be a valid index in yinData jassert(position >= 0 && position < yinData_.getNumSamples()); if (position == 0 || position == yinData_.getNumSamples() - 1) return position; s0 = data[position - 1]; s1 = data[position]; s2 = data[position + 1]; return position + 0.5 * (s0 - s2) / (s0 - 2 * s1 + s2); } // Implementation of the YIN algorithm void PitchDetection::updatePitch() { int j, tau; int period; float tmp1 = 0.0, tmp2 = 0.0; float* yin = yinData_.getWritePointer(0); const float* input = inputBuffer_.getReadPointer(0); float detectedPitch = -1.0; yin[0] = 1.0; for (tau = 1; tau < yinData_.getNumSamples(); tau++) { yin[tau] = 0.0; for (j = 0; j < yinData_.getNumSamples(); j++) { tmp1 = input[j] - input[j+tau]; yin[tau] += tmp1 * tmp1; } tmp2 += yin[tau]; if (tmp2 != 0) { yin[tau] *= tau/tmp2; } else { yin[tau] = 1.0; } period = tau - 3; if (tau > 4 && yin[period] < tolerance_ && yin[period] < yin[period+1]) { detectedPitch = quadIntMin(period); break; } } if (detectedPitch < 0.0) { // Run Quadtatic Interpolation on minimum element float* minElement = std::min(yin, yin + yinData_.getNumSamples()); detectedPitch = quadIntMin(minElement - yin); } // Update the f0 pointer and write to detected pitch array f0Pointer_ = (f0Pointer_ + 1) % maxFreqSmoothing; detectedF0_.insert(f0Pointer_, detectedPitch); }
true