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
9b0f737828dde5fe76ec899c6cb1313098894f5c
C++
TerpDAC/MicrophoneControllerCode
/mic.ino
UTF-8
2,277
2.78125
3
[]
no_license
/* * Terrapin Development and Consulting (TerpDAC) * Microphone-Traffic Mapping * Written by William Heimsoth * Created: 11/29/2015 * Last modified: 11/30/2015 * Basic Algorithm: * (1) Initialize * (2) Sample the mic as fast as possible * (3) Analyze collected data * (4) Send analyzed data * (5) Repeat from (2) */ // Define to activate lower precision, faster sample rate // ADC conversion (visit http://forum.arduino.cc/index.php?topic=6549.0) #define FASTADC 1 // Definitions required to set and clear bits at AVR level #ifndef cbi #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) #endif #ifndef sbi #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) #endif // Constants: const int micPin = A0; const int numberSamples = 1000; const int lowThreshold = 200; const int highThreshold = 400; const int levelOne = 1; const int levelTwo = 2; const int levelThree = 3; // Variables: void setup() { Serial.begin(9600); #if FASTADC // Set ADC prescale to 16 (normally 128) for higher sample rate // but lower precision (~9.6kHz => ~77kHz) sbi(ADCSRA, ADPS2); cbi(ADCSRA, ADPS1); cbi(ADCSRA, ADPS0); #endif } void loop() { // Add a variable to see if the state has changed/need to sendAnalysis int samples[numberSamples], level = 0; collectData(samples); level = analyzeData(samples); sendAnalysis(level); } void collectData(int samples[]) { int i = 0; for (i = 0; i < numberSamples; i++) { samples[i] = analogRead(micPin); } } int analyzeData(int samples[]) { int i = 0, average = 0, level = 0; // Map the values from -512 to 511 and take the absolute value /*for (i = 0; i < numberSamples; i++) { samples[i] = map(samples[i], 0, 1023, -512, 511); }*/ // Mapping can also be accomplished with subtraction for (i = 0; i < numberSamples; i++) { samples[i] -= 512; samples[i] = abs(samples[i]); } // Assume that the samples are all noise, so take the average for (i = 0; i < numberSamples; i++) { average += samples[i]; } average /= numberSamples; if (average < lowThreshold) { level = levelOne; } else if (average > lowThreshold && average < highThreshold) { level = levelTwo; } else { level = levelThree; } return level; } void sendAnalysis(int level) { // Wifi stuff }
true
fe713d0d9be0b05f668314156f60a76e20409952
C++
MikhailGorobets/FaceGenBaseLibrary
/source/LibFgBase/src/Fg3dSurface.hpp
UTF-8
9,704
2.625
3
[ "MIT" ]
permissive
// // Coypright (c) 2020 Singular Inversions Inc. (facegen.com) // Use, modification and distribution is subject to the MIT License, // see accompanying file LICENSE.txt or facegen.com/base_library_license.txt // #ifndef FG3DSURFACE_HPP #define FG3DSURFACE_HPP #include "FgStdString.hpp" #include "FgTypes.hpp" #include "FgMatrixC.hpp" #include "FgMatrixV.hpp" #include "FgImage.hpp" namespace Fg { struct LabelledVert { Vec3F pos; String label; // Handy for lookup: bool operator==(String const & lab) const {return (label == lab); } }; typedef Svec<LabelledVert> LabelledVerts; // Returns the vertices with the selected labels in that order: Vec3Fs selectVerts(const LabelledVerts & labVerts,Strings const & labels); struct SurfPoint { uint triEquivIdx; Vec3F weights; // Barycentric coordinate of point in triangle String label; // Optional SurfPoint() {}; SurfPoint(uint t,Vec3F const & w) : triEquivIdx(t), weights(w) {} bool operator==(String const & rhs) const {return (label == rhs); } }; typedef Svec<SurfPoint> SurfPoints; inline Vec3F cBarycentricVert(Vec3UI inds,Vec3F weights,Vec3Fs const & verts) { return verts[inds[0]] * weights[0] + verts[inds[1]] * weights[1] + verts[inds[2]] * weights[2]; } inline Vec2F cBarycentricUv(Vec3UI inds,Vec3F weights,Vec2Fs const & uvs) { return uvs[inds[0]] * weights[0] + uvs[inds[1]] * weights[1] + uvs[inds[2]] * weights[2]; } template<uint dim> struct FacetInds { typedef Mat<uint,dim,1> Ind; Svec<Ind> posInds; // CC winding Svec<Ind> uvInds; // CC winding. Empty or same size as 'posInds' FacetInds() {} explicit FacetInds(const Svec<Ind> & vtInds) : posInds(vtInds) {} FacetInds(const Svec<Ind> & vtInds, const Svec<Ind> & uvIds) : posInds(vtInds), uvInds(uvIds) {} bool valid() const {return ((uvInds.size() == 0) || (uvInds.size() == posInds.size())); } size_t size() const {return posInds.size(); } bool empty() const {return posInds.empty(); } bool hasUvs() const {return (posInds.size() == uvInds.size()); } void erase(size_t idx) // Erase a facet { FGASSERT(idx < posInds.size()); if (!uvInds.empty()) { FGASSERT(uvInds.size() == posInds.size()); uvInds.erase(uvInds.begin()+idx); } posInds.erase(posInds.begin()+idx); } void offsetIndices(size_t vertsOff,size_t uvsOff) { Ind vo = Ind(uint(vertsOff)), uo = Ind(uint(uvsOff)); for (size_t ii=0; ii<posInds.size(); ++ii) posInds[ii] += vo; for (size_t ii=0; ii<uvInds.size(); ++ii) uvInds[ii] += uo; } }; typedef FacetInds<3> Tris; typedef FacetInds<4> Quads; typedef Svec<Tris> Triss; typedef Svec<Triss> Trisss; template<uint dim> void cat_(FacetInds<dim> & lhs,const FacetInds<dim> & rhs) { // Avoid 'hasUvs()' compare if one is empty: if (rhs.empty()) return; if (lhs.empty()) { lhs = rhs; return; } if (lhs.hasUvs() != rhs.hasUvs()) { fgout << fgnl << "WARNING: Merging surfaces with UVs and without. UVs discarded."; lhs.uvInds.clear(); } else cat_(lhs.uvInds,rhs.uvInds); cat_(lhs.posInds,rhs.posInds); } Vec3UIs quadsToTris(const Vec4UIs & quads); struct TriUv { Vec3UI posInds; Vec3UI uvInds; }; // the returned 'uvInds' is all zeros if there are no UVs: TriUv cTriEquiv(Tris const & tris,Quads const & quads,size_t tt); Vec3UI cTriEquivPosInds(Tris const & tris,Quads const & quads,size_t tt); Tris cTriEquivs(Tris const & tris,Quads const & quads); Vec3F cSurfPointPos( SurfPoint const & sp, Tris const & tris, Quads const & quads, Vec3Fs const & verts); struct Material { bool shiny = false; // Ignored if 'specularMap' below is non-empty Sptr<ImgC4UC> albedoMap; // Can be nullptr but should not be the empty image Sptr<ImgC4UC> specularMap; // TODO: Change to greyscale }; typedef Svec<Material> Materials; typedef Svec<Materials> Materialss; // A grouping of facets (tri and quad) sharing material properties: struct Surf { Ustring name; Tris tris; Quads quads; SurfPoints surfPoints; Material material; // Not saved with mesh - set dynamically Surf() {} explicit Surf(Vec3UIs const & ts) : tris(ts) {} explicit Surf(const Vec4UIs & ts) : quads(ts) {} Surf(Vec3UIs const & triPosInds,Vec4UIs const & quadPosInds) : tris(triPosInds), quads(quadPosInds) {} Surf(const Svec<Vec4UI> & verts,const Svec<Vec4UI> & uvs) : quads(verts,uvs) {} Surf(Ustring const & n,Tris const & ts,SurfPoints const & sps,Material const & m) : name(n), tris(ts), surfPoints(sps), material(m) {} bool empty() const {return (tris.empty() && quads.empty()); } uint numTris() const {return uint(tris.size()); } uint numQuads() const {return uint(quads.size()); } uint numFacets() const {return (numTris() + numQuads()); } uint numTriEquivs() const {return numTris() + 2*numQuads(); } uint vertIdxMax() const; std::set<uint> vertsUsed() const; TriUv getTriEquiv(size_t idx) const {return cTriEquiv(tris,quads,idx); } Vec3UI getTriPosInds(uint ind) const {return tris.posInds[ind]; } Vec4UI getQuadPosInds(uint ind) const {return quads.posInds[ind]; } // Returns the vertex indices for the tri equiv: Vec3UI getTriEquivPosInds(size_t ind) const {return cTriEquivPosInds(tris,quads,ind); } Tris getTriEquivs() const {return cTriEquivs(tris,quads); } bool isTri(size_t triEquivIdx) const {return (triEquivIdx < tris.size()); } bool hasUvIndices() const {return !(tris.uvInds.empty() && quads.uvInds.empty()); } Vec3F surfPointPos(Vec3Fs const & verts,size_t idx) const {return cSurfPointPos(surfPoints[idx],tris,quads,verts); } // Label must correspond to a surface point: Vec3F surfPointPos(Vec3Fs const & verts,String const & label) const; Vec3Fs surfPointPositions(Vec3Fs const & verts) const; LabelledVerts surfPointsAsLabelledVerts(Vec3Fs const &) const; FacetInds<3> asTris() const; Surf convertToTris() const {return Surf {name,asTris(),surfPoints,material}; } void merge(Surf const & surf); void checkMeshConsistency(uint maxCoordIdx,uint maxUvIdx); // Return a surface with all indices offset by the given amounts: Surf offsetIndices(size_t vertsOffset,size_t uvsOffset) const { Surf ret(*this); ret.tris.offsetIndices(vertsOffset,uvsOffset); ret.quads.offsetIndices(vertsOffset,uvsOffset); return ret; } // Useful for searching by name: bool operator==(Ustring const & str) const {return (name == str); } void setAlbedoMap(ImgC4UC const & img) {material.albedoMap = std::make_shared<ImgC4UC>(img); } ImgC4UC & albedoMapRef() { if (!material.albedoMap) material.albedoMap = std::make_shared<ImgC4UC>(); return *material.albedoMap; } void removeTri(size_t triIdx); void removeQuad(size_t quadIdx); private: void checkInternalConsistency(); }; void fgReadp(std::istream &,Surf &); void fgWritep(std::ostream &,Surf const &); std::ostream& operator<<(std::ostream&,Surf const&); typedef Svec<Surf> Surfs; Surf removeDuplicateFacets(Surf const &); Surf mergeSurfaces(const Surfs & surfs); // Split a surface into its (one or more) discontiguous (by vertex index) surfaces: Surfs splitByContiguous(Surf const & surf); // Name any unnamed surfaces as numbered extensions of the given base name, // or just the base name if there is only a single (unnamed) surface: Surfs fgEnsureNamed(const Surfs & surfs,Ustring const & baseName); Vec3Fs cVertsUsed(Vec3UIs const & tris,Vec3Fs const & verts); bool hasUnusedVerts(Vec3UIs const & tris,Vec3Fs const & verts); Uints removeUnusedVertsRemap(Vec3UIs const & tris,Vec3Fs const & verts); struct TriSurf { Vec3Fs verts; Vec3UIs tris; bool hasUnusedVerts() const {return Fg::hasUnusedVerts(tris,verts); } }; Vec3UIs reverseWinding(Vec3UIs const &); TriSurf reverseWinding(TriSurf const &); TriSurf meshRemoveUnusedVerts(Vec3Fs const & verts,Vec3UIs const & tris); inline TriSurf meshRemoveUnusedVerts(TriSurf const & ts) {return meshRemoveUnusedVerts(ts.verts,ts.tris); } struct TriSurfFids { TriSurf surf; Vec3Fs fids; // When it's handy to have fiducial points explicitly separate from surface }; typedef Svec<TriSurfFids> TriSurfFidss; struct QuadSurf { Vec3Fs verts; Vec4UIs quads; }; } #endif
true
49c25e5738209fccbd478a8192a01b0d6c7e4a43
C++
saobangmath/Java-Practice
/src/NTULabs/Animal.h
UTF-8
446
3.046875
3
[]
no_license
#include <iostream> // header in standard library #include<string> using namespace std; enum COLOR { Green, Blue, Black, Brown, White }; #pragma once class Animal { public: Animal(); Animal(string n, COLOR c); ~Animal(); virtual void speak() const; virtual void move() const; private: string _name; COLOR _color; }; class Mammal : public Animal { public: Mammal(string n, COLOR c); ~Mammal(); void eat() const; };
true
81b31d523fb896503bc134bb5795aed108c1a102
C++
jiangwei221/3d_npr
/src/selector.h
UTF-8
10,440
2.84375
3
[]
no_license
/* select a set of vector of points, basically, vector<vector<dvec3>> from a point cloud jiang wei uvic start: 2018.10.9 */ #pragma once #include <iostream> #include <limits> #include <algorithm> #include "bezier.h" #include "glm/vec3.hpp" #include "glm/glm.hpp" #include <math.h> #include <vector> #include <pcl/io/pcd_io.h> #include <pcl/io/ply_io.h> #include <pcl/point_types.h> using namespace glm; #define SLICE_AXIS y #define BUILD_AXIS z class Selector { public: int num_slices; int num_max_line; int num_max_pts; Selector() { num_slices = 10; num_max_line = 100; num_max_pts = 100; } std::vector<std::vector<dvec3>> selectPoints(const pcl::PointCloud<pcl::PointXYZRGBNormal> &in_cloud, std::vector<std::vector<dvec3>> &color_list, int num_curves) { std::vector<std::vector<dvec3>> result; std::vector<std::vector<dvec3>> sliced_cloud_color; std::vector<std::vector<dvec3>> sliced_cloud = sliceCloud(in_cloud, sliced_cloud_color, num_slices); // std::cout<<sliced_cloud_color.size()<<std::endl; for(int i=0; i<sliced_cloud.size(); i++) { // std::cout<<sliced_cloud_color[i].size()<<std::endl; std::vector<std::vector<dvec3>> lines_color; std::vector<std::vector<dvec3>> lines = buildLine(sliced_cloud[i], sliced_cloud_color[i], lines_color, num_max_pts, num_max_line); result.insert( result.end(), lines.begin(), lines.end() ); // std::cout<<lines_color.size()<<std::endl; color_list.insert( color_list.end(), lines_color.begin(), lines_color.end() ); } return result; } std::vector<dvec3> copyPoints(const pcl::PointCloud<pcl::PointXYZRGBNormal> &in_cloud) { std::vector<dvec3> result; for(int i=0; i<in_cloud.size(); i++) { result.push_back(dvec3(in_cloud.points[i].x, in_cloud.points[i].y, in_cloud.points[i].z)); } return result; } std::vector<float> getHighAndLow(const pcl::PointCloud<pcl::PointXYZRGBNormal> &in_cloud) { int num_pts = in_cloud.width; assert(in_cloud.height == 1); float height_max = std::numeric_limits<float>::min(); float height_min = std::numeric_limits<float>::max(); for(int i=0;i<num_pts;i++) { if(in_cloud.points[i].SLICE_AXIS > height_max) height_max = in_cloud.points[i].SLICE_AXIS; if(in_cloud.points[i].SLICE_AXIS < height_min) height_min = in_cloud.points[i].SLICE_AXIS; } std::vector<float> result; result.push_back(height_max+0.000001); result.push_back(height_min); return result; } std::vector<std::vector<dvec3>> sliceCloud(const pcl::PointCloud<pcl::PointXYZRGBNormal> &in_cloud, std::vector<std::vector<dvec3>> &sliced_cloud_color, int num_slices) { std::vector<std::vector<dvec3>> result (num_slices); sliced_cloud_color = std::vector<std::vector<dvec3>>(num_slices); std::vector<float> high_low = getHighAndLow(in_cloud); float high = high_low[0]; float low = high_low[1]; int num_pts = in_cloud.width; for(int i=0;i<num_pts;i++) { int index = int((in_cloud.points[i].SLICE_AXIS - low) / ((high-low)/num_slices)); // std::cout<<"index: "<<index<<" num_slices: "<<num_slices<<std::endl; assert(index >= 0 && index < num_slices); result[index].push_back(dvec3(in_cloud.points[i].x, in_cloud.points[i].y, in_cloud.points[i].z)); sliced_cloud_color[index].push_back(dvec3(in_cloud.points[i].r, in_cloud.points[i].g, in_cloud.points[i].b)); } return result; } std::vector<std::vector<dvec3>> buildLine(const std::vector<dvec3> &in_pts, const std::vector<dvec3> &in_colors, std::vector<std::vector<dvec3>> &out_colors, int num_max_pts, int num_max_line) { std::vector<std::vector<dvec3>> result; std::vector<dvec3> temp = in_pts; // temp.swap(in_pts) std::vector<bool> temp_flag (temp.size(), true); std::vector<std::vector<float>> dist_mtrx = buildDistanceMtrx(in_pts); for(int i=0; i<num_max_line; i++) { // std::vector<bool>::iterator itr = std::find(temp_flag.begin(), temp_flag.end(), true); // int start_id = std::distance(temp_flag.begin(), itr); // for(int j=start_id; j<temp_flag.size(); j++) // { // } bool is_new_line = false; std::vector<dvec3> c_line; std::vector<dvec3> c_line_color; // std::vector<bool>::iterator itr = std::find(temp_flag.begin(), temp_flag.end(), true); // int start_id = std::distance(temp_flag.begin(), itr); float start_pos = std::numeric_limits<float>::max(); int start_id = -1; for(int j=0; j<temp_flag.size(); j++) { if(temp_flag[j]==true) { if(temp[j].BUILD_AXIS < start_pos) { start_pos = temp[j].BUILD_AXIS; start_id = j; } } } if(start_id == -1) break; float prev_dist = std::numeric_limits<float>::max(); for(int j=0; j<num_max_pts; j++) { //find the closest pt of start_id float dist_min = std::numeric_limits<float>::max(); int dist_min_id = -1; for(int k=0; k<temp.size(); k++) { if(temp_flag[k] == true && k!=start_id) { if(dist_mtrx[start_id][k] < dist_min) { dist_min = dist_mtrx[start_id][k]; dist_min_id = k; } } } if(dist_min / 200.0f > prev_dist) break; prev_dist = dist_min; //set temp_flag[start_id] = false temp_flag[start_id] = false; //add temp[start_id] to c_line c_line.push_back(temp[start_id]); c_line_color.push_back(in_colors[start_id]); //set start_id to the closest pt's index start_id = dist_min_id; //if no point to add if(dist_min_id == -1) { break; } } if(c_line.size() >= 4) { result.push_back(c_line); out_colors.push_back(c_line_color); // std::cout<<c_line_color.size()<<std::endl; is_new_line = true; } if(is_new_line == false) break; } return result; } std::vector<std::vector<dvec3>> buildLine(const std::vector<dvec3> &in_pts, int num_max_pts, int num_max_line) { std::vector<std::vector<dvec3>> result; std::vector<dvec3> temp = in_pts; // temp.swap(in_pts) std::vector<bool> temp_flag (temp.size(), true); std::vector<std::vector<float>> dist_mtrx = buildDistanceMtrx(in_pts); for(int i=0; i<num_max_line; i++) { // std::vector<bool>::iterator itr = std::find(temp_flag.begin(), temp_flag.end(), true); // int start_id = std::distance(temp_flag.begin(), itr); // for(int j=start_id; j<temp_flag.size(); j++) // { // } bool is_new_line = false; std::vector<dvec3> c_line; // std::vector<bool>::iterator itr = std::find(temp_flag.begin(), temp_flag.end(), true); // int start_id = std::distance(temp_flag.begin(), itr); float start_pos = std::numeric_limits<float>::max(); int start_id = -1; for(int j=0; j<temp_flag.size(); j++) { if(temp_flag[j]==true) { if(temp[j].BUILD_AXIS < start_pos) { start_pos = temp[j].BUILD_AXIS; start_id = j; } } } if(start_id == -1) break; float prev_dist = std::numeric_limits<float>::max(); for(int j=0; j<num_max_pts; j++) { //find the closest pt of start_id float dist_min = std::numeric_limits<float>::max(); int dist_min_id = -1; for(int k=0; k<temp.size(); k++) { if(temp_flag[k] == true && k!=start_id) { if(dist_mtrx[start_id][k] < dist_min) { dist_min = dist_mtrx[start_id][k]; dist_min_id = k; } } } if(dist_min / 200.0f > prev_dist) break; prev_dist = dist_min; //set temp_flag[start_id] = false temp_flag[start_id] = false; //add temp[start_id] to c_line c_line.push_back(temp[start_id]); //set start_id to the closest pt's index start_id = dist_min_id; //if no point to add if(dist_min_id == -1) { break; } } if(c_line.size() >= 4) { result.push_back(c_line); is_new_line = true; } if(is_new_line == false) break; } return result; } std::vector<std::vector<float>> buildDistanceMtrx(const std::vector<dvec3> &in_pts) { int num_pts = in_pts.size(); std::vector<std::vector<float>> result (num_pts, std::vector<float>(num_pts)); for(int i=0; i<num_pts; i++) { for(int j=0; j<num_pts; j++) { result[i][j] = distance(in_pts[i], in_pts[j]); } } return result; } };
true
a2261fae8998439d3277038b2bc5d234f7a65493
C++
96light/SpaceAventural
/Program/TrainingFramework/src/GameObject/Bullet3.cpp
UTF-8
1,109
2.9375
3
[]
no_license
#include "Bullet3.h" Bullet3::Bullet3(std::shared_ptr<Models>& model, std::shared_ptr<Shaders>& shader, std::shared_ptr<Texture>& texture) :Sprite2D(model, shader, texture) { m_speed = 500.0; m_active = true; m_type = BULLET_TYPE3::None; m_SizeCollider = 10; m_Damage = 5; } Bullet3::~Bullet3() { } void Bullet3::Update(GLfloat deltatime) { if (!m_active) return; Vector2 pos = Get2DPosition(); pos.y = pos.y - m_speed * deltatime; pos.x = pos.x + 200 * deltatime; Set2DPosition(pos); if (pos.y <= 0 || pos.y > Application::screenHeight) m_active = false; } bool Bullet3::IsActive() { return m_active; } void Bullet3::SetActive(bool status) { m_active = status; } void Bullet3::SetSpeed(float speed) { m_speed = speed; } void Bullet3::SetType(BULLET_TYPE3 type) { m_type = type; } BULLET_TYPE3 Bullet3::GetType() { return m_type; } void Bullet3::SetColliderSize(float size) { m_SizeCollider = size; } float Bullet3::GetColliderSize() { return m_SizeCollider; } void Bullet3::SetDamage(float damage) { m_Damage = damage; } float Bullet3::GetDamage() { return m_Damage; }
true
6f8698a083f0e31b781d1a89506d65dfca603460
C++
lasse-steinnes/FYS4150-Project1
/cpp-code/lu_eigen.cpp
UTF-8
2,661
3.265625
3
[]
no_license
/* Code for solving a differential equation using LU-decomposition with library eigen and writing to file */ #include <iostream> #include <cmath> #include <stdlib.h> #include <fstream> #include <iomanip> #include <Eigen/Dense> #include <chrono> #include <sstream> using namespace std; double f(double x){ /*The right handside of the differential equation*/ return 100*exp(-10*x); } double exact(double x){ /*The analytic solution of the differential equation*/ return 1-(1-exp(-10))*x-exp(-10*x); } int main(int argc,char *argv[]){ /*takes input n = number of columns and rows */ int n = atof(argv[1]); //Allocating memory for arrays double *x = new double[n+1]; Eigen::VectorXd rhs(n); // original right hand side: source function Eigen::VectorXd v_num(n); double *u_exact = new double[n]; //Fill arrays x[0] = 0; x[n] = 1; double h = (double) (x[n]-x[0])/(n); double hh = h*h; // Initialize for (int i = 0; i<n; i++){ x[i] = i*h; rhs(i) = f(x[i])*hh; u_exact[i] = exact(x[i]); } // Solve for x with lu for specific matrix A given below Eigen::MatrixXd A(n,n); // fill in for the matrix A: for (int i = 0; i < n; ++i){ //n*n elements,n-1 highest index A(i,i) = 2; //diagonal elements } for (int i = 0; i < n-1; ++i){ A(i+1,i) = -1; // Fill in for elemnts below diag A(i,i+1) = -1; // Fill in for elements above diag } auto t1 = std::chrono::high_resolution_clock::now(); // declare start and final time /* LU decomposition */ Eigen::MatrixXd I(n,n); I << Eigen::MatrixXd::Identity(n, n); Eigen::MatrixXd A_inv = A.lu().solve(I); // lu solver v_num = A_inv*rhs; auto t2 = std::chrono::high_resolution_clock::now(); //get final time std::chrono::duration<double, std::milli> time_ms = t2 - t1; //get in milliseconds //Write to file char *str_full = new char[30]; ostringstream size_; size_ << n; string num = size_.str(); //make string of solutionsize string folder("Results/lu_eigen"); string file_(".csv"); string adding = folder + num + file_; std::size_t length = adding.copy(str_full,adding.length(),0); str_full[length]='\0'; cout << "Writing to file \n"<< str_full << endl; ofstream solutionfile; solutionfile.open(str_full); solutionfile << "step_size," << setw(20) << "x," << setw(20) << "v_num," << setw(20) << "u_exact," << setw(20) << "time,"<< "\n"<< endl; for (int i = 0; i < n; ++i){ solutionfile << h << ',' << setw(20) << x[i] <<',' << setw(20) << v_num(i) << ','<< setw(20) << u_exact[i+1] << ',' << setw(20) << time_ms.count() << ',' <<"\n"<<endl; } solutionfile.close(); delete[] x; delete[] u_exact; return 0; }
true
8e00ba13f1909b30f2da670ad0608169a83b3884
C++
Stephenhua/Data-Construct
/LeetCode_7/LeetCode_7/源.cpp
GB18030
1,177
3.515625
4
[]
no_license
# include <iostream> # include <math.h> using namespace std; int reverse(int x)// { int ret = 0; bool isNegative = false; if (x < 0) { isNegative = true; x *= -1; } while (x > 0) { int lastDigit = x % 10; if (lastDigit == 0 && ret == 0) { x = x / 10; continue; } if (ret > (INT_MAX - lastDigit) / 10) { return 0; } ret = (ret * 10 + lastDigit); x = x / 10; } return ret*((isNegative) ? -1 : 1); } int reverse1(int x) {//ַתʵַһ int res = 0; while (x != 0) { if (abs(res) > INT_MAX / 10) return 0; res = res * 10 + x % 10; x /= 10; } return res; } int reverse2(int x) { bool a = (x > 0);//жx long x_long = (a) ? x : -x;//ȡֵ long ans = 0; while (x_long > 0)//ȡȡȡ { if (ans > INT_MAX / 10 || ans < INT_MIN / 10) { return 0; } ans = ans * 10 + x_long % 10; x_long = x_long / 10; } return (a) ? ans : -ans;//ֵ } int main() { int x = 432492024; cout << reverse(x) << endl; cout << reverse1(x) << endl; cout << reverse2(x) << endl; system("pause"); return EXIT_SUCCESS; }
true
7bead761995760c94b17a0359aaee9e4378bfcfc
C++
maenujem/arduino
/testNanoPins.ino
UTF-8
5,979
2.953125
3
[ "MIT" ]
permissive
/* Test for pin soldering (PCB socket pins) for Arduino Nano (if you buy it without their "legs" attached and solder these yourself) Initial testing using external power source (1. to 13.) The semi-automated test (14.) is based on the built-in pullup-resistors and the built-in LED diode. Required: USB connection: only required for sketch upload, but it can also be used for running the test (14.) Three jumper wires (eg. red 5V, black GND and other color), a breadboard and four 1.2V AA batteries with connector wire for the test */ /* Test setup: 1. connect batterys (4*1.2V) to + and - on breadboard and check for 5V voltage 2. connect + to 5V and - to -GND(1) and check if arduino blinks/startup -> GND(1) ok 3. re-connect GND from (1) to (2 on ICSP) and check if arduino blinks/startup -> GND(2) ok 4. re-connect GND from (2) to (3) and check if arduino blinks/startup -> GND(3) ok 5. measure 5V on ICSP 5V (and on RST 1,2,3) 6. measure 3V3 on 3V3 7. press RST button and check if arduino blinks/startup 8. connect RST(1) to GND and check if arduino blinks/startup, disconnect 9. connect RST(2 on ICSP) to GND and check if arduino blinks/startup, disconnect 10. connect RST(3) to GND and check if arduino blinks/startup, disconnect 11. disconnect batterys 12. connect USB and upload script, disconnect USB 13. connect batterys 14. script will set all analog and digital pins to INPUT (default), then one by one (D0..D13, A0..A7): blink three times (ready), wait 2sec set pin to INPUT_PULLUP read, blink once on internal diode if ok (HIGH) / twice if nok, set pin to INPUT blink four times to signal check for LOW then one by one (D0..D13, A0..A7): blink three times (ready), wait 2sec -> connect pin to GND using a wire set pin to INPUT_PULLUP read, blink once on internal diode if ok (LOW) / twice if nok, set pin to INPUT disconnect wire TODO: testing VIN? TODO: testing REF? TODO: D13 not detected correctly (LOW instead HIGH) TODO: A6,A7 do not have INPUT_PULLUP (-> floating default values) and are only analogRead() */ #define LED_PIN 13 // internal LED pin #define WAIT_TIME 2000 // in msec int digitalPins[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; // no aliases D0.. existing int analogPins[] = {A0, A1, A2, A3, A4, A5, A6, A7}; // A0 is alias for pin 14... /* set all pins in pinarray to INPUT */ void initPinsAsInput(int pinarr[], size_t arrsize) { for (int i = 0; i < arrsize; i++) { pinMode(pinarr[i], INPUT); } } /* blink n-times per second on specified pin */ void blink(int blinkPerSecond, int blinkPin) { int onTime = 1000 / (blinkPerSecond * 2); // init again after possible digitalWrite on pin 13 pinMode(blinkPin, OUTPUT); digitalWrite(blinkPin, LOW); for (int i = 0; i < blinkPerSecond; i++ ) { // turn LED on: digitalWrite(blinkPin, HIGH); delay(onTime); // turn LED off: digitalWrite(blinkPin, LOW); delay(onTime); } } /* check connection of pins in pinarray based on pintype (D/A) and expected state (1/0) */ void checkPins(int pinarr[], size_t arrsize, char pinType, int checkState) { // print what will be tested Serial.print(F("Testing ")); if (pinType == 'D') { // digital pins Serial.print(F("digital ")); } else if (pinType == 'A') { // analog pins Serial.print(F("analog ")); } if (checkState == HIGH) { // check for (pullup-resistor) HIGH = no current loss Serial.print(F("HIGH: ")); } else if (checkState == LOW) { // check for LOW = pin leads current through wire to GND Serial.print(F("LOW: ")); } Serial.println(arrsize); // print pin type & number, input measured and result to serial // blink three times for each pin when measuring starts // blink once if measurement is ok / twice if measurement is not as expected for (int i = 0; i < arrsize; i++) { int pinState = 0; Serial.print(F("Next pin is ")); Serial.print(pinType); Serial.print(pinarr[i]); Serial.print(": "); blink(3, LED_PIN); delay(WAIT_TIME); pinMode(pinarr[i], INPUT_PULLUP); pinState = (pinType == 'D') ? digitalRead(pinarr[i]) : analogRead(pinarr[i]); Serial.print(pinState); // 'convert' analog measurement (0..1023) to digital (0/1) if (pinType == 'A' && pinState > 950) { pinState = 1; } else if (pinType == 'A' && pinState < 100) { pinState = 0; } if (pinState == checkState) { blink(1, LED_PIN); // 1x = ok Serial.println(F("ok ")); } else { blink(2, LED_PIN); // 2x = nok Serial.println(F("nok ")); } pinMode(pinarr[i], INPUT); } } void setup() { // put your setup code here, to run once: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } // initialize the internal LED pin as an output: pinMode(LED_PIN, OUTPUT); // initialize the digital & analog pins on pin as an input (default) initPinsAsInput(digitalPins, sizeof digitalPins / sizeof * digitalPins); initPinsAsInput(analogPins, sizeof analogPins / sizeof * analogPins); } void loop() { // put your main code here, to run rexpeatedly: // checking pins 0..21 for HIGH (do not connect respective pin to ground with wire) checkPins(digitalPins, sizeof digitalPins / sizeof * digitalPins, 'D', HIGH); checkPins(analogPins, sizeof analogPins / sizeof * analogPins, 'A', HIGH); blink(4, LED_PIN); // indicate that test for HIGH is done, LOW is next // checking pins 0..21 for LOW (DO connect respective pin to ground with wire) checkPins(digitalPins, sizeof digitalPins / sizeof * digitalPins, 'D', LOW); checkPins(analogPins, sizeof analogPins / sizeof * analogPins, 'A', LOW); blink(4, LED_PIN); // indicate that both tests are done on all pins blink(4, LED_PIN); }
true
6dd61a3976223b4c9599b694a52ed712350ce4e3
C++
G4me4u/pic-programmer-arduino
/src/arduino_code/PIC16F88X_pic_programmer.cpp
UTF-8
3,215
2.828125
3
[ "MIT" ]
permissive
#include "./PIC16F88X_pic_programmer.h" PIC16F88X_PicProgrammer::PIC16F88X_PicProgrammer(unsigned int flags) : PIC12F1822_PicProgrammer(flags) { } bool PIC16F88X_PicProgrammer::enterProgrammingMode() { // If we're already programming, // return false. if (this->programming) return false; // Set PGM high, if in low voltage mode if (lowVoltageMode) { digitalWrite(PGM, HIGH); delayMicroseconds(2); } // Set MCLR as output. pinMode(MCLR, OUTPUT); if (lowVoltageMode) { // MCLR is activated on the // falling-edge. digitalWrite(MCLR, LOW); digitalWrite(MCLR, HIGH); } else { // Turn on the high voltage // on MCLR pin (see schematic). // Should be connected to approx. // one kilo-ohm pull-down resistor. digitalWrite(MCLR, HIGH); } delayMicroseconds(1); digitalWrite(PVCC, HIGH); delay(1); // We're now ready to program the device. this->programming = true; // Reset address to zero this->address = 0L; this->extendedAddress = 0; return true; } void PIC16F88X_PicProgrammer::leaveProgrammingMode() { // We have to set the PGM pin // low (in low voltage mode) if (this->lowVoltageMode) { digitalWrite(PGM, LOW); // Wait for device to leave // programming mode. delayMicroseconds(1); // If chip is in low voltage // programming mode, the MCLR // pin is most likely used. We // can reset the chip to ensure // proper code execution after // the programming finishes. if (this->programming) { digitalWrite(MCLR, LOW); digitalWrite(MCLR, HIGH); } } // We can use the same implementation // as the PIC12F1822. PIC12F1822_PicProgrammer::leaveProgrammingMode(); } void PIC16F88X_PicProgrammer::commandResetAddress() { // The PIC16F88X specification does not // mention any reset command. To reset // the address we have to re-enter the // programming mode instead. if (this->programming) { this->leaveProgrammingMode(); this->enterProgrammingMode(); } } // --------------- PROGRAMMING COMMANDS --------------- // void PIC16F88X_PicProgrammer::commandBeginInternalProgramming() const { this->commandEntry(BEG_IN_CMD); // The PIC16F88X specification only // takes 3 ms to program it's program- // memory. This is probably because // the configuration addresses are in // the low 2000h and not in the extended // range. delay(3); } // -------------- ERASE MEMORY COMMANDS --------------- // void PIC16F88X_PicProgrammer::commandBulkEraseProgramMemory() const { // All erase commands in the // PIC16F88X programming specification // take 6 ms (TERA) to complete. this->commandEntry(ER_PRO_CMD); delay(6); } void PIC16F88X_PicProgrammer::commandBulkEraseDataMemory() const { // All erase commands in the // PIC16F88X programming specification // take 6 ms (TERA) to complete. this->commandEntry(ER_DAT_CMD); delay(6); } void PIC16F88X_PicProgrammer::commandRowEraseProgramMemory() const { // All erase commands in the // PIC16F88X programming specification // take 6 ms (TERA) to complete. this->commandEntry(ER_ROW_CMD); delay(6); } // ---------- PROGRAMMING HELPER FUNCTIONS ------------ // long long PIC16F88X_PicProgrammer::getConfigAddress() const { return PIC16F88X_CONFIG_ADDR; }
true
3687e2f95cfda44828c91708a06b0ee62aa31ff7
C++
prakash123mayank/C-Plus-Plus-Programming-Language
/String/Check string Palindrome.cpp
UTF-8
501
3.171875
3
[]
no_license
#include<iostream> using namespace std; int main() { char A[]="madam"; char B[6]; cout<<"String 1:"<<A<<endl; int i,j; for(i=0;A[i]!='\0';i++) {} i=i-1; for(j=0;i>=0;i--,j++) { B[j]=A[i]; } cout<<"String 2:"<<B<<endl; for(i=0,j=0;A[i]!='\0'&&B[j]!='\0';i++,j++) { if (A[i]!=B[j]) break; } if(A[i]==B[j]) cout<<"Strings are Palindrome"; else cout<<"Strings are not Palindrome"; return 0; }
true
6794e77623e4a410fb5d335dcf1671d6b0b88eab
C++
kcd71461/sw-engineering-hw3
/src/Reservation.cpp
UTF-8
1,327
2.90625
3
[]
no_license
// // Created by 김창덕 on 2018-05-24. // #include "Reservation.h" const std::string &Reservation::getHostID() const { return hostid; } void Reservation::setHostid(const std::string &hostid) { Reservation::hostid = hostid; } const std::string &Reservation::getName() const { return name; } void Reservation::setName(const std::string &name) { Reservation::name = name; } const std::string &Reservation::getAddress() const { return address; } void Reservation::setAddress(const std::string &address) { Reservation::address = address; } const std::string &Reservation::getDate() const { return date; } void Reservation::setDate(const std::string &date) { Reservation::date = date; } int Reservation::getCost() const { return cost; } void Reservation::setCost(int cost) { Reservation::cost = cost; } const string &Reservation::getGuestID() const { return guesid; } void Reservation::setGuesid(const string &guesid) { Reservation::guesid = guesid; } Reservation::Reservation(const string &hostid, const string &guesid, const string &name, const string &address, const string &date, int cost) : hostid(hostid), guesid(guesid), name(name), address(address), date(date), cost(cost) {}
true
dca58e0e004a923682dc7e60f527c29705a78e96
C++
AhmedAboutaleb94/2DSnakeGame
/src/game_menu.cpp
UTF-8
1,288
3.09375
3
[]
no_license
#include "game_menu.h" void Menu::MainMenu(){ cout << "\033[2J\033[1;1H"; cout << "/------------- Welcome to 2D Snake Game -------------/" << endl; cout << "/--------------------- Main Menu --------------------/" << endl; cout << "1. Play Game" << endl; cout << "2. Show Game History" << endl; } void Menu::GetPlayerName(){ cout << "\033[2J\033[1;1H"; cout << "/------------------ Game Settings -------------------/" << endl; cout << "Please enter your name: "; } void Menu::HistoryMenu(){ cout << "\033[2J\033[1;1H"; cout << "/------------------ History Menu -------------------/" << endl; cout << "1. Game History" << endl; cout << "2. Hall of Fame" << endl; cout << "3. Highest Score Player" << endl; } int Menu::Input_number(){ int _key; while(!(cin >> _key)){ cin.clear(); while(cin.get() != '\n') continue; //Ask user to try again cout << "Warning Invalid Input, Please Try Again."; } return _key; } string Menu::Input_string(){ string _key; while(!(cin >> _key)){ cin.clear(); while(cin.get() != '\n') continue; //Ask user to try again cout << "Warning Invalid Input, Please Try Again."; } return _key; }
true
7a74e8ab6d40b8bab8f5b6beaaf63e6da305253c
C++
safaaougunir/IOT
/conn_mqtt_Potentiometre.ino
UTF-8
3,789
2.5625
3
[]
no_license
#include <SPI.h> #include <Ethernet.h> #include <PubSubClient.h> #define TOLERANCE 10 int state = 0; /*************************************************************************** * Internet Connectivity Setup - Variables & Functions **************************************************************************/ // Enter a MAC address for your controller below (newer Ethernet shields // have a MAC address printed on a sticker on the shield) byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x22, 0x11 }; int oldVal = 0; int oldVal1 = 0; int val; int val1; // Set the static IP address to use if the DHCP fails to assign IPAddress staticIP(10, 0, 0, 20); // IP address of the Mosquitto server char server[] = {"m14.cloudmqtt.com"}; int port = 13086; char topic[] = {"building1/room1/light"}; void callback(char* topic, byte* payload, unsigned int length) { Serial.print("[INFO] Topic : " ); Serial.println(topic); Serial.print("[INFO] Message :"); Serial.println(String((char *)payload)); Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i=0;i<length;i++) { char receivedChar = (char)payload[i]; Serial.print(receivedChar); Serial.println(); } } EthernetClient ethClient; PubSubClient pubSubClient(server, port, callback, ethClient); void connectToInternet() { // Attempt to connect to Ethernet with DHCP if (Ethernet.begin(mac) == 0) { Serial.print("[ERROR] Failed to Configure Ethernet using DHCP"); // DHCP failed, attempt to connect to Ethernet with static IP Ethernet.begin(mac, staticIP); } // Delay to let Ethernet shield initialize delay(1000); // Connection successful Serial.println("[INFO] Connection Successful"); Serial.print(""); printConnectionInformation(); Serial.println("-----------------------------------------------"); Serial.println(""); } void printConnectionInformation() { // Print Connection Information Serial.print("[INFO] IP Address: "); Serial.println(Ethernet.localIP()); Serial.print("[INFO] Subnet Mask: "); Serial.println(Ethernet.subnetMask()); Serial.print("[INFO] Gateway: "); Serial.println(Ethernet.gatewayIP()); Serial.print("[INFO] DNS: "); Serial.println(Ethernet.dnsServerIP()); } /*************************************************************************** * Standard Arduino Functions - setup(), loop() **************************************************************************/ void setup() { // Initialize serial port Serial.begin(9600); // Connect Arduino to internet connectToInternet(); //Connect MQTT Broker Serial.println("[INFO] Connecting to MQTT Broker"); if (pubSubClient.connect("arduinoClient", "tojighyl", "G0D6od2oUAKN")) { Serial.println("[INFO] Connection to MQTT Broker Successfull"); //pubSubClient.subscribe(topic); Serial.println("[INFO] Successfully Subscribed to MQTT Topic "); Serial.println("[INFO] Publishing to MQTT Broker"); //pubSubClient.publish("puublidhingTest", "Test Message"); pubSubClient.publish("building1/room1/lightLevel",String(sensorValue).c_str(), true); } else { Serial.println("[INFO] Connection to MQTT Broker Failed"); } } void loop() { // read the input on analog pin 0: val = analogRead(A0); val = map(val, 0, 1023, 0, 254); Serial.println(val); delay(15); int diff = abs(val - oldVal); if(diff > TOLERANCE) { oldVal = val; // only save if the val has changed enough to avoid slowly drifting // and so on Serial.println("changement save"); pubSubClient.publish("building1/room1/light",String(val).c_str(), true); } // Wait for messages from MQTT broker //pubSubClient.loop(); }
true
7b31184474397fbaa44b9310b43a7a32e9ef7892
C++
Kingshida/GUL
/GULTestTool/GULLib/GNSSUtilityLibrary/Ephemeris/IGNSSEphemeris.cpp
UTF-8
1,414
2.640625
3
[]
no_license
#include "IGNSSEphemeris.h" #include <cmath> #include <cstring> namespace sixents { namespace Math { IGNSSEphemeris::IGNSSEphemeris() { InitVar(); } IGNSSEphemeris::~IGNSSEphemeris() {} DOUBLE IGNSSEphemeris::GetCurTime() const { return m_curTime; } void IGNSSEphemeris::InitVar() { m_clock = DOUBLE_ZONE_LITTLE; memset(&m_pos, 0, sizeof(SXYZ)); m_curTime = DOUBLE_ZONE_LITTLE; } DOUBLE IGNSSEphemeris::GetClock() { return m_clock; } void IGNSSEphemeris::SetClock(const DOUBLE clock) { m_clock = clock; } SXYZ IGNSSEphemeris::GetPos() { return m_pos; } void IGNSSEphemeris::SetPos(const SXYZ& pos) { m_pos = std::move(pos); } void IGNSSEphemeris::SetPos(const DOUBLE x, const DOUBLE y, const DOUBLE z) { m_pos.m_x = x; m_pos.m_y = y; m_pos.m_z = z; } INT32 IGNSSEphemeris::SetCurTime(const DOUBLE time) { if (time < 0) { return RETURN_ERROR_PARAMETER; } m_curTime = time; return RETURN_SUCCESS; } } // namespace Math } // namespace sixents
true
e513267d6ec1f9ec6d17349331f27dee43e6d734
C++
zanfire/zanbase
/src/base/zEvent.cpp
UTF-8
846
2.609375
3
[]
no_license
#include "zEvent.h" zEvent::zEvent(void) { #if defined(_WIN32) _event = INVALID_HANDLE_VALUE; _event = CreateEvent(NULL, true, false, NULL); #elif HAVE_PTHREAD_H sem_init(&_event, 0, 0); #endif } zEvent::~zEvent(void) { #if defined(_WIN32) if(_event != NULL) { CloseHandle(_event); _event = NULL; } #else sem_destroy(&_event); #endif } void zEvent::wait(int timeoutMillis) { #if defined(_WIN32) WaitForSingleObject( _event, timeoutMillis); #else if (timeoutMillis < 0) { sem_wait(&_event); } else { timespec request_time; request_time.tv_sec = (int)(timeoutMillis / 1000); request_time.tv_nsec = (int)(timeoutMillis % 1000) * 1000; sem_timedwait(&_event, &request_time); } #endif } void zEvent::signal(void) { #if defined(_WIN32) SetEvent(_event); #else sem_post(&_event); #endif }
true
9ddc2b0daf6e35a689b307789221268aa04ab146
C++
dotnet/dotnet-api-docs
/snippets/cpp/VS_Snippets_CLR/MissingMethodException/cpp/MissingMethodException.cpp
UTF-8
2,505
3.40625
3
[ "MIT", "CC-BY-4.0" ]
permissive
//Types:System.MissingMethodException //Types:System.MissingMemberException //Types:System.MissingFieldException //<snippet1> using namespace System; using namespace System::Reflection; ref class App { }; int main() { //<snippet2> try { // Attempt to call a static DoSomething method defined in the App class. // However, because the App class does not define this method, // a MissingMethodException is thrown. App::typeid->InvokeMember("DoSomething", BindingFlags::Static | BindingFlags::InvokeMethod, nullptr, nullptr, nullptr); } catch (MissingMethodException^ ex) { // Show the user that the DoSomething method cannot be called. Console::WriteLine("Unable to call the DoSomething method: {0}", ex->Message); } //</snippet2> //<snippet3> try { // Attempt to access a static AField field defined in the App class. // However, because the App class does not define this field, // a MissingFieldException is thrown. App::typeid->InvokeMember("AField", BindingFlags::Static | BindingFlags::SetField, nullptr, nullptr, gcnew array<Object^>{5}); } catch (MissingFieldException^ ex) { // Show the user that the AField field cannot be accessed. Console::WriteLine("Unable to access the AField field: {0}", ex->Message); } //</snippet3> //<snippet4> try { // Attempt to access a static AnotherField field defined in the App class. // However, because the App class does not define this field, // a MissingFieldException is thrown. App::typeid->InvokeMember("AnotherField", BindingFlags::Static | BindingFlags::GetField, nullptr, nullptr, nullptr); } catch (MissingMemberException^ ex) { // Notice that this code is catching MissingMemberException which is the // base class of MissingMethodException and MissingFieldException. // Show the user that the AnotherField field cannot be accessed. Console::WriteLine("Unable to access the AnotherField field: {0}", ex->Message); } //</snippet4> } // This code produces the following output. // // Unable to call the DoSomething method: Method 'App.DoSomething' not found. // Unable to access the AField field: Field 'App.AField' not found. // Unable to access the AnotherField field: Field 'App.AnotherField' not found. //</snippet1>
true
04dab509ad381ede2eea0567dccfe9640c0b4d31
C++
kpratyush12345/Codeforces
/Codeforces Ladder A/469A_I_Wanna_Be_the_Guy.cpp
UTF-8
459
2.78125
3
[]
no_license
//469A - I Wanna Be the Guy //https://codeforces.com/problemset/problem/469/A #include <bits/stdc++.h> using namespace std; int main() { int n,x,y; cin>>n; cin>>x; int arr[200]; int flag=0; for(int i=0;i<x;i++){ cin>>arr[i]; } cin>>y; for(int i=x;i<x+y;i++){ cin>>arr[i]; } sort(arr,arr +(x+y)); for(int i=0;i<x+y;i++){ if(arr[i]!=arr[i+1]){ flag++; } } if(flag==n){ cout<<"I become the guy."; } else{ cout<<"Oh, my keyboard!"; } return 0; }
true
5dbba34788612b0f44b8d3e6ae69026c90b8815a
C++
gymnasy55/COW_BULL
/COW_OR_BULL_GAME.cpp
UTF-8
3,469
3.390625
3
[]
no_license
// COW_OR_BULL_GAME.cpp: Ковальов Сергій, П-81 #define NUMDIGITS 3 #define MAXGUESS 10 #include <iostream> #include <ctime> #include <string> #include <algorithm> #include <vector> #include <Windows.h> using namespace std; bool IsValid(string str) { return str[0] != str[1] && str[0] != str[2] && str[1] != str[2]; } string GetSecretNum() // Возвращает строку случайных чисел, которые не повторяются { srand(time(NULL)); string secretNum = ""; int* numbers = new int[NUMDIGITS]; bool* checked = new bool[10]; for (int i = 0; i < 10; i++) checked[i] = false; for (int i = 0; i < NUMDIGITS; i++) { while(true) { int temp = rand() % 10; if(checked[temp] == false) { checked[temp] = true; numbers[i] = temp; break; } } secretNum += to_string(numbers[i]); } return secretNum; } string Clues(string guess, string secretNumber) // Возвращает строку с подсказкой { vector<string> clues = {}; string res = ""; for(int i = 0; i < NUMDIGITS; i++) { if (guess[i] == secretNumber[i]) clues.push_back("Горячо "); else if(secretNumber.find(guess[i]) != string::npos) // Где-то есть символ clues.push_back("Тепло "); } if (clues.empty()) return "Холодно"; sort(clues.begin(), clues.end()); for (int i = 0; i < clues.size() - 1; i++) res += clues[i]; res += clues[clues.size() - 1]; return res; } bool IsOnlyDigits(string num) // Проверяет то, что строка состоит только из цифр { if (num.empty()) return false; for (char digit : num) { if (digit < '0' || digit > '9') return false; } return true; } void Rules() // Правила игры { cout << "Я загадаю число с таким кол-вом знаков: " << NUMDIGITS << endl; cout << "У вас будет " << MAXGUESS << " попыток." << endl; cout << "Я буду Вам подсказывать." << endl; cout << "Холодно - Вы ничего не отгадали." << endl; cout << "Тепло - Вы отгадали число, но не отгадали его позицию" << endl; cout << "Горячо - Вы отгадали число и позицию" << endl; } int main() { SetConsoleCP(1251); SetConsoleOutputCP(1251); Rules(); while(true) { string secretNum = GetSecretNum(); cout << "Я загадал Вам число. У вас есть " << MAXGUESS << " попыток, чтобы отгадать его."; int guesses = 1; char playAgain; while (guesses <= MAXGUESS) { string guess = ""; while (guess.length() != NUMDIGITS || !IsOnlyDigits(guess) || !IsValid(guess)) { cout << endl << "Попытка номер: " << guesses << endl; cin >> guess; } cout << Clues(guess, secretNum); guesses++; if (guess == secretNum) { cout << endl << "Вы победитель!! Поздравляем!!" << endl; break; } if (guesses > MAXGUESS) cout << endl << "Вы проиграли! У вас закончились попытки! Я загадал число - " << secretNum << endl; } cout << endl << "Хотите сыграть снова? Да(y) или Нет(n)?" << endl; cin >> playAgain; if (tolower(playAgain) != 'y') break; } }
true
12ef791c57b2da00d7f496bf0b561b09f0d141bc
C++
amiedes/consultorio-medico
/Clinic.h
UTF-8
6,943
3.140625
3
[ "MIT" ]
permissive
// // Consultorio.h // T10-Juez-I // // Created by Alberto Miedes on 13/5/16. // Copyright © 2016 Alberto Miedes. All rights reserved. // #ifndef Clinic_h #define Clinic_h #include <string> #include <list> #include <iosfwd> #include "TreeMap.h" #include "Appointment.h" #include "Appointments.h" #include "Date.h" #include "ClinicException.h" using namespace std; using Medic = std::string; // Medic type using Patient = std::string; // Patient type struct PatientDate { string paciente; unsigned int hora; unsigned int minuto; }; string format_patient_date(struct PatientDate pd) { string s = pd.paciente + " "; if (pd.hora < 10) { s += "0" + to_string(pd.hora); } else s += to_string(pd.hora); s += ":"; if (pd.minuto < 10) { s += "0" + to_string(pd.minuto); } else s += to_string(pd.minuto); return s; } /** * Main class. Keeps track of all the medics in the system and their appointments. */ class Clinic { private: TreeMap<Medic, Appointments> _medics; public: /** * nuevoMedico(m) - creates a new medic in the clinic. If it was already * in the system, it is not modified. * Complexity: O(logN), N = _medics.size() * * @param m The name of new medic */ void nuevoMedico(Medic m) { _medics[m]; // Si no existe lo crea, pero si existe no modifica el valor. } /** * Patient p makes an appintment with m Medic on Date d. * A patient may have several appointments with the same medic as long as * they're not in the same moment (hour:minute) * Complexity: max( O(logN), O(m) ), N = _medics.size(), m = _appointments.size() * * @param p The patient who wants an appointment * @param m The medic the patient wants to visit * @param d The date of the appointment * @throws MedicNotFoundException si el médico no está dado de alta. * @throws EFechaOcupada si la fecha ya está reservada. */ void pideConsulta(Patient p, Medic m, Date d) { // Get an iterator pointing at the medic TreeMap<Medic, Appointments>::Iterator it = _medics.find(m); // O(logN) ----> Revisar si no viene mejor operator[] // If medic doesn't exist, throw exception if (it == _medics.end()) throw MedicNotFoundException(); // O(1) // Get medic's appointment list Appointments* apps = &(it.value()); // O(1) // Create new appointment Appointment a(p, d); // Add the new appointment apps->new_appointment(a); // O(m), m = _appointments.size() } /** * Retrieves next patient to be 'treated' by a medic. For 'next patient' we * understand the one who has the closest date. * Complexity: O(logN), N = _medics.size() * * @param m Medic whose next patient we want to retrieve * @throws MedicNotFoundException if medic is not present in the clinic. * @throws EmptyAppointmentListException if medic has no patients assigned. */ const Patient & siguientePaciente(Medic m) const { // Get an iterator pointing at the medic TreeMap<Medic, Appointments>::ConstIterator it = _medics.find(m); // O(logN) // If medic doesn't exist, throw exception if (it == _medics.cend()) throw MedicNotFoundException(); // O(1) // En este caso he optado por realizar toda la operación en una misma línea // pues al tratarse de un observador, sólo me deja utilizar ConstIterator return it.value().next_appointment().patient(); // O(1) } /** * Deletes m's next patient. For 'next patient' we understand the one who * has the closest date. * Complexity: O(logN), N = _medics.size() * * @throws MedicNotFoundException if medic is not present in the clinic. * @throws EmptyAppointmentListException if medic has no patients assigned. */ void atiendeConsulta(Medic m) { // Obtener un iterador apuntando al médico m TreeMap<Medic, Appointments>::Iterator it = _medics.find(m); // O(logN) // Si el médico no existe, lanzar una excepción if (it == _medics.end()) throw MedicNotFoundException(); // O(1) // Obtener una referencia modificable a las citas del médico Appointments* aps = &(it.value()); // O(1) // Get next appointment (throws EmptyAppointmentListException) aps->pop_appointment(); // O(1) } /** * listaPacientes(m,f) - devuele la lista de pacientes de un cierto médico * (m) que tienen cita el día (f). Se supone que el día es un número entero * correcto. Si el médico no tiene pacientes ese día, * la lista de retorno será vacía. * Complexity: max( O(logN), O(m) ), N = _medics.size(), m = appointments.size() * * @throws MedicNotFoundException if medic is not present in the clinic. */ list<struct PatientDate> listaPacientes(Medic m, Date d) const { // Obtener un iterador apuntando al médico m TreeMap<Medic, Appointments>::ConstIterator it = _medics.find(m); // O(logN) // Si el médico no existe, lanzar una excepción if (it == _medics.cend()) throw MedicNotFoundException(); // O(1) // Obtener una referencia constante a las citas del médico Appointments aps = it.value(); // O(1) // Obtener la lista de citas en la fecha indicada list<Appointment> aps_date = aps.get_appointments_on_date(d); // O(m), m = appointments.size() list<PatientDate> patients; list<Appointment>::const_iterator apps_it = aps_date.cbegin(); while (apps_it != aps_date.cend()) { // Body -> O(1) - Loop: O(q), q = aps_date.size() struct PatientDate aux; aux.paciente = (*apps_it).patient(); aux.hora = (*apps_it).date().hour(); aux.minuto = (*apps_it).date().minute(); patients.push_back(aux); apps_it++; } return patients; } /** * Returns m's number of appointments. * Complexity: O(logN), N = _medics.size() * * @throws MedicNotFoundException if medic is not present in the clinic. */ size_t numero_citas(Medic m) const { // Obtener un iterador apuntando al médico m TreeMap<Medic, Appointments>::ConstIterator it = _medics.find(m); // O(logN) // Si el médico no existe, lanzar una excepción if (it == _medics.cend()) throw MedicNotFoundException(); // O(1) // Obtener una referencia constante a las citas del médico Appointments aps = it.value(); // O(1) return aps.size(); } }; #endif /* Consultorio_h */
true
0886cd1c73540f84f30d6261fe9283dc54bec2c2
C++
TasnimZia/UniThings
/CSC101-CPP/CSE-101-master/MultiplicationTableRevisited.cp
UTF-8
460
3.640625
4
[]
no_license
#include<iostream> using namespace std; int main() { int m, n; cout<<"Enter Two Numbers: "; cin>>m>>n; //MAX and MIN int mx = m; int mn = n; if (mx < n) { mx = n; mn = m; } for (int j = mx;j >= mn;j--) { cout<<endl; //MULTIPLICATION TABLE for (int i = 1;i <= 10;i++) cout<<j<<" * "<<i<<" = "<<j * i<<endl; } return 0; }
true
0d197f1c2c1f5364851fc6551a2065270f8b9583
C++
leeeyupeng/leeeyupeng.github.io
/project/algorithm/usaco/src/milk3.cpp
UTF-8
1,728
2.734375
3
[]
no_license
/* ID: leeyupeng LANG: C++11 PROG: milk3 */ #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <set> #include <algorithm> using namespace std; #define PROG milk3 #define FILESTREAM #ifdef FILESTREAM #define IN(prog) TMP(prog.in) #define OUT(prog) TMP(prog.out) #define TMP(prog) #prog #endif class Solution { private: int ABC[3]; //set<int> record; bool record[1024 * 32 + 2]{false}; bool vans[21]{false}; void DFS(int state) { if (record[state] == true) { return; } { int abc[3]; abc[0] = (state >> 10) & 0x1F; abc[1] = (state >> 5) & 0x1F; abc[2] = state & 0x1F; if (abc[0] == 0) { vans[abc[2]] = true; } } record[state] = true; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i != j) { int abc[3]; abc[0] = (state >> 10) & 0x1F; abc[1] = (state >> 5) & 0x1F; abc[2] = (state & 0x1F); if (abc[i] == 0) { break; } if (abc[j] == ABC[j]) { continue; } if (abc[i] <= ABC[j] - abc[j]) { abc[j] += abc[i]; abc[i] = 0; } else { abc[i] -= ABC[j] - abc[j]; abc[j] = ABC[j]; } DFS((abc[0] << 10) + (abc[1] << 5) + abc[2]); } } } } public: void PROG() { cin >> ABC[0] >> ABC[1] >> ABC[2]; int initstate = 0; initstate = ABC[2]; DFS(initstate); vector<int> v; for (int i = 0; i < 21; i++) { if (vans[i] == true) { v.push_back(i); } } for (int i = 0; i < v.size() - 1; i++) { cout << v[i]<<" "; } cout << v[v.size() - 1] << endl; } }; //int main() //{ //#ifdef FILESTREAM // freopen(IN(PROG), "r", stdin); // freopen(OUT(PROG), "w", stdout); //#endif // Solution s; // s.PROG(); // return 0; //}
true
3977b4610f649a1df080c708cb617a0d80cda8cf
C++
elinoyam/CPP_OOP_Exercise
/dynamicArray.h
UTF-8
8,005
3.484375
3
[]
no_license
#pragma once #include <iostream> using namespace std; template <class T> class DynamicArray { public: DynamicArray(int size = 2) :lSize(0), pSize(size), arr(new T[size]){} DynamicArray(const DynamicArray& other) : arr(nullptr) { *this = other; } ~DynamicArray() { delete[] arr; } int size()const { return lSize; } int capacity() const { return pSize; } bool isEmpty() const { return lSize == 0; } void clear() { lSize = 0; } const T& front() const { return arr[0]; } const DynamicArray& operator=(const DynamicArray& other) { if (this != &other) { lSize = other.lSize; pSize = other.pSize; delete[] arr; try { arr = new T[pSize]; } catch (bad_alloc& ba) { cout << ba.what() << "dynamic array h, line 27" << endl; } for (int i = 0; i < lSize; i++) arr[i] = other.arr[i]; } return *this; } const T& operator[](int i) const { return arr[i]; } T& operator[](int i) { return arr[i]; } const T& at(int i) const { if (0 <= i && i < lSize) return arr[i]; else throw invalid_argument("The given index is out of range."); } T& at(int i) { if (0 <= i && i < lSize) return arr[i]; else throw invalid_argument("The given index is not valid.");// choose index between 0 and " + lSize); } void push_back(const T& item) { if (lSize == pSize) resize(); arr[lSize++] = item; } // method to (only) increase the physical size of the array to a wanted new size // the method doesn't make the physical size smaller! void resize(int newSize) { if (newSize > pSize) { pSize = newSize; T* temp = new T[pSize]; for (int i = 0; i < lSize; i++) temp[i] = arr[i]; delete[] arr; arr = temp; } } //void print() const { // for (int i = 0; i < lSize; i++) // cout << arr[i] << " "; // cout << endl; //} class const_iterator; // forward declaration class reverse_iterator; // forward declaration class iterator { public: // this is must have settings for iterator class - DON'T EARASE using iterator_category = std::bidirectional_iterator_tag; using different_type = std::ptrdiff_t; using value_type = T; using pointer = T*; using reference = T&; iterator(DynamicArray& arr, int i) : a(&arr), index(i) {} iterator(const iterator& other) :a(other.a), index(other.index) {} const iterator& operator=(const iterator& other){ if (*this != other) { a = other.a; index = other.index; } return (*this); } bool operator==(const iterator& other) const { return ((a == other.a) && (index == other.index)); } bool operator!=(const iterator& other) const { return !(*this == other); } T& operator*() { return a->arr[index]; } T* operator->() { return &(a->arr[index]); } iterator& operator++() { ++index; return *this; } iterator operator++(int) { iterator temp(*this); ++index; return temp; } iterator& operator--() { --index; return *this; } iterator operator--(int) { iterator temp(*this); --index; return temp; } private: DynamicArray* a; int index; friend class const_iterator; friend class reverse_iterator; }; class const_iterator { public: // this is must have settings for iterator class - DON'T EARASE using iterator_category = std::bidirectional_iterator_tag; using different_type = std::ptrdiff_t; using value_type = T; using pointer = T*; using reference = T&; const_iterator(const DynamicArray& arr, int i) : a(&arr), index(i) {} const_iterator(const_iterator& other) : a(other.a), index(other.index) {} const_iterator(const iterator& other) : a(other.a), index(other.index) {} const_iterator& operator=(const iterator& other) { if (*this != other) { a = other.a; index = other.index; } return (*this); } bool operator==(const_iterator& other) const { return ((a == other.a) && (index == other.index)); } bool operator!=(const_iterator& other) const { return !(*this == other); } const T& operator*() { return a->arr[index]; } const T* operator->() { return &(a->arr[index]); } const_iterator& operator++() { ++index; return *this; } const_iterator operator++(int) { const_iterator temp(*this); ++index; return temp; } const_iterator& operator--() { --index; return *this; } const_iterator operator--(int) { const_iterator temp(*this); --index; return temp; } private: const DynamicArray* a; int index; }; class reverse_iterator { public: // this is must have settings for iterator class - DON'T EARASE using iterator_category = std::bidirectional_iterator_tag; using different_type = std::ptrdiff_t; using value_type = T; using pointer = T*; using reference = T&; reverse_iterator(const DynamicArray& arr, int i) : a(&arr), index(i) {} reverse_iterator(const iterator& other) : a(other.a), index(other.index) {} const reverse_iterator& operator=(const iterator& other) { if (*this != other) { a = other.a; index = other.index; } return (*this); } bool operator==(reverse_iterator& other) const { return ((a == other.a) && (index == other.index)); } bool operator!=(reverse_iterator& other) const { return !(*this == other); } const T& operator*() { return a->arr[index]; } const T* operator->() { return &(a->arr[index]); } reverse_iterator& operator++() { --index; return *this; } reverse_iterator operator++(int) { reverse_iterator temp(*this); --index; return temp; } reverse_iterator& operator--() { ++index; return *this; } reverse_iterator operator--(int) { reverse_iterator temp(*this); ++index; return temp; } private: DynamicArray* a; int index; }; iterator begin() { return iterator(*this, 0); } iterator end() { return iterator(*this, lSize); } const_iterator cbegin() const { // to return const_iterator even if the array isn't const return const_iterator(*this, 0); } const_iterator cend() const { // to return const_iterator even if the array isn't const return const_iterator(*this, lSize); } const_iterator begin() const { return const_iterator(*this, 0); } const_iterator end() const { return const_iterator(*this, lSize); } reverse_iterator rbegin() { return reverse_iterator(*this, lSize); } reverse_iterator rend() { return reverse_iterator(*this, 0); } iterator erase(const iterator& itr) { if(itr!=end()) { iterator temp = itr; iterator last = ++itr; while (last != end()) { temp.a[temp.index] = last.a[last.index]; ++temp; ++last; } } --lSize; return itr; } iterator erase(const iterator& first, const iterator& last) { if (last == end()) { // need to erase only the last items while (first != end()) --lSize; } else if (first == last) return erase(first); else { iterator start = first; iterator stop = ++last; while (stop != end) { start.a[start.index] = stop.a[stop.index]; ++start; ++stop; --lSize; } } } void insert(const iterator& itr, const T& item) { if (lSize == pSize) resize(); iterator itrEnd = end(); iterator itrCurrent = itrEnd, itrPrev = --itrEnd; while (itrCurrent != itr) { *itrCurrent = *itrPrev; itrCurrent = itrPrev--; } iterator p = itr; *p = item; ++lSize; } private: T* arr; int pSize; int lSize; void resize() { pSize *= 2; T* temp; try { temp = new T[pSize]; } catch (bad_alloc& ba) { throw ba; } for (int i = 0; i < lSize; i++) temp[i] = arr[i]; delete[] arr; arr = temp; } };
true
db3e5b2690b16a6ba2c5ad2dfb843e8434af4cb5
C++
David-Butlr/Circular_LInked_List
/LotteryCircularLinkedList.cpp
UTF-8
13,875
3.6875
4
[]
no_license
/*---------------------------------| David Butler | CSC 210 | 4/4/2019 | This program uses a circular linked| list to display a rigged lottery | and writes the results to a file | ----------------------------------*/ #include <iostream> //used to access input and output stream #include <cassert> //used for the assert #include <fstream> //used for file input and output stream #include <stdlib.h> //used for std library #include <iomanip> //used for output manipulation #include <ctime> //used for getting time #include <string> //used for string options using namespace std; #include "Circlist.cpp" //implementation file used to create our object #include "CircListSorted.cpp" //implementation file that performs sorting of our object ifstream fin ("CircInput.txt"); //input file ofstream fout("CircOutput.txt"); //output file void title(string &myName); //function that prints out the title and stores a name to the variable myName void date(string &myName); //function that gets the date and prints it void originalList (CircListSorted &list1, CircListSorted &list2, string msg); //function that prints the two original list void process(CircListSorted list2, int numDelete, string name); //function that performs all processing for the lottery and prints results int main() { string myName; //declares a string variable that holds myName to be used in the title function and for the math in the date function CircListSorted list1, list2; //creates two objects fin >> list1; // reads in all data from input file and assigns it to list 1, the insertion operator is overloaded in the implementation file list2 = list1; // assigns values from list 1 to list 2, the = operator is overloaded in the implementation file title(myName); // calls title function date(myName); // calls date function originalList(list1, list2, "Main original unsorted "); // calls originalList function the first time process(list2, 2, "Baker"); // calls process function the first time cout << "\n\n"; // displays to end lines process(list1, 7, "Kiley"); // calls process function the second time cout << "\n\n"; // displays to end lines originalList(list1, list2, "Main original "); // calls originalList function the second time fin.close(); fout.close(); return 0; } void title(string &myName) { myName = "David Butler"; // assigns my name to the myName variable //prints title to console cout << "A C I R C U L A R L Y L I N K E D L I S T ( T H E J O S E P H U S P R O B L E M )" << "\n\n"; cout << "Twelve prisoners are captured and put into a cave. They form a circle and choose who starts." << endl << "A lottery is made to skip some prisoners and determine who is to be executed. Counting right," << endl << "every prisoner that reaches this multiple must be executed. A mutual agreement is made that" << endl << "the last remaining prisoner must commit suicide. However, the last prisoner decides to escape" << endl << "by stealing a horse. This deviously rigged lottery and escape is planned by Josephus. This" << endl << "C++ program will simulate two of Josephus' devious plans and map each result to console/file."; cout << endl << endl; cout << setw(45) << "By" << "\n\n"; cout << setw(50) << myName << "\n\n"; // prints myName to console //writes title to the output file fout << "A C I R C U L A R L Y L I N K E D L I S T ( T H E J O S E P H U S P R O B L E M )" << "\n\n"; fout << "Twelve prisoners are captured and put into a cave. They form a circle and choose who starts." << endl << "A lottery is made to skip some prisoners and determine who is to be executed. Counting right," << endl << "every prisoner that reaches this multiple must be executed. A mutual agreement is made that" << endl << "the last remaining prisoner must commit suicide. However, the last prisoner decides to escape" << endl << "by stealing a horse. This deviously rigged lottery and escape is planned by Josephus. This" << endl << "C++ program will simulate two of Josephus' devious plans and map each result to console/file."; fout << endl << endl; fout << setw(45) << "By" << "\n\n"; fout << setw(50) << myName << "\n\n"; // writes myName to output file } void date(string &myName) { time_t t = time(0); // declares a variable to access time struct tm * timeStruct = localtime(&t); // declares a struct pointer that points at the local time int month = timeStruct->tm_mon+1; // initializes month to hold the number of the month string dmonth = "empty"; // intializes dmonth with empty which will later hold the month and the rest of the date int counter = 0; // initalizes counter with 0 which later will help with calculating the centering of the date // switch statement to help change month from number to name of month switch (month) { case 1: dmonth = "January"; // assigns January to dmonth if month is 1 break; case 2: dmonth = "February"; // assigns February to dmonth if month is 2 break; case 3: dmonth = "March"; // assigns March to dmonth if month is 3 break; case 4: dmonth = "April"; // assigns April to dmonth if month is 4 break; case 5: dmonth = "May"; // assigns May to dmonth if month is 5 break; case 6: dmonth = "June"; // assigns June to dmonth if month is 6 break; case 7: dmonth = "July"; // assigns July to dmonth if month is 7 break; case 8: dmonth = "August"; // assigns August to dmonth if month is 8 break; case 9: dmonth = "September"; // assigns September to dmonth if month is 9 break; case 10: dmonth = "October"; // assigns October to dmonth if month is 10 break; case 11: dmonth = "November"; // assigns November to dmonth if month is 11 break; case 12: dmonth = "December"; // assigns December to dmonth if month is 12 break; } // assigns the whole date to dmonth including day, month, and year; dmonth = "Current Date: " + dmonth + " " + to_string(timeStruct->tm_mday) + ", " + to_string(timeStruct->tm_year + 1900) + "\n\n"; // takes length of dmonth - myName and then divides it by 2, this is the equation that determines the centering of the date counter = (dmonth.length() - myName.length())/2; // for loop, that adds the necessary spaces to dmonth in order to center the date for (int i = 0; i < 39-counter; i++) { dmonth = " " + dmonth; // adds spaces to dmonth which contains the date } cout << dmonth; // displays date to console fout << dmonth; // writes date to the output file } void originalList (CircListSorted &list1, CircListSorted &list2, string msg) { // displays original list 1 to the console cout << msg << "list1. List size = " << list1.size() << endl << "---------------------------------------------------------------------------------------------" << endl << list1 << "---------------------------------------------------------------------------------------------" << "\n\n"; // displays original list 2 to the console cout << msg << "list2. List size = " << list2.size() << endl << "---------------------------------------------------------------------------------------------" << endl << list2 << "---------------------------------------------------------------------------------------------" << "\n\n"; // writes original list 1 to the output file fout << msg << "list1. List size = " << list1.size() << endl << "---------------------------------------------------------------------------------------------" << endl << list1 << "---------------------------------------------------------------------------------------------" << "\n\n"; // writes original list 2 to the output file fout << msg << "list2. List size = " << list2.size() << endl << "---------------------------------------------------------------------------------------------" << endl << list2 << "---------------------------------------------------------------------------------------------" << "\n\n"; } void process(CircListSorted list2, int numDelete, string name) { static int counter = 1; // initializes counter which keeps track of which lottery it's processing bool answer = true; // initializes answer which determines whether the lottery can be processed string holdName; // declares holdName which holds the name of people being deleted list2.sortCircList(); // sorts the list for the lottery // displays the sorted list to the console cout << "Sorted copy of list2. List size = " << list2.size() << endl << "---------------------------------------------------------------------------------------------" << endl << list2 << "---------------------------------------------------------------------------------------------" << "\n\n"; // writes the sorted list to the output file fout << "Sorted copy of list2. List size = " << list2.size() << endl << "---------------------------------------------------------------------------------------------" << endl << list2 << "---------------------------------------------------------------------------------------------" << "\n\n"; answer = list2.find(name); // assigns the decision of whether the lottery can be processed, to answer // if statement, to check if lottery can be processed if (answer == true) { // displays where the starting point for the lottery is, to the console cout << "Lottery #" << counter << " starts with " << name << " and eliminates multiples of " << numDelete << " prisoners. List size = " << list2.size() << endl << "---------------------------------------------------------------------------------------------" << endl << list2 << "---------------------------------------------------------------------------------------------" << "\n\n"; // writes where the starting point for the lottery is, to the output file fout << "Lottery #" << counter << " starts with " << name << " and eliminates multiples of " << numDelete << " prisoners. List size = " << list2.size() << endl << "---------------------------------------------------------------------------------------------" << endl << list2 << "---------------------------------------------------------------------------------------------" << "\n\n"; // for loop to complete all but the last lines of the lottery for (int i = 0; i < 10; i++) { holdName = list2.deleteNthNode(numDelete); // assigns the deleted prisoners name to holdName // displays the list and deleted prisoners to the console cout << holdName << " is deleted. List size = " << list2.size() << endl << "---------------------------------------------------------------------------------------------" << endl << list2 << "---------------------------------------------------------------------------------------------" << "\n\n"; // writes the list and deleted prisoners to the output file fout << holdName << " is deleted. List size = " << list2.size() << endl << "---------------------------------------------------------------------------------------------" << endl << list2 << "---------------------------------------------------------------------------------------------" << "\n\n"; } holdName = list2.deleteNthNode(numDelete); // assigns the deleted prisoners name to holdName // displays the last line of the lottery to the console cout << holdName << " is deleted. List size = " << list2.size() << endl << "---------------------------------------------------------------------------------------------" << endl << list2 << "---------------------------------------------------------------------------------------------" << "\n\n" << "Josef is the remaining prisoner that escapes on his horse!" << "\n\n"; // writes the last line of the lottery to the output file fout << holdName << " is deleted. List size = " << list2.size() << endl << "---------------------------------------------------------------------------------------------" << endl << list2 << "---------------------------------------------------------------------------------------------" << "\n\n" << "Josef is the remaining prisoner that escapes on his horse!" << "\n\n"; } counter ++; // increments counter }
true
507f0484b564d03218fc9217ab7cf7f4614828fa
C++
iaraujopaulo/Arduino
/assistenteArduino.ino
UTF-8
2,008
3.28125
3
[]
no_license
String inputString = ""; // a String to hold incoming data - String de entrada vazia bool stringComplete = false; // whether the string is complete - confirma se a string chegou inteira e completa void setup() { // initialize serial: Serial.begin(9600); // reserve 200 bytes for the inputString: inputString.reserve(200); //String de entrada com 200 bytes de caracteres para armazenar pinMode(LED_BUILTIN, OUTPUT); //led embarcado natural do arduino } void loop() { // print the string when a newline arrives: if (stringComplete) { Serial.print("Assistente Mil Grau Falando: "); Serial.print(inputString); // clear the string: if(inputString.startsWith("ligar")){ //se a instrigue de entrada começar com a palavra ligar //importante: qualquer texo com a palvra ligar digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));// toggle - escrev o inverso do estado atual, vou ler o led e inverter o estado } inputString = ""; //quando chegar a string compelta ele esvazia stringComplete = false; } } /* SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs, so using delay inside loop can delay response. Multiple bytes of data may be available. */ //Leitura da porta Serial void serialEvent() { //o Arduino tem essa função importante, ele tem esse serialEvent, vc chamando ele roda o loop e depois esse serialEvent while (Serial.available()) {//Enquanto tiver alguma coisa recebendo na Serial // get the new byte: char inChar = (char)Serial.read();//Leitura no Serial.read e converto para caracter // add it to the inputString: inputString += inChar;//coloca a variável inChar letra por letra ouvida na String // if the incoming character is a newline, set a flag so the main loop can // do something about it: if (inChar == '\n') { stringComplete = true;//quando chegar no /n ele conclui q recebeu a frase inteira } } }
true
2da2f1681add8ffc66cf467a97ed3783107b951e
C++
cleybertandre/CppNotes
/test/algorithms/strings/test_find_unique_char_in_str.hpp
UTF-8
1,167
2.84375
3
[ "MIT" ]
permissive
#ifndef TEST_FIND_UNIQUE_CHAR_IN_STR_HPP #define TEST_FIND_UNIQUE_CHAR_IN_STR_HPP #include <boost/test/unit_test.hpp> #include "algorithms/strings/find_unique_char_in_str.hpp" BOOST_AUTO_TEST_CASE(test_fucis_empty_str) { FindUnique::Solution solution; std::string str; int expected = -1; BOOST_CHECK(expected == solution.firstUniqChar(str)); } BOOST_AUTO_TEST_CASE(test_fucis_str_size_one) { FindUnique::Solution solution; std::string str("a"); int expected = 0; BOOST_CHECK(expected == solution.firstUniqChar(str)); } BOOST_AUTO_TEST_CASE(test_fucis_str_no_unique) { FindUnique::Solution solution; std::string str("aaaabbb"); int expected = -1; BOOST_CHECK(expected == solution.firstUniqChar(str)); } BOOST_AUTO_TEST_CASE(test_fucis_str_have_unique) { FindUnique::Solution solution; { std::string str("leetcode"); int expected = 0; BOOST_CHECK(expected == solution.firstUniqChar(str)); } { std::string str("loveleetcode"); int expected = 2; BOOST_CHECK(expected == solution.firstUniqChar(str)); } } #endif // TEST_FIND_UNIQUE_CHAR_IN_STR_HPP
true
b7094db1f71c0d10a44e9a2e9748c3884c5fa6f5
C++
stupid-turtle/LearningOpenGL2.0
/Getting Started/Hello Triangle/Hello Triangle/main.cpp
GB18030
8,952
2.78125
3
[]
no_license
// GLAD #include <glad/glad.h> // GLFW #include <GLFW/glfw3.h> #include <iostream> void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow* window); void check_shader_compile_success(GLuint shader); void check_program_link_success(GLuint program); const char* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "\nvoid main()\n" "{\n" " gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n" "}\0"; const char* fragmentShaderSource1 = "#version 330 core\n" "out vec4 FragColor;\n" "\nvoid main()\n" "{\n" " FragColor = vec4(1.0f, 1.0f, 0.0f, 1.0f);\n" "}\0"; const char* fragmentShaderSource2 = "#version 330 core\n" "out vec4 FragColor;\n" "\nvoid main()\n" "{\n" " FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n" "}\0"; int main() { // ʼGLFW glfwInit(); // 趨OpenGLİ汾Ϊ 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // 汾 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // ΰ汾 // ʹúģʽ glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 趨ڵĿߡ⣨ʣʱܣ GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", nullptr, nullptr); if (window == NULL) { std::cout << "Fail to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLEW" << std::endl; return -1; } // GLFWлȡӿڵά glViewport(0, 0, 800, 600); // ڴСıʱú glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); GLfloat triangleVertices[] = { -0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f }; GLfloat firstTriangle[] = { -0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f }; GLfloat secondTriangle[] = { 0.5f, -0.5f, 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f }; GLuint VAOs[2]; glGenVertexArrays(2, VAOs); // 㻺(Vertex Buffer Objects, VBO) // IDΪ1 GLuint VBOs[2]; glGenBuffers(2, VBOs); glBindVertexArray(VAOs[0]); glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(firstTriangle), firstTriangle, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GL_FLOAT), (void*)0); glEnableVertexAttribArray(0); glBindVertexArray(VAOs[1]); glBindBuffer(GL_ARRAY_BUFFER, VBOs[1]); glBufferData(GL_ARRAY_BUFFER, sizeof(secondTriangle), secondTriangle, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GL_FLOAT), (void*)0); glEnableVertexAttribArray(0); // glBufferData: רûݸƵǰ󶨻ĺ // target: Ŀ껺 // size: ݴС // data: ʵ // usage: Կݵʽ // - GL_STATIC_DRAW: ݲ򼸺ı // - GL_DYNAMIC_DRAW: ݻᱻıܶ // - GL_STREAM_DRAW: ÿλʱı //glBufferData(GL_ARRAY_BUFFER, sizeof(triangleVertices), triangleVertices, GL_STATIC_DRAW); GLfloat vertices[] = { 0.2f, 0.2f, 0.0f, // 0.8f, 0.2f, 0.0f, // 0.8f, 0.6f, 0.0f, // 0.2f, 0.6f, 0.0f, // -0.8f, -0.5f, 0.0f, 0.0f, -0.5f, 0.0f, -0.4f, 0.5f, 0.0f }; GLuint indices[] = { 0, 1, 2, 0, 2, 3, 4, 5, 6 }; //GLuint EBO; //glGenBuffers(1, &EBO); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); //glBufferData(GL_ARRAY_BUFFER, sizeof(triangleVertices), triangleVertices, GL_STATIC_DRAW); //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); //glBindBuffer(GL_ARRAY_BUFFER, 0); // һɫɫΪGL_VERTEX_SHADER GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); // һɫƬɫΪGL_FRAGMENT_SHADER GLuint fragmentShader1 = glCreateShader(GL_FRAGMENT_SHADER); GLuint fragmentShader2 = glCreateShader(GL_FRAGMENT_SHADER); // glShaderSource: ɫԴ븽ӵɫ // shader: Ҫɫ // count: ַ // *string: ɫԴ // *length: glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); check_shader_compile_success(vertexShader); glShaderSource(fragmentShader1, 1, &fragmentShaderSource1, NULL); glCompileShader(fragmentShader1); check_shader_compile_success(fragmentShader1); glShaderSource(fragmentShader2, 1, &fragmentShaderSource2, NULL); glCompileShader(fragmentShader2); check_shader_compile_success(fragmentShader2); // һ GLuint shaderProgram1 = glCreateProgram(); // ɫ븽ӵϣȻ glAttachShader(shaderProgram1, vertexShader); glAttachShader(shaderProgram1, fragmentShader1); glLinkProgram(shaderProgram1); GLuint shaderProgram2 = glCreateProgram(); glAttachShader(shaderProgram2, vertexShader); glAttachShader(shaderProgram2, fragmentShader2); glLinkProgram(shaderProgram2); // glUseProgram(shaderProgram1); glUseProgram(shaderProgram2); // ɾɫ glDeleteShader(vertexShader); glDeleteShader(fragmentShader1); glDeleteShader(fragmentShader2); // OpenGLν // index: Եλֵ // size: ԴС // type: // normalized: Ƿϣݱ׼ // stride: // *pointer: λڻʼλõƫ //glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); // öݣΪλֵ // ĬϽ //glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // Game Loop ֤ڲմ򿪾ͱر while (!glfwWindowShouldClose(window)) { // processInput(window); // Ⱦ // ɫ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(shaderProgram1); glBindVertexArray(VAOs[0]); glDrawArrays(GL_TRIANGLES, 0, 3); glUseProgram(shaderProgram2); glBindVertexArray(VAOs[1]); glDrawArrays(GL_TRIANGLES, 0, 3); //glBindVertexArray(VAO); //glDrawArrays(GL_TRIANGLES, 0, 6); //glDrawElements(GL_TRIANGLES, 9, GL_UNSIGNED_INT, 0); //glBindVertexArray(0); // ˫ glfwSwapBuffers(window); // ûд¼ glfwPollEvents(); } glDeleteVertexArrays(2, VAOs); glDeleteBuffers(2, VBOs); //glDeleteVertexArrays(1, &VAO); //glDeleteBuffers(1, &VBO); //glDeleteBuffers(1, &EBO); glDeleteProgram(shaderProgram1); glDeleteProgram(shaderProgram2); // ʱͷԴ glfwTerminate(); return 0; } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } void processInput(GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } } void check_shader_compile_success(GLuint shader) { int success; char infoLog[512]; glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::COMPILATION_FAILED\n" << infoLog << std::endl; } } void check_program_link_success(GLuint program) { int success; char infoLog[512]; glGetProgramiv(program, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(program, 512, NULL, infoLog); std::cout << "ERROR::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; } }
true
ab4bbb7258c0548e6c6038d49abeaa3d326d03cd
C++
LeeMyeungJun/INHAstudy
/HomeStudy/DirectVec/cMatrix.cpp
UHC
2,752
3.0625
3
[]
no_license
#include "stdafx.h" #include "cMatrix.h" #include <random> using namespace std; cMatrix::cMatrix() { } cMatrix::~cMatrix() { } cMatrix::cMatrix(int nDimension):dimension(nDimension) { std::vector<float> insert; for (int i = 0; i < nDimension; i++) { matrix.push_back(insert); for (int j = 0; j < nDimension; j++) { matrix[i].push_back(float(rand() % 2)); } } } void cMatrix::Print() { for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { cout << matrix[i][j]<<" "; } cout << endl; } } void cMatrix::Resize(int nDimension) { } cMatrix cMatrix::Identity(int nDimension) { return cMatrix(); } bool cMatrix::operator==(cMatrix & mat) { if (this->dimension != mat.dimension) return false; if (this->matrix != mat.matrix) return false; return true; } bool cMatrix::operator!=(cMatrix & mat) { if (this->dimension != mat.dimension) return true; if (this->matrix != mat.matrix) return true; return false; } cMatrix cMatrix::operator+(cMatrix & mat) { cMatrix temp(dimension); for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { temp.matrix[i][j] = this->matrix[i][j] + mat.matrix[i][j]; } } return temp; } cMatrix cMatrix::operator-(cMatrix & mat) { cMatrix temp(dimension); for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { temp.matrix[i][j] = this->matrix[i][j] - mat.matrix[i][j]; } } return temp; } cMatrix cMatrix::operator*(cMatrix & mat) { cMatrix temp(dimension); for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { float element = 0; for (int k = 0; k < dimension; k++) { element += matrix[i][k] * mat.matrix[k][j]; } temp.matrix[i][j] = element; } } return temp; } cMatrix cMatrix::operator*(float & f) { cMatrix temp(dimension); for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { temp.matrix[i][j] = this->matrix[i][j]; temp.matrix[i][j] *= f; } } return temp; } cMatrix cMatrix::Transpose() //ġ { cMatrix temp(dimension); for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { temp.matrix[j][i] = this->matrix[i][j]; } } return temp; } cMatrix cMatrix::Inverse(OUT float & fDeterminant) { return cMatrix(); } float cMatrix::Determinant() { return 0.0f; } cMatrix cMatrix::Adjoint() { return cMatrix(); } float cMatrix::Cofactor(int nRow, int nCol) //μ { return 0; } float cMatrix::Minor(int nRow, int nCol) // { float minor; for (int i = 0; i < dimension; i++) { if (i == nRow) continue; for (int j = 0; j < dimension; j++) { if (j == nCol) continue; } } return 0.0f; }
true
97868e4688b255ed5075de9e5efc47833bb66e55
C++
G33k1973/CodingGames
/SexyPrimes2.cpp
UTF-8
609
2.65625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; bool prime[10000001]; int main() { int m = 10000001; for (int i = 0; i < m; i++) { prime[i] = true; } for (int i = 2; i < m; i++) { if (prime[i] == true) { for (int j = i + i; j < m; j += i) { prime[j] = false; } } } int t; cin >> t; while (t-- > 0) { int l, r; cin >> l >> r; int p = 2; for (int i = l; i <= r - 6; i++) { if (prime[i] == true && prime[i + 6] == true) { cout << i << " " << i + 6 << " "; p = 4; } } if (p == 2) { cout << -1; } cout << endl; } return 0; }
true
1ac669c4c4479cb4607def832c5a5d222b2da995
C++
ahmoura/TAG
/p2/grafo_extrair_funcoes.cpp
UTF-8
5,268
3.09375
3
[]
no_license
/* UnB - Universidade de Brasilia Projeto 1 TAG - Teoria e Aplicacao de Grafos Professor: Dibio Aluno: Antonio Henrique de Moura Rodrigues Matricula: 15 / 0118236 */ #include <iostream> // funcoes de entrada e saida de dados #include <fstream> // funcoes de manipulacao de arquivos #include <string> // funcoes de manipulacao de cadeia de caracteres #include <vector> // funcoes de vetor dinamico #include <algorithm> // funcoes de sort #include <cstdlib> // funcoes de conversao de tipos de arquivo using std::fstream; using std::ofstream; using std::ifstream; using std::ios; using std::string; using namespace std; typedef struct vertex{ // Estrutura de elo int position; // Numero do vertice (Equivalente a matricula) string name; // Nome do aluno vector<int> edge; // Lista de arestas conectadas a ele } vertex; typedef struct graph{ // Estrutura de grafo vector<vertex> adj; // Conjunto de elos (adj refere-se a adjacencia) } graph; vector<graph> cliques; int printg(graph); // Funcao de interseccao de elementos dos vetores de int; graph intersectv(graph a, graph b){ graph c; unsigned int i, j; for(i = 0; i < a.adj.size(); i++){ for(j = 0; j < b.adj.size(); j++){ if (a.adj[i].position == b.adj[j].position) c.adj.push_back(a.adj[i]); // todos valores iguais nos dois vetores sao adicionados } } return c; } // Funcao de uniao dos elementos do vetor int graph unionv(graph a, graph b){ graph c; bool flag; unsigned int i, j, size; for(i = 0; i < a.adj.size(); i++){ //Adiciona todo mundo de a em c c.adj.push_back(a.adj[i]); } size = c.adj.size(); for(i = 0; i < b.adj.size(); i++){ flag = false; for(j = 0; j < size; j++){ if (b.adj[i].position == c.adj[j].position){ //Remove de c os elementos de d flag = true; } } if (flag == false) { c.adj.push_back(b.adj[i]); // Adiciona caso nao esteja no vetor } } return c; } // Funcao que encontra o complementar de a em relacao a b graph complementv(graph a, graph b){ graph c, d, e; bool flag; unsigned int i, j; for(i = 0; i < a.adj.size(); i++){ c.adj.push_back(a.adj[i]); } d = intersectv (a, b); //Encontra os elementos da interseccao entre a e b for(i = 0; i < c.adj.size(); i++){ flag = false; for(j = 0; j < d.adj.size(); j++){ if (c.adj[i].position == d.adj[j].position){ //Remove elementos da interseccao flag = true; } } if (flag == false) { e.adj.push_back(c.adj[i]); //Adiciona caso nao esteja no vetor } } return e; } // Funcao para achar vizinhaca de um vertice v graph neighborhoods (graph g, vertex v) { graph neighborhoods; unsigned int i; for (i = 0; i < v.edge.size(); i++) { neighborhoods.adj.push_back(g.adj[v.edge[i]-1]); // Procura os vertices ligados a v } return neighborhoods; } /* void kahn(graph g){ graph aux_g = g, out_g; int size_g = g.digraph.size(); int i, j, k, visited = 0; while (aux_g.digraph.size() != 0){ //Usando aux_g de fila cout << "TESTE 1"; for (i = 0; i < aux_g.digraph.size(); i++){ // Procurando vertices com 0 chegadas cout << "TESTE 2"; if (aux_g.digraph[i].nofrequirements == 0){ // Se tiver achado um vertice sem pre requisitos cout << "TESTE 3"; out_g.digraph.push_back(aux_g.digraph[i]); // Copia para o grafo de saida k = 0; for(j = 0; j < aux_g.digraph.size(); j++){ // Vai procurar em todos os outros vertices se esse tem essa materia como requisito cout << "TESTE 4"; while (k <= aux_g.digraph[j].requirements.size()){ // Verifica a quantidade de pre requisitos que cada materia tem cout << "TESTE 5"; if (aux_g.digraph[j].requirements.size() != 0) if (aux_g.digraph[i].number == aux_g.digraph[j].requirements[k]){ // Caso ache materia que tem ela de pre requisito cout << "TESTE 6"; aux_g.digraph[j].requirements.erase(aux_g.digraph[j].requirements.begin()+ k); // Apaga o pre requisito aux_g.digraph[j].nofrequirements--; // Tira um pre requisito da lista k == aux_g.digraph[j].requirements.size(); // Ignora os proximos requisitos } k++; } } aux_g.digraph.erase(aux_g.digraph.begin()+i); } } } printg(out_g); } */ int main () { // Grafos da funcao bronker (Bron-Kerbosch) graph g; graph R; graph X; unsigned int i; loadfile(g); bronker(g, R, g, X); cout << "Clique Maximo:" << endl; for (i = 0; i < cliques[49].adj.size(); i++) { if (i != 0) { cout << " - "; } cout << cliques[49].adj[i].name; } cout << endl << endl << "Clique Maximal:" << endl; for (i = 0; i < cliques[51].adj.size(); i++) { if (i != 0) { cout << " - "; } cout << cliques[51].adj[i].name; } cout << endl; csort(g); cout << endl << "Grafo ordenado por numero de amigos:" << endl << endl; printg(g); return 0; }
true
8a473ab1794150bd254fde01cc8956d213ed5aea
C++
semiessessi/NNL
/Network/FeedForward.cpp
UTF-8
3,292
2.5625
3
[]
no_license
// Copyright (c) 2015 Cranium Software #include "FeedForward.h" #include "Neuron/SigmoidNeuron.h" #include <cstdio> namespace NNL { void FeedForwardNetwork::AddLayer( Layer& xLayer ) { if( mapxLayers.size() > 0 ) { Layer& xPrevious = *( mapxLayers.back() ); // connect all the neurons to each other for( int i = 0; i < xLayer.GetNeuronCount(); ++i ) { for( int j = 0; j < xPrevious.GetNeuronCount(); ++j ) { NeuronBase* pxNew = xLayer.GetNeuron( i ); NeuronBase* pxOld = xPrevious.GetNeuron( j ); pxNew->SetInputVirtual( j, pxOld ); } } } mapxLayers.push_back( &xLayer ); } void FeedForwardNetwork::Load( const char* const szPath ) { printf( "Loading...\r\n" ); FILE* pxFile = fopen( szPath, "rb" ); if( pxFile ) { const unsigned char aucMagic[] = { 'C', 'N', 'N', 'D' }; unsigned char aucRead[ 4 ]; fread( aucRead, 1, 4, pxFile ); for( int i = 0; i < 4; ++i ) { if( aucMagic[ i ] != aucRead[ i ] ) { fclose( pxFile ); printf( "Unrecognised file format.\r\n" ); } } int iRead = 0; fread( &iRead, sizeof( int ), 1, pxFile ); // SE - TODO:what type of neuron? fread( &iRead, sizeof( int ), 1, pxFile ); const int iLayerCount = iRead; if( iLayerCount != static_cast< int >( mapxLayers.size() ) ) { printf( "Wrong number of layers.\r\n" ); fclose( pxFile ); return; } // read in all of the weights and biases. for( int i = 0; i < iLayerCount; ++i ) { const int iNeuronCount = mapxLayers[ i ]->GetNeuronCount(); for( int j = 0; j < iNeuronCount; ++j ) { const int iInputCount = mapxLayers[ i ]->GetNeuron( j )->GetInputCount(); fread( mapxLayers[ i ]->GetNeuron( j )->GetWeightPointer( ), sizeof( float ), iInputCount + 1, pxFile ); } } fclose( pxFile ); printf( "Done.\r\n" ); } else { printf( "Failed to open file.\r\n" ); } } void FeedForwardNetwork::Save( const char* const szPath ) { printf( "Saving...\r\n" ); FILE* pxFile = fopen( szPath, "wb" ); if( !pxFile ) { printf( "Failed to open file.\r\n" ); return; } const unsigned char aucMagic[] = { 'C', 'N', 'N', 'D' }; fwrite( aucMagic, 1, 4, pxFile ); // SE - TODO: neuron type fwrite( aucMagic, sizeof( int ), 1, pxFile ); const int iLayerCount = static_cast< int >( mapxLayers.size() ); fwrite( &iLayerCount, sizeof( int ), 1, pxFile ); // write out all of the weights and biases. for( int i = 0; i < iLayerCount; ++i ) { const int iNeuronCount = mapxLayers[ i ]->GetNeuronCount(); for( int j = 0; j < iNeuronCount; ++j ) { const int iInputCount = mapxLayers[ i ]->GetNeuron( j )->GetInputCount(); fwrite( mapxLayers[ i ]->GetNeuron( j )->GetWeightPointer(), sizeof( float ), iInputCount + 1, pxFile ); } } fclose( pxFile ); printf( "Done.\r\n" ); } }
true
44dcf124ac5bd5faa5551bf364d0773acd54aadb
C++
iamrakesh28/Competitve-Programming
/Algorithms-Implementation/bfs.cpp
UTF-8
1,112
2.734375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define pb(x) push_back(x) class Graph{ public: int V; list <int> *adj; void addEdge(int,int); Graph(int); void BFS(int); }; Graph::Graph(int v) { this->V = v; adj = new list <int> [V]; } void Graph::addEdge(int u,int v) { adj[u].pb(v); adj[v].pb(u); } void Graph:: BFS(int root) { bool *visited = new bool [V]; memset(visited,false,sizeof(visited)); visited[root] = true; queue <int> q; q.push(root); list <int> :: iterator it; vector <int> dist(V,-1); dist[root] = 0; while(!q.empty()) { int p = q.front(); q.pop(); for(it = adj[p].begin();it!= adj[p].end();++it) { if(visited[*it] == false) { visited[*it] = true; q.push(*it); dist[*it] = dist[p] + 6; } } } for(int i=0;i<V;++i) { if(i != root) printf("%d ",dist[i]); } printf("\n"); } int main() { int q; scanf("%d",&q); while(q--) { int n,m; scanf("%d%d",&n,&m); Graph graph(n); for(int i=0;i<m;++i) { int u,v; scanf("%d%d",&u,&v); graph.addEdge(u-1,v-1); } int s; scanf("%d",&s); graph.BFS(s-1); } return 0; }
true
5d788c654fd1992f00060533fc0ff639755a3ba6
C++
mingyuefly/C_Primer_Plus-
/C_Primer_Plus++/diwuzhang/diwuzhang/comstr2.cpp
UTF-8
455
2.828125
3
[ "MIT" ]
permissive
// // comstr2.cpp // diwuzhang // // Created by mingyue on 15/12/22. // Copyright © 2015年 G. All rights reserved. // #include <iostream> #include <string> int main(int argc, const char * argv[]){ using namespace std; string word = "?ate"; for (char ch = 'a'; word != "mate"; ch++) { cout << word << endl; word[0] = ch; } cout << "After loop ends, word is " << word << endl; return 0; }
true
47ad3c34c24e10e463fc5135f2c16ceb03c0d1ac
C++
goforit00/ChatServer1
/ChatServer1/ChatServer1/CLFuncProviderNameServer.cpp
WINDOWS-1252
1,088
2.625
3
[]
no_license
#include "CLFuncProviderNameServer.h" #include <string.h> CLFuncProviderNameServer* CLFuncProviderNameServer::m_Instance = NULL; CLFuncProviderNameServer* CLFuncProviderNameServer::GetInstance() { if( m_Instance == NULL ) m_Instance = new CLFuncProviderNameServer(); return m_Instance; } CLFuncProviderNameServer::CLFuncProviderNameServer() { } CLFuncProviderNameServer::~CLFuncProviderNameServer() { //ͷеmap } bool CLFuncProviderNameServer::Register(const char* strName , CLFunctionProvider* pFunctionProvider ) { std::map<std::string , CLFunctionProvider*>::iterator it = m_Name_FuncProvider.find(strName); if( it != m_Name_FuncProvider.end() ) return false; m_Name_FuncProvider[strName] = pFunctionProvider; return true; } CLFunctionProvider* CLFuncProviderNameServer::GetFunctionProvider(const char* strName ) { if( strName == NULL || strlen(strName) == 0 ) return NULL; std::map<std::string , CLFunctionProvider*>::iterator it = m_Name_FuncProvider.find( strName ); if( it == m_Name_FuncProvider.end() ) return NULL; return it->second; }
true
0801bc45e92b4acff75251a8da43428c8b8b440d
C++
hechenyu/book_code
/libtr1/funobjref/refcref.cpp
UTF-8
467
3.265625
3
[]
no_license
#include <tr1/functional> #include <iostream> using std::tr1::reference_wrapper; using std::tr1::ref; using std::tr1::cref; using std::cout; void show(int &i) { cout << "int &: " << i << '\n'; } void show(const int &i) { cout << "const int &: " << i << '\n'; } int main() { int Miller = 3; show(ref(Miller)); reference_wrapper<int> rw0(Miller); show(ref(rw0)); show(cref(Miller)); reference_wrapper<const int> rw1(Miller); show(cref(rw1)); return 0; }
true
6d31ddc8936d3cada976980af9d23bf8ab9cf213
C++
Crogarox/Mahatta
/tools/gfx_d3d/math/ray.cpp
UTF-8
3,505
2.703125
3
[]
no_license
#include "common.h" #include "GFX\gfx_math.h" //ray stuff #define EPSILON 1.0e-10 //0.03125f #define CLOSE_TOLERANCE 1.0e-6 #define DEPTH_TOLERANCE 1.0e-6 //normals for the box f32 g_boxNorm[6][3] = {{-1,0,0}, {1,0,0}, {0,-1,0}, {0,1,0}, {0,0,-1}, {0,0,1}}; ///////////////////////////////////// // Name: GFXIntersectBox // Purpose: not really related to // anything Graphics but nice // to have. Intersect given // ray to axis aligned bound box. // Output: tOut and nOut filled // Return: scalar t, if 1, then no intersect ///////////////////////////////////// f32 F_API RayIntersectBox(const Vec3D *p, const Vec3D *dir, const Vec3D *boxMin, const Vec3D *boxMax, Vec3D *nOut) { f32 t, tmin, tmax; s32 minSide=0, maxSide=0; tmin = 0.0; //tmax = 100000000; tmax = 1; /* * Sides first. */ if (dir->x < -EPSILON) { t = (boxMin->x - p->x) / dir->x; if (t < tmin) return 1.0f; if (t <= tmax) { maxSide = 0; tmax = t; } t = (boxMax->x - p->x) / dir->x; if (t >= tmin) { if (t > tmax) return 1.0f; minSide = 1; tmin = t; } } else { if (dir->x > EPSILON) { t = (boxMax->x - p->x) / dir->x; if (t < tmin) return 1.0f; if (t <= tmax) { maxSide = 1; tmax = t; } t = (boxMin->x - p->x) / dir->x; if (t >= tmin) { if (t > tmax) return 1.0f; minSide = 0; tmin = t; } } else { if ((p->x < boxMin->x) || (p->x > boxMax->x)) { return 1.0f; } } } /* * Check Top/Bottom. */ if (dir->y < -EPSILON) { t = (boxMin->y - p->y) / dir->y; if (t < tmin) return 1.0f; if (t <= tmax - CLOSE_TOLERANCE) { maxSide = 2; tmax = t; } t = (boxMax->y - p->y) / dir->y; if (t >= tmin + CLOSE_TOLERANCE) { if (t > tmax) return 1.0f; minSide = 3; tmin = t; } } else { if (dir->y > EPSILON) { t = (boxMax->y - p->y) / dir->y; if (t < tmin) return 1.0f; if (t <= tmax - CLOSE_TOLERANCE) { maxSide = 3; tmax = t; } t = (boxMin->y - p->y) / dir->y; if (t >= tmin + CLOSE_TOLERANCE) { if (t > tmax) return 1.0f; minSide = 2; tmin = t; } } else { if ((p->y < boxMin->y) || (p->y > boxMax->y)) { return 1.0f; } } } /* Now front/back */ if (dir->z < -EPSILON) { t = (boxMin->z - p->z) / dir->z; if (t < tmin) return 1.0f; if (t <= tmax - CLOSE_TOLERANCE) { maxSide = 4; tmax = t; } t = (boxMax->z - p->z) / dir->z; if (t >= tmin + CLOSE_TOLERANCE) { if (t > tmax) return 1.0f; minSide = 5; tmin = t; } } else { if (dir->z > EPSILON) { t = (boxMax->z - p->z) / dir->z; if (t < tmin) return 1.0f; if (t <= tmax - CLOSE_TOLERANCE) { maxSide = 5; tmax = t; } t = (boxMin->z - p->z) / dir->z; if (t >= tmin + CLOSE_TOLERANCE) { if (t > tmax) return 1.0f; minSide = 4; tmin = t; } } else { if ((p->z < boxMin->z) || (p->z > boxMax->z)) { return 1.0f; } } } if (tmax < DEPTH_TOLERANCE) { return 1.0f; } //if(minSide>= 0) { if(nOut) memcpy(nOut, g_boxNorm[minSide], sizeof(f32)*3); } //else //{ // *tOut = tmax; //if(nOut) //memcpy(nOut, g_boxNorm[maxSide], sizeof(float)*eMaxPt); //} return tmin; }
true
b378b5f7895c78075ba9e9b1f61cb65880bee665
C++
BrunoLQS/Projects_and_ITA
/CES-10/lab_01 x/lab_01_Bruno_Lima_Queiroz_Santos.cpp
ISO-8859-1
957
2.9375
3
[]
no_license
#include<stdio.h> #include<stdlib.h> int main() { /*declarao de variveis*/ int aluno,numalunos,p1,p2,p3,p4;float n1,n2,n3,n4; printf("NOTAS DE DIVERSOS ALUNOS EM 4 PROVAS:\n\n"); printf("Digite o numero de alunos:"); scanf("%d",&numalunos);printf("\n\n");aluno = 1; printf("Digite o peso da prova 1:"); scanf("%d",&p1);printf("\n"); printf("Digite o peso da prova 2:"); scanf("%d",&p2);printf("\n"); printf("Digite o peso da prova 3:"); scanf("%d",&p3);printf("\n"); printf("Digite o peso da prova 4:"); scanf("%d",&p4);printf("\n\n\n"); while (aluno <= numalunos) {printf("Aluno %d:\n\n\tNota na prova 1:",aluno); scanf("%f",&n1); printf("\n\tNota na prova 2:"); scanf("%f",&n2); printf("\n\tNota na prova 3:"); scanf("%f",&n3); printf("\n\tNota na prova 4:"); scanf("%f",&n4); printf("\n\n\tMedia: %g\n", ((p1*n1)+(p2*n2)+(p3*n3)+(p4*n4))/(p1+p2+p3+p4)); aluno= aluno+1; } printf("\n\nDigite algo para encerrar :"); system ("PAUSE"); return 0;}
true
042c44a9651ee5cbb1d28ec4d52fae5b4dc1e39b
C++
lbondi7/Element-2.0
/ElementEngine/enginelib/src/VknRenderPass.cpp
UTF-8
6,015
2.546875
3
[ "MIT" ]
permissive
#include "VknRenderPass.h" #include "VkFunctions.h" #include "Device.h" #include <element/GameSettings.h> #include "VkInitializers.h" #include <stdexcept> Element::RenderPass::RenderPass(VkFormat imageFormat) { // createVkRenderPass(imageFormat); } Element::RenderPass::RenderPass(SwapChain* swapChain) { init(swapChain); } Element::RenderPass::~RenderPass() { Destroy(); } void Element::RenderPass::init(SwapChain* swapChain) { m_swapChain = swapChain; createVkRenderPass(); createFrameBuffers(); } void Element::RenderPass::createVkRenderPass() { const auto& samples = Device::GetPhysicalDevice()->GetSelectedDevice().msaaSamples; bool isMSAAx1 = samples & VK_SAMPLE_COUNT_1_BIT; bool depthEnabled = GameSettings::get().depthEnabled; VkAttachmentDescription colorAttachment = Element::VkInitializers::attachmentDescription(m_swapChain->ImageFormat(), samples, isMSAAx1 ? VK_IMAGE_LAYOUT_PRESENT_SRC_KHR : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_UNDEFINED, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE, VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE); VkAttachmentDescription depthAttachment = Element::VkInitializers::attachmentDescription(findDepthFormat(), samples, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_UNDEFINED, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE, VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE); VkAttachmentDescription colorAttachmentResolve = Element::VkInitializers::attachmentDescription(m_swapChain->ImageFormat(), VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_UNDEFINED, VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_STORE, VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE); VkAttachmentReference colorAttachmentRef = Element::VkInitializers::attachmentReference(0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); VkAttachmentReference depthAttachmentRef = Element::VkInitializers::attachmentReference(1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); VkAttachmentReference colorAttachmentResolveRef = Element::VkInitializers::attachmentReference(depthEnabled ? 2 : 1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); VkSubpassDescription subpass{}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; subpass.pDepthStencilAttachment = depthEnabled ? &depthAttachmentRef : nullptr; subpass.pResolveAttachments = !isMSAAx1 ? &colorAttachmentResolveRef : nullptr; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; std::vector<VkAttachmentDescription> attachments; attachments.emplace_back(colorAttachment); if (depthEnabled) attachments.emplace_back(depthAttachment); if (!isMSAAx1) attachments.emplace_back(colorAttachmentResolve); VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size()); renderPassInfo.pAttachments = attachments.data(); renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; if (vkCreateRenderPass(Device::getVkDevice(), &renderPassInfo, nullptr, &m_vkRenderPass) != VK_SUCCESS) { throw std::runtime_error("failed to create render pass!"); } } void Element::RenderPass::createFrameBuffers() { m_frameBuffers = std::make_unique<FrameBuffers>(m_swapChain, m_vkRenderPass); } void Element::RenderPass::Destroy() { if(m_vkRenderPass != VK_NULL_HANDLE) vkDestroyRenderPass(Device::getVkDevice(), m_vkRenderPass, nullptr); m_vkRenderPass = VK_NULL_HANDLE; if (m_frameBuffers) { m_frameBuffers->Destroy(); m_frameBuffers.reset(); } m_swapChain = nullptr; } VkRenderPass Element::RenderPass::GetVkRenderPass() { return m_vkRenderPass; } VkFormat Element::RenderPass::findDepthFormat() { return Element::VkFunctions::findSupportedFormat(Device::GetVkPhysicalDevice(), { VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT }, VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT ); } void Element::RenderPass::begin(VkCommandBuffer vkCommandBuffer, int i) { VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = m_vkRenderPass; renderPassInfo.framebuffer = m_frameBuffers->GetVkFrameBuffer(i); renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = m_swapChain->Extent(); std::vector<VkClearValue> clearValues; clearValues.emplace_back(); clearValues[0].color = { m_clearColour.r, m_clearColour.g, m_clearColour.b, 1.0f }; if (GameSettings::get().depthEnabled) { clearValues.emplace_back(); clearValues[1].depthStencil = { 1.0f, 0 }; } renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size()); renderPassInfo.pClearValues = clearValues.data(); vkCmdBeginRenderPass(vkCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); } void Element::RenderPass::end(VkCommandBuffer vkCommandBuffer) { vkCmdEndRenderPass(vkCommandBuffer); } void Element::RenderPass::setClearColour(const glm::vec3& clearColour) { m_clearColour = clearColour; }
true
c22229a38b3f06682172d765afa4dc995d5701c8
C++
vvoZokk/dnn
/dnn_project/spikework/kernels/rbf_dot.cpp
UTF-8
1,053
2.578125
3
[ "MIT" ]
permissive
#include "rbf_dot.h" #include <dnn/util/func_param_parser.h> #include <dnn/util/fastapprox/fastexp.h> namespace dnn { void RbfDotKernel::usage(ostream &str) const { str << "spec: RbfDot(sigma = " << o.sigma << ")\n"; str << "desc: Gaussian radial basis function, which is a general purpose kernel\n"; } double RbfDotKernel::operator () (const vector<double> &x, const vector<double> &y) const { assert(x.size() == y.size()); double acc = 0.0; // double x_norm = 0.0, y_norm = 0.0; for(size_t i=0; i<x.size(); ++i) { acc += o.sigma*(x[i]-y[i])*(x[i] - y[i]); // x_norm += x[i]*x[i]; // y_norm += y[i]*y[i]; } acc = fastexp(-acc); // x_norm = sqrt(x_norm); // y_norm = sqrt(y_norm); // return acc/(x_norm*y_norm); return acc; } void RbfDotKernel::processSpec(const string &spec) { L_DEBUG << "RbfDotKernel, processing spec: " << spec; FuncParamParser::TParserMap m; m["sigma"] = FuncParamParser::genDoubleParser(o.sigma); FuncParamParser::parse(spec, m); } }
true
eaae1e58787f0303af33c0584450bdcc2867e381
C++
shugo256/AtCoder
/AGC/002_C_Knot_Puzzzle.cpp
UTF-8
560
2.65625
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int n; long l; cin >> n >> l; long a, prev=-10000000000; int i = 0; for ( ; i<n; i++) { cin >> a; if (a + prev >= l) break; prev = a; } if (i == n) { cout << "Impossible" << '\n'; return 0; } cout << "Possible" << '\n'; for (int j=1; j<i; j++) cout << j << '\n'; for (int j=n-1; j>i; j--) cout << j << '\n'; cout << i << '\n'; return 0; }
true
729dec0e292b2a31e1fd5218915115642d16cd69
C++
jonathenzc/Algorithm
/LeetCode/iter1/c++/CombinationSumIII.cpp
UTF-8
1,073
3.296875
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using namespace std; void helper(int index, int sum, int cnt,int target, vector<int>& candidates, vector<int> &curV, vector<vector<int>> &v) { if (sum == target) { if(curV.size() == cnt) v.push_back(curV); } else { for (int i = index + 1; i < candidates.size(); i++) { if (sum + candidates[i] <= target) { curV.push_back(candidates[i]); helper(i, sum + candidates[i], cnt,target, candidates, curV, v); curV.pop_back(); } } } } vector<vector<int>> combinationSum3(int k, int n) { vector<vector<int>> v; vector<int> candidates; for(int i=1;i<10;i++) candidates.push_back(i); vector<int> tmpV; helper(-1, 0, k,n, candidates, tmpV, v); return v; } void testPrint(int k, int n) { cout << "k " << k << " n " << n << endl; vector<vector<int>> combinationV = combinationSum3(k, n); for (auto tmpV : combinationV) { for (auto num : tmpV) cout << num << " "; cout << endl; } cout << endl; } int main() { testPrint(3, 7); testPrint(3, 9); return 0; }
true
3743f265541385d5833def5853f1a5901d025b71
C++
bricewillous/BedControl
/legacy/arduino (old)/src/debugPrint.ino
UTF-8
10,522
2.8125
3
[]
no_license
#include "arduino.h" void printPrefix (int debugLevel) { Serial.print ("["); debugPrintDigits (day()); Serial.print ("/"); debugPrintDigits (month()); Serial.print ("/"); Serial.print (year()); Serial.print (" "); debugPrintDigits (hour()); Serial.print (":"); debugPrintDigits (minute()); Serial.print (":"); debugPrintDigits (second()); Serial.print ("]" + debugLevelSpace (debugLevel) + "[" + debugLevelName (debugLevel) + "] "); } void printSdPrefix (int debugLevel) { logFile.print ("["); sdPrintDigits (day()); logFile.print ("/"); sdPrintDigits (month()); logFile.print ("/"); logFile.print (year()); logFile.print (" "); sdPrintDigits (hour()); logFile.print (":"); sdPrintDigits (minute()); logFile.print (":"); sdPrintDigits (second()); logFile.print ("]" + debugLevelSpace (debugLevel) + " [" + debugLevelName (debugLevel) + "] "); } // Utility for digital clock display: prints leading 0 void debugPrintDigits (int digits) { if (digits < 10) Serial.print (0); Serial.print (digits); } void sdPrintDigits (int digits) { if (digits < 10) logFile.print (0); logFile.print (digits); } // ------------------------------------------------------------------------------------- // // ---------------------------------- Print functions ---------------------------------- // // ------------------------------------------------------------------------------------- // void print (int debugLevel, const __FlashStringHelper * message, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.print (message); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.print (message); } } void print (int debugLevel, const String &message, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.print (message); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.print (message); } } void print (int debugLevel, const char * message, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.print (message); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.print (message); } } void print (int debugLevel, unsigned char message, int base, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.print (message, base); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.print (message, base); } } void print (int debugLevel, int message, int base, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.print (message, base); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.print (message, base); } } void print (int debugLevel, unsigned int message, int base, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.print (message, base); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.print (message, base); } } void print (int debugLevel, long message, int base, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.print (message, base); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.print (message, base); } } void print (int debugLevel, unsigned long message, int base, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.print (message, base); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.print (message, base); } } void print (int debugLevel, double message, int base, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.print (message, base); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.print (message, base); } } void print (int debugLevel, const Printable &message, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.print (message); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.print (message); } } void println (int debugLevel, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.println(); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.println(); } } void println (int debugLevel, const __FlashStringHelper * message, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.println (message); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.println (message); } } void println (int debugLevel, const String &message, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.println (message); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.println (message); } } void println (int debugLevel, const char * message, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.println (message); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.println (message); } } void println (int debugLevel, unsigned char message, int base, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.println (message, base); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.println (message, base); } } void println (int debugLevel, int message, int base, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.println (message, base); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.println (message, base); } } void println (int debugLevel, unsigned int message, int base, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.println (message, base); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.println (message, base); } } void println (int debugLevel, long message, int base, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.println (message, base); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.println (message, base); } } void println (int debugLevel, unsigned long message, int base, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.println (message, base); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.println (message, base); } } void println (int debugLevel, double message, int base, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.println (message, base); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.println (message, base); } } void println (int debugLevel, const Printable &message, boolean prefix) { if (SD_LOG_ENABLED && logFileAvailable && debugLevel <= SD_LOG_LEVEL) { logFile = SD.open (sdFileName, FILE_WRITE); if (prefix) printSdPrefix (debugLevel); logFile.println (message); logFile.close(); } if (SERIAL_LOG_ENABLED && debugLevel <= SERIAL_LOG_LEVEL) { if (prefix) printPrefix (debugLevel); Serial.println (message); } }
true
87dea907ebbfd2b0f7f88e10ed91ef4ce861ab10
C++
huangcaohui/Data-Structure-And-Algorithm
/tree.h
UTF-8
1,748
3.671875
4
[]
no_license
#include <iostream> using namespace std; template<class T> class TreeNode //树结点的ADT { private: T m_Value; //树结点的值 TreeNode<T> *pChild; //第一个左孩子指针 TreeNode<T> *pSibling; //由兄弟指针 public: TreeNode(const T &value); //拷贝构造函数 virtual ~TreeNode() {}; //析构函数 bool isLeaf(); //判断当前结点是否为叶节点 T value(); //返回结点的值 TreeNode<T> *LeftMostChild(); //返回第一个左孩子 TreeNode<T> *RightSibling(); //返回右兄弟 void setValue(const T &value); //设置当前结点的值 void setChild(TreeNode<T> *pointer); //设置左孩子 void setSibling(TreeNode<T> *pointer); //设置左兄弟 void InsertFirst(TreeNode<T> *node); //以第一个左孩子身份插入结点 void InsertNext(TreeNode<T> *node); //以右兄弟的身份插入结点 }; template<class T> class Tree { public: Tree(); //构造函数 virtual ~Tree(); //析构函数 TreeNode<T> *getRoot(); //返回树中的根结点 void CreateRoot(const T &rootValue); //创建值为rootValue的根节点 bool isEmpty(); //判断是否为空树 TreeNode<T> *Parent(TreeNode<T> *current); //返回父结点 TreeNode<T> *PreSibling(TreeNode<T> *current); //返回前一个兄弟 void DeleteSubTree(TreeNode<T> *subroot); //删除以subroot子树 void DestroyNodes(TreeNode<T> *root); //删除以root为代表的所有结点 void RootFirstTraverse(TreeNode<T> *root); //先根深度优先遍历树 void RootLastTraverse(TreeNode<T> *root); //后根深度优先遍历树 void WidthTraverse(TreeNode<T> *root); //广度优先遍历树 };
true
42fb57de21925214921f70a50f1042597cbe07d7
C++
fooad444/OS
/ex2/tests/tester.cpp
UTF-8
11,992
2.671875
3
[]
no_license
// ///* // * tester.cpp // * // * Created on: Apr 7, 2015 // * Author: moshemandel //*/ // // // //#include <unistd.h> //#include "uthreads.h" //#include "iostream" //#define INTERVAL 1000000 //using namespace std; // //int totalQuantums = 0; // //void foo() { // while(true) { // if (uthread_get_total_quantums() > totalQuantums) // { // cout << "[tester] "; // cout<< "thread #: " << uthread_get_tid() << ". foo: "<< uthread_get_quantums(uthread_get_tid() )<<endl; // totalQuantums = uthread_get_total_quantums(); // } // } //} // //void bar() { // while(true) { // if (uthread_get_total_quantums() > totalQuantums) // { // cout << "[tester] "; // cout<< "thread #: " << uthread_get_tid() << ". bar: "<< uthread_get_quantums(uthread_get_tid() )<<endl; // totalQuantums = uthread_get_total_quantums(); // } // } //} // //void something() { // while(true) { // if (uthread_get_total_quantums() > totalQuantums) // { // cout << "[tester] "; // cout<< "thread #: " << uthread_get_tid() << ". something: "<< uthread_get_quantums(uthread_get_tid() )<<endl; // totalQuantums = uthread_get_total_quantums(); // } // } //} //void barSuspend() { // bool susSwitch = false; // while(true) { // if (uthread_get_total_quantums() > totalQuantums) // { // cout << "[tester] "; // cout<< "thread #: " << uthread_get_tid() << ". barSuspend: "<< uthread_get_quantums(uthread_get_tid() )<<endl; // totalQuantums = uthread_get_total_quantums(); // if(uthread_get_quantums(uthread_get_tid() )%10 == 1 ) { // cout << "[tester] return value of suspend: "<<uthread_suspend(1) << endl; // } // if (uthread_get_quantums(uthread_get_tid() )%10 == 6 ) { // cout << "[test2] trying to resume"<< endl; // cout << "[tester] return value of resume: "<<uthread_resume(1)<< endl; // } // } // // } //} // //void selfSuspendFoo() { // int counter = 0; // int self_suspend_ctr = 0; // while(true) { // if (counter == INTERVAL) { // counter = 0; // cout << "[tester] "; // cout << "I'm a thread! foo , thread number : ["<< uthread_get_tid() <<"]" << endl; // } // if (self_suspend_ctr == INTERVAL*10) { // self_suspend_ctr = 0; // cout << "[test3] trying to suspend "<< uthread_get_tid() << endl; // cout << "[tester] return value of suspend: "<<uthread_suspend(uthread_get_tid())<<endl; // cout.flush(); // } // self_suspend_ctr++; // counter++; // } //} // //void barResumeOtherThread() { // int counter = 0; // int unsusCounter = 0; // while(true) { // if (counter == INTERVAL) { // counter = 0; // cout << "[tester] "; // cout << "I'm a thread! barResumOtherThread , thread number : ["<< uthread_get_tid() <<"]" << endl; // } // if (unsusCounter == INTERVAL*20 ) { // cout << "[test3] trying to resume 1"<< endl; // cout << "[tester] return value of resume: "<<uthread_resume(1) <<endl; // cout.flush(); // unsusCounter = 0; // } // unsusCounter ++; // counter++; // } //} // //void barTerminateSelf() { // int counter = 0; // int killCounter = 0; // while(true) { // if (counter == INTERVAL) { // counter = 0; // cout << "[tester] "; // cout << "I'm a thread! barTermSelf , thread number : ["<< uthread_get_tid() <<"]" << endl; // } // if (killCounter == INTERVAL*5 ) { // cout << "[test4] farewell sweet world!!! (self terminate)"<< endl; // cout << "[tester] return value of terminate: "<< uthread_terminate(uthread_get_tid())<<endl; // killCounter = 0; // } // killCounter ++; // counter++; // } //} // // ///*void barSleep() { // int counter = 0; // int sleepCounter = 0; // while(true) { // if (counter == INTERVAL) { // counter = 0; // cout << "[tester] "; // cout << "I'm a thread!, thread number : ["<< uthread_get_tid() <<"]" << endl; // } // if (sleepCounter == INTERVAL*10 ) { // cout << "[test7] I'm going to sleep"<< endl; // cout << "[tester] return value of sleep: "<< uthread_sleep(7)<< endl; // sleepCounter = 0; // } // sleepCounter ++; // counter++; // } //}*/ // // //void fooCreatesNewThread() { // int counter = 0; // int create_counter = 0; // while(true) { // if (counter == INTERVAL) { // counter = 0; // cout << "[tester] "; // cout << "I'm a thread! fooCreatesNewThread , thread number : ["<< uthread_get_tid() <<"]" << endl; // } // if (create_counter == INTERVAL*20) { // create_counter = 0; // cout << "[tester] return value of spawn: "<< uthread_spawn(foo,RED)<<endl; // } // create_counter++; // counter++; // } //} // //void fooTerminatesMainThread() { // int counter = 0; // int kill_counter = 0; // while(true) { // if (counter == INTERVAL) { // counter = 0; // cout << "[tester] "; // cout << "I'm a thread! fooTerminatesMainThread , thread number : ["<< uthread_get_tid() <<"]" << endl; // } // if (kill_counter == INTERVAL*5) { // kill_counter = 0; // cout << "[tester] return value of terminate: "<< uthread_terminate(0)<<endl; // cout.flush(); // } // kill_counter++; // counter++; // } //} // //void barTerminateOther() { // int counter = 0; // int killCounter = 0; // bool to_kill = true; // while(true) { // if (counter == INTERVAL) { // counter = 0; // cout << "[tester] "; // cout << "I'm a thread! barTermOther , thread number : ["<< uthread_get_tid() <<"]" << endl; // } // if (to_kill == true && killCounter == INTERVAL*5) { // to_kill = false; // cout << "[test6] farewell sucker!!! (terminate 1)"<< endl; // cout << "[tester] return value of terminate: "<< uthread_terminate(1)<< endl; // killCounter = 0; // } // killCounter ++; // counter++; // } //} // //void barQuantum() { // int counter = 0; // int quantumCounter = 0; // while(true) { // if (counter == INTERVAL) { // counter = 0; // cout << "[tester] "; // cout << "I'm a thread!, bar at your service, thread number : ["<< uthread_get_tid() <<"]" << endl; // } // if (quantumCounter == INTERVAL*3 ) { // cout << "[test8] (bar) I'm bar, counting quantums: {" << uthread_get_quantums(uthread_get_tid()) << "}"<< endl; // quantumCounter = 0; // } // quantumCounter ++; // counter++; // } //} // //void fooQuantum() { // int counter = 0; // int quantumCounter = 0; // while(true) { // if (counter == INTERVAL) { // counter = 0; // cout << "[tester] "; // cout << "I'm a thread!, foo at your service, thread number : ["<< uthread_get_tid() <<"]" << endl; // } // if (quantumCounter == INTERVAL*3 ) { // cout << "[test8] (foo) I'm foo, counting quantums: {" << uthread_get_quantums(uthread_get_tid()) << "}"<< endl; // cout << "[test8] (foo) Total quantums: {" << uthread_get_total_quantums() << "}"<< endl; // quantumCounter = 0; // } // quantumCounter ++; // counter++; // } //} // //// basic switch test //void test1() { // cout << "[tester] Test 1: basic test" <<endl; // if (uthread_init(1000000) != 0) { // cout << "[tester] ohh snap! init returned an error code" <<endl; // } // else { // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(foo,RED)<<endl; // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(bar,RED)<<endl; // } //} // //// suspend test //void test2() { // cout << "[tester] Test 2: suspend test and unsuspend" <<endl; // uthread_init(1000000); // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(foo,RED) <<endl; // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(barSuspend,RED) <<endl; //} // //// suspend running thread //void test3() { // cout << "[tester] Test 3: suspend running thread and unsuspend it" <<endl; // uthread_init(1000000); // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(selfSuspendFoo,RED) <<endl; // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(barResumeOtherThread,RED) <<endl; //} // //// terminate self. create new thread to check that number 2 is used again. //void test4() { // cout << "[tester] Test 4: thread terminates itself" <<endl; // uthread_init(1000000); // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(fooCreatesNewThread,RED) <<endl; // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(barTerminateSelf,RED) <<endl; // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(something,RED) <<endl; //} // //// try to terminate main //void test5() { // cout << "[tester] Test 5: thread tries to terminates main thread" <<endl; // uthread_init(1000000); // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(fooTerminatesMainThread,RED) <<endl; // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(bar,RED) <<endl; //} //// try to terminate other thread //void test6() { // cout << "[tester] Test 6: thread terminates other thread" <<endl; // uthread_init(1000000); // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(foo,RED) <<endl; // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(barTerminateOther,RED) <<endl; //} // // ////// sleep test ////void test7() { //// cout << "[tester] Test 7: sleep test" <<endl; //// uthread_init(1000000); //// cout <<"[tester] spawn should not return -1: " <<uthread_spawn(barSleep,RED) <<endl; ////} // // //// quantum test //void test8() { // cout << "[tester] Test 8: quantum test" <<endl; // uthread_init(1000000); // cout << "[tester] Total quantums: " << uthread_get_total_quantums() << endl; // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(fooQuantum,RED) <<endl; // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(barQuantum,RED) <<endl; //} // //// suspend test with large quantum so we can see quantum stopped before it is up //void test9() { // cout << "[tester] Test 9: suspend running thread and unsuspend it" <<endl; // uthread_init(10000000); // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(selfSuspendFoo,RED) <<endl; // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(barResumeOtherThread,RED) <<endl; //} //// test more than 100 threads //void test10() { // uthread_init(1000000); // for (int i = 1; i < 20; i++) { // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(foo,RED) <<endl; // } // usleep(4000000); // // cout << "(test10) after sleep" << endl; // // // // for (int i = 19; i > 0; i--) { // // cout <<"[tester] spawn should not return -1: " <<uthread_terminate(i) <<endl; // // } // // for (int i = 1; i < 100; i++) { // // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(foo) <<endl; // // } // // cout <<"[tester] spawn should return -1: " <<uthread_spawn(foo) <<endl; // // cout <<"[tester] return value of terminate: "<< uthread_terminate(5)<<endl; // // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(foo) <<endl; // // cout <<"[tester] spawn should return -1: " <<uthread_spawn(foo) <<endl; //} // //// valgrind //void test11() { // cout << "[tester] Test 11: terminate main thread" <<endl; // uthread_init(1000000); // cout <<"[tester] spawn should not return -1: " <<uthread_spawn(foo,RED) <<endl; // uthread_terminate(0); //} // //int main(){ //// test1(); // test2(); //// test3(); //// test4(); //// test5(); //// test6(); ////// test7(); //// test8(); //// test9(); //// test10(); //// test11(); // int counter = 0, quantumCounter = 0; // while(true) { // if (uthread_get_total_quantums() > totalQuantums) // { // cout<< "thread #: " << uthread_get_tid() << ". main: "<<uthread_get_quantums(uthread_get_tid()) <<endl; // totalQuantums = uthread_get_total_quantums(); // } // //// if (counter == INTERVAL) { // //// counter = 0; // //// cout << "[tester] "; // //// cout << "I'M SEXY AND I KNOW IT, thread number : ["<< uthread_get_tid() <<"]" << endl; // //// } // //// if (quantumCounter == INTERVAL*3 ) { // //// cout << "[test8] (MAIN) I'm MAIN, counting quantums: {" << uthread_get_quantums(uthread_get_tid()) << "}"<< endl; // //// cout << "[test8] (MAIN) Total quantums: {" << uthread_get_total_quantums() << "}"<< endl; // //// quantumCounter = 0; // // } // // quantumCounter ++; // // counter++; // } // return 0; //} // //
true
8fffad15e1ece26658d6704697855f794fde3361
C++
javierborja95/CSC17C
/Project/WheelOfFortune_V5/Player.h
UTF-8
738
3.359375
3
[]
no_license
/* File: Player.h * Author: Javier B * Created on October 20, 12:00 PM * Purpose: Struct Specification File for Player */ #ifndef PLAYER_H #define PLAYER_H //System Libraries #include <iostream> #include <string> using namespace std; //Namespace of the System Libraries //User Libraries struct Player{ string name; int money; unsigned int score; Player(){ money=50; //Player starts with $500.00 score=0; //Player starts with 0 points } friend bool operator> (const Player &left, const Player &right) {return left.score>right.score;} }; struct name_sort{ bool operator()(const Player &left, const Player &right) {return left.name<right.name;} }; #endif /* PLAYER_H */
true
7cce15cd3e983fa4cc8594c65334ee5f244b3a9c
C++
808sam/Personal-Coding-Projects
/Datalog/Rule.h
UTF-8
749
3.171875
3
[]
no_license
#ifndef RULE_H #define RULE_H #include "Predicate.h" #include <vector> #include <string> //holds which predicates allow for creation of tuples //headPred(<params>) :- pred1(<params>), pred2(<params>) //if tuples for all body preds, rule says can create tuple for headPred class Rule { public: Rule(Predicate headIn, std::vector<Predicate> listIn) : headPredicate(headIn), predicateList(listIn) {} ~Rule(); //prints head predicate to string, ":-", then all predicates in the rules list std::string ToString(); //getters Predicate GetHead() { return headPredicate; }; std::vector<Predicate> GetPreds() { return predicateList; } private: Predicate headPredicate; std::vector<Predicate> predicateList; }; #endif
true
44c51ae3af86ec6d381939d68e5a4a4289e3f07a
C++
hexlet-basics/exercises-cpp
/modules/40-data-types/70-const-type/main.cpp
UTF-8
228
2.875
3
[]
no_license
#include <iostream> int main(int argc, char *argv[]) { using centimeters = double; centimeters radius { atof(argv[1]) }; // BEGIN constexpr double kPi { 3.14 }; std::cout << 2 * kPi * radius << std::endl; // END }
true
743458393f189d65fa338c2c575d81b28e6f2195
C++
pcuji/Meetup_challenges-
/main.cpp
UTF-8
416
2.796875
3
[]
no_license
// // main.cpp // contains_duplicate // // Created by Pedro Jose Cuji on 9/20/17. // Copyright © 2017 Pedro Jose Cuji. All rights reserved. // #include <iostream> #include <list> int main(int argc, const char * argv[]) { // insert code here... // declring list std::list <int> A; std::list <int> B; A.insert(1,2.3,4); //B.insert(3,22,22,3,2); std::cout << "hello World" << "\n"; return 0; }
true
2a5741e491d2f480858eac623cd3958b88ea90c4
C++
bobreg/weather_station_on_arduino
/1_loop.ino
UTF-8
2,867
2.796875
3
[]
no_license
void loop() { if (flag_button_wake_up == false) { // если кнопка прерывания не была нажата, то... count_sleepss_period = 0; // обнулим количество периодов долгого сна measure(); // опросим датчики update_history(); // обновим историю //Serial.println("всё измерили и обновили историю"); digitalWrite(4, LOW); // уберём питание с датчиков и экрана long_sleep(); // и опять уйдём в сон } else { // если кнопка прерывания была нажата, то if (millis() - last_times_1 > 5000) { // каждые пять секунд меняем информацию last_times_1 = millis(); // на экране view_weather(); } if (millis() - last_times_2 > 60000) { //через минуту уходим в сон (60000) flag_button_wake_up = false; // сбросим флаг кнопки прерывания digitalWrite(4, LOW); // уберём питание с датчиков и экрана long_sleep(); // уйдём в догий сон } } // по короткому нажатию кнопки меняем инф на экране // длинное нажатие (3 секунды) переведёт нас на одну минуту в режим графиков button_plus.check(&view_weather, &history_measuring_as_graf); button_set.check(&settings, &history_measuring_as_data); } //-----------долгий сон----------------- void long_sleep() { // когда ардуина выходит из сна она проверяет сколько // прошло периодов и уходит обратно в сон или дальше // на выполнение while (count_sleepss_period < period_sleep) { delay(300); //перед сном нужно выдержать паузу, чтобы отработала переферия power.sleep(SLEEP_8192MS); count_sleepss_period++; if (flag_button_wake_up == true) { break; } Serial.println(count_sleepss_period); } digitalWrite(4, HIGH); // включим датчики last_times_1 = millis(); last_times_2 = millis(); delay(1000); // выдержим паузу } //-------функция для прерывания которая возводит флаг //-------и по этому флагу ардуина выходит из долгого сна------------- void empty_func() { flag_button_wake_up = true; //Serial.println("нажали кнопку"); }
true
ff91d779a79cb0e5b26866489fb6b672d5359645
C++
abhijeetmokate/OOP_CPP
/jump_search.cpp
UTF-8
599
3.828125
4
[]
no_license
#include<iostream> #include<cmath> using namespace std; int jump_search(int *arr, int size, int value) { int block_size = sqrt(size); int start = 0; int end = block_size; while(arr[end]<=value && end<size-1) // |1|2|3|4|5|6|7|8|9|10|11| { start = end; end = end+block_size; if(end>size-1) end = size-1; } for(int i=start;i<=end;i++) //linear search { if(arr[i] == value) return i; } return -1; } int main() { int arr[10] = {1,2,3,4,5,6,7,8,9,10}; cout<<jump_search(arr,10,4); return 0; }
true
a8ca6ef146dda1874ba494a94d8b5f49c886b653
C++
ericjohnsonKC/CS325-DataStructures
/wk1_stacks/stackImplementation.cpp
UTF-8
7,379
3.75
4
[]
no_license
/************************************************* * Author: Eric Johnson * Date 11/17/2020 * * Grantham University * CS325 Data Structures * Week 1 Assignment: Stack Implementation * * Description: * This is the main program file, created per the * assignment instructions. ****************************************************/ #include "webPage.h" #include "linkedStack.h" #include <iostream> #include <cassert> #include <string> using namespace std; // Declare functions needed for main program... void displayMenu(); // This function will display the main menu int userMenuSelection(); // This function will get user menu selection int menuSelection; // This will hold the user's menu selection linkedStack<webPage> webPages_back; // This is the linked list stack that will hold the webPages for going back linkedStack<webPage> webPages_forward; // This will hold the stack for webPages going forward. void newWebPageUserInput(webPage & newWebPage); // This function will be used when adding a new page to get user input void listAllPages(linkedStack<webPage> webPages_back, linkedStack<webPage> webPages_forward); // This function will list all the webPages from the forward and back stacks. void resetTheStacks(linkedStack<webPage> & resultingStack, linkedStack<webPage> & stackToEmpty); // This function will put all the visited pages on the back stack to prep for adding a new page. int main() { displayMenu(); menuSelection = userMenuSelection(); while (menuSelection != 9){ switch(menuSelection){ case 1: { if(webPages_back.size() < 2) { // Check to see if going back is possible, note that the top of the back stack is the current page in the history. cout << endl << "No previous page in the history" << endl; break; } else{ webPages_forward.push(webPages_back.peek()); // Put current page into forward stack webPages_back.pop(); // Remove the page from the back stack // Now print the new current page location: cout << endl; cout << "Current page: " << webPages_back.peek().getTitle(); cout << endl; break; } } case 2: { if(webPages_forward.isEmptyStack()) { // Check to see if going forward is possible cout << endl << "There are not forward pages in the history. " << endl; break; } else { webPages_back.push(webPages_forward.peek()); // Put next page from forward stack on the back stack webPages_forward.pop(); // Remove the page from the forward stack // Now print the new current page location: cout << endl; cout << "Current page: " << webPages_back.peek().getTitle(); cout << endl; break; } } case 3: { listAllPages(webPages_back, webPages_forward); break; } case 4: { resetTheStacks(webPages_back, webPages_forward); // Put all the visited pages on the back stack to add new page to top webPage newWebPage; // Creates a new webPage newWebPageUserInput(newWebPage); // Gets user input for webPage properties webPages_back.push(newWebPage); // Pushes the new webPage onto the stack. cout << "Page added. " << endl; break; } case 5: { if(!webPages_back.isEmptyStack()) { // Check if back stack is empty webPages_back.pop(); cout << "Page deleted." << endl; break; } else cout << endl << "Nothing in History to delete." << endl; break; } default: cout << "Invalid selection" << endl; break; } displayMenu(); menuSelection = userMenuSelection(); } cout << "Exiting the program..." << endl; return 0; } void displayMenu(){ cout << endl << endl; cout << "MAIN MENU:" << endl; cout << "1. Go back" << endl; cout << "2. Go forward" << endl; cout << "3. List all pages" << endl; cout << "4. Add page" << endl; cout << "5. Delete page" << endl; cout << endl; cout << "9. Exit the program" << endl << endl; } int userMenuSelection(){ string str; // Will temporarily hold string input before converting to type int int menuSelection; cout << "Please enter a numeric option from the menu: "; getline(cin, str); menuSelection = stoi(str); // Convert user input to type int cout << endl; return menuSelection; } void newWebPageUserInput(webPage & newWebPage) { string title, description, url, dateAccessed; // declare temp variables to hold input cout << endl << "Please enter web page title: "; getline(cin, title); cout << endl << "Please enter web page description: "; getline(cin, description); cout << endl << "Please enter web page url: "; getline(cin, url); cout << endl << "Please enter web page date accessed: "; getline(cin, dateAccessed); newWebPage.setTitle(title); newWebPage.setDescription(description); newWebPage.setUrl(url); newWebPage.setDateAccessed(dateAccessed); } void listAllPages(linkedStack<webPage> webPages_back, linkedStack<webPage> webPages_forward) { if(webPages_back.isEmptyStack()) // Because the current page is the top of the back stack cout << endl << "The history is empty." << endl; else { resetTheStacks(webPages_forward, webPages_back); // This will reset the local stack copies into one stack for ordered output // Notice I've passed the arguments in reverse order so I can // Pull the oldest page off first and print chronologically. while(!webPages_forward.isEmptyStack()) { // Because of the above order of parameters to the resetTheStacks call, // now everything is in the forward stack, ready to print from oldest // to newest. cout << endl; cout << endl << "Page Title: " << webPages_forward.peek().getTitle(); cout << endl << "Page Description: " << webPages_forward.peek().getDescription(); cout << endl << "Page URL: " << webPages_forward.peek().getUrl(); cout << endl << "Date Accessed: " << webPages_forward.peek().getDateAccessed(); cout << endl; webPages_forward.pop(); } } } void resetTheStacks(linkedStack<webPage> & resultingStack, linkedStack<webPage> & stackToEmpty) { while(!stackToEmpty.isEmptyStack()) { resultingStack.push(stackToEmpty.peek()); // Copy top element of stackToEmpty to top of resultingStack stackToEmpty.pop(); // Delete the top element of the stackToEmpty } }
true
82282a08fda69b1252d90237622335b8cfbcf4b3
C++
takase1121/libcompat
/tests/test.cpp
UTF-8
531
2.765625
3
[]
no_license
#include <iostream> #include "../compat.h" using namespace std; int main() { cout << "Sleep for 2 seconds." << endl; compat_sleep(2000); cout << "Try beeping for 1 second" << endl; compat_beep(1000, 1000); compat_cls(); cout << "Did you catch that? I cleared the screen!" << endl; compat_color("fc"); cout << "BOO! Alright, I,ll turn it back" << endl; compat_color(""); cout << "Finally," << endl; compat_open("test.jpg"); cout << "I'm out of tricks. Bye!" << endl; compat_pause(); return 0; }
true
eb8c1fd198bd18c0efa352f344f62538e87bb4cb
C++
mchlp/competitive-programming
/DMOJ/CCC/ccc18s4.cpp
UTF-8
569
2.703125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; unordered_map<int, long long> memo; long long recur(int weight) { if (memo.count(weight) == 0) { if (weight == 1) { memo[weight] = 1; } else { long long total = 0; for (int i=2; i<=weight; i++) { int cweight = weight / i; total += recur(cweight); } memo[weight] = total; } } return memo[weight]; } int main() { int N; scanf("%d", &N); printf("%lld\n", recur(N)); return 0; }
true
2579c80469983271b4593c61bdb8171b69791bb7
C++
Blubehriluv/Assignment-07-Keywords-II
/Assignment 07/Keywords II/Source1.cpp
UTF-8
1,291
3.234375
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <ctime> #include <cctype> using namespace std; char guess; const int MAX_WRONG = 8; //How many guesses you can get wrong vector<string> words; //words to guess const string THE_WORD = words[0]; //words to guess int wrong = 0; //number of incorrect guesses string soFar(THE_WORD.size(), '-'); //word guessed so far string used = ""; //letters already guessed void guesses(); int main() { //Setup for the program words.push_back("DOCUMENT"); words.push_back("INFILTRATE"); words.push_back("GOLDENEYE"); srand(static_cast<unsigned int>(time(0))); random_shuffle(words.begin(), words.end()); //letters already guessed cout << "Welcome, Agent 626. We've been expecting you." << endl; cout << "The Training Course for Deciphering will now begin." << endl; system("pause"); guesses(); } //Player's Guesses void guesses() { cout << "\n\nEnter your guess: "; cin >> guess; guess = toupper(guess); } void checking() { if ((wrong < MAX_WRONG) && (soFar != THE_WORD)) { cout << "\n\nYou have " << (MAX_WRONG - wrong); cout << " incorrect guesses left.\n"; cout << "\nYou've used the following letters:\n" << used << endl; cout << "\nSo far, the word is:\n" << soFar << endl; } }
true
b5af1aa64fad54bc38227de57127ab3cd5aa84eb
C++
camaren/woo
/Person.hpp
UTF-8
663
3
3
[]
no_license
// Person.hpp // // 'Hello World' class. Function declarations. // // (C) Datasim Education BV 2005-2006 // #ifndef Person_HPP #define Person_HPP #include "datasimdate.hpp" // My dates and other useful stuff #include <string> // Standard string class in C++ using namespace std; class Person { public: // Everything public, for convenience only // Data string nam; // Name of person DatasimDate dob; // Date of birth DatasimDate createdD; // Internal, when object was created public: Person (const string& name, const DatasimDate& DateofBirth); void print() const; int age() const; }; #endif
true
c8c1ed416605682599a8d21730cb2cb3eda0158f
C++
eluqm/load-forescasting-ia2
/network.cpp
UTF-8
6,792
2.765625
3
[]
no_license
#include "network.h" #include <math.h> #include <iostream> #include <stdlib.h> #include <time.h> #include <math.h> //For tanh #include <fstream> #include <vector> // returns a float in the range -1.0f -> - 1.0f #define RANDOM_CLAMP (((float)rand()-(float)rand())/RAND_MAX) //returns a float between 0 & 1 #define RANDOM_NUM ((float)rand()/(RAND_MAX+1)) Network::Network() { } int Network::SetData(double learning_rate,unsigned long layers[],unsigned long tot_layers) { //Function to set various parameters of the net if (tot_layers<2) return(-1); //Return error if total no. of layers < 2 //Because input and output layers are necessary net_learning_rate=learning_rate; net_layers= new unsigned long [tot_layers]; //Initialize the layers array Layers=new Layer[tot_layers]; for(int i=0;i<tot_layers;i++){ net_layers[i]=layers[i]; Layers[i].Initialize(layers[i]); //Initialize each layer with the specified size } net_inputs=new double[layers[0]]; net_outputs=new double[layers[tot_layers-1]]; net_tot_layers=tot_layers; return 0; } int Network::SetInputs(vector<long double> inputs){ //Function to set the inputs for(int i=0;i<net_layers[0];i++){ Layers[0].Neurons[i].n_value=inputs[i]; } return 0;} void Network::RandomizeWB(void){ //Randomize weights and biases int i,j,k; for(i=0;i<net_tot_layers;i++){ for(j=0;j<net_layers[i];j++){ if(i!=(net_tot_layers-1)){ //la ultima capa no requiere pesos Layers[i].Neurons[j].SetDendrites(net_layers[i+1]); //Initialize the dendites for(k=0;k<net_layers[i+1];k++){ Layers[i].Neurons[j].Dendrites[k].d_weight=GetRand(); //Let weight be the random value } } if(i!=0){ //First layer does not need biases Layers[i].Neurons[j].n_bias=GetRand(); } } } } double * Network::GetOutput(void){ //Gives the output of the net double *outputs; int i,j,k; outputs=new double[net_layers[net_tot_layers-1]]; //Temp ouput array for(i=1;i<net_tot_layers;i++){ for(j=0;j<net_layers[i];j++){ Layers[i].Neurons[j].n_value=0; for(k= 0;k<net_layers[i-1];k++){ Layers[i].Neurons[j].n_value=Layers[i].Neurons[j].n_value+Layers[i-1].Neurons[k].n_value*Layers[i-1].Neurons[k].Dendrites[j].d_weight; //Multiply and add all the inputs } Layers[i].Neurons[j].n_value=Layers[i].Neurons[j].n_value+Layers[i].Neurons[j].n_bias; //Add bias Layers[i].Neurons[j].n_value=Limiter(Layers[i].Neurons[j].n_value); //Squash that value } } for(i=0;i<net_layers[net_tot_layers-1];i++){ outputs[i]=Layers[net_tot_layers-1].Neurons[i].n_value; } return outputs; //Return the outputs } void Network::Update(void){ //Just a dummy function //double *temp; //Temperory pointer //temp=GetOutput(); GetOutput(); //delete temp; } /* void SetOutputs(double outputs[]){ //Set the values of the output layer for(int i=0;i<net_layers[net_tot_layers-1];i++){ Layers[net_tot_layers-1].Neurons[i].n_value=outputs[i]; //Set the value } } */ double Network::Limiter(double value){ //Limiet to limit value between 1 and -1 //return tanh(value); //Currently using tanh return (1.0/(1+exp(-value))); } double Network::GetRand(void){ //Return a random number between range -1 to 1 using time to seed the srand function time_t timer; struct tm *tblock; timer=time(NULL); tblock=localtime(&timer); int seed=int(tblock->tm_sec+100*RANDOM_CLAMP+100*RANDOM_NUM); //srand(tblock->tm_sec); srand(seed); return (RANDOM_CLAMP+RANDOM_NUM); } double Network::SigmaWeightDelta(unsigned long layer_no, unsigned long neuron_no){ //Calculate sum of weights * delta. Used in back prop. layer_no is layer number. Layer number and neuron number can be zero double result=0.0; for(int i=0;i<net_layers[layer_no+1];i++) { //va atravez de todas las neuronas de la siguiente capa result=result+Layers[layer_no].Neurons[neuron_no].Dendrites[i].d_weight*Layers[layer_no+1].Neurons[i].n_delta; //Comput the summation } return result; } //neuron_no is neuron number. This function is used in back prop /*For output layer: Delta = (TargetO - ActualO) * ActualO * (1 - ActualO) Weight = Weight + LearningRate * Delta * Input For hidden layers: Delta = ActualO * (1-ActualO) * Summation(Weight_from_current_to_next AND Delta_of_next) Weight = Weight + LearningRate * Delta * Input */ int Network::Train(vector<long double> inputs,vector<long double> outputs){ //The standard Backprop Learning algorithm int i,j,k; double Target, Actual, Delta; SetInputs(inputs); //Set the inputs Update(); //Update all the values //SetOutputs(outputs); //Set the outputs for(i=net_tot_layers-1;i>0;i--){ //Go from last layer to first layer for(j=0;j<net_layers[i];j++) {//Go thru every neuron if(i==net_tot_layers-1){ //Output layer, Needs special atential Target=outputs[j]; //Target value Actual=Layers[i].Neurons[j].n_value; //Actual value Delta= (Target - Actual) * Actual * (1 - Actual); //Function to compute error Layers[i].Neurons[j].n_delta=Delta; //Compute the delta for(k=0;k<net_layers[i-1];k++) { Layers[i-1].Neurons[k].Dendrites[j].d_weight += Delta*net_learning_rate*Layers[i-1].Neurons[k].n_value; //Calculate the new weights } Layers[i].Neurons[j].n_bias = Layers[i].Neurons[j].n_bias + Delta*net_learning_rate*1; //n_value is always 1 for bias } else { //Here //Target value Actual=Layers[i].Neurons[j].n_value; //valor actual de la neurona Delta= Actual * (1 - Actual)* SigmaWeightDelta(i,j); //Function para calcular el error sumatoria de pesos y el anterior delta for(k=0;k<net_layers[i-1];k++){ Layers[i-1].Neurons[k].Dendrites[j].d_weight += Delta*net_learning_rate*Layers[i-1].Neurons[k].n_value; //Calculate the new weights } if(i!=0) //Input layer does not have a bias Layers[i].Neurons[j].n_bias = Layers[i].Neurons[j].n_bias + Delta*net_learning_rate*1; //n_value is always 1 for bias } } } return 0; } Network::~Network(){ delete Layers; }
true
aba5c75a85a0809f0c7625c1af17a87f34c2f8b8
C++
Nebul5/CPS
/headers/shape.h
UTF-8
1,787
3.03125
3
[]
no_license
#ifndef SHAPE_H #define SHAPE_H #include <string> // std::string #include <utility> // std::pair #include <memory> // std::shared_ptr #include <initializer_list> // std::initializer_list // This is the Shape Base class that Circle, Rectangle and Regular Polygon // Inherit from namespace cps { class Shape { public: using BoundBoxType = std::pair<double, double>; using PointType = std::pair<int, int>; using ShapePtr = std::shared_ptr<Shape>; protected: BoundBoxType bound_box; // bound_Box(width,height) PointType current_point; // current_Point(x,y) PointType starting_point; std::string x_coord_str = "x_coord"; std::string y_coord_str = "y_coord"; public: Shape() = default; ~Shape() = default; Shape(BoundBoxType bound_box, PointType current_point); void scale(double x_scale, double y_scale); virtual void rotate(int rotation_Angle); virtual void vertical(const std::initializer_list<Shape> &list); virtual void horizontal(); void layer(); BoundBoxType maxDimensions(const std::initializer_list<Shape> &list); virtual std::string toPostScript(); BoundBoxType getBoundBox(); PointType getCurrentPoint(); const BoundBoxType getBoundBox() const; PointType getCurrentPoint() const; void setBoundBox(BoundBoxType bound_box); virtual void setCurrentPoint(PointType new_point); PointType getStartingPoint(); void rotateBoundBox(int angle); }; // Stores a syntax tree representing a postscript program struct SyntaxTree { // TODO }; // Stores a postscript program whose source is a string written in standard C++ class Program { private: SyntaxTree AST; public: Program(std::string source); Program(const Program &p); std::string toString(); void interpret(std::string source); }; } // namespace cps #endif
true
d592836390d8111da29da5760d59519f83b34426
C++
playerxq/algorithm-design
/algorithm design/leetcode-335-地图穿插/leetcode-335-地图穿插/leetcode-335-地图穿插.cpp
GB18030
1,110
2.703125
3
[]
no_license
// leetcode-335-ͼ.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include <cstdio> #include <iostream> #include <sstream> #include <string.h> #include <math.h> #include <vector> #include <queue> #include <map> #include <set> #include <unordered_map> #include <stack> #include<iomanip> #include <ctype.h> #include <algorithm> using namespace std; class Solution { public: bool isSelfCrossing(vector<int>& x) { x.insert(x.begin(),4,0); int i = 4; for (; i < x.size(); i++) { if (x[i]>x[i - 2]) continue; else break; } if (i == x.size()) return false; if (i == x.size() - 1) return false; int t = x[i-2] - x[i]; if (t <= x[i - 4] &&x[i + 1] + x[i - 3] >= x[i - 1]) return true; i++; for (; i < x.size(); i++) { if (x[i] < x[i - 2]) continue; else break; } if (i == x.size()) return false; return true; } }; int _tmain(int argc, _TCHAR* argv[]) { vector<int> ve; ve.push_back(1); ve.push_back(1); ve.push_back(2); ve.push_back(1); ve.push_back(1); Solution s; s.isSelfCrossing(ve); return 0; }
true
493e061b07d8fe3b04effc8ad5f64650ff23d1b7
C++
maskottchentech/Arduino
/Labmate_code/service.ino
UTF-8
4,666
2.921875
3
[]
no_license
void secondscreen5() { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Enter Password"); while (secondscreenflag5 == true) { delay(180); int up = digitalRead(up_buttonPin); // down_buttonPin key int down = digitalRead(down_buttonPin); // down key lcd.setCursor(2, 1); lcd.print(password1); if (digitalRead(up_buttonPin) == 1) { password1++; digitalWrite(buzzerpin, HIGH); delay(20); digitalWrite(buzzerpin, LOW); } if (down == 1) { digitalWrite(buzzerpin, HIGH); delay(20); digitalWrite(buzzerpin, LOW); password1--; if (password1 <= 0) { password1 = 0; } } int enter = digitalRead(enter_button); // enter key if (enter == 1) { digitalWrite(buzzerpin, HIGH); delay(20); digitalWrite(buzzerpin, LOW); secondscreenflag5 = false; password2flag = true; password_2(); } if (digitalRead(7) == 1) { secondscreenflag5 = false; firstscreenflag = true; digitalWrite(buzzerpin, HIGH); delay(20); digitalWrite(buzzerpin, LOW); firstscreen(); } } //end of while loop } //end of secondscreen5 void password_2() { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Enter Password"); lcd.setCursor(2, 1); lcd.print(password1); while (password2flag == true) { delay(180); lcd.setCursor(4, 1); lcd.print(password2); int enter = digitalRead(enter_button); // enter key int up = digitalRead(up_buttonPin); // down_buttonPin key int down = digitalRead(down_buttonPin); // down key if (up == 1) { digitalWrite(buzzerpin, HIGH); delay(20); digitalWrite(buzzerpin, LOW); password2++; } if (down == 1) { digitalWrite(buzzerpin, HIGH); delay(20); digitalWrite(buzzerpin, LOW); password2--; if (password2 <= 0) { password2 = 0; } } if (enter == 1) { digitalWrite(buzzerpin, HIGH); delay(20); digitalWrite(buzzerpin, LOW); password2flag = false; password3flag = true; password_3(); } if (digitalRead(7) == 1) { password2flag = false; secondscreenflag5 = true; digitalWrite(buzzerpin, HIGH); delay(20); digitalWrite(buzzerpin, LOW); secondscreen5(); } } } void password_3() { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Enter Password"); lcd.setCursor(2, 1); lcd.print(password1); lcd.setCursor(4, 1); lcd.print(password2); while (password3flag == true) { delay(150); lcd.setCursor(6, 1); lcd.print(password3); int enter = digitalRead(enter_button); // enter key int up = digitalRead(up_buttonPin); // down_buttonPin key int down = digitalRead(down_buttonPin); // down key if (up == 1) { digitalWrite(buzzerpin, HIGH); delay(20); digitalWrite(buzzerpin, LOW); password3++; } if (down == 1) { digitalWrite(buzzerpin, HIGH); delay(20); digitalWrite(buzzerpin, LOW); password3--; if (password3 <= 0) { password3 = 0; } } if (enter == 1) { digitalWrite(buzzerpin, HIGH); delay(20); digitalWrite(buzzerpin, LOW); if (password1 == 1 && password2 == 0 && password3 == 3) { password1 = 0; password2 = 0; password3 = 0; password3flag = false; correctPasswordflag = true; correctPassword(); //this function is in admin file } else { password1 = 0; password2 = 0; password3 = 0; WrongPasswordflag = true; password3flag = false; wrongPassword(); } } if (digitalRead(7) == 1) { password3flag = false; password2flag = true; digitalWrite(buzzerpin, HIGH); delay(20); digitalWrite(buzzerpin, LOW); password_2(); } } } void wrongPassword() { while (WrongPasswordflag == true) { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Wrong Password"); delay(2000); WrongPasswordflag = false; firstscreenflag = true; firstscreen(); } }
true
5c3fcf698674ae8fe59cc2c757b65a5f61212891
C++
BinaryBrain/Elodie-Dream
/src/Menu/Menu.cpp
UTF-8
2,272
2.875
3
[]
no_license
#include "Menu.h" const std::string Menu::SELECTOR_PATH = "assets/img/sprites/poro.png"; Menu::Menu(const std::string& label, GameState state): MenuComponent(label, state) { selectortexture.loadFromFile(SELECTOR_PATH, sf::IntRect(102, 16, 120, 30)); selector.setTexture(selectortexture); background.setOutlineColor(MENU_BACKGROUND_OUTLINE_COLOR); background.setFillColor((sf::Color(0x00, 0x00, 0x00, 0x7f))); background.setOutlineThickness(3); background.setPosition(MENU_X-60, MENU_Y-5); isMenu = true; } Menu::~Menu() { if(text) { delete text; text = NULL; } for(size_t i = 0; i < items.size(); ++i) { if (items[i] && !isParent[i]) { delete items[i]; items[i] = NULL; } } } void Menu::addItem(MenuComponent* item, bool isParent) { sf::Text* text = item->getText(); text->setCharacterSize(MENU_CHAR_SIZE); text->setStyle(sf::Text::Bold); text->setColor(MENU_ITEM_COLOR); item->setText(text); items.push_back(item); this->isParent.push_back(isParent); } // Draws the everything in the menu void Menu::draw(GameView& view) { background.setSize(sf::Vector2f(MENU_WIDTH, MENU_ITEMS_INTERSPACE * visibles.size())); view.addDrawable(ViewLayer::MENU, &background); for (size_t i = 0; i < visibles.size(); ++i) { visibles[i]->getText()->setPosition(MENU_X, MENU_Y + MENU_ITEMS_INTERSPACE * i); view.addDrawable(ViewLayer::MENU, (visibles[i]->getText())); } selector.setPosition(MENU_X - 40, MENU_Y + 10 + MENU_ITEMS_INTERSPACE * index); view.addDrawable(ViewLayer::MENU, &selector); } void Menu::incIndex() { if (index == visibles.size() - 1) { index = 0; } else { ++index; } } void Menu::decIndex() { if (index == 0) { index = visibles.size() - 1; } else { --index; } } int Menu::getIndex() { return index; } MenuComponent* Menu::getSelectedItem() { return visibles[index]; } void Menu::prepareVisibles() { visibles.clear(); for (size_t i = 0; i < items.size(); ++i) { if (items[i]->isVisible()) { visibles.push_back(items[i]); } } }
true
23ece01d03df847d837421205d236fad01ce164d
C++
Roarw/SteampunkFriends
/SteampunkFriends/CPPGameWorld/Collider.h
UTF-8
718
2.609375
3
[]
no_license
#ifndef COLLIDER_H #define COLLIDER_H #include "Component.h" #include <stack> #include <vector> #include "IDraw.h" #include "Vector2.h" #include "RectangleF.h" class SpriteRenderer; class Transform; class Collider : public Component, public IDraw { private: SpriteRenderer * spriter; Transform * transform; void CheckCollision(); public: vector<Collider*> collisions; Vector2 Size; bool Enabled = true; void Update(); void Draw(DrawHandler* drawHandler); std::string GetName(); RectangleF CollisionBox(); Collider(GameObject * g, Transform * transform, RectangleF sizeRect); Collider(GameObject * g, Transform * transform, SpriteRenderer * spriteRenderer); ~Collider(); }; #endif // !COLLIDER_H
true
72da6f6930bda8a1303394009ed546e02b95236c
C++
PranabSarker10/CPlusPlus
/32 to 42.Operator/32 to 42.OPERATOR PROGRAMMING/39.1ASSIGNMENT OPERATOR OVERLOADING.cpp
UTF-8
596
3.8125
4
[]
no_license
///Assignment Operator overloading #include<iostream> using namespace std; class Number { int x,y;///Private member variable public: Number() {x=0; y=0;}///constructor Number(int a, int b){x=a; y=b;}///constructor void get(int &a,int &b){a=x; b=y;} void set(int a, int b){x=a; y=b;} void print(){cout<<x<<" "<<y<<endl;} Number operator = (Number ob); }; Number Number::operator = (Number ob) { x = ob.x; y = ob.y; } int main() { Number n1(4,0),n2(4,4),n3; n1.print(); n2.print(); n1 = n2; n1.print(); n2.print(); return 0; }
true
eae177cab3c513e3aadce65c7a1309e2d907fe9c
C++
msaaddev/Basic-Cpp-Programs
/Continuously takes number from the user until user enters -1, and then gives the maximum number among the inputed number.cpp
UTF-8
350
2.921875
3
[]
no_license
#include <iostream> using namespace std; int main() { int maximum, a; maximum=0; while (a!=-1) { cout << "enter the number="; cin >> a; if (a<-1) { } else { if (a>maximum) { maximum=a; } else { } } } cout << "Maximum number=" << maximum; return 0; }
true
6a581f324debf883f45fc2db480d39f6c5bd554a
C++
wtrsltnk/GraphicsFileLoader
/Graphics/GraphicsView.cpp
UTF-8
2,007
2.78125
3
[]
no_license
// GraphicsView.cpp: implementation of the GraphicsView class. // ////////////////////////////////////////////////////////////////////// #include "GraphicsView.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// GraphicsView::GraphicsView() { this->m_nX = 0; this->m_nY = 0; this->m_nWidth = 100; this->m_nHeight = 100; this->m_fAspect = 1.0f; this->m_fFOV = 45.0f; this->m_fNear = 0.1f; this->m_fFar = 100.0f; } GraphicsView::~GraphicsView() { } LRESULT GraphicsView::InitView(int x, int y, int width, int height) { this->m_nX = x; this->m_nY = y; this->m_nWidth = width; if (height > 0) { this->m_nHeight = height; } this->m_fAspect = (float)this->m_nWidth / (float)this->m_nHeight; return TRUE; } LRESULT GraphicsView::Resize(int width, int height) { this->m_nWidth = width; if (height > 0) { this->m_nHeight = height; } this->m_fAspect = (float)this->m_nWidth / (float)this->m_nHeight; return TRUE; } LRESULT GraphicsView::Move(int x, int y) { this->m_nX = x; this->m_nY = y; return TRUE; } LRESULT GraphicsView::Setup3D() { ::glViewport(this->m_nX, this->m_nY, this->m_nWidth, this->m_nHeight); ::glMatrixMode(GL_PROJECTION); ::glLoadIdentity(); ::gluPerspective(this->m_fFOV, this->m_fAspect, this->m_fNear, this->m_fFar); ::glMatrixMode(GL_MODELVIEW); ::glLoadIdentity(); ::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ::glClearColor(0.0f, 0.0f, 0.0f, 0.0f); return TRUE; } LRESULT GraphicsView::Setup2D() { ::glViewport(this->m_nX, this->m_nY, this->m_nWidth, this->m_nHeight); ::glMatrixMode(GL_PROJECTION); ::glLoadIdentity(); ::gluOrtho2D(0.0, (GLdouble)this->m_nWidth, 0.0, (GLdouble)this->m_nHeight); ::glMatrixMode(GL_MODELVIEW); ::glLoadIdentity(); ::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ::glClearColor(0.0f, 0.0f, 0.0f, 0.0f); return TRUE; }
true
27463a6966a872a99d5aedc1c705dd7d39ccd7c1
C++
dbgtmaster/sepbackupmonitor-client
/MainWindow/MainMenu.h
UTF-8
1,026
2.515625
3
[]
no_license
#ifndef MAINMENU_H #define MAINMENU_H #include <QObject> #include <QWidget> #include <QLayout> #include "QPushButton" #include <MainWindow/MainWindow.h> class MdiAbstractWindowFactory; class MdiAbstractWindow; class MainMenu : public QWidget { Q_OBJECT private: QHBoxLayout _layout; // Eine Liste, welcher Button wellchem Factory zugeordnet ist. QHash<QPushButton*, MdiAbstractWindowFactory*> _hashButtonToFactory; // Eine Liste, welcher Factory welches Fenster erstellt hat: QHash<MdiAbstractWindowFactory*, MdiAbstractWindow*> _hashFactoryToWindow; public: explicit MainMenu(QWidget *parent = 0); // Fügt einen neuen Eintrag ins Menü hinzu... void addMenuEntry(const QString &name, MdiAbstractWindowFactory *factory); void openMenuEntry(const QString &name); signals: public slots: // Slot wird aufgerufen, wenn ein Button gedrückt wurde: void buttonPressed(); // Wenn ein SUBFenster geschlossen wurde. void mdiWindowClosed(); }; #endif // MAINMENU_H
true
3a99cde0d4d013d5f22add3b3c02335c01bd4bb7
C++
itsdrell/SoftwareDevelopment
/Engine/Code/Engine/Math/Geometry/Plane.cpp
UTF-8
826
3.109375
3
[]
no_license
#include "Plane.hpp" #include "..\..\Core\Tools\ErrorWarningAssert.hpp" #include "..\MathUtils.hpp" Plane::Plane(const Vector3 & theNormal, const Vector3 & pos) { distance = DotProduct(normal, pos); normal = theNormal; } Plane::Plane(const Vector3 & a, const Vector3 & b, const Vector3 & c) { Vector3 e0 = b - a; Vector3 e1 = c - a; normal = Cross( e1, e0); GUARANTEE_OR_DIE( !IsNearZero(normal.GetLength()), "Plane Construction Failed"); normal.Normalize(); distance = DotProduct(normal, a); } float Plane::GetDistance(const Vector3 & pos) const { float dist = DotProduct(pos, normal); return dist - distance; } bool Plane::IsInFront(const Vector3 & pos) const { return GetDistance(pos) > 0.f; } void Plane::FlipNormal() { // Gotta do both, not just the normal normal = -normal; distance = -distance; }
true
50514f46073c01e2bd92f968a6f8c68207bf62d2
C++
sakrejda/Lux
/include/slicer-continuous.hpp
UTF-8
2,607
2.5625
3
[]
no_license
#ifndef SLICER_CONTINUOUS_H #define SLICER_CONTINUOUS_H #include <trng/yarn2.hpp> #include <trng/uniform01_dist.hpp> #include <trng/exponential_dist.hpp> #include <cmath> #include <algorithm> template <class T_PDF, class T_DOMAIN> class Slicer_Continuous { public: Slicer_Continuous(); Slicer_Continuous( const T_PDF lpdf, T_DOMAIN x_, T_DOMAIN domain_min, T_DOMAIN domain_max, trng::yarn2 * pR ); T_DOMAIN draw(); void jump(T_DOMAIN x_); private: const T_PDF plpdf; trng::yarn2 * R; trng::uniform01_dist<double> U; trng::exponential_dist<double> EXPO; T_DOMAIN min, max; T_DOMAIN w, l_bound, r_bound; // width of stepping-out steps, and bounds std::vector<T_DOMAIN> w_vector; unsigned int m; // max number of step-out steps to take T_DOMAIN x, x_new; // location on density double ly, ly_new; // runif(0,f(x)) void step_out(); }; template <class T_PDF, class T_DOMAIN> Slicer_Continuous<T_PDF, T_DOMAIN>::Slicer_Continuous() : plpdf(0), min(0), max(0), R(0), EXPO(1.0), w(1.0), m(10) {} template <class T_PDF, class T_DOMAIN> Slicer_Continuous<T_PDF, T_DOMAIN>::Slicer_Continuous( const T_PDF lpdf, T_DOMAIN x_, T_DOMAIN domain_min, T_DOMAIN domain_max, trng::yarn2 * pR ) : plpdf(lpdf), min(domain_min), max(domain_max), R(pR), EXPO(1.0), w(1.0), m(10), x(x_), w_vector(100) { for (unsigned int i=0; i < 100; ++i) { draw(); w_vector[i] = r_bound - l_bound; } std::nth_element(w_vector.begin(), w_vector.begin() + w_vector.size()/2, w_vector.end()); double width_estimate = w_vector[w_vector.size()/2]; w = width_estimate/5; jump(x_); } template <class T_PDF, class T_DOMAIN> T_DOMAIN Slicer_Continuous<T_PDF, T_DOMAIN>::draw() { // y = U(*R) * plpdf(x); ly = plpdf(x) - EXPO(*R); step_out(); while(true) { x_new = l_bound + (U(*R) * std::abs(r_bound - l_bound)); ly_new = plpdf(x_new); if ((ly_new > ly) && (x_new > min) && (x_new < max)) break; else { if (x_new <= x) { l_bound = x_new; } else { r_bound = x_new; } } } x = x_new; return x; } template <class T_PDF, class T_DOMAIN> void Slicer_Continuous<T_PDF, T_DOMAIN>::step_out() { l_bound = x - w * U(*R); r_bound = l_bound + w; int j = std::floor(m * U(*R)); int k = (m-1) - j; while ((j>0) && ly < plpdf(l_bound) && (min < l_bound)) { l_bound = l_bound - w; j = j - 1; } while ((k>0) && ly < plpdf(r_bound) && (max > r_bound)) { r_bound = r_bound + w; k = k - 1; } } template <class T_PDF, class T_DOMAIN> void Slicer_Continuous<T_PDF, T_DOMAIN>::jump(T_DOMAIN x_) { if ( (x_ > min) && (x_ < max)) x = x_; } #endif
true
4a23a1f676f943285129f504dceee739da63f2c7
C++
jackjoynson/MedicalImaging
/ImageReconstruction/ITERATIVECOINC/Cone.h
UTF-8
1,084
2.96875
3
[]
no_license
#ifndef Cone_h #define Cone_h class Cone { private: double _StartX, _StartY, _StartZ; double _DirectionX, _DirectionY, _DirectionZ; double _HalfAngle; public: Cone(double startX, double startY, double startZ, double directionX, double directionY, double directionZ, double halfAngle); double GetStartX() { return _StartX; } double GetStartY() { return _StartY; } double GetStartZ() { return _StartZ; } double GetDirectionX() { return _DirectionX; } double GetDirectionY() { return _DirectionY; } double GetDirectionZ() { return _DirectionZ; } double GetHalfAngle() { return _HalfAngle; } void SetStartX(double startX) { _StartX = startX; } void SetStartY(double startY) { _StartY = startY; } void SetStartZ(double startZ) { _StartZ = startZ; } void SetDirectionX(double dirX) { _DirectionX = dirX; } void SetDirectionY(double dirY) { _DirectionY = dirY; } void SetDirectionZ(double dirZ) { _DirectionZ = dirZ; } void SetHalfAngle(double halfAngle) { _HalfAngle = halfAngle; } }; #endif
true
5443bc32de6a6d4e67e4f2708b3e8fa2d01f8e98
C++
BearPolarny/ComplexNumbers
/ComplexNumbers/ComplexNumber.h
UTF-8
778
2.890625
3
[]
no_license
#pragma once #include <iostream> #include <string> static int count; class ComplexNumber { public: ComplexNumber(); ComplexNumber(double _real, double _imaginary); ComplexNumber(double _real); //ComplexNumber(std::string _str); ComplexNumber(const ComplexNumber &COther); ~ComplexNumber(); ComplexNumber operator + (ComplexNumber &COther); ComplexNumber operator - (ComplexNumber &COther); ComplexNumber operator * (ComplexNumber &COther); ComplexNumber operator / (ComplexNumber &COther); ComplexNumber &operator = (ComplexNumber &COther); friend std::ostream &operator << (std::ostream &out, ComplexNumber &COther); friend std::istream &operator >> (std::istream &out, ComplexNumber &COther); bool isZero(); private: double dReal; double dImaginary; };
true
ee6971ae8222822ac8fe3b04268ae859639020d2
C++
tanzfisch/IH
/src/game/GameLayer.h
UTF-8
3,207
2.578125
3
[]
no_license
#ifndef __GAMELAYER_H__ #define __GAMELAYER_H__ #include "Plane.h" class HUDLayer; class GameLayer : public iLayer { public: /*! init members */ GameLayer(iWindow *window, int32 zIndex); /*! does nothing */ virtual ~GameLayer() = default; /*! sets the hud layer so it's content can be controled by the game layer \param hudLayer the hud layer */ void setHud(HUDLayer *hudLayer); private: /*! the main view */ iView _view; /*! main scene */ iScene *_scene = nullptr; /*! handle to hud layer */ HUDLayer *_hudLayer = nullptr; /*! noise function to generate terrain */ iPerlinNoise _perlinNoise; /*! flag to control wether or not controls are active */ bool _activeControls = true; /*! light position */ iNodeTransform *_lightTranslate = nullptr; /*! light direction */ iNodeTransform *_lightRotate = nullptr; /*! light */ iNodeLight *_lightNode = nullptr; /*! voxel terrain */ iVoxelTerrain *_voxelTerrain = nullptr; Plane *_plane = nullptr; /*! instancing material for vegetation etc */ iMaterialID _materialWithInstancing = iMaterial::INVALID_MATERIAL_ID; /*! skybox material */ iMaterialID _materialSkyBox = iMaterial::INVALID_MATERIAL_ID; /*! flush models task */ iTaskID _taskFlushModels = iTask::INVALID_TASK_ID; /*! flush textures task */ iTaskID _taskFlushTextures = iTask::INVALID_TASK_ID; void playerCrashed(); void playerLanded(); void onVoxelDataGenerated(iVoxelBlockPropsInfo voxelBlockPropsInfo); void onGenerateVoxelData(iVoxelBlockInfo *voxelBlockInfo); void onRenderOrtho(); void registerHandles(); void unregisterHandles(); void initViews(); void initScene(); void initPlayer(); void initVoxelData(); void deinitVoxelData(); /*! called when model was loaded */ void onModelReady(iNodeID nodeID); /*! init */ void onInit() override; /*! deinit */ void onDeinit() override; /*! called on application pre draw event */ void onPreDraw() override; /*! called on any other event */ void onEvent(iEvent &event) override; /*! called when key was pressed \param event the event to handle */ bool onKeyDown(iEventKeyDown &event); /*! called when key was released \param event the event to handle */ bool onKeyUp(iEventKeyUp &event); /*! handles mouse key down event \param event the mouse key down event \returns true if consumed */ bool onMouseKeyDownEvent(iEventMouseKeyDown &event); /*! handles mouse key up event \param event the mouse key up event \returns true if consumed */ bool onMouseKeyUpEvent(iEventMouseKeyUp &event); /*! handles mouse move event \param event the mouse move event \returns true if consumed */ bool onMouseMoveEvent(iEventMouseMove &event); /*! handles mouse wheel event \param event the mouse wheel event \returns true if consumed */ bool onMouseWheelEvent(iEventMouseWheel &event); }; #endif // __GAMELAYER_H__
true
10cfabb0ad77a185d5624ac17efaca346dd5e80c
C++
grishavanika/bittorrent_client
/src/bencoding/include/bencoding/be_parse_utils.h
UTF-8
2,208
2.609375
3
[ "MIT" ]
permissive
#pragma once #include <bencoding/be_element_ref.h> #include <bencoding/be_errors.h> #include <small_utils/utils_string.h> #include <type_traits> namespace be { template<typename T> outcome::result<const T*> ElementRefAs(const ElementRef& e); template<typename T> outcome::result<T*> ElementRefAs(ElementRef& e); outcome::result<std::uint64_t> ParseAsUint64(const std::string_view& n); template<typename T> outcome::result<const T*> ElementRefAs(const ElementRef& e) { if constexpr (std::is_same_v<StringRef, T>) { if (auto v = e.as_string()) { return outcome::success(v); } return outcome::failure(ParseErrorc::NotString); } else if constexpr (std::is_same_v<IntegerRef, T>) { if (auto v = e.as_integer()) { return outcome::success(v); } return outcome::failure(ParseErrorc::NotInteger); } else if constexpr (std::is_same_v<ListRef, T>) { if (auto v = e.as_list()) { return outcome::success(v); } return outcome::failure(ParseErrorc::NotList); } else if constexpr (std::is_same_v<DictionaryRef, T>) { if (auto v = e.as_dictionary()) { return outcome::success(v); } return outcome::failure(ParseErrorc::NotDictionary); } } template<typename T> outcome::result<T*> ElementRefAs(ElementRef& e) { outcome::result<const T*> r = ElementRefAs<T>(const_cast<const ElementRef&>(e)); if (r) { return outcome::success(const_cast<T*>(r.value())); } return outcome::failure(r.error()); } inline outcome::result<std::uint64_t> ParseAsUint64(const std::string_view& n) { std::uint64_t v = 0; if (ParseLength(n, v)) { return outcome::success(v); } return outcome::failure(ParseErrorc::InvalidInteger); } } // namespace be
true
f2c446f1d6948ebbad4b7091ca6a1632d5f57d78
C++
xuguocong/LeetCodeAnswer
/leetCodemianshi/48.cpp
UTF-8
1,355
3.71875
4
[]
no_license
// 48. 旋转图像 // 给定一个 n × n 的二维矩阵表示一个图像。 // 将图像顺时针旋转 90 度。 // 说明: // 你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。 // 示例 1: // 给定 matrix = // [ // [1,2,3], // [4,5,6], // [7,8,9] // ], // 原地旋转输入矩阵,使其变为: // [ // [7,4,1], // [8,5,2], // [9,6,3] // ] // 示例 2: // 给定 matrix = // [ // [ 5, 1, 9,11], // [ 2, 4, 8,10], // [13, 3, 6, 7], // [15,14,12,16] // ], // 原地旋转输入矩阵,使其变为: // [ // [15,13, 2, 5], // [14, 3, 4, 1], // [12, 6, 8, 9], // [16, 7,10,11] // ] #include<iostream> #include<unordered_map> #include<vector> #include<string> #include<algorithm> using namespace std; class Solution { public: void rotate(vector<vector<int>>& matrix) { int n = matrix.size(); for(int i = 0; i < (n+1) / 2; ++i) { for(int j = 0; j < n/2; ++j) { int temp = matrix[i][j]; matrix[i][j] = matrix[n-j-1][i]; matrix[n-j-1][i] = matrix[n-i-1][n-j-1]; matrix[n-i-1][n-j-1] = matrix[j][n-i-1]; matrix[j][n-i-1] = temp; } } } }; int main() { Solution test; return 0; }
true
895ab60748a164eee575a378048253a4c62d5b27
C++
Ritzing/Algorithms-2
/InsertionSort/C++/insertion_sort.cpp
UTF-8
1,113
4.28125
4
[ "Apache-2.0" ]
permissive
/* * @author Abhishek Datta * @github_id abdatta * @since 15th October, 2017 * * The following algroithm takes a list of numbers * and sorts them using the insertion sort algorithm. */ #include <iostream> using namespace std; // function to swap two numbers void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } // function to perform insertion sort void insertion_sort(int *a, int n) { for (int i = 1; i < n; i++) // iterating over all the elements { int j = i; // j denotes the final position of the current element, which is initialised to the current position while (j > 0 && a[j-1] > a[j]) // shift j until it is in the correct position { swap(a[j], a[j-1]); // swap with the shifted element j--; } } } // main function to try the algorithm int main() { int n; // number of elements to be read cin>>n; int *a = new int[n]; // reading a list of unsorted numbers for (int i = 0; i < n; ++i) cin>>a[i]; insertion_sort(a, n); // sorting the list // printing the sorted list for (int i = 0; i < n; ++i) cout<<a[i]<<' '; cout<<endl; return 0; }
true
454ba1a020e41d9a0daf3db818a6f8aae47ae4b5
C++
TanVD/SpbSU-Homeworks
/1_year/1_term/9/9-1/main.cpp
UTF-8
1,798
3.3125
3
[]
no_license
#include <iostream> #include <fstream> #include "stringATD.h" #include "rabin-carp.h" int main() { char fileFirstLocation[100]; char fileSecondLocation[100]; std::cout << "This program will create file which contain idenctical lines of two chosen files"; std::cout << "Enter location of first file: "; std::cin >> fileFirstLocation; std::cout << "Enter location of second file: ";\ std::cin >> fileSecondLocation; FILE* text1 = fopen(fileFirstLocation, "r"); FILE* text2 = fopen(fileSecondLocation, "r"); if (text1 == nullptr || text2 == nullptr) { std::cout << "Didn't find your file"; return 1; } StringATD* firstTextString = createStringATD(text1); StringATD* secondTextString = createStringATD(text2); std::ofstream out("newText.txt"); int indexFirst = 0; for (int i = 0; i < lengthOfString(firstTextString); i++) { if ((indexElement(firstTextString, i) == '\n') || (i == lengthOfString(firstTextString) - 1)) { int length = i - indexFirst + 1; StringATD* stringForSearch = subString(firstTextString, indexFirst, length); if (rabinCarp(secondTextString, stringForSearch)) { char* outArray = transformToChar(stringForSearch); for (int i = 0; i < lengthOfString(stringForSearch) - 1; i++) { out << outArray[i]; } out << '\n'; delete[] outArray; } deleteString(stringForSearch); indexFirst = i + 1; } } deleteString(firstTextString); deleteString(secondTextString); out.close(); fclose(text1); fclose(text2); std::cout << "File created"; return 0; }
true
502cf68161c17ba21aa75830498b9144a0abe81c
C++
swrni/simple_gui
/Common/Common.cpp
ISO-8859-3
2,265
2.984375
3
[ "MIT" ]
permissive
#include "Common.hpp" #include <iostream> #include <algorithm> // std::remove_if, ... void TrimString( std::wstring& str, const std::wstring& cs_to_save ) { str.erase( std::remove_if( std::begin( str ), std::end( str ), [&cs_to_save]( const wchar_t& c ){ return cs_to_save.find( c ) == std::wstring::npos; } ), std::end( str ) ); } #include "Shlwapi.h" // For PathFileExists #pragma comment( lib, "Shlwapi.lib" ) // For PathFileExists void CleanPath( std::wstring& path ) { static const std::wstring alphabets( L"abcdefghijklmnopqrstuvwxyz" ); static const std::wstring c_alphabets( L"ABCDEFGHIJKLMNOPQRSTUVWXYZ" ); static const std::wstring nums( L"0123456789" ); static const std::wstring specials( L"+-_.:/\\ ()" ); static const std::wstring characters = alphabets + c_alphabets + nums + specials; TrimString( path, characters ); } bool FindPath( std::wstring& path ) { wchar_t buffer[ MAX_PATH+1 ] = {0}; const auto chars_copied = GetFullPathName( path.c_str(), MAX_PATH, buffer, nullptr ); if ( chars_copied == 0 ) return false; path = std::wstring( buffer, chars_copied ); /*if ( PathIsRelative( path.c_str() ) == TRUE ) { wchar_t buffer[ MAX_PATH+1 ] = {0}; const auto chars_copied = GetFullPathName( path.c_str(), MAX_PATH, buffer, nullptr ); if ( chars_copied == 0 ) return false; path = std::wstring( buffer, chars_copied ); }*/ /*if ( PathFileExists( path.c_str() ) ) return true; wchar_t buffer[ MAX_PATH+1 ] = {0}; const auto chars_copied = GetFullPathName( path.c_str(), MAX_PATH, buffer, nullptr ); if ( chars_copied == 0 ) return false; path = std::wstring( buffer, chars_copied );*/ return ( PathFileExists( path.c_str() ) == TRUE ); } bool FindAndCleanPath( std::wstring& path ) { CleanPath( path ); return FindPath( path ); } void ToLower( std::wstring& str ) { std::transform( std::begin( str ), std::end( str ), std::begin( str ), ::tolower ); } void PrintItems( const std::vector<std::wstring>& items ) { std::wcout << L"Item count: " << items.size() << L"\n"; /*for ( const auto& item : items ) { std::wcout << item << L"\n"; }*/ for ( int i=0; i<items.size(); ++i ) { std::wcout << items[i] << L'\n'; } }
true
e05260964866f6ca79ab135dfe045add6416402e
C++
KimBoWoon/HomeWork
/Visual Studio 2013/Projects/Binary_Search_Tree/Binary_Search_Tree/Binary_Search_Tree_Main.cpp
UTF-8
1,022
3.140625
3
[]
no_license
// HW 2 : Binary Search Tree // Name : // Student ID : //#include "hw2.h" //#include "lab.hpp" #include "Binary_Search_Tree.cpp" int cnt = 0; int main() { BinaryST<Item> bst; // a binary search tree of type Item while (1) { cerr << "BST > "; string command; cin >> command; // cout << command << " "; if (command.compare("quit") == 0) { break; } else if (command.compare("ins") == 0) { int key; char val; cin >> key >> val; if (bst.Insert(Item(key, val)) == false) cout << "Key Updated" << endl; } else if (command.compare("del") == 0) { int key; cin >> key; if (bst.Delete(Item(key)) == false) cout << "Cannot Delete, Non Existing Key" << endl; } else if (command.compare("get") == 0) { int key; cin >> key; Item p = bst.Get(Item(key)); if (p.key == -1) cout << "Non Existing Key" << endl; else cout << "Item " << p.key << " " << p.val << endl; } // show the current binary search tree bst.Show(); } cerr << endl; return 1; }
true
dff3accf8faf7fc3757e0747994c52b2e82953ee
C++
dawagner/libstructure
/examples/parameter-framework/exportValue.cpp
UTF-8
4,425
2.5625
3
[ "BSD-3-Clause" ]
permissive
/* * Copyright (c) 2016, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "export.hpp" #include "structure/functions.hpp" #include "structure/type/stock.hpp" #include <string> using namespace structure; class PfwTagVisitor : public structure::StructureVisitor { public: PfwTagVisitor(std::ostringstream &out, bool open) : mResult(out), mOpen(open) {} void visit(const structure::Block &) override { // This could never happen because it has been taken care of by the structure visitor. throw std::runtime_error("Trying to get a block's atomic value, which makes no sense."); } void visit(const structure::GenericField &) override { throw std::runtime_error("Trying to serialize an unsupported type."); } void visit(const structure::Integer &i) override { if (mOpen) { mResult << "<IntegerParameter Name=\"" + i.getName() + "\" Size=\"" << i.getSize() << "\" Signed=\"" << std::boolalpha << i.getSignedness() << "\">"; } else { mResult << "</IntegerParameter>"; } } void visit(const structure::FloatingPoint &f) override { if (mOpen) { mResult << "<FloatingPointParameter Name=\"" + f.getName() + "\" Size=\"32\">"; } else { mResult << "</FloatingPointParameter>"; } } void visit(const structure::FixedQ &q) override { if (not q.getSignedness()) { throw std::runtime_error( "The Parameter Framework does not support unsigned Q numbers."); } if (mOpen) { mResult << "<FixedPointParameter Name=\"" + q.getName() + "\" Size=\"" << q.getSize() << "\" Integral=\"" << q.getIntegral() << "\" Fractional=\"" << q.getFractional() << "\">"; } else { mResult << "</FixedPointParameter>"; } } std::ostringstream &mResult; bool mOpen; }; std::string exportValue(const StructureValue &value) { PfwValueVisitor visitor; value.accept(visitor); return visitor.mResult.str(); } static auto tab = [](int level) { return std::string(4 * level, ' '); }; void PfwValueVisitor::visit(const BlockValue &block) { mResult << tab(mLevel) << "<ParameterBlock Name=\"" << block.getName() << "\">\n"; mLevel++; for (const auto &field : block.getFields()) { field->accept(*this); } mLevel--; mResult << tab(mLevel) << "</ParameterBlock>\n"; } void pushTag(std::ostringstream &out, bool open, const Structure &type) { PfwTagVisitor tagVisitor(out, open); type.accept(tagVisitor); } void PfwValueVisitor::visit(const GenericFieldValue &value) { mResult << tab(mLevel); pushTag(mResult, true, value.getStructure()); mResult << value.getValue(); pushTag(mResult, false, value.getStructure()); mResult << std::endl; }
true
86544f70dbc3cd8810bebc40927d7004b702ca08
C++
frblazquez/ACA
/Homework3/kernels/kernel4/kernel4_test.cpp
UTF-8
776
2.921875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include "kernel4.h" int main() { int input_array[ARRAY_SIZE], output_array[ARRAY_SIZE], index[ARRAY_SIZE], offset; offset = rand()%35; for(int i = 0; i < ARRAY_SIZE; i++ ) { input_array[i] = rand()%16; output_array[i] = input_array[i]; index[i] = rand()%16; } kernel4(output_array, index, offset); for(int i=offset+1; i<ARRAY_SIZE-1; i++) { input_array[offset] = input_array[offset]-index[i]*input_array[i]+index[i]*input_array[i+1]; } for(int i = 0; i < ARRAY_SIZE; i++) { if(input_array[i] != output_array[i]) { printf("Test failed !!!\n"); return i; } } printf("Test passed !\n"); return 0; }
true
d777c3fb5813e082aacfb1ab0c7987b01f0a72d2
C++
kim-ae/cad_tool
/src/main.cpp
UTF-8
6,052
3.3125
3
[]
no_license
#include <cstdlib> #include <list> #include "aagReader.h" #include "aigBuilder.h" using namespace std; typedef enum{ READ_FILE, CREATE_XOR, CREATE_AND_OR_GATE, STATISTICS, SHOW, EXIT, BACK, INVALID }options; options stringToEnum(string option){ if(option == "statistics") return STATISTICS; if(option == "read file") return READ_FILE; if(option == "create xor") return CREATE_XOR; if(option == "create a+bc") return CREATE_AND_OR_GATE; if(option == "show") return SHOW; if(option == "exit") return EXIT; if(option == "back") return BACK; return INVALID; } void showMenu1(); void showMenu2(); int main() { Aig* aig = NULL; bool outerContinue = true; bool fileContinue = true; bool continueAction = true; string choice; while(outerContinue){ while(fileContinue){ showMenu1(); cout<<"Choose one (i.e. read file): "; getline(cin, choice); switch(stringToEnum(choice)){ case CREATE_XOR:{ string aigName; aig = new Aig(); cout << "Aig name: "; cin >> aigName; aig->setName(aigName); aig->createInputs(2); AigNode* out = AigBuilder::buildXor(aig, aig->getInputs()); AndNode* outCast = (AndNode*)out; aig->createOutputs(out, outCast->isNaturalInverted()); cout << "Xor2 created." << endl; cout << "Aig " << aig->getName() << " created." << endl; fileContinue = false; continueAction = true; break; } case READ_FILE:{ string fileName; cout << "Relative path: "; cin >> fileName; AAGReader reader(fileName); aig = reader.readFile(); fileContinue = false; continueAction = true; cout << "File " << fileName << " read." << endl; cout << "Aig " << aig->getName() << " created." << endl; break; } case CREATE_AND_OR_GATE:{ string aigName; aig = new Aig(); cout << "Aig name: "; cin >> aigName; aig->setName(aigName); aig->createInputs(3); AigNode* out = AigBuilder::buildAplusBC(aig, aig->getInputs()); AndNode* outCast = (AndNode*)out; aig->createOutputs(out, outCast->isNaturalInverted()); fileContinue = false; continueAction = true; cout << "Aig " << aig->getName() << " created." << endl; break; } case EXIT:{ continueAction = false; fileContinue = false; outerContinue = false; break; } case INVALID: default: cout << "Essa escolha não existe" << endl; } cin.sync(); } while(continueAction){ showMenu2(); cout<<"Choose one: "; getline(cin, choice); switch(stringToEnum(choice)){ case STATISTICS:{ aig->AIGStatistics(); cout << "press enter to continue." << endl; cin.ignore(256, '\n'); break; } case SHOW:{ aig->showAIG(); cout << "press enter to continue." << endl; cin.ignore(256, '\n'); break; } case BACK:{ continueAction = false; fileContinue = true; break; } case EXIT:{ outerContinue = false; continueAction = false; break; } case INVALID: default: cout << "Essa escolha não existe" << endl; } cin.sync(); } } return 0; } void showMenu1(){ cout << "#############################################################" << endl; cout << "### \033[33mread file\033[0m: Read the aig from a file given by the user ###" << endl; cout << "### \033[33mcreate xor\033[0m: Create a xor ###" << endl; cout << "### \033[33mcreate a+bc\033[0m: Create a a+bc gate ###" << endl; cout << "### \033[31mexit\033[0m: Exit the system ###" << endl; cout << "#############################################################" << endl; } void showMenu2(){ cout << "#############################################################" << endl; cout << "### \033[33mstatistics\033[0m: Display the critical path for each ###" << endl; cout << "### input-output pair and the critical path to###" << endl; cout << "### the aig ###" << endl; cout << "### \033[33mshow\033[0m: Show each node with the respectives inputs and ###" << endl; cout << "### outputs ###" << endl; cout << "### \033[32mback\033[0m: Go back to the aig read part ###" << endl; cout << "### \033[31mexit\033[0m: Exit the system ###" << endl; cout << "#############################################################" << endl; }
true
51288f459f91570e2214a04163d6955bf06674b2
C++
pial08/Practice
/practice1.cpp
UTF-8
3,024
3.046875
3
[]
no_license
#include <stdio.h> #include <iostream> #include <vector> #include <cstring> #include <limits.h> #include <algorithm> using namespace std; vector<vector<vector<bool> > > dp; vector<int> res; vector<int> original; int total_size; bool possible(int index, int sum, int sz) { if (sz == 0) return (sum == 0); if (index >= total_size) return false; if (dp[index][sum][sz] == false) return false; if (sum >= original[index]) { res.push_back(original[index]); if (possible(index + 1, sum - original[index], sz - 1)) { cout << original[index] << " "; return true; } res.pop_back(); } if (possible(index + 1, sum, sz)) return true; return dp[index][sum][sz] = false; } bool subarraypartition(vector <int> arr, int len, int sum, int limit) { //cout << "limit " << limit << endl; if(limit == 0) { if(sum == 0) cout << "sum found in limit\n"; return (sum == 0); } if(sum == 0) { //counter++; cout << "sum found\n"; return true; } if(len == 0 && sum != 0) return false; if(arr[len - 1] > sum) return subarraypartition(arr, len - 1, sum, limit); else { bool a, b; a = subarraypartition(arr, len - 1, sum, limit); b = subarraypartition(arr, len - 1, sum - arr[len - 1], limit - 1); if(b) { cout << arr[len - 1] << endl; //temp.push_back(arr[len - 1]); } return a || b; } } int calculate(vector <int> v, int len, int sum, int limit) { if(limit == 0) { //cout << endl; return (sum == 0); } /*if(sum == 0) { cout << endl; return 1; } */ if(sum != 0 && len == 0) return 0; if(v[len - 1] > sum) return calculate(v, len - 1, sum, limit); else { int a = calculate(v, len - 1, sum, limit); int b = calculate(v, len - 1, sum - v[len - 1], limit - 1); if(b) { cout << v[len - 1] << " "; } return a + b; } } int main() { original = {47, 14, 30, 19, 30, 4, 32, 32, 15, 2, 6, 24}; int limit = 4; sort(original.begin(), original.end(), greater<int>()); int total_sum = 0; for(int i = 0; i < original.size(); i++) { cout << original[i] << " "; total_sum += original[i]; } cout << endl; /*total_size = original.size(); sort(original.begin(), original.end()); int total_sum = 0; for(int i = 0; i < original.size(); i++) { cout << original[i] << " "; total_sum += original[i]; } cout << endl; cout << total_size << endl; dp.resize(original.size(), vector<vector<bool> > (total_sum + 1, vector<bool> (total_size, true))); possible(0, 85, limit); */ subarraypartition(original, original.size(), 85, limit); //int r = bombs(v, v.size(), R); // cout << endl << r << endl; }
true
fa239edcb01b26d4985385a03be36e4f2d35d7ac
C++
peeyuuec/intern
/interleaving_arrays.cpp
UTF-8
722
3.640625
4
[]
no_license
#include<iostream> #include<cstring> using namespace std; void join(char *arr1,char *arr2,int depth1,int depth2,char *temp,int current){ int length1=strlen(arr1); int length2=strlen(arr2); if(length1+length2!=0){ if(current==length1+length2){ cout<<temp<<endl; } else{ if(depth1<length1){ temp[current]=arr1[depth1]; temp[current+1]='\0'; join(arr1,arr2,depth1+1,depth2,temp,current+1); } if(depth2<length2){ temp[current]=arr2[depth2]; temp[current+1]='\0'; join(arr1,arr2,depth1,depth2+1,temp,current+1); } } } else cout<<"Empty array not allowed"<<endl; } int main(){ char arr1[100],arr2[100],temp[100]; cin>>arr1>>arr2; join(arr1,arr2,0,0,temp,0); return 0; }
true
0cdd790aa675f99d134203c5ad0c42cf6ef73166
C++
elianalien/nature-of-code-cinder
/chapter03/Example2/src/Mover.cpp
UTF-8
1,275
2.59375
3
[]
no_license
/* * Mover.cpp * Example2 * * Created by Nathan Koch on 1/5/13 * Copyright 2013 __MyCompanyName__. All rights reserved. * */ #include "cinder/app/AppBasic.h" #include "cinder/Color.h" #include "cinder/Rand.h" #include "Mover.h" using namespace ci; using namespace ci::app; using namespace std; Mover::Mover( float m, float x , float y ) { mMass = m; mLocation = Vec2f( x, y ); mVelocity = Vec2f( randFloat( -1.0, 1.0 ), randFloat( -1.0, 1.0 ) ); mAcceleration = Vec2f( 0.0, 0.0 ); mAngle = 0; mAVelocity = 0; mAAcceleration = 0; } void Mover::applyForce( Vec2f force ) { Vec2f f = force / mMass; mAcceleration += f; } void Mover::update() { mVelocity += mAcceleration; mLocation += mVelocity; mAAcceleration = mAcceleration.x / 10.0; mAVelocity += mAAcceleration; mAVelocity = constrain( mAVelocity, -0.1f, 0.1f ); mAngle += toDegrees(mAVelocity); mAcceleration *= 0; } void Mover::draw() { float w = mMass*16; Rectf rect = Rectf( -w/2, -w/2, w/2, w/2 ); glPushMatrix(); gl::translate( mLocation ); gl::rotate( mAngle ); // draw solid gl::color( ColorA8u::gray( 175, 200 ) ); gl::drawSolidRect( rect ); // draw outline glLineWidth( 2.0 ); gl::color( Color::black() ); gl::drawStrokedRect( rect ); glPopMatrix(); }
true
9cd9b9a996c32b439dc9d0063d9f136db1ca1c95
C++
Michal-Stempkowski/isGCS
/cyk_table.h
UTF-8
4,322
2.640625
3
[]
no_license
#include "cuda_all_helpers.h" #include "preferences.h" #if !defined(CYK_TABLE_H) #define CYK_TABLE_H class cyk_table { public: enum info : int { replicated = 1, not_enough_space = 2 }; CCM cyk_table(const int block_id_, const char* source_code_localization_, int* prefs_, int* table_, int* table_header_); CCM ~cyk_table(); CCM int size() const; CCM int depth() const; CCM int get_number_of_symbols_in_cell(int row, int col); CCM int get_symbol_at(int row, int col, int pos); CCM int add_symbol_to_cell(int row, int col, int symbol); CCM int get_row_coord_for_thread(int thread_id, int current_row, int current_col); CCM int get_starting_col_coord_for_thread(int thread_id); CCM int get_coord_col_for_thread(int thread_id, int current_row, int current_col); private: const int block_id; const int number_of_blocks; const char* source_code_localization; const int size_; const int depth_; int* prefs; int* table; int* table_header; CCM int set_symbol_at(int row, int col, int pos, int val); }; CCM cyk_table::cyk_table(const int block_id_, const char* source_code_localization_, int* prefs_, int* table_, int* table_header_) : block_id(block_id_), number_of_blocks(preferences(block_id_, source_code_localization_).get(prefs_, preferences::number_of_blocks)), source_code_localization(source_code_localization_), prefs(prefs_), table(table_), table_header(table_header_), size_(preferences(block_id_, source_code_localization_).get(prefs_, preferences::sentence_length)), depth_(preferences(block_id_, source_code_localization_).get(prefs_, preferences::max_symbols_in_cell)) { } CCM cyk_table::~cyk_table() { } CCM int cyk_table::size() const { return size_; } CCM int cyk_table::depth() const { return depth_; } CCM int cyk_table::get_number_of_symbols_in_cell(int row, int col) { return table_get(table_header, generate_absolute_index( block_id, number_of_blocks, row, size(), col, size())); } CCM int cyk_table::get_symbol_at(int row, int col, int pos) { return table_get(table, generate_absolute_index( block_id, number_of_blocks, row, size(), col, size(), pos, get_number_of_symbols_in_cell(row, col))); } CCM int cyk_table::set_symbol_at(int row, int col, int pos, int val) { //log_debug("block_id=%d, row=%d, col=%d, pos=%d, val=%d\n", block_id, row, col, pos, val); return table_set(table, generate_absolute_index( block_id, number_of_blocks, row, size(), col, size(), pos, depth()), val); } CCM int cyk_table::add_symbol_to_cell(int row, int col, int symbol) { int symbols_in_cell = get_number_of_symbols_in_cell(row, col); for (int i = 0; i < symbols_in_cell; ++i) { if (get_symbol_at(row, col, i) == symbol) { return info::replicated; } } if (symbols_in_cell >= depth()) { return info::not_enough_space; } int result = set_symbol_at(row, col, symbols_in_cell, symbol); if (result == error::no_errors_occured) { result = table_set(table_header, generate_absolute_index( block_id, number_of_blocks, row, size(), col, size()), symbols_in_cell + 1); return result; } return result; } CCM int cyk_table::get_row_coord_for_thread(int thread_id, int current_row, int current_col) { int number_of_threads = preferences(block_id, AT).get(prefs, preferences::number_of_threads); int margin = size() - current_row; int active_threads = min(number_of_threads, margin); if (thread_id >= active_threads) { return error::index_out_of_bounds; } return current_row + (current_col + active_threads) / margin; } CCM int cyk_table::get_starting_col_coord_for_thread(int thread_id) { return thread_id < size() ? thread_id : error::index_out_of_bounds; } CCM int cyk_table::get_coord_col_for_thread(int thread_id, int current_row, int current_col) { int number_of_threads = preferences(block_id, AT).get(prefs, preferences::number_of_threads); int margin = size() - current_row; int active_threads = min(number_of_threads, margin); //log_debug("thread_id=%d, current_row=%d, current_col=%d, number_of_threads=%d, size()=%d, margin=%d, active_threads=%d occured!\n", // thread_id, current_row, current_col, number_of_threads, size(), margin, active_threads); if (thread_id >= active_threads) { return error::index_out_of_bounds; } return (current_col + active_threads) % margin; } #endif
true
78263b0b719cfa22beb22952922d19752ce1856c
C++
oshiroscope/KHR-Segway-PC
/command_gen.cpp
UTF-8
1,715
2.703125
3
[]
no_license
#include "command_gen.hpp" std::vector<unsigned char> CommandGen::SeriesServoMove(std::map<int, int> dest, int frame) { int cnt = dest.size(); unsigned char size = (unsigned char)(8 + 2 * cnt + 1); std::vector<unsigned char> cmd((int)size); cmd[0] = size; cmd[1] = 0x10; cmd[7] = (unsigned char)frame; int select_index = 2; int dest_index = 8; int servo_cnt = 0; for(auto i : dest) { int quot = (int)(i.first / 8); int offset = i.first % 8; cmd[select_index + quot] += (unsigned char)(0x01 << offset); cmd[dest_index + servo_cnt * 2] = i.second & 0xFF; cmd[dest_index + servo_cnt * 2 + 1] = i.second >> 8; servo_cnt++; } unsigned char sum = 0; for(int i = 0; i < (int)size - 1; i++) { sum += cmd[i]; } cmd[size - 1] = sum; return cmd; } std::vector<unsigned char> CommandGen::SetFree(int id) { int size = 9; std::vector<unsigned char> cmd(size); cmd[0] = (unsigned char)size; cmd[1] = 0x00; cmd[2] = 0b00000010; // literal -> ram unsigned int addr = 0x044 + 20 * id + 6; cmd[3] = addr & 0xFF; cmd[4] = addr >> 8; cmd[5] = 0x00; cmd[6] = 32767 & 0xFF; cmd[7] = 32767 >> 8; cmd[8] = 0x00; for(int i = 0; i < size - 1; i++) { cmd[8] += cmd[i]; } return cmd; } std::vector<unsigned char> CommandGen::PlayMotion(std::vector<unsigned char> addr) { int size = 7; std::vector<unsigned char> cmd(size); cmd[0] = (unsigned char)size; cmd[1] = 0x0C; cmd[2] = addr[0]; cmd[3] = addr[1]; cmd[4] = addr[2]; cmd[5] = 0x00; cmd[6] = 0x00; for(int i = 0; i < size - 1; i++) { cmd[6] += cmd[i]; } return cmd; }
true
f14ccf0203b310ffcc5ebf7a9c12a337a8c4fa0f
C++
egortrue/NeVK
/src/engine/core/commands/commands.h
UTF-8
2,598
2.578125
3
[]
no_license
#pragma once // Внутренние библиотеки #include "core.h" #include "resources/resources.h" class Core; class Commands { public: Core::Manager core; explicit Commands(Core::Manager); ~Commands(); //========================================================================= // Области выделения командных буферов public: VkCommandPool createCommandBufferPool(bool shortLived = false); void resetCommandBufferPool(VkCommandPool); // Сбросит все буферы, сохранит все ресурсы void freeCommandBufferPool(VkCommandPool); // Сбросит все буферы, освободит все ресурсы (вернёт их системе) void destroyCommandBufferPool(VkCommandPool); // Уничтожет пул и все буферы, освободит все ресурсы (вернёт их системе) //========================================================================= // Выделенные командные буферы VkCommandBuffer createCommandBuffer(VkCommandPool); void resetCommandBuffer(VkCommandBuffer); // Сбросит буфер, сохранит ресурсы void freeCommandBuffer(VkCommandBuffer); // Сбросит буфер, освободит ресурсы (вернёт их в пул) void destroyCommandBuffer(VkCommandPool, VkCommandBuffer); // Уничтожет буфер, освободит ресурсы (вернёт их в пул) //========================================================================= // Единовременные командные буферы VkCommandPool singleTimeCommandBufferPool; VkCommandBuffer beginSingleTimeCommands(); void endSingleTimeCommands(VkCommandBuffer); //========================================================================= // Общие операции над ресурсами // Копирование в памяти устройства void copyBuffer(VkCommandBuffer, VkBuffer src, VkBuffer dst, VkDeviceSize size); void copyBufferToImage(VkCommandBuffer, VkBuffer src, VkImage dst, uint32_t width, uint32_t height); // Перевод из памяти приложения в память устройства void copyDataToBuffer(void* src, VkBuffer dst, VkDeviceSize size); void copyDataToImage(void* src, VkImage dst, VkDeviceSize size, uint32_t width, uint32_t height); void changeImageLayout(VkCommandBuffer, VkImage, VkImageLayout oldLayout, VkImageLayout newLayout); };
true
4deb7f7bffc90d883a666a2f90e9c4425b80c3fc
C++
YnPagani/Learning-Cpp
/section20/function_templates/src/main.cpp
UTF-8
1,097
3.859375
4
[]
no_license
#include <iostream> #include <string> template <typename T> T min(T a, T b){ return (a < b) ? a : b; } template <typename T1, typename T2> void func(T1 a, T2 b){ std::cout << a << " " << b << std::endl; } struct Person{ std::string name; int age; // necessary since the compiler doesn't know how to compare two Person obj bool operator<(const Person &rhs){ return (this->age) < (rhs.age); } }; std::ostream& operator<<(std::ostream &os, const Person &obj){ os << obj.name << " " << obj.age; return os; } int main(){ std::cout << min<int>(2,3) << std::endl; std::cout << min(2,3) << std::endl; std::cout << min('A','B') << std::endl; std::cout << min(12.3,39.2) << std::endl; std::cout << min(5+2*2,7+40) << std::endl; Person p1{"Ronald", 50}; Person p2{"Dudi", 32}; Person p3 = (p1 < p2) ? p1 : p2; std::cout << p3 << std::endl; func<int, int>(10, 20); func(10,20); func<char, double>('A', 12.4); func(2000, "testing"); func(1000, std::string("Frank")); return 0; }
true
f6caf12c638a9f02f8b81f933117081f5a9d05af
C++
marcelomata/competitive-programming-1
/UVA/AdHoc/MutantFlatworldExplorers.cpp
UTF-8
2,256
3.046875
3
[]
no_license
#include<stdio.h> #include<iostream> #include<cstring> #include<string> bool visited [52] [52]; int x,y,row,col; char dir; bool pos; using namespace std; void update (char n){ if ( dir == 'S' && n == 'R' ) dir = 'W'; else if ( dir == 'S' && n == 'L' ) dir = 'E'; else if ( dir == 'N' && n == 'R' ) dir = 'E'; else if ( dir == 'N' && n == 'L' ) dir = 'W'; else if ( dir == 'E' && n == 'R' ) dir = 'S'; else if ( dir == 'E' && n == 'L' ) dir = 'N'; else if ( dir == 'W' && n == 'R' ) dir = 'N'; else if ( dir == 'W' && n == 'L' ) dir = 'S'; if ( n == 'F' ) { switch ( dir ) { case 'N' : if ( row == y && visited[x][y]) break; else if ( row == y && !visited[x][y]) { visited[x][y] = 1; cout<<x<<" "<<y<<" "<<dir<<" LOST"<<endl; pos = 1; break; } y++; break; case 'S' : if ( y == 0 && visited[x][y]) break; else if ( y == 0 && !visited[x][y]) { visited[x][y] = 1; cout<<x<<" "<<y<<" "<<dir<<" LOST"<<endl; pos = 1; break; } y--; break; case 'E' : if ( col == x && visited[x][y]) break; else if ( col == x && !visited[x][y]) { visited[x][y] = 1; cout<<x<<" "<<y<<" "<<dir<<" LOST"<<endl; pos = 1; break; } x++; break; case 'W' : if ( x == 0 && visited[x][y]) break; else if ( x == 0 && !visited[x][y]) { visited [x][y] = 1; cout<<x<<" "<<y<<" "<<dir<<" LOST"<<endl; pos = 1; break; } x--; } } } int main (){ memset(visited,0,sizeof(visited)); cin>>col>>row; while ( cin>>x>>y>>dir) { string s; cin>>s; pos = 0; for ( int i = 0; s[i] && !pos; i++)update (s[i]); if (!pos) cout<<x<<" "<<y<<" "<<dir<<endl; } return 0; }
true
b4877e09d3d04e1c17ff0aaa8b5a562dda8b8264
C++
tapasjain/SDPOR
/event_buffer.hh
UTF-8
1,914
2.515625
3
[]
no_license
#ifndef __EVENT_BUFFER_H__ #define __EVENT_BUFFER_H__ #ifdef __GNUC__ #include <ext/hash_map> using __gnu_cxx::hash_map; using __gnu_cxx::hash; #else #include <hash_map> #endif #include <utility> #include <string> #include "inspect_util.hh" #include "inspect_event.hh" #include "program_state.hh" using std::pair; using std::string; /** * the socket index at the scheduler's side */ class SchedulerSocketIndex { public: SchedulerSocketIndex(); ~SchedulerSocketIndex(); typedef hash_map<int, Socket*, hash<int> >::iterator iterator; inline iterator begin() { return sockets.begin(); } inline iterator end() { return sockets.end(); } Socket * get_socket( int fd ); Socket * get_socket_by_thread_id(int tid); Socket * get_socket(InspectEvent &); void add(Socket * socket); void update(int thread_id, Socket*); void remove(int fd); void remove_sc_fd(int fd); void remove(Socket * socket); void clear(); bool has_fd(int fd); public: hash_map<int, Socket*, hash<int> > sockets; hash_map<int, Socket*, hash<int> > tid2socket; }; class EventBuffer { public: typedef hash_map<int, InspectEvent>::iterator iterator; public: EventBuffer(); ~EventBuffer(); bool init(string socket_file, int time_out, int backlog); void reset(); void close() { server_socket.close(); } void collect_events(); inline bool has_event(int tid); InspectEvent get_the_first_event(); InspectEvent get_event(int tid); InspectEvent receive_event(Socket * socket); pair<int,int> set_read_fds(); void approve(InspectEvent & event); inline bool is_listening_socket(int fd); string toString(); public: ServerSocket server_socket; SchedulerSocketIndex socket_index; Socket * sc_socket; // the socket to connect with the state-capturing thread fd_set readfds; hash_map<int, InspectEvent> buffer; }; #endif
true
5432cb0762972d20a6d1865b7afcbe74473e8279
C++
s-valentin/Laboratoare-POO
/Exercitii jmekere/Lab3 OOP/Math.cpp
UTF-8
1,550
3.171875
3
[]
no_license
#include "Math.h" #include <stdarg.h> int Math::Add(int nr1, int nr2) { return nr1 + nr2; } int Math::Add(int nr1, int nr2, int nr3) { return nr1 + nr2 + nr3; } int Math::Add(double nr1, double nr2) { double sum = nr1 + nr2; return (int)sum; } int Math::Add(double nr1, double nr2, double nr3) { double sum = nr1 + nr2 + nr3; return (int)sum; } int Math::Mul(int nr1, int nr2) { return nr1 * nr2; } int Math::Mul(int nr1, int nr2, int nr3) { return nr1 * nr2 * nr3; } int Math::Mul(double nr1, double nr2) { double prod = nr1 * nr2; return (int)prod; } int Math::Mul(double nr1, double nr2, double nr3) { double prod = nr1 * nr2 * nr3; return (int)prod; } int Math::Add(int count,...) { int i, value, sum=0; va_list v1; va_start(v1, count); for (i = 0; i < count; i++) { value = va_arg(v1, int); sum += value; } va_end(v1); return sum; } char* Math::Add(const char* p1, const char* p2) { if (p1 == nullptr || p2 == nullptr) return nullptr; else { int lungime=0, i, k=0; for (i = 0; p1[i] != '\0'; i++) // strlen(p1) lungime++; for (i = 0; p2[i] != '\0'; i++) // strlen(p2) lungime++; char *total = new char[lungime+1]; // alocare spatiu de lungime + 1 caractere; // Type * nume = new Type - aloca spatiu pentru un element; // Type * nume = new Type[elemente] - basically un vector; // delete si delete[]; for (i = 0; p1[i] != '\0'; i++) { total[k] = p1[i]; k++; } for (i = 0; p2[i] != '\0'; i++) { total[k] = p2[i]; k++; } total[k] = '\0'; return total; } }
true
138e468eec5474ec2e17c6e0e28b724636d82f7d
C++
mytlsdnkr/algo
/complete/9461/9461.cpp
UTF-8
454
2.90625
3
[]
no_license
#include <iostream> using namespace std; int main(){ long triangle[101]; int testcase; int length; int i; cin>>testcase; triangle[1]=1; triangle[2]=1; triangle[3]=1; triangle[4]=2; for(i=5;i<=100;i++){ triangle[i]=triangle[i-3]+triangle[i-2]; } for(i=0;i<testcase;i++){ cin>>length; if(length<1 || length>100) return 0; cout<<triangle[length]<<endl; } return 0; }
true
cad8ba8d9a0439c0a0744e53721b20f9e5b0b95d
C++
seidyizawa/programacao-avancada
/prova1/main.cpp
UTF-8
1,821
3.3125
3
[]
no_license
#include "vetorint.h" #include "data.h" #include <iostream> using namespace std; int main(){ VetorInt v1(4),v2(4),escalar(4),soma(4),sub(4),v3(4); v1.setValor(0,2); v1.setValor(1,5); v1.setValor(2,8); v1.setValor(3,4); v3.setValor(0,2); v3.setValor(1,5); v3.setValor(2,8); v3.setValor(3,4); v2.setValor(0,8); v2.setValor(1,4); v2.setValor(2,2); v2.setValor(3,1); cout << "Vetores" << endl; cout << "V1 = "; v1.imprime(); cout << "V2 = "; v2.imprime(); cout << endl << "Soma" <<endl; cout << "V1 + V2 = "; soma = v1 + v2; soma.imprime(); cout << endl << "Subtracao" <<endl; cout << "V1 - V2 = "; sub = v1 - v2; sub.imprime(); cout << endl << "Produto Interno" << endl; cout << "V1 * V2 = " << v1*v2 << endl; cout << endl << "Multiplicacao por escalar" << endl; cout << "V1 * 4 = "; escalar = v1 * 4; escalar.imprime(); cout << endl << "Soma" << endl; cout << "V2 += V1 = "; v2 += v1; v2.imprime(); cout << endl << "Subtracao" << endl; cout << "V2 -= V2 = "; v2 -= v1; v2.imprime(); cout << endl << "Multiplicacao por escalar" << endl; cout << "V2 * 4 = "; v2 *= 4; v2.imprime(); cout << endl << "Teste de igualdade" << endl; if(v1==v3){ v1.imprime(); v3.imprime(); cout << "sao iguais" << endl <<endl; } cout << endl << "Valor" << endl; v1.imprime(); cout << "V1[1] = " << v1[1] << endl; cout << "V1(1) = " << v1(1) << endl << endl; Data tamanho1000[1000]; cout << "Datas de Janeiro" << endl; for(int i = 1;i<32;i++){ tamanho1000[i] = Data(i,1,2020); tamanho1000[i].imprime(); } return 0; }
true
f9d050c254a6f1dd3cec6c8b6e32b420b7f828a5
C++
nitsas/pareto-approximator
/DifferentDimensionsException.h
UTF-8
1,694
3.25
3
[]
no_license
/*! \file DifferentDimensionsException.h * \brief The declaration and definition of the DifferentDimensionsException * exception class. * \author Christos Nitsas * \date 2012 */ #ifndef DIFFERENT_DIMENSIONS_EXCEPTION_H #define DIFFERENT_DIMENSIONS_EXCEPTION_H #include <exception> /*! * \weakgroup ParetoApproximator Everything needed for the Pareto set approximation algorithms. * @{ */ //! The namespace containing everything needed for the Pareto set approximation algorithms. namespace pareto_approximator { //! The namespace containing all the exception classes. namespace exception_classes { /*! * \brief Exception thrown when two instances have different/incompatible * dimensions. * * An exception thrown when: * - Two Point instances were supposed to be compared but they have * different dimensions. (they belong to spaces of different dimensions) * - We were trying to compute the ratio distance between two Point * instances or a Point instance and a Facet instance but they * had different dimensions. (they belong to spaces of different * dimensions) * - We were trying to initialize a Facet from a given set of * n Point instances but not all the Point instances had dimension n. * (they belong to spaces of different dimensions) */ class DifferentDimensionsException : public std::exception { public: //! Return a simple char* message. const char* what() const throw() { return "The given instances have different/incompatible dimensions."; } }; } // namespace exception_classes } // namespace pareto_approximator /*! @} */ #endif // DIFFERENT_DIMENSIONS_EXCEPTION_H
true
409a1114c0e1945a1cccc1bcf0ade66b9d9b8ce2
C++
vital228/Algorithm
/sportprog1/sportprog1/Handle.cpp
UTF-8
509
2.71875
3
[]
no_license
#include<stack> #include<queue> #include<deque> #include<map> #include<set> #include<string> #include<numeric> #include<iostream> using namespace std; int main() { map<string, string> m; int n; cin >> n; for (int i = 0; i < n; i++) { string a, b; cin >> a >> b; if (m.find(a) != m.end()) { m[b] = m[a]; m.erase(a); } else { m[b] = a; } } cout << m.size() << endl; for (auto it = m.begin(); it != m.end(); it++) { auto p = *it; cout << p.second << " " << p.first << endl; } }
true
f08908dc9bd144c9e8c6ee83fd831d12fa7a4288
C++
Mashiatmm/Offlines
/2-1/Data Structure & Algorithms Part 1/Offline 7/statistics.cpp
UTF-8
4,186
3.046875
3
[]
no_license
#include<cstdio> #include<iostream> #include<ctime> #include<chrono> using namespace std; void Merge(int a[],int l,int mid,int h){ int n1=mid-l+1; int n2=h-mid; int L[n1],H[n2]; for(int i=0;i<n1;i++){ L[i]=a[l+i]; } for(int i=0;i<n2;i++){ H[i]=a[l+n1+i]; } int i=0,j=0,k=l; while(i<n1&&j<n2){ if(L[i]<H[j]){ a[k]=L[i]; i++; } else{ a[k]=H[j]; j++; } k++; } while(i<n1){ a[k]=L[i]; i++; k++; } while(j<n2){ a[k]=H[j]; j++; k++; } } void MergeSort(int a[],int l,int h){ if(l>=h) return; int mid=(l+h)/2; MergeSort(a,l,mid); MergeSort(a,mid+1,h); Merge(a,l,mid,h); } int partition(int a[],int l,int h){ int pivot=a[h],start=l; for(int i=l;i<h;i++){ if(a[i]<=pivot){ int temp=a[start]; a[start]=a[i]; a[i]=temp; start++; } } int temp=a[start]; a[start]=pivot; a[h]=temp; return start; } void QuickSort(int a[],int l,int h){ if(l>=h) return; int mid=partition(a,l,h); QuickSort(a,l,mid-1); QuickSort(a,mid+1,h); } int main(){ int s[]={10,100,500,1000,2000,5000}; srand(time(0)); int turn,n; for(int i=0;i<6;i++){ if(s[i]<=1000) turn=1000; else turn=100; n=s[i]; double time_taken=0,time_taken_2=0,time_taken_best=0,time_taken_best_2=0,time_taken_worst=0,time_taken_worst_2=0; int array[n],array2[n],array3[n],array4[n]; for(int i=0; i<turn; i++) { for(int i=0; i<n; i++) { array[i]=rand()%100000; array2[i]=array[i]; } //Random Case auto start=chrono::high_resolution_clock::now(); MergeSort(array,0,n-1); auto end=chrono::high_resolution_clock::now(); time_taken+=chrono::duration_cast<chrono::microseconds>(end - start).count(); start=chrono::high_resolution_clock::now(); QuickSort(array2,0,n-1); end=chrono::high_resolution_clock::now(); time_taken_2+=chrono::duration_cast<chrono::microseconds>(end - start).count(); //Ascending Case start=chrono::high_resolution_clock::now(); MergeSort(array,0,n-1); end=chrono::high_resolution_clock::now(); time_taken_best+=chrono::duration_cast<chrono::microseconds>(end - start).count(); start=chrono::high_resolution_clock::now(); QuickSort(array2,0,n-1); end=chrono::high_resolution_clock::now(); time_taken_best_2+=chrono::duration_cast<chrono::microseconds>(end - start).count(); //Descending Case for(int i=0; i<n; i++) { array3[i]=array[n-1-i]; array4[i]=array3[i]; } start=chrono::high_resolution_clock::now(); MergeSort(array3,0,n-1); end=chrono::high_resolution_clock::now(); time_taken_worst+=chrono::duration_cast<chrono::microseconds>(end - start).count(); start=chrono::high_resolution_clock::now(); QuickSort(array4,0,n-1); end=chrono::high_resolution_clock::now(); time_taken_worst_2+=chrono::duration_cast<chrono::microseconds>(end - start).count(); } time_taken/=turn; time_taken_2/=turn; time_taken_best/=turn; time_taken_best_2/=turn; time_taken_worst/=turn; time_taken_worst_2/=turn; cout<<"n: "<<n<<endl; cout<<"Merge Sort: "<<endl<<time_taken<<" microseconds(Average Case)"<<endl<<time_taken_best<<" microseconds(Ascending Case)"<<endl; cout<<time_taken_worst<<" microseconds(Descending Case)"<<endl<<endl; cout<<"Quick Sort: "<<endl<<time_taken_2<<" microseconds(Average Case)"<<endl<<time_taken_best_2<<" microseconds(Ascending Case)"<<endl; cout<<time_taken_worst_2<<" microseconds(Descending Case)"<<endl<<endl; cout<<endl; } }
true
22f6724a82d308889b96c4c3907fc2e75f63f30d
C++
madisoncooney/HPR_Titan
/NoFAT/Arduino Code/HPDF/HPDF.h
UTF-8
1,902
2.515625
3
[ "MIT" ]
permissive
/* Test.h - Test library for Wiring - description Copyright (c) 2006 John Doe. All right reserved. */ // ensure this library description is only included once #ifndef HPDF_h #define HPDF_h //Library includes #include "Arduino.h" //Define baseclock in millis #define HPDF_BCLK 50 /// /// Data structure classes /// class HPDF_t_FrameData { public: byte A; byte B; byte C; byte D; HPDF_t_FrameData(int posneg,int exponent,int significand1,int significand2,int significand3,int significand4,int significand5,int significand6,int channel); }; class HPDF_t_float { public: int sign; int exponent; int significand1; int significand2; int significand3; int significand4; int significand5; int significand6; HPDF_t_float(float f); }; /// /// Library definition /// class HPDF { public: static void sendPacket(byte control,HPDF_t_FrameData data,Stream *port); static int val(char c); static int toDeci(char *str,int base); static byte decimalToNibble(int n); static byte joinNibble(byte n1, byte n2); static byte joinNibbleStream(byte n1, byte n2); static byte generateControl(char *sensorN, int feedN); static void sendFrame(byte data,Stream &port); static void sendFrameTerminator(Stream &port); }; //Sensor class class HPDF_Sensor { public: char* id; bool enabled; void (*apiRead)(); //Sensor.apiRead = &somefunction; ,, Function defined by sensor OEM that reads data from sensor int freq; //Hz int wait; HPDF_Sensor(char* identification, int frequency); }; //Feed class class HPDF_Feed { public: int id, channel; char* sensorID; float (*source)(); //Feed.source = &somefunction; ,, Function defined by us that returns a single float from an apiFeed read byte controlStream; Stream &port; HPDF_Feed(char *parentID, int identification, byte controlByte, Stream &desiredPort); void transmit(); }; #endif
true
40730493cf97d22a92eafedbd50212fa7c54aea4
C++
fanofxiaofeng/cpp
/jobdu/1058/main.cpp
UTF-8
225
2.703125
3
[]
no_license
#include <iostream> #include <cstdio> using namespace std; char cs[5]; int main(){ while(scanf("%s", cs) > 0){ swap(cs[0], cs[3]); swap(cs[1], cs[2]); printf("%s\n", cs); } return 0; }
true
5d5949b0a1e37681713b9b7afc6e3822f38f7aa7
C++
webturing/ACM-1
/按 OJ 分类/51Nod/f-51Nod-1574-排列转换/f-51Nod-1574-排列转换/main.cpp
UTF-8
975
2.609375
3
[]
no_license
// // main.cpp // f-51Nod-1574-排列转换 // // Created by ZYJ on 2017/5/19. // Copyright ? 2017年 ZYJ. All rights reserved. // #include <cstdio> #include <algorithm> using namespace std; typedef long long ll; const int MAXN = 2e5 + 10; int A[MAXN]; int B[MAXN]; bool vis[MAXN]; int abs(int a) { return a < 0 ? -a : a; } int main () { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", A + i); } int b; for (int i = 1; i <= n; i++) { scanf("%d", &b); B[b] = i; } for (int i = 1; i <= n; i++) { A[i] = B[A[i]]; } ll ans = 0; for (int i = 1; i <= n; i++) { if (vis[i]) { continue; } ll sum = 0; for (int j = i; !vis[j]; j = A[j]) { sum += abs(j - A[j]); vis[j] = true; } ans += sum / 2; } printf("%lld\n", ans); return 0; }
true
42e8014dc3547d078cfca887654f362e6aae0af9
C++
mapsiva/network-master
/t3/Httpd.cpp
UTF-8
2,763
2.578125
3
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/wait.h> #include <sys/signal.h> #include "Httpd.h" #include "Util.h" #include "FileManager.h" #include "Mime.h" #include "Thread.h" #include "Config.h" Httpd::Httpd(int modo, int qtd_t, int port) { _modo = modo; _qtd_threads = qtd_t; _port = port; Config::Config(); } void * Httpd::Kill_Defuncts() { int status; while (wait3(&status, WNOHANG, (struct rusage *) 0) > 0) { //printf("matando defuntos\n"); } return 0; } int Httpd::PassiveTCPSocket() { struct sockaddr_in sin; int sockd, reusage = 1; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons((u_short)_port); if ((sockd = socket(PF_INET, SOCK_STREAM, 0)) < 0) perror_exit("Socket error"); setsockopt(sockd, SOL_SOCKET, SO_REUSEADDR, &reusage, sizeof(reusage)); if (bind(sockd, (struct sockaddr *)&sin, sizeof(sin)) < 0) perror_exit("Bind error"); if (listen(sockd, _QLEN) < 0) perror_exit("Listen error"); return sockd; } void Httpd::Start() { Run(); } void Httpd::Run() { int msock; /* master socket descriptor */ int ssock; /* slave socket descriptor */ unsigned int alen; /* from-address length */ struct sockaddr_in fsin; /* address of a client */ pid_t ppid; /* id of process */ msock = PassiveTCPSocket(); printf("Server Running.\n"); Thread ** Pool = new Thread*[_qtd_threads]; int I= 0; while(1) { alen = sizeof(struct sockaddr_in); ssock = accept(msock, (struct sockaddr *)&fsin,(socklen_t *) &alen); if (ssock < 0) perror_exit("Error Accept: "); char *queryString; char bc[1024]; read(ssock, bc, sizeof(bc)); queryString = strtok (bc, " "); queryString = strtok (NULL, " "); FileManager *f = new FileManager(queryString, &ssock); //Verificando o tipo de funcionamento do Servidor HTTP if (_modo == _HTTP_PROCESS) { ppid = fork(); if (ppid == -1) perror_exit("Error Process:"); else if (ppid == 0) { //interpreta o sinal SIGCHLD //Tem que ver pq não está funfando signal(SIGCHLD,(sighandler_t)Httpd::Kill_Defuncts); close(msock); f->Write(); delete f; close(ssock); exit(1); } else close(ssock); } else { if(Thread::_Instances >= _qtd_threads) printf("Pool Overflow \n"); else { Pool[(I%_qtd_threads)+1] = new Thread(f, &ssock); Pool[(I%_qtd_threads)+1]->Start(NULL); I++; } } //_modo == _HTTP_THREAD } }
true
b8d57010c9e6c47382f194af795ec761242f44f7
C++
ThomasMillard123/Mario
/MarioV1/MarioV1/GameScreenManager.cpp
UTF-8
1,206
2.75
3
[]
no_license
#include "GameScreenManager.h" #include"GameScreen.h" #include"GameScreenLevel1.h" #include"GameScreenLevel2.h" GameScreenManager::GameScreenManager(SDL_Renderer* renderer, SCREENS startScreen) { mRenderer = renderer; mCurrentScreen= NULL; ChangeScreen(startScreen); } void GameScreenManager::Render() { mCurrentScreen->Render(); } void GameScreenManager::Update(float deltaTime, SDL_Event e) { mCurrentScreen->Update(deltaTime, e); } void GameScreenManager::ChangeScreen(SCREENS newScreen) { if (mCurrentScreen != NULL) { delete mCurrentScreen; } GameScreenLevel1* tempScreen; GameScreenLevel2* tempScreen1; switch (newScreen) { case SCREEN_INTRO: break; case SCREEN_MENU: break; case SCREEN_LEVEL1: tempScreen = new GameScreenLevel1(mRenderer); mCurrentScreen = (GameScreen*)tempScreen; tempScreen = NULL; break; case SCREEN_LEVEL2: tempScreen1 = new GameScreenLevel2(mRenderer); mCurrentScreen = (GameScreen*)tempScreen1; tempScreen1 = NULL; break; case SCREEN_GAMEOVER: break; case SCREEN_HIGHSCORES: break; default: break; } } GameScreenManager::~GameScreenManager() { mRenderer = NULL; delete mCurrentScreen; mCurrentScreen = NULL; }
true
5b1539794d25e5ddd1504251408c8982b83a0603
C++
crasmu75/Dont-Byte-Me-Bro
/Server/spreadsheetSession/spreadsheetSession.h
UTF-8
1,752
2.84375
3
[]
no_license
#include <string> #include <vector> #include <queue> #include <map> #include <stack> #include "workItem.h" #include "cell.h" #include<vector> #include "../DependencyGraph/DependencyGraph.h" #include <mutex> //This class creates a spreadsheet session. The session should //be responsible for spinning all the new threads necessary for incoming //users to the session. It ensures non blocking asynchronous communication //between the users and the server, by putting each new socket on a thread. //A queue is used to process commands, and a stack is used to keep track of //previous commands for undo. The cellContentsMap holds the contents of all //the cells in the spreadsheet. class spreadsheetSession { private: std::mutex *queueLock; std::string spreadsheetName; //Holds all information about cells in the spreadsheet std::map<std::string,std::string> cellContentsMap; //Used to process request std::queue<workItem::workItem*> sessionQueue; //used to process undo std::stack<cell::cell*> sessionStack; //used to keep track of all active sockets std::vector<int> socketFDs; //keeps track of circular dependencies between cells DependencyGraph::DependencyGraph dependencyGraph; //List of all active spreadsheetSessions std::vector<spreadsheetSession*> *spreadsheetSessions; bool closed; bool active; public: spreadsheetSession(std::string, std::vector<std::string>*, std::mutex*, std::vector<spreadsheetSession::spreadsheetSession*>*); spreadsheetSession(const spreadsheetSession &other); ~spreadsheetSession(); std::string getspreadsheetName(); void enqueue(workItem::workItem*); void dequeue(workItem::workItem*); void addSocketFD(int); std::mutex* getQueueLock(); bool isClosed(); };
true
596344f41f60fd52c5aed160c3593e3d168f4929
C++
SenKetZu/FinalLaboratorio2
/Gameplay.cpp
UTF-8
4,166
2.609375
3
[]
no_license
#include "Gameplay.h" #include "Joystick.h" #include "ElementoConTexto.h" Gameplay::Gameplay() { } void Gameplay::pause() { sf::RectangleShape pauseBackground; pauseBackground.setSize(Render::getInstance().getSize()); pauseBackground.setFillColor(sf::Color(50, 50, 50, 2)); _cancion.playMusic(false); ElementoConTexto a; std::vector<ElementoConTexto> menu;// = { std::string("Continuar"),std::string("Salir") }; menu.push_back(a); menu.push_back(a); menu[0].setNombreCancion("Continuar"); menu[1].setNombreCancion("Salir"); menu[0].setAltura((Render::getInstance().getSize().y / 2) - 60); menu[1].setAltura((Render::getInstance().getSize().y / 2) + 60); while (_estadoActual == Pausa) { Render::getInstance().handleEvents(); showMenuPause(menu, pauseBackground); for (int i = 0; i < 2;++i) { if (menu[i].isSelected()) { menu[i].highlight(true); if (Joystick::getInstance().checkClick()) { switch (i) { case 0: _estadoActual = ESTADOSJUEGO::Jugando; _cancion.playMusic(true); return; break; case 1: _estadoActual = ESTADOSJUEGO::Terminado; return; break; default: break; } } } else { menu[i].highlight(false); } } if (Joystick::getInstance().checkTeclado()[0] == Pause) { _estadoActual = Gameplay::Jugando; _cancion.playMusic(true); } } } bool Gameplay::check(KEYS tecla) { bool isCorrect = false; isCorrect = _trast.isNoteColliding(_cancion.getNotas(tecla)); return isCorrect; } void Gameplay::initSong(){ //ciclo donde se ejecutara la cancion setConfig(); _estadoActual = ESTADOSJUEGO::Jugando; gameLoop(); } void Gameplay::setConfig() { _cancion.SetCancionOsu(); _cancion.getSonido().setVolume(15); _cancion.getSonido().setLoop(false); _cancion.getSonido().play(); } void Gameplay::gameLoop() { _tic = 0; while (_estadoActual!=Terminado) { if (_tic == 61) { _tic = 0; } Render::getInstance().handleEvents(); process(); switch (_estadoActual) { case Gameplay::Jugando: //entrada inputs(); break; case Gameplay::Pausa: pause(); break; case Gameplay::Terminado: break; default: break; } //dibujado show(); ++_tic; } } void Gameplay::process() { if (_cancion.isFinished()) { _estadoActual = Terminado; } } void Gameplay::inputs() { _teclaPulsada = Joystick::getInstance().checkTeclado(); for (KEYS tecla : _teclaPulsada) { switch (tecla) { case Blue:case Green:case Red:case Orange: if (check(tecla)) { Render::getInstance().actualizarPuntaje(); } break; case Pause: _estadoActual = Pausa; break; default: break; } } } void Gameplay::show() { Render::getInstance().clear().mostrarFondo().dibujar(_trast.getTrast()); Render::getInstance().actualizarNotas(_cancion.getCancionNotas()).mostrarPuntaje(); Render::getInstance().display(); } void Gameplay::showMenuPause(std::vector<ElementoConTexto>& ele, sf::RectangleShape pauseBackground) { Render::getInstance().clear(); Render::getInstance().dibujar(pauseBackground); Render::getInstance().dibujar(ele[0].getElements()); Render::getInstance().dibujar(ele[1].getElements()); Render::getInstance().display(); }
true