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
b8d6ecc095f43a58a4882dae4123a693d8fe66de
C++
CloverTinTin/CppPrimerStudy
/chapter_03/vector/Exercise_3_14/readFromCinStoreInVector.cpp
UTF-8
258
3.109375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { vector<int> Vint; int temp; while(cin >> temp) Vint.push_back(temp); for(decltype(Vint.size()) i = 0; i < Vint.size(); ++i) cout << Vint[i] << " "; cout << endl; return 0; }
true
a9815264941e81720feaf631397da6488ce08be5
C++
vxl/vxl
/contrib/mul/pdf1d/pdf1d_exponential.h
UTF-8
2,812
2.96875
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
// This is mul/pdf1d/pdf1d_exponential.h #ifndef pdf1d_exponential_h #define pdf1d_exponential_h //: // \file // \brief Univariate exponential PDF // \author Tim Cootes #include <iostream> #include <iosfwd> #include <pdf1d/pdf1d_pdf.h> #ifdef _MSC_VER # include <vcl_msvc_warnings.h> #endif //: Class for exponential distributions // $p(x)=\lambda exp(-\lambda x)$ class pdf1d_exponential : public pdf1d_pdf { double lambda_; double log_lambda_; public: //: Dflt ctor (creates exponential distribution in range [0,1]) pdf1d_exponential(); //: Dflt ctor (creates exponential distribution in range [lo,hi]) pdf1d_exponential(double lambda); //: Destructor ~pdf1d_exponential() override; //: Return standard deviation double sd() const { return 1.0/lambda_; } //: Creates exponential distribution with given lambda void set_lambda(double lambda); //: Value of lambda double lambda() const { return lambda_; } //: Create a sampler object on the heap // Caller is responsible for deletion. pdf1d_sampler* new_sampler() const override; //: Probability density at x double operator()(double x) const override; //: Log of probability density at x // This value is also the Normalised Mahalanobis distance // from the centroid to the given vector. double log_p(double x) const override; //: Cumulative Probability (P(x'<x) for x' drawn from the distribution) // Returns 1-exp(-x/lambda) double cdf(double x) const override; //: Return true if cdf() uses an analytic implementation bool cdf_is_analytic() const override; //: Gradient of PDF at x double gradient(double x, double& p) const override; //: Compute threshold for PDF to pass a given proportion double log_prob_thresh(double pass_proportion) const override; //: Compute nearest point to x which has a density above a threshold // If log_p(x)>log_p_min then x returned unchanged. Otherwise x is moved // (typically up the gradient) until log_p(x)>=log_p_min. // \param x This may be modified to the nearest plausible position. // \param log_p_min lower threshold for log_p(x) double nearest_plausible(double x, double log_p_min) const override; //: Version number for I/O short version_no() const; //: Name of the class std::string is_a() const override; //: Does the name of the class match the argument? bool is_class(std::string const& s) const override; //: Create a copy on the heap and return base class pointer pdf1d_pdf* clone() const override; //: Print class to os void print_summary(std::ostream& os) const override; //: Save class to binary file stream void b_write(vsl_b_ostream& bfs) const override; //: Load class from binary file stream void b_read(vsl_b_istream& bfs) override; }; #endif // pdf1d_exponential_h
true
299c12c60c455994b1a480dac6cfceee54905f99
C++
Spourmoafi/Euclid-classification-algorithm-C-implementation
/Table.hpp
UTF-8
1,913
3.046875
3
[]
no_license
#ifndef Table_hpp #define Table_hpp #include <fstream> // // Table.hpp // lab // // Created by Sajid on 11/20/16. // Copyright © 2016 Sajid. All rights reserved. // #include <iostream> #include <sstream> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <algorithm> #include <list> #include <map> using namespace std; class Table{ protected: vector<vector<double>> table_data,std_table;//Represent The main vector in the class double average_column,sample_std_dev,number_of_rows,number_of_columns,current_cell,changed_cell; public: // vector<vector<double>> MainMain; void setTableData(string file_name); void print_table();//1.Populate the table with the data from a CSV file. void print_std_table();//1.Populate the table with the data from a CSV file. double getAverage_column(int column_number);//2.Get the average of a column specified by the user double getSampleStdDevOfColumn(int column_number);//3.Get the corrected sample standard deviation of a column specified by the user. int getNumberOfRows();//4.Get the number of rows in the table int getNumerOfColumns();//5.Get the number of columns in the table. double getCell(int x,int y) ;//6.Get the value of a specific cell in the table. void changeCell(int x_row,int y_col,double new_value);//7.Change the value of a specific cell in the table. void methodStdTable(); //8.Call a method that standardises the data in the table void removeRow(int row_num);//9.Remove a specific row from the table. void removeColumn(int col_num);//10.Remove a specific column from the table. void addRow();//11.Add a column containing numbers to the table. void addColumn();//12.Add a column containing numbers to the table. friend ostream &operator<<(ostream &stream, Table &obj);//13.Add a column containing numbers to the table }; #endif
true
4cb392c689947c96342d945d137efbc9be8d2771
C++
zhaofeng-shu33/tech-chores-archive
/2014/cplusplus_summer/linklist_of_maple.cpp
UTF-8
2,993
3.3125
3
[]
no_license
#include<iostream> #include<cmath> using namespace std; class complex{ public: complex(){ // cout<<"complex0"; } complex(double a, double b) {real=a;img=b;}//?? complex(const complex& c){ real=c.real; img=c.img; //cout<<"complex2"; } ~complex(){ // cout<<"~complex"; } void Input(){ cin>>real>>img; } void Output(){ cout<<real<<"+"<<img<<'i'<<endl; } void Add(complex & c){ real+=c.real; img+=c.img; } void Sub(complex & c){ real-=c.real; img-=c.img; } void Mul(complex & c){ double temp_real=real,temp_img=img; real=temp_real*c.real-temp_img*c.img; img=temp_img+c.real+temp_real*c.img; } void Div(complex & c){ double temp=real*real+img*img,temp_real=real,temp_img=img; real=(temp_real*c.real+temp_img*c.img)/temp; img=(temp_img+c.real-temp_real*c.img)/temp; } double modulus(){ return sqrt(real*real+img*img); } complex operator - ( complex& n1) { // complex temp(real-n1.real,img-n1.img); // return temp; //can not return a temporary unnamed object?? return complex(real-n1.real,img-n1.img); } bool operator ==(const complex& a) const{ if(real==a.real && (img==a.img)) return true; return false; } void operator = (const complex& a) { //assignment real=a.real; img=a.img; } friend istream& operator >>(istream& fin, complex& n1); friend ostream& operator <<(ostream& fout,const complex& n1); complex operator * (complex& n1){ complex tem; tem.real=real*n1.real-img*n1.img; tem.img=real*n1.img+img*n1.real; return tem; } private: double real, img; }; istream& operator >>(istream& fin, complex& n1){ return fin>>n1.real>>n1.img; } ostream& operator <<(ostream& fout, const complex& n1){ fout<<n1.real<<'+'<<n1.img<<'i'; return fout; } struct LinkNode { int data; LinkNode *next; LinkNode(int data, LinkNode *next):data(data),next(next){}; }; struct LinkedList { LinkNode *first; LinkNode *last; int size; LinkedList():size(0){ last = new LinkNode(0, NULL); first = new LinkNode(0, last); } void ListInsert(int data, LinkNode* & node) { // LinkNode *next = node->next; // node->next = new LinkNode(data, next); LinkNode* tem=new LinkNode(data,node->next); node->next=tem; size++; } void ListDeleteNext(LinkNode *node) { LinkNode *tmp = node->next; node->next = node->next->next; delete tmp; size--; } void ListPrint() { LinkNode *tmp = first->next; while (tmp != last) { cout << tmp->data << " "; tmp = tmp->next; } cout << endl; } }; int main() { LinkedList list = LinkedList(); for (int i = 0; i < 10; ++i) { //cout << i << endl; list.ListInsert(i * 3, list.first); } //cout<<list.first->next->next->data<<' '; list.ListPrint(); char ch; cin>>ch; return 0; }
true
184dff1b93aad56f98fe0ab5907f190d81a9328c
C++
Code4fun4ever/pc-code
/solved/i-k/id-codes/idcodes.cpp
UTF-8
401
2.90625
3
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
#include <algorithm> #include <cstdio> #include <cstring> using namespace std; #define MAXLEN 50 char str[MAXLEN + 1]; int len; int main() { while (true) { scanf("%s", str); if (str[0] == '#') break; len = strlen(str); if (next_permutation(str, str + len)) printf("%s\n", str); else puts("No Successor"); } return 0; }
true
301b9cbb5ffe5484d41761ca6c76b9ae97f042f0
C++
pythogeeker/dsalgo
/linked list/kthNodeFromEnd.cpp
UTF-8
1,030
3.625
4
[]
no_license
#include<iostream> using namespace std; struct node { int data; node *next; }; int kthNode(struct node **head, int k) { if (k < 0 || head == NULL) return -1; node *p, *q; p = q = *head; for (int count = 0; count < k; count++) { if (q == NULL) return -1; q = q->next; } while (q) { q = q->next; p = p->next; } return p ? p->data : -1; } void insert(struct node **head, int data) { struct node *newNode = new node(); newNode->data = data; newNode->next = *head; *head = newNode; } void printList(struct node **head) { if (*head == NULL) { cout << "empty " << endl; } for (struct node *temp = *head; temp; temp = temp->next) cout << temp->data << " "; cout << endl; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif struct node *head = NULL; insert(&head, 5); insert(&head, 6); insert(&head, 7); insert(&head, 8); insert(&head, 9); insert(&head, 10); printList(&head); cout << kthNode(&head, 4) << endl; return 0; }
true
0c2bd79856c3273fa702a5f23d005c51c7c41ef6
C++
tylerfunf555/ParsecSoda
/ParsecSoda/Stringer.h
UTF-8
2,778
3.328125
3
[ "MIT" ]
permissive
#pragma once #include <string> #include <cmath> #include <vector> #define STRINGER_MAX_WEIGHT (uint64_t)63 #define STRINGER_MAX_DISTANCE (uint64_t)(-1) #define STRINGER_DISTANCE_CHARS(N) ((uint64_t)1 << (STRINGER_MAX_WEIGHT - N)) #define STRINGER_DEFAULT_MATCH (uint64_t)3 using namespace std; /** * A pack of utility functions for string handling. */ class Stringer { public: /** * Assigns a distance score based on character matching. * @param str1 First string to compare. * @param str2 Second string to compare. */ static const uint64_t fuzzyDistance(const char* str1, const char* str2); /** * Assigns a distance score based on character matching. * @param str1 First string to compare. * @param str2 Second string to compare. */ static const uint64_t fuzzyDistance(string str1, string str2); /** * Returns true if the two strings match all characters (of the shortest one). * @param str First string to compare. * @param pattern Second string to compare. */ static const bool startsWithPattern(const char* str, const char * pattern); /** * Returns true if the two strings match at least some amount of characters. * @param str1 First string to compare. * @param str2 Second string to compare. * @param matches The amount of chars to match. */ static const bool isCloseEnough(const char* str1, const char* str2, uint8_t matches = STRINGER_DEFAULT_MATCH); /** * Returns true if the two strings match at least some amount of characters. * @param str1 First string to compare. * @param str2 Second string to compare. * @param matches The amount of chars to match. */ static const bool isCloseEnough(const string str1, const string str2, uint8_t matches = STRINGER_DEFAULT_MATCH); /** * Converts a whole string to lower case. * @param str The string to be converted. * @return Lower case string. */ static string toLower(const string str); /** * Compares two strings, but ignores case (internally converts both to lower case). * @param a First string. * @param b Second string. * @result Comparison result. */ static int compareNoCase(const string a, const string b); /** * Recursively replaces all occurrences of a pattern in a string with another pattern. * @param source Original string reference to be edited. * @param oldPattern Pattern to be replaced. * @param newPattern Pattern to insert. */ static void replacePattern(string& source, string oldPattern, string newPattern); /** * Non-recursively replaces all occurrences of a pattern in a string with another pattern. * @param source Original string reference to be edited. * @param oldPattern Pattern to be replaced. * @param newPattern Pattern to insert. */ static void replacePatternOnce(string& source, string oldPattern, string newPattern); };
true
0f07d42df0cda163180728a8c6b12b15bac84b28
C++
7haomeng/Sening_Intelligent_System
/07-Robot_Arm_1/catkin_ws/src/sis_arm/src/vis_workspace.cpp
UTF-8
2,103
2.609375
3
[]
no_license
#include <ros/ros.h> #include <visualization_msgs/Marker.h> #include <geometry_msgs/Point.h> #include <geometry_msgs/Vector3.h> #include <std_msgs/ColorRGBA.h> #include <std_msgs/Header.h> #include <cmath> class FK { private: const double _d0 = 0.045, _d1 = 0.06, _a2 = 0.065, _d3 = 0.07; double x_, y_, z_; // Position double j1_, j2_; // Joint values double c1_, s1_, c2_, s2_; double j1_ulimit_ = 2.616, j1_llimit_ = -2.616, j2_ulimit_ = 0.8, j2_llimit_ = -2.0; int count_ = 0; // count points number ros::NodeHandle nh_; ros::Publisher pub_marker_; visualization_msgs::Marker marker_; void make_marker(double x, double y, double z) { marker_.header.frame_id = "base"; marker_.type = visualization_msgs::Marker::POINTS; marker_.action = visualization_msgs::Marker::ADD; geometry_msgs::Point p; p.x = x; p.y = y; p.z = z; std_msgs::ColorRGBA color; color.r = 0; color.g = 1.0; color.b = 0; color.a = 1.0; marker_.scale.x = marker_.scale.y = marker_.scale.z = 0.001; marker_.points.push_back(p); marker_.colors.push_back(color); } public: FK() { pub_marker_ = nh_.advertise<visualization_msgs::Marker>("/workspace", 10); for (j1_ = j1_llimit_; j1_ <= j1_ulimit_; j1_ += 0.03) { for (j2_ = j2_llimit_; j2_ <= j2_ulimit_; j2_ += 0.03) { c1_ = cos(j1_), s1_ = sin(j1_), c2_ = cos(j2_), s2_ = sin(j2_); x_ = -_a2 * s1_ * s2_ - _d3 * s1_ * c2_; y_ = _d1 + _a2 * c2_ - _d3 * s2_; z_ = _d0 - _a2 * c1_ * s2_ - _d3 * c1_ * c2_; make_marker(x_, y_, z_); } ++count_; if(count_%10 == 0) {ROS_INFO("There are %d points now.", count_);} } ROS_INFO("Marker initial comppleted, start publish marker..."); } ~FK() {} void publish_marker() { pub_marker_.publish(marker_); } }; int main(int argv, char** argc) { ros::init(argv, argc, "visualize_workspace_node"); FK fk; ros::Rate r(1); // 1Hz while(ros::ok()) { fk.publish_marker(); r.sleep(); } return 0; }
true
aee765cc42fd844b8e277bd68c72c8e89b95c555
C++
farhanahad/Basic
/(2)increment,decrement.cpp
UTF-8
347
2.765625
3
[]
no_license
#include<iostream> using namespace std; int main() { int x=6; int y=--x; cout<<x<<endl; cout<<y<<endl; int a=8; int b=x--; cout<<a<<endl; cout<<b<<endl; int c=7; int d=++x; cout<<c<<endl; cout<<d<<endl; int e=9; int f=x++; cout<<e<<endl; cout<<f<<endl; }
true
b1692a9338c0c22aafe1dd076e19922e2ccde3bf
C++
ZhaoboDing/RayTracer
/src/model/Material.h
UTF-8
687
2.71875
3
[]
no_license
/** * Author: Zhaobo Ding (me@dingzhaobo.net) */ #ifndef RAYTRACER_MATERIAL_H #define RAYTRACER_MATERIAL_H #include <glm/glm.hpp> class Material { bool transparency; double shine, refl, refr; glm::vec3 kd, ks; public: Material(); Material( glm::vec3 kd, glm::vec3 ks, double shine, double refl = 0, double refr = 0, bool tran = false); Material &operator=(const Material &other); glm::vec3 diffuse() const; glm::vec3 specular() const; double shininess() const; double reflect() const; double refract() const; bool transparent() const; }; #endif //RAYTRACER_MATERIAL_H
true
6ccebf83c1da9c1faf2247c2afeda1c8141ad6f1
C++
slowstone/leetcode
/hard/188 Best Time to Buy and Sell Stock IV/web_test/main.cpp
UTF-8
919
2.875
3
[]
no_license
class Solution { public: int maxProfit(int k, vector<int>& prices) { int n = prices.size(); if (n <= 1) return 0; int maxProfit = 0; if (k >= n / 2) { // if k >= n/2, then you can make maximum number of transactions. for (int i = 1; i < n; i++) { if (prices[i] > prices[i-1]) maxProfit += prices[i] - prices[i-1]; } return maxProfit; } vector<vector<int>> f(k+1, vector<int>(prices.size(), 0)); for (int j = 1; j <= k; ++j) { int tmpMax = f[j-1][0] - prices[0]; for (int i = 1; i < prices.size(); ++i) { f[j][i] = max(f[j][i-1], prices[i] + tmpMax); tmpMax = max(tmpMax, f[j-1][i] - prices[i]); maxProfit = max(f[j][i], maxProfit); } } return maxProfit; } };
true
44061da9f94e22b82554bd605c7bcbeb4de8c0ad
C++
roooodcastro/gamedev-coursework
/Game/Leaderboard.h
UTF-8
1,176
3.359375
3
[ "MIT" ]
permissive
/* * Author: Rodrigo Castro Azevedo * * Description: This class is just a helper to organize the leaderboard. Its purpose is * mainly take a score and check if it will get into the leaderboard, and also loading * and saving the leaderboard to the system. The leaderboard consists of 5 top scores, * and each time a new score higher than one of them is achieved, it will make into the * leaderboard, pushing the lower scores out of it. */ #pragma once #include "ConfigurationManager.h" class Leaderboard { public: ~Leaderboard(void); static Leaderboard *getInstance(); /* * Pushes a new score into the leaderboard. If it's higher than at * least the fifth place, it will replace it. It returns the position * on the leaderboard of the score, or 0 if it wasn't high enough. */ int pushNewScore(int score); /* Returns the score of the requested position, ranging from 1 to 5 */ int getScore(int position); protected: Leaderboard(void); static Leaderboard *instance; /* Update the leaderboard on the file saved to the disk */ void updateFile(); /* Variables to hold the leaderboard values */ int first; int second; int third; int fourth; int fifth; };
true
eb7845fdd48a5e35da16647bd11a7300e5e6d4b3
C++
Nuos/KGLT
/kglt/loaders/opt_loader.h
UTF-8
2,093
2.5625
3
[ "BSD-2-Clause" ]
permissive
#ifndef OPT_LOADER_H #define OPT_LOADER_H #include <map> #include <vector> #include "../types.h" #include "../loader.h" namespace kglt { class SubMesh; namespace loaders { typedef int32_t Offset; class OPTLoader : public Loader { public: OPTLoader(const unicode& filename, std::shared_ptr<std::stringstream> data): Loader(filename, data) {} void into(Loadable& resource, const LoaderOptions& options=LoaderOptions()); private: void read_block(std::istream& file, Offset offset); void process_vertex_block(std::istream& file); void process_texcoord_block(std::istream& file); void process_normal_block(std::istream& file); void process_face_block(std::istream& file); void process_reused_texture_block(std::istream& file); void process_lod_block(std::istream& file); void process_embedded_texture_block(std::istream& file); Offset global_offset; /* Temp Data storage */ std::vector<Vec3> vertices; std::vector<Vec2> texture_vertices; std::vector<Vec3> vertex_normals; struct Texture { std::string name; int32_t width; int32_t height; int32_t bytes_per_pixel; std::vector<uint8_t> data; }; std::vector<Texture> textures; std::string current_texture; std::map<std::string, SubMesh*> texture_submesh; std::map<std::string, TextureID> texture_name_to_id; struct Triangle { Vec3 positions[3]; Vec2 tex_coords[3]; Vec3 normals[3]; Vec3 face_normal; std::string texture_name; }; std::vector<std::vector<Triangle> > triangles; //Triangles for each LOD uint8_t current_lod; }; class OPTLoaderType : public LoaderType { public: unicode name() { return "opt"; } bool supports(const unicode& filename) const { //FIXME: check magic return filename.lower().contains(".opt"); } Loader::ptr loader_for(const unicode& filename, std::shared_ptr<std::stringstream> data) const { return Loader::ptr(new OPTLoader(filename, data)); } }; } } #endif // OPT_LOADER_H
true
2a20e94f7e2146058b218e56c721a62f259c6a04
C++
controlol/project-robotica2021
/vision/headers/place.hpp
UTF-8
1,102
3.484375
3
[]
no_license
#ifndef placeheader #define placeheader #include <iostream> class place { private: /* data */ int x; int y; public: place(int x=0, int y=0); ~place(); int GetX(); int GetY(); void SetX(int); void SetY(int); void ChangeXY(int x, int y); bool operator==(place p1) { if (p1.GetX() == x && p1.GetY() == y) { return (true); } return (false); } bool operator!=(place p1) { if (p1.GetX() != x || p1.GetY() != y) { return (true); } return (false); } friend std::ostream& operator<<(std::ostream& os,place c1) { os<<c1.GetX()<<" "<<c1.GetY(); return os; } place operator+(place p1) { place temp; temp.SetX(p1.GetX()+x); temp.SetY(p1.GetY()+y); return (temp); } place operator-(place p1) { place temp; temp.SetX(x-p1.GetX()); temp.SetY(y-p1.GetY()); return (temp); } }; #endif
true
2e22606618a027528e5629474188cdb4f84731e7
C++
m2ci-msp/mri-shape-tools
/shared_include/image/segmentation/chanvese/ChanVeseDiffusionTensorFieldBuilder.h
UTF-8
2,600
2.515625
3
[ "MIT" ]
permissive
#ifndef __CHAN_VESE_DIFFUSION_TENSOR_FIELD_BUILDER_H__ #define __CHAN_VESE_DIFFUSION_TENSOR_FIELD_BUILDER_H__ #include <cmath> #include <armadillo> #include "image/segmentation/chanvese/ChanVeseSettings.h" #include "image/filter/diffusion/DiffusionTensorField.h" #include "image/ImageCalculus.h" #include "image/ImageData.h" class ChanVeseDiffusionTensorFieldBuilder{ private: DiffusionTensorField tensorField; ImageData& levelSetData; const ImageCalculus calculus; const ChanVeseSettings& settings; public: /*--------------------------------------------------------------------------*/ ChanVeseDiffusionTensorFieldBuilder( ImageData& levelSetData, const ChanVeseSettings& settings ) : // dimensions tensorField( levelSetData.nx, levelSetData.ny, levelSetData.nz, levelSetData.hx, levelSetData.hy, levelSetData.hz ), levelSetData(levelSetData), calculus(levelSetData), // settings settings(settings) { } /*--------------------------------------------------------------------------*/ void update() { update_diffusion_tensors(); } /*--------------------------------------------------------------------------*/ const DiffusionTensorField& get_field() const { return this->tensorField; } /*--------------------------------------------------------------------------*/ private: double compute_regularized_L1_norm(const arma::vec& value) const { // FIXME: 0.0001 is currently hardcoded return sqrt(arma::dot(value, value) + 0.0001); } /*--------------------------------------------------------------------------*/ void update_diffusion_tensors() { for( int i = 0; i < this->levelSetData.nx; ++i) { for( int j = 0; j < this->levelSetData.ny; ++j) { for( int k = 0; k < this->levelSetData.nz; ++k) { const arma::vec gradient = this->calculus.gradient(i, j, k); const double value = 1. / compute_regularized_L1_norm(gradient); this->tensorField.D11.at_grid(i, j, k) = value; this->tensorField.D22.at_grid(i, j, k) = value; this->tensorField.D33.at_grid(i, j, k) = value; this->tensorField.D12.at_grid(i, j, k) = 0.; this->tensorField.D13.at_grid(i, j, k) = 0.; this->tensorField.D23.at_grid(i, j, k) = 0.; } // end for k } // end for j } // end for i } // end update_diffusion_tensors }; #endif
true
4e027649a21a40f18dc557143b3366c32f641b4c
C++
Stomach-ache/Codeforces
/Bayan/B.cpp
UTF-8
1,043
2.640625
3
[]
no_license
/************************************************************************* > File Name: B.cpp > Author: Stomach_ache > Mail: sudaweitong@gmail.com > Created Time: 2014年10月05日 星期日 22时22分39秒 > Propose: ************************************************************************/ #include <cmath> #include <string> #include <cstdio> #include <fstream> #include <cstring> #include <iostream> #include <algorithm> using namespace std; /*Let's fight!!!*/ int n, m; char a[35], b[35]; bool ok(char up, char down, char left, char right) { if (up == down) return false; if (left == right) return false; if (up == '<' && left == '^') return false; if (down == '<' && left == 'v') return false; if (up == '>' && right == '^') return false; if (down == '>' && right == 'v') return false; return true; } int main(void) { scanf("%d%d", &n, &m); scanf("%s%s", a, b); char up = a[0], down = a[n - 1]; char left = b[0], right = b[m - 1]; if (ok(up, down, left, right)) printf("YES\n"); else printf("NO\n"); return 0; }
true
32acaaf3d603ce89346c6e5a749f94c8e339e777
C++
fuersten/sun_ray
/sun_ray/script/objects/ring_pattern.h
UTF-8
2,529
2.5625
3
[ "BSD-3-Clause" ]
permissive
// // ring_pattern.h // sun_ray // // Created by Lars-Christian Fürstenberg on 07.03.20. // Copyright © 2020 Lars-Christian Fürstenberg. All rights reserved. // #pragma once #include <sun_ray/feature/ring_pattern.h> #include <sun_ray/script/objects/color.h> #include <sun_ray/script/objects/pattern.h> namespace sunray { namespace script { class RingPattern : public Pattern { public: RingPattern(MetaClassPtr meta_class, const Color& a, const Color& b) : Pattern(meta_class) , a_{a.color()} , b_{b.color()} { } std::string to_string() const override { return fmt::format("RingPattern"); } sunray::PatternPtr pattern() const override { return std::make_shared<sunray::RingPattern>(a_, b_, trans_.matrix()); } private: sunray::Color a_; sunray::Color b_; }; class RingPatternMetaClass : public PatternMetaClass { public: RingPatternMetaClass() = default; const std::string& name() const override { static const std::string name = "RingPattern"; return name; } void init(sunray::script::FunctionRegistry& registry) override { auto self = std::dynamic_pointer_cast<RingPatternMetaClass>(shared_from_this()); registry.add_variadic_function("RingPattern_constructor", [self](const std::vector<Variant>& parameter) { if (parameter.size() != 2) { throw std::runtime_error{ fmt::format("Plane constructor called with wrong parameter count. Should be 2, but is {}.", parameter.size())}; } return self->construct(as_class(parameter[0]), as_class(parameter[1])); }); registry.add_function("RingPattern_scale", scale); registry.add_function("RingPattern_shear", shear); registry.add_function("RingPattern_translate", translate); registry.add_function("RingPattern_rotate_x", rotate_x); registry.add_function("RingPattern_rotate_y", rotate_y); registry.add_function("RingPattern_rotate_z", rotate_z); } std::shared_ptr<RingPattern> construct(const sunray::script::MutableClassPtr& color_a, const sunray::script::MutableClassPtr& color_b) const { return std::make_shared<RingPattern>(shared_from_this(), cast_object<Color, ColorMetaClass>(color_a, "color"), cast_object<Color, ColorMetaClass>(color_b, "color")); } }; } }
true
9cc9710f2a4859fa57f2c21cfa891b26494fa856
C++
abhi1362/HackerRank
/Algorithms/Implementation/Apple and Orange.cpp
UTF-8
519
2.71875
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int s,t,m,n,a,b,temp; cin>>s>>t>>a>>b>>m>>n; int orange_count=0,apple_count=0; for(int i=0;i<m;i++){ cin>>temp; if(temp+a >= s && temp+a <=t) apple_count++; } for(int i=0;i<n;i++){ cin>>temp; if(b+temp <=t && b+temp >= s) orange_count++; } cout<<apple_count<<endl<<orange_count<<endl; return 0; }
true
7ca37fe812db066edb856efbd17b9f3a6003a239
C++
gappadyl/sfmlCity
/sfmlCity/MovementComponent.cpp
UTF-8
2,377
3.328125
3
[]
no_license
#include "MovementComponent.h" //Constructor/destructor MovementComponent::MovementComponent(const float maxVelocity, sf::Sprite& sprite, float acceleration, float deceleration):sprite(sprite), maxVelocity(maxVelocity), acceleration(acceleration), deceleration(deceleration) { direction.x = 1; //set a initial direction for character } MovementComponent::~MovementComponent() { } //Functions void MovementComponent::move(const float x, const float y, const float& dt) { //Acceleration setCurrentVelocity(x, y, dt); if(velocity.x!=0.f) //dont want the direction to be nothing setCurrentDirection(velocity.x, velocity.y); } void MovementComponent::setCurrentVelocity(const float dir_x, const float dir_y, const float& dt) {//accelerates sprite this->velocity.x += acceleration * dir_x*dt *25.f ; this->velocity.y += acceleration * dir_y*dt*25.f; } void MovementComponent::setCurrentDirection(const float dir_x, const float dir_y) { this->direction.x = dir_x; this->direction.y = dir_y; } sf::Vector2f MovementComponent::getVelocity()const { return this->velocity; } sf::Vector2f MovementComponent::getDirection() const { return this->direction; } void MovementComponent::manualControl() { } void MovementComponent::setVelocity(float x, float y) { this->velocity.x = x; this->velocity.y = y; } void MovementComponent::update(const float& dt) { /*Decelerates velocity and checks maxSpeed */ if (velocity.x > 0) { //Deceleration velocity.x -= deceleration*700.f*dt; if (velocity.x < 0.f) velocity.x = 0.f; //check maxVelocity if (this->velocity.x > maxVelocity) { this->velocity.x = maxVelocity; } } else if (velocity.x < 0) { //Deceleration velocity.x += deceleration*700.f*dt; if (velocity.x > 0) velocity.x = 0; //check maxVelocity if (velocity.x < -maxVelocity) { velocity.x = -maxVelocity; } } if (velocity.y > 0) { //Deceleration velocity.y -= deceleration*700.f*dt; if (velocity.y < 0) velocity.y = 0; //check maxVelocity if (this->velocity.y > maxVelocity) { this->velocity.y = maxVelocity; } } else if (velocity.y < 0) { //Deceleration velocity.y += deceleration*700.f*dt; if (velocity.y > 0) velocity.y = 0; //check maxVelocity if (velocity.y < -maxVelocity) { velocity.y = -maxVelocity; } } sprite.move(velocity * dt); }
true
c212b8f2c441702b422b7b9acb5733ecd532f3c9
C++
yqbeyond/Algorithms
/uva/uva1585.cpp
UTF-8
412
2.640625
3
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> char str[100]; int main() { freopen("in.txt", "r", stdin); int n; scanf("%d", &n); while(n--) { scanf("%s", str); int len = strlen(str); int score = 0; int tmp = 0; for (int i = 0; i < len; i++) { if (str[i] == 'O') { ++tmp; score += tmp; } else { tmp = 0; } } printf("%d\n", score); } return 0; }
true
bd074aef167b17c58bd6c510f4bbe0da8332e8cb
C++
poechsel/raytracer
/python/PythonContext.h
ISO-8859-1
901
2.96875
3
[]
no_license
#ifndef PYTHONCONTEXT_H #define PYTHONCONTEXT_H #include <string> #include <Python.h> #include <vector> #include <iostream> /* Une suite de fonctions permettant de convertir une variable en la variable * python correspondante */ inline PyObject* convertToPy(std::string str) { return PyUnicode_FromString(str.c_str()); } inline PyObject* convertToPy(long v) { return PyLong_FromLong(v); } inline PyObject* convertToPy(double v) { return PyFloat_FromDouble(v); } PyObject* convertToPy(std::vector<long> vec); std::vector<long> convertFromPy(PyObject *py); void decrefListPy(PyObject *list); /* Classe appeler pour pouvoir grer les fichiers pythons. Elle modifie * entre-autre le path */ class PythonContext { public: PythonContext(); void setCWD(std::string path); virtual ~PythonContext(); protected: private: }; #endif // PYTHONCONTEXT_H
true
40810d3964a5f0f23f28f30c03c7a510a1ff464b
C++
xuefrye/PAT-Advanced-Level-Practice
/1142 Maximal Clique (25 分)/1142 Maximal Clique (25 分).cpp
GB18030
1,662
3.28125
3
[]
no_license
/* 1142 Maximal Clique 25 ֣ 201922417:49:01 Ѷ,28 ע. 1.˼·Ҫ öṹʾܺͲ,Ҷӽǽ. */ #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> using namespace std; const int maxn = 210; int G[maxn][maxn] = { 0 }; vector<int> clique; int nv, ne, m, k; int e1, e2; int c; int findNum(vector<int> &v, int &num) { for (int i = 0; i < v.size(); i++) { if (num == v[i]) return i; } return -1; } int judge(vector<int> &v) // -1clique 1 0not max { for (int i = 0; i < v.size() - 1; i++) { for (int j = i + 1; j < v.size(); j++) { if (G[v[i]][v[j]] == 0) return -1; } } for (int x = 1; x <= nv; x++) //нڵ { if (findNum(v, x) == -1) //x { bool exsit = true; for (int i = 0; i < v.size(); i++) { if (G[x][v[i]] == 0) { exsit = false; break; } } if (exsit == true) //һʹclique,ônot max clique return 0; } } return 1; // Ҳκһʹclique,max clique } int main() { scanf("%d %d", &nv, &ne); for (int i = 0; i < ne; i++) { scanf("%d %d", &e1, &e2); G[e1][e2] = G[e2][e1] = 1; } scanf("%d", &m); for (int i = 0; i < m; i++) { scanf("%d", &k); clique.clear(); for (int j = 0; j < k; j++) { scanf("%d", &c); clique.push_back(c); } int Case = judge(clique); if (Case == -1) printf("Not a Clique\n"); else if (Case == 0) printf("Not Maximal\n"); else if (Case == 1) printf("Yes\n"); } system("pause"); }
true
a9d0f995265eaff8856b7efddc1ffd3f52e0ea94
C++
tomfunkhouser/gaps
/pkgs/R3Utils/R3SurfelClassifier.cpp
UTF-8
8,766
2.609375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
/* Source file for the surfel scene classifier class */ //////////////////////////////////////////////////////////////////////// // Include files //////////////////////////////////////////////////////////////////////// #include "R3Utils.h" //////////////////////////////////////////////////////////////////////// // Namespace //////////////////////////////////////////////////////////////////////// namespace gaps { //////////////////////////////////////////////////////////////////////// // Surfel predictor constructor/destructor //////////////////////////////////////////////////////////////////////// R3SurfelClassifier:: R3SurfelClassifier(R3SurfelScene *scene) : scene(scene), training_set() { // Initialize training set for (int i = 0; i < scene->NObjects(); i++) { R3SurfelObject *object = scene->Object(i); R3SurfelLabel *label = object->HumanLabel(); if (label && strcmp(label->Name(), "Unknown")) { training_set.Insert(object); } } // Predict label assignments // PredictLabelAssignments(); } R3SurfelClassifier:: ~R3SurfelClassifier(void) { } //////////////////////////////////////////////////////////////////////// // Label assignment functions //////////////////////////////////////////////////////////////////////// int R3SurfelClassifier:: PredictLabelAssignment(R3SurfelObject *object) const { // Check labels if (scene->NLabels() <= 1) return 0; /////////// REMOVE PREVIOUS PREDICTED ASSIGNMENTS ///////// // Find previous predicted assignments RNArray<R3SurfelLabelAssignment *> previous_assignments; for (int i = 0; i < object->NLabelAssignments(); i++) { R3SurfelLabelAssignment *a = object->LabelAssignment(i); if (a->Originator() != R3_SURFEL_MACHINE_ORIGINATOR) continue; previous_assignments.Insert(a); } // Remove previous predicted assignments for (int i = 0; i < previous_assignments.NEntries(); i++) { R3SurfelLabelAssignment *a = previous_assignments.Kth(i); scene->RemoveLabelAssignment(a); } /////////// COMPUTE DISTANCE TO CLOSEST TRAINING OBJECT FOR EACH LABEL ///////// // Initialize best distance for each label type RNScalar *best_squared_distance_per_label = new RNScalar [ scene->NLabels() ]; for (int i = 0; i < scene->NLabels(); i++) { best_squared_distance_per_label[i] = FLT_MAX; } // Get feature vector for object // const R3SurfelFeatureVector& vector = object->FeatureVector(); R3SurfelFeatureVector vector(3); // TEMPORARY vector.SetValue(0, object->Centroid().X()); vector.SetValue(1, object->Centroid().Y()); vector.SetValue(2, object->Centroid().Z()); // Find best distance for each label type for (int i = 0; i < training_set.NEntries(); i++) { // Get object R3SurfelObject *training_object = training_set.Kth(i); // Get label R3SurfelLabel *training_label = training_object->HumanLabel(); if (!training_label) continue; // Get feature vector // const R3SurfelFeatureVector& training_vector = training_object->FeatureVector(); R3SurfelFeatureVector training_vector(3); // TEMPORARY training_vector.SetValue(0, training_object->Centroid().X()); training_vector.SetValue(1, training_object->Centroid().Y()); training_vector.SetValue(2, training_object->Centroid().Z()); // Compute squared distance to feature vector RNScalar squared_distance = vector.EuclideanDistanceSquared(training_vector); // Remember squared distance if it is the best for the label type if (squared_distance < best_squared_distance_per_label[training_label->SceneIndex()]) { best_squared_distance_per_label[training_label->SceneIndex()] = squared_distance; } } /////////// FIND BEST LABEL ///////// // Find best label R3SurfelLabel *best_label = NULL; RNScalar best_squared_distance = FLT_MAX; RNScalar second_best_squared_distance = FLT_MAX; for (int i = 0; i < scene->NLabels(); i++) { if (best_squared_distance_per_label[i] < best_squared_distance) { best_label = scene->Label(i); second_best_squared_distance = best_squared_distance; best_squared_distance = best_squared_distance_per_label[i]; } else if (best_squared_distance_per_label[i] < second_best_squared_distance) { second_best_squared_distance = best_squared_distance_per_label[i]; } } //////// COMPUTE CONFIDENCE ///////// // Compute confidence RNScalar confidence = 0; if ((best_label == NULL) || (best_squared_distance == FLT_MAX)) { confidence = 0; } else if (second_best_squared_distance == FLT_MAX) { confidence = RN_EPSILON; } else if (second_best_squared_distance == 0) { confidence = 0.5; } else { confidence = 1.0 - 2.0 * best_squared_distance / (best_squared_distance + second_best_squared_distance); } // Check confidence RNScalar min_confidence = 0; if (confidence < min_confidence) { best_label = scene->FindLabelByName("Unknown"); confidence = 0; } //////// CREATE ASSIGNMENT /////////// // Insert label assignment if (best_label) { R3SurfelLabelAssignment *assignment = new R3SurfelLabelAssignment(object, best_label, confidence, R3_SURFEL_MACHINE_ORIGINATOR); scene->InsertLabelAssignment(assignment); } // Delete temporary data delete [] best_squared_distance_per_label; // Return success return 1; } int R3SurfelClassifier:: PredictLabelAssignments(const RNArray<R3SurfelObject *>& objects) const { // Check labels if (scene->NLabels() <= 1) return 0; // Predict label assignments for all objects in set for (int i = 0; i < objects.NEntries(); i++) { R3SurfelObject *object = objects.Kth(i); if (object->HumanLabelAssignment()) continue; if (!PredictLabelAssignment(object)) return 0; } // Return success return 1; } int R3SurfelClassifier:: PredictLabelAssignments(void) const { // Predict label assignments for all objects in scene (except root) for (int i = 1; i < scene->NObjects(); i++) { R3SurfelObject *object = scene->Object(i); R3SurfelObjectAssignment *assignment = object->CurrentLabelAssignment(); if (assignment && (assignment->Originator() == R3_SURFEL_HUMAN_ORIGINATOR)) continue; if (assignment && (assignment->Confidence() >= 1.0)) continue; if (!PredictLabelAssignment(object)) return 0; } // Return success return 1; } //////////////////////////////////////////////////////////////////////// // Input/output functions //////////////////////////////////////////////////////////////////////// int R3SurfelClassifier:: ReadFile(const char *filename) { // Return success return 1; } int R3SurfelClassifier:: WriteFile(const char *filename) const { // Return success return 1; } //////////////////////////////////////////////////////////////////////// // Input/output functions //////////////////////////////////////////////////////////////////////// void R3SurfelClassifier:: UpdateAfterInsertObject(R3SurfelObject *object) { // Add to training set R3SurfelLabel *label = object->HumanLabel(); if (label && strcmp(label->Name(), "Unknown")) { if (!training_set.FindEntry(object)) { training_set.Insert(object); } } } void R3SurfelClassifier:: UpdateBeforeRemoveObject(R3SurfelObject *object) { // Remove from training set R3SurfelLabel *label = object->HumanLabel(); if (label && strcmp(label->Name(), "Unknown")) { if (training_set.FindEntry(object)) { training_set.Remove(object); } } } void R3SurfelClassifier:: UpdateAfterInsertLabelAssignment(R3SurfelLabelAssignment *assignment) { // Get convenient variables R3SurfelObject *object = assignment->Object(); R3SurfelLabel *label = assignment->Label(); // Update training set if (object->HumanLabel() && (assignment->Originator() == R3_SURFEL_HUMAN_ORIGINATOR)) { if (strcmp(label->Name(), "Unknown")) { if (!training_set.FindEntry(object)) { // Insert object into training set training_set.Insert(object); } } } } void R3SurfelClassifier:: UpdateBeforeRemoveLabelAssignment(R3SurfelLabelAssignment *assignment) { // Get convenient variables R3SurfelObject *object = assignment->Object(); R3SurfelLabel *label = assignment->Label(); // Check assignment if (object->HumanLabel() && (assignment->Originator() == R3_SURFEL_HUMAN_ORIGINATOR)) { if (strcmp(label->Name(), "Unknown")) { if (training_set.FindEntry(object)) { // Remove object from training set training_set.Remove(object); } } } } void R3SurfelClassifier:: UpdateAfterInsertFeature(R3SurfelFeature *feature) { } void R3SurfelClassifier:: UpdateBeforeRemoveFeature(R3SurfelFeature *feature) { } }; // end namespace
true
9fdc1a86cdeb00bae74fc9b92ef48b833fe8dfd2
C++
tangjz/acm-icpc
/leetcode/1001-2000/1836-remove-duplicates-from-an-unsorted-linked-list.cpp
UTF-8
942
3.265625
3
[ "Apache-2.0" ]
permissive
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* deleteDuplicatesUnsorted(ListNode* head) { unordered_map<int, int> ctr; for(ListNode *ptr = head; ptr != nullptr; ptr = ptr -> next) ++ctr[ptr -> val]; ListNode *ret = nullptr, *tail = nullptr; for(ListNode *ptr = head; ptr != nullptr; ptr = ptr -> next) { if(ctr[ptr -> val] != 1) continue; if(ret == nullptr) { ret = tail = ptr; } else { tail -> next = ptr; tail = ptr; } } if(tail != nullptr) tail -> next = nullptr; return ret; } };
true
6708fb0ec87ee698763cf445b9f59b91ebc2e006
C++
igoroogle/codeforces
/тренировка 7/ZAD_J_4.cpp
UTF-8
1,780
2.6875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { string s, s1; srand(time(0)); cin >> s; cout << "left: 1 2 3 right: 4 5 6\n"; fflush(stdout); cin >> s; if (s != "equal") { cout << "left: 1 2 3 right: 7 8 9\n"; fflush(stdout); cin >> s1; if (s1 == "equal") { cout << "left: 4 right: 5\n"; fflush(stdout); cin >> s1; if (s1 == "equal") cout << "answer: 6\n"; else if (s1 == s) cout << "answer: 5\n"; else cout << "answer: 4\n"; fflush(stdout); return 0; } s = s1; cout << "left: 1 right: 2\n"; fflush(stdout); cin >> s1; if (s1 == "equal") cout << "answer: 3\n"; else if (s1 == s) cout << "answer: 1\n"; else cout << "answer: 2\n"; fflush(stdout); return 0; } cout << "left: 7 8 right: 9 10\n"; fflush(stdout); cin >> s; if (s == "equal") { cout << "left: 10 right: 11\n"; fflush(stdout); cin >> s1; if (s1 == "equal") cout << "answer: 12\n"; else cout << "answer: 11\n"; fflush(stdout); return 0; } cout << "left: 7 right: 8\n"; fflush(stdout); cin >> s1; if (s1 != "equal") { if (s == s1) cout << "answer: 7\n"; else cout << "answer: 8\n";//uuuddffddfdfddddsssss1sssdsdsjkdhjk fflush(stdout); return 0; } if (rand() % 2) cout << "answer: 9\n"; else cout << "answer: 10\n"; fflush(stdout); return 0; }
true
3c28ab5c68076c557f22b75f3a3e85472c8687d2
C++
aalto-speech/ftk
/test/msfgtest.cc
UTF-8
3,039
2.53125
3
[ "BSD-3-Clause" ]
permissive
#include <boost/test/unit_test.hpp> #include "defs.hh" #include "MSFG.hh" using namespace std; BOOST_AUTO_TEST_CASE(MultiStringFactorGraphTest1) { MultiStringFactorGraph msfg(start_end_symbol); set<string> vocab = {"k", "i", "s", "a", "sa", "ki", "kis", "kissa", "lle", "kin", "kala"}; string sentence("kissa"); FactorGraph fg(sentence, start_end_symbol, vocab, 5); string sentence2("kissallekin"); FactorGraph fg2(sentence2, start_end_symbol, vocab, 5); string sentence3("kissakala"); FactorGraph fg3(sentence3, start_end_symbol, vocab, 5); msfg.add(fg); BOOST_CHECK_EQUAL( 1, (int)msfg.string_end_nodes.size() ); BOOST_CHECK_EQUAL( 7, (int)msfg.num_paths(sentence) ); msfg.add(fg2); BOOST_CHECK_EQUAL( 2, (int)msfg.string_end_nodes.size() ); BOOST_CHECK_EQUAL( 7, msfg.num_paths(sentence2) ); msfg.add(fg3); BOOST_CHECK_EQUAL( 3, (int)msfg.string_end_nodes.size() ); BOOST_CHECK_EQUAL( 7, (int)msfg.num_paths(sentence3) ); } BOOST_AUTO_TEST_CASE(MultiStringFactorGraphTest2) { MultiStringFactorGraph msfg(start_end_symbol); set<string> vocab = {"k", "i", "s", "a", "sa", "ki", "kis", "kissa", "lle", "kin", "kala"}; string sentence("kissa"); FactorGraph fg(sentence, start_end_symbol, vocab, 5); string sentence2("kissallekin"); FactorGraph fg2(sentence2, start_end_symbol, vocab, 5); string sentence3("kissakala"); FactorGraph fg3(sentence3, start_end_symbol, vocab, 5); msfg.add(fg, false); BOOST_CHECK_EQUAL( 1, (int)msfg.string_end_nodes.size() ); BOOST_CHECK_EQUAL( 7, (int)msfg.num_paths(sentence) ); msfg.add(fg2, false); BOOST_CHECK_EQUAL( 2, (int)msfg.string_end_nodes.size() ); BOOST_CHECK_EQUAL( 7, msfg.num_paths(sentence2) ); msfg.add(fg3, false); BOOST_CHECK_EQUAL( 3, (int)msfg.string_end_nodes.size() ); BOOST_CHECK_EQUAL( 7, (int)msfg.num_paths(sentence3) ); } BOOST_AUTO_TEST_CASE(MultiStringFactorGraphTest3) { MultiStringFactorGraph msfg(start_end_symbol); set<string> vocab = {"k", "i", "s", "a", "sa", "ki", "la", "kis", "kissa", "lle", "kin", "kala"}; string sentence("kissa"); FactorGraph fg(sentence, start_end_symbol, vocab, 5); string sentence2("kala"); FactorGraph fg2(sentence2, start_end_symbol, vocab, 5); string sentence3("kissakala"); FactorGraph fg3(sentence3, start_end_symbol, vocab, 5); msfg.add(fg); msfg.add(fg2); msfg.add(fg3); } BOOST_AUTO_TEST_CASE(MultiStringFactorGraphTest4) { MultiStringFactorGraph msfg(start_end_symbol); set<string> vocab = {"aarian", "aari", "an", "a", "ari", "ri", "ar", "i", "n", "r"}; string word("aarian"); FactorGraph fg(word, start_end_symbol, vocab, 6); msfg.add(fg); vector<vector<string> > paths; msfg.get_paths(word, paths); BOOST_CHECK_EQUAL( 11, fg.num_paths() ); BOOST_CHECK_EQUAL( 11, (int)paths.size() ); BOOST_CHECK_EQUAL( 11, msfg.num_paths(word) ); }
true
81f28e5126afa50468d941af1f1d28534f5ced66
C++
Spyka/Class-Projects
/CS530/Final/symtab.h
UTF-8
1,234
3.34375
3
[]
no_license
/* CS 530, Spring 2014 symtab.h */ #ifndef SYMTAB_H #define SYMTAB_H #include <string> #include <map> #include <utility> #include <cstdlib> #include <iostream> #include <sstream> using namespace std; class symtab { public: // ctor symtab(); //Inserts a label and its value (address or immediate) into the symbol //table. Throws an exception if the label is already in the symbol table void insert_label(string ,string); //Returns the value of the label passed through if it contains one string get_value(string); //sets the value of the label if the label is already //defined or inserts the label if not void set_value(string,string); //prints the contents of the symbol table - the label and the value void print_symtab(); //checks to see if the label is in the symbol table bool contains_symbol(string); private: //map containing the label and its value //and iterators used to access the map map<string, string > symbol; map<string, string >::iterator sym_itr; map<string, string >::iterator print_itr; string sym_value; }; #endif
true
b37bfa4f5bd98dfee911a57cd47a036af07fa290
C++
pingany/poj
/3630/3614682_WA.cc
UTF-8
1,328
2.765625
3
[]
no_license
#include<iostream> using namespace std; const int MAX_NEXT=10;// max length of next array inline char hash(char c){return c-'0';}//use to store element struct Trie { int num; bool allowend; struct Trie *next[MAX_NEXT]; Trie(){init(0);} void init(int cc) { allowend=false; num=cc; memset(next,0,sizeof(next)); } Trie(int cc) { init(cc); } }; Trie root,*pr=&root; int build(char s[])//创建,同时统计出现的次数 { int i; Trie* p=pr; while(*s) { i=hash(*s); if(p->next[i]==0) { p->next[i]=new Trie(); } p=p->next[i]; s++; } p->allowend=true; p->num++; return p->num; } int build_test(char s[]) { int i; Trie* p=pr; while(*s) { i=hash(*s); if(p->next[i]==0) { p->next[i]=new Trie(); } p=p->next[i]; if(p->num>=1)return 0; s++; } p->allowend=true; p->num++; return p->num; } int main() { //freopen("c:/acm/pku_3630.txt","r",stdin); char s[100]; bool errorf=false; int ncase,n; scanf("%d",&ncase); while(ncase--) { errorf=false; scanf("%d\n",&n); while(n--) { gets(s); if(errorf) continue; if( !build_test(s)){printf("NO\n");errorf=true;} } if(!errorf)printf("YES\n"); } return 0; }
true
51f0c946996ae39674f95cc20b02bd2e086e49d5
C++
rjdsilv/OpenGLLib
/OpenGLLib/OpenGLShader.cpp
UTF-8
3,464
3.296875
3
[]
no_license
#include "OpenGLShader.h" #include <stdexcept> #include <fstream> #include <sstream> #include <iostream> #include <stdio.h> /* * Method : Class constructor. * Description: It will initialize the Shader with the path for the shaders files. * Param : vertexShaderPath - The path to the vertex shader code file. * Param : fragmentShaderPath - The path to the fragment shader code file. */ OpenGLShader::OpenGLShader(const GLchar* vertexShaderPath, const GLchar* fragmentShaderPath) { validateParameter(vertexShaderPath, "vertexShaderPath"); validateParameter(fragmentShaderPath, "fragmentShaderPath"); linkProgram(vertexShaderPath, fragmentShaderPath); } void OpenGLShader::use() { if (!isProgramInvalid()) { glUseProgram(this->program); } else { throw logic_error("The Shader Program hasn't be created!"); } } GLint OpenGLShader::getUniform(const GLchar* name) { if (!isProgramInvalid()) { return glGetUniformLocation(this->program, name); } return SHADER_INVALID_UNIFORM; } string OpenGLShader::readShader(const GLchar * shaderPath, stringstream& shaderStream) { ifstream shaderFile; // Ensure ifstream can throw exceptions. shaderFile.exceptions(ifstream::failbit | ifstream::badbit); try { // Read the stream buffer and return its string shaderFile.open(shaderPath); shaderStream.str(""); shaderStream.clear(); shaderStream << shaderFile.rdbuf(); shaderFile.close(); string shaderCode = shaderStream.str(); return shaderCode; } catch (ifstream::failure fail) { cout << "ERROR::SHADER::FILE_NOT_SUCCESSFULLY_READ" << endl; } return ""; } GLuint OpenGLShader::compileShader(string& code, GLenum type) { const GLchar* shaderName = (type == GL_VERTEX_SHADER) ? "VERTEX" : "FRAGMENT"; const GLchar* shaderCode = code.c_str(); GLint success; GLchar infoLog[512]; GLuint shader = glCreateShader(type); glShaderSource(shader, 1, &shaderCode, nullptr); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 512, nullptr, infoLog); cout << "ERROR::SHADER::" << shaderName << "::COMPILATION_FAILURE\n" << infoLog << endl; } return shader; } void OpenGLShader::linkProgram(const GLchar* vertexShaderPath, const GLchar* fragmentShaderPath) { stringstream shaderStream; GLint success; GLchar infoLog[512]; GLuint vertexShader = compileShader(readShader(vertexShaderPath, shaderStream), GL_VERTEX_SHADER); GLuint fragmentShader = compileShader(readShader(fragmentShaderPath, shaderStream), GL_FRAGMENT_SHADER); // Create and link the shader program this->program = glCreateProgram(); glAttachShader(this->program, vertexShader); glAttachShader(this->program, fragmentShader); glLinkProgram(this->program); glGetProgramiv(this->program, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(this->program, 512, nullptr, infoLog); cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << endl; } // Delete already used the shaders. glDeleteShader(vertexShader); glDeleteShader(fragmentShader); } void OpenGLShader::validateParameter(const GLchar* shaderPath, const GLchar* parameterName) { const GLuint size = 64; GLchar errorMsg[size]; sprintf_s(errorMsg, size, "The '%s' argument cannot be NULL!", parameterName); if (nullptr == shaderPath) { throw invalid_argument(errorMsg); } } bool OpenGLShader::isProgramInvalid() { return SHADER_INVALID_PROGRAM == this->program; }
true
3d3db4f51a2d0dbabe5fdb8b39780b1e908e715c
C++
davara13/algoritmicToolbox
/semana4/majority_element.cpp
UTF-8
1,131
3.359375
3
[]
no_license
#include <algorithm> #include <iostream> #include <vector> #include <cstdlib> using std::vector; void swap(int* a, int* b){ int t = *a; *a = *b; *b = t; } int RQS(vector<int> &a, int r, int l, int n){ if(l>=r){ return 0; } /*else if(r-l<(n/2+1)){ return 0; }*/ int k = l + rand()%(r-l); int x = a[k]; swap(&a[k],&a[l]); int pi=l; int si = pi + 1; int count = 1; for(int i = pi + 1 ; i<=r; i++){ if(a[i]<x){ swap(&a[si],&a[i]); si++; } if(a[i]==x){ count++; } if(count>(int)(n/2)){ return 1; } } swap(&a[si-1],&a[pi]); RQS(a,si-2,l,n); RQS(a,r,si,n); } int get_majority_element(vector<int> &a, int left, int right) { int x = a[0]; int c = 1; for(int i = 1; i<a.size(); i++){ if(a[i]==x){ c++; }else{ if(c>(a.size()/2)){ return 1; }else{ c = 1; x=a[i]; } } } if(c >(a.size()/2)){ return 1; }else{ return 0; } } int main() { int n; std::cin >> n; vector<int> a(n); for (size_t i = 0; i < a.size(); ++i) { std::cin >> a[i]; } std::sort(a.begin(),a.end()); std::cout<<get_majority_element(a, 0, a.size()-1); }
true
9cc46ae34f72b7756d21493ed626a6a04fa13e12
C++
JuJinHyeong/DirectX11Engine
/DirectX11Engine/DirectX11Engine/Graphics/PixelShader.cpp
UTF-8
717
2.546875
3
[]
no_license
#include "PixelShader.h" bool PixelShader::Initialize(Microsoft::WRL::ComPtr<ID3D11Device>& device, std::wstring& shaderpath) { HRESULT hr = D3DReadFileToBlob(shaderpath.c_str(), m_shaderBuffer.GetAddressOf()); if (FAILED(hr)) { OutputDebugString("failed to read pixel shader"); exit(-1); } hr = device->CreatePixelShader(m_shaderBuffer.Get()->GetBufferPointer(),m_shaderBuffer.Get()->GetBufferSize(), NULL, m_pixelShader.GetAddressOf()); if (FAILED(hr)) { OutputDebugString("failed to create pixel shader"); exit(-1); } return true; } ID3D11PixelShader* PixelShader::GetPixelShader() { return m_pixelShader.Get(); } ID3D10Blob* PixelShader::GetShaderBuffer() { return m_shaderBuffer.Get(); }
true
580c933eebda6cea879b6f5baeca216b047992b5
C++
youssefAli11997/Project-Euler-Solutions
/001 - Multiples of 3 and 5.cpp
UTF-8
271
2.90625
3
[]
no_license
// coded by : Hossam Ali #include <iostream> using namespace std; int main() { int Count = 0; for (int i = 3 ; i < 1000 ; i++) { if(i % 3 == 0 || i % 5 == 0) Count = Count + i; } cout<<Count<<endl; return 0; }
true
0ba023320f5278911c52b08c44cdffe27f5e6a31
C++
WhiteStaff/OOP_3sem
/3/main.cpp
UTF-8
1,120
2.890625
3
[]
no_license
#include <iostream> #include "wav_core.h" using namespace std; int main(int argc, char *argv[]) { cout << "************** | WavCore | **************" << endl; // ################ Tests for WavCore ################ const char* input_fname = "c:\\temp\\0.wav"; const char* output_fname = "c:\\temp\\out.wav"; Wav myClass, Class1; try { // #### Opening WAV file, checking header. myClass.read_header(input_fname); // #### Printing header. myClass.print_info(); // #### Reading PCM data from file. myClass.extract_data_int16(input_fname); cout << endl << "********************" << endl; // #### Make several changes to PCM data. // # Making signal mono from stereo. myClass.make_mono(); // # Add a reverberation myClass.make_reverb(0.5, 0.6f); // #### Making new WAV file using edited PCM data. myClass.make_wav_file(output_fname); // #### Reading the file just created to check its header corectness. Class1.read_header(output_fname); Class1.print_info(); } catch (const std::exception& e) { cout << e.what() << endl; } return 0; }
true
3b9001c8b52036a25e1c31f162117cb8db102be2
C++
sunilsarode/allc-programs
/eclerx/BinaryExponentiation.cpp
UTF-8
366
2.53125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef long long int ll; #define MOD 1000000007 ll power(ll x,ll y){ if(y==0){ return 1; }else if(y%2==0){ return power((x*x)%MOD,y/2); }else{ return (x*power((x*x)%MOD,(y-1)/2))%MOD; } } int main(){ ll s,n,m; cin>>s>>n>>m; cout<<power(power(s,n)%10,m)<<endl; return 0; }
true
0f1d26bbf68edf9a78da8708e8968fc29846d974
C++
SunBo123/pratice
/每天学习/每天学习/Day1.cpp
GB18030
3,455
2.890625
3
[]
no_license
#include "stdafx.h" #include "Day1.h" Day1::Day1() { } Day1::~Day1() { } void Day1::show() { /*Mat src = imread("1.png",1); resize(src,src,Size(640,480)); imwrite("1.png",src); Mat src2 = imread("5.png", 1); resize(src2, src2, Size(640, 480)); imwrite("5.png", src2);*/ Mat src = imread("1.png", 1); namedWindow("IMG",1); imshow("IMG",src); Mat src2 = imread("5.png", 1); //Ȥѡ Mat ROI; Mat dst = imread("2.bmp",1); ROI = src2(Rect(100,100,dst.cols,dst.rows)); dst.copyTo(ROI,dst); imshow("ROI",src2); //ͼں //computes weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma) addWeighted(src,0.5,src2,0.5,0,src,-1); imshow("IMG2",src); waitKey(0); } //ͼ void Day1::split1() { Mat src = imread("1.png", 1); namedWindow("IMG", 1); imshow("IMG",src); Mat dst = imread("1.jpg",0); vector<Mat> channels; split(src,channels); Mat imageBlueChannel; imageBlueChannel = channels.at(0); Mat roi0 = imageBlueChannel(Rect(100, 100, dst.cols, dst.rows)); addWeighted(roi0,1,dst,0.5,0,roi0); /*addWeighted(imageBlueChannel(Rect(100, 100, dst.cols, dst.rows)), 1.0, dst, 0.5, 0, imageBlueChannel(Rect(500, 250, dst.cols, dst.rows)));*/ imshow("IMG0",imageBlueChannel); Mat imageGreenChannel; imageGreenChannel = channels.at(1); Mat roi1 = imageGreenChannel(Rect(100, 100, dst.cols, dst.rows)); addWeighted(roi1, 1, dst, 0.5, 0, roi1); /*addWeighted(imageGreenChannel(Rect(100, 100, dst.cols, dst.rows)), 1.0, dst, 0.5, 0, imageGreenChannel(Rect(500, 250, dst.cols, dst.rows)));*/ imshow("IMG1", imageGreenChannel); Mat imageRedChannel; imageRedChannel = channels.at(2); Mat roi2 = imageRedChannel(Rect(100, 100, dst.cols, dst.rows)); addWeighted(roi2, 1, dst, 0.5, 0, roi2); /*addWeighted(imageRedChannel(Rect(100, 100, dst.cols, dst.rows)), 1.0, dst, 0.5, 0, imageRedChannel(Rect(500, 250, dst.cols, dst.rows)));*/ imshow("IMG2", imageRedChannel); // merge(channels, src); imshow("After",src); waitKey(0); } Mat src1, dst1; int g_nContrast; //Աȶֵ int g_nBright; //ֵ void ContrastAndBright(int, void *) { // namedWindow("ԭʼͼڡ", 1); //forѭִ g_dstImage(i,j) =a*g_srcImage(i,j) + b for (int y = 0; y < src1.rows; y++) { for (int x = 0; x < src1.cols; x++) { for (int c = 0; c < 3; c++) { dst1.at<Vec3b>(y, x)[c] = saturate_cast<uchar>((g_nContrast*0.01)*(src1.at<Vec3b>(y, x)[c]) + g_nBright); } } } //ʾͼ imshow("ԭʼͼڡ", src1); imshow("Чͼڡ", dst1); } //켣 Աȶ void Day1::Trace() { system("color5F"); //ûṩͼ src1 = imread("1.png"); if (!src1.data) { printf("Ohnoȡg_srcImageͼƬ~\n"); //return false; } dst1 = Mat::zeros(src1.size(), src1.type()); //趨ԱȶȺȵijֵ g_nContrast = 80; g_nBright = 80; // namedWindow("Чͼڡ", 1); //켣 createTrackbar("Աȶȣ", "Чͼڡ", &g_nContrast, 300, ContrastAndBright); createTrackbar(" ȣ", "Чͼڡ", &g_nBright, 200, ContrastAndBright); //ûص ContrastAndBright(g_nContrast, 0); ContrastAndBright(g_nBright, 0); //¡qʱ˳ while (char(waitKey(1)) != 'q') {} waitKey(0); }
true
f6759b3e124ab2776c92750c4e8ea7589997403a
C++
chuckfairy/liborza
/src/Audio/ControlInterface.h
UTF-8
567
2.765625
3
[]
no_license
/** * Basic control interface */ #pragma once namespace Audio { class ControlInterface { public: /** * Virtual override methods */ virtual void start() {}; virtual void stop() {}; virtual void run() {}; virtual void pause() {}; /** * IO based */ virtual void clearInputs() {}; /** * Main active use methods */ bool isActive() { return ACTIVE; }; void setActive( bool now ) { ACTIVE = now; }; protected: ControlInterface() {}; ~ControlInterface() {}; private: bool ACTIVE = false; }; };
true
4e1da3f43e0621773cbc8b4cd73175fddcbbb8f5
C++
getjump/os_stuff
/task3/main.cpp
UTF-8
733
3.171875
3
[]
no_license
#include <iostream> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #define CHILD_PROCESS_ID 0 #define INVALID_PID(x) ((x) < CHILD_PROCESS_ID) using namespace std; int main() { pid_t pid = fork(); if(pid == CHILD_PROCESS_ID) { cout << "Child pid = " << getpid() << "; Parent pid = " << getppid() << endl; } else if(INVALID_PID(pid)) { cerr << "Failed to fork" << endl; exit(1); } else { cout << "Parent Pid = " << getpid() << "; child = " << pid << endl; } int status = -1; waitpid(pid, &status, WEXITED); if(pid == CHILD_PROCESS_ID) { cout << "Child"; } else { cout << "Parent"; } cout << " exited with return code " << status << endl; exit(EXIT_SUCCESS); }
true
ab4eacff782303170e86963694192ffd5ba25cf9
C++
NoahBGriffin/LoanIt
/LoanIt/Print.cpp
UTF-8
864
3.15625
3
[]
no_license
#include "Print.h" /** * Prints the list of items currently in the LoanIt tracker * @param itemList the list of items in LoanIt to be printed * @param mainMenu if true it will go to Return which creates a prompt to return to the main menu */ void PrintItemList(vector<Item> itemList, bool mainMenu) { cout << "Printing list of items....\n\n"; for (auto i : itemList) { i.Print(); } cout << endl; if (mainMenu) { Return(2); } } /** * Prints the list of loans in the LoanIt tracker * @param loanList the list of laons in LoanIt to be printed */ void PrintLoanList(vector<Loan> loanList, bool mainMenu) { cout << "Printing list of loans....\n\n"; for (auto i : loanList) { i.Print(); } cout << endl; if (mainMenu) { Return(2); } }
true
cd24f3d11fb909a910912d6948cb7ae7d0a9bb1c
C++
omochi/cpp-rhetoric
/src/rhetoric/option.h
UTF-8
1,292
2.625
3
[]
no_license
#pragma once #include "./std_dependency.h" #include "./assert.h" #include "./attribute.h" #include "./concept_macro.h" #include "./either.h" #include "./none.h" namespace rhetoric { constexpr Either2Tag NoneTag = Either2Tag::Case0; constexpr Either2Tag SomeTag = Either2Tag::Case1; template <typename T> class Option { public: using ValueType = T; Option(); /* implicit */ Option(const None &); explicit Option(const Either2CaseWrapper<SomeTag, T> & value); Option(const Option<T> & other); Option<T> & operator=(const Option<T> & other); template <typename U> Option(const Option<U> & other, std::enable_if_t<std::is_convertible<U, T>::value> * = nullptr); ~Option(); bool presented() const; explicit operator bool() const; const T & value() const; const T * operator->() const; const T & operator*() const; bool operator==(const Option<T> & other) const; RHETORIC_EQUATABLE_DEFAULT(Option<T>); T GetOr(const T & default_value) const; private: Either2<None, T> either_; }; template <typename T> Option<T> Some(const T & value); } #include "./option_inline.h"
true
1bfb00eeb649f10d1366bcb3b836f02cbbbf156e
C++
AzureeDev/100-Tangerine-Juice
/100 Tangerine Juice/LButton.cpp
UTF-8
5,702
2.96875
3
[]
no_license
#include "LButton.h" #include "Globals.h" #include "SFXManager.h" /* LButton Manages a button with automatic event handle. */ LButton::LButton() { } LButton::~LButton() { this->buttonVisible = false; } LButton::LButton(const string id, const string btnTexturePath) { this->buttonId = id; this->buttonTexture.setNewTexture(btnTexturePath); this->buttonPath = btnTexturePath; this->buttonHeight = this->buttonTexture.getHeight(); this->buttonWidth = this->buttonTexture.getWidth(); } LTexture& LButton::getTexture() { return this->buttonTexture; } string LButton::getId() { return this->buttonId; } void LButton::disable() { this->setVisible(false); this->setEnabled(false); } void LButton::activate() { this->setVisible(true); this->setEnabled(true); } bool LButton::isMouseInside() { bool inside = true; if (Globals::mousePositionX < this->buttonX) { inside = false; } else if (Globals::mousePositionX > this->buttonX + this->buttonTexture.getWidth()) { inside = false; } else if (Globals::mousePositionY < this->buttonY) { inside = false; } else if (Globals::mousePositionY > this->buttonY + this->buttonTexture.getHeight()) { inside = false; } return inside; } bool LButton::isEnabled() { return this->buttonEnabled; } void LButton::supplyCallback(const std::function<void()> clbk) { this->buttonCallback = clbk; } void LButton::supplyCallback(std::function<void(string)> clbk, const string arg) { this->buttonStrCallback = clbk; this->buttonBindedStr = arg; } void LButton::supplyUnitCallback(Unit* unit, std::function<void(Unit*)> clbk) { this->buttonBindedUnit = unit; this->buttonUnitCallback = clbk; } void LButton::executeCallback() { if (this->buttonCallback != NULL) { this->buttonCallback(); } if (this->buttonStrCallback != NULL) { this->buttonStrCallback(this->buttonBindedStr); } if (this->buttonUnitCallback != NULL) { this->buttonUnitCallback(this->buttonBindedUnit); } } void LButton::event(const SDL_Event& ev) { if (!this->buttonEnabled) { return; } if (ev.type == SDL_MOUSEBUTTONDOWN) { if (ev.button.button == SDL_BUTTON_LEFT && this->isMouseInside()) { if (this->allowSound) { SFXManager::playSFX("btn_clicked"); } this->executeCallback(); } } } int LButton::getX() { return this->buttonX; } int LButton::getY() { return this->buttonY; } void LButton::setX(const int x) { this->buttonX = x; this->buttonTexture.setX(x); // Recalculate text position if (this->buttonTextStr != "") { this->buttonText.setPosition( this->buttonTexture.getX() + (this->buttonTexture.getWidth() / 2) - buttonText.getWidth() / 2, this->buttonTexture.getY() + (this->buttonTexture.getHeight() / 2) - buttonText.getHeight() / 2 ); } } void LButton::setY(const int y) { this->buttonY = y; this->buttonTexture.setY(y); // Recalculate text position if (this->buttonTextStr != "") { this->buttonText.setPosition( this->buttonTexture.getX() + (this->buttonTexture.getWidth() / 2) - buttonText.getWidth() / 2, this->buttonTexture.getY() + (this->buttonTexture.getHeight() / 2) - buttonText.getHeight() / 2 ); } } void LButton::setPosition(const int x, const int y) { this->buttonX = x; this->buttonTexture.setX(x); this->buttonY = y; this->buttonTexture.setY(y); this->buttonText.setPosition( this->buttonTexture.getX() + (this->buttonTexture.getWidth() / 2) - buttonText.getWidth() / 2, this->buttonTexture.getY() + (this->buttonTexture.getHeight() / 2) - buttonText.getHeight() / 2 ); this->animationMaxButtonX = x + 20; this->animationOriginalX = x; } void LButton::setPosition(const Vector2i pos) { this->setPosition(pos.x, pos.y); } void LButton::setVisible(const bool state) { this->buttonVisible = state; } void LButton::setEnabled(const bool state) { this->buttonEnabled = state; } void LButton::setHighlightColor(const SDL_Color color) { this->buttonHighlightColor = color; this->buttonTexture.setHighlightColor(color); } void LButton::setText(const string text) { this->buttonTextStr = text; this->buttonText.createText(text, this->buttonTextColor, this->buttonTexture.getWidth(), Globals::resources->getFont("defaultFont32")); this->buttonText.setPosition( this->buttonTexture.getX() + (this->buttonTexture.getWidth() / 2) - buttonText.getWidth() / 2, this->buttonTexture.getY() + (this->buttonTexture.getHeight() / 2) - buttonText.getHeight() / 2 ); } void LButton::setText(const string text, const SDL_Color color) { this->setTextColor(color); this->setText(text); } void LButton::setTextColor(const SDL_Color color) { this->buttonTextColor = color; } void LButton::setAllowSound(const bool state) { this->allowSound = state; } void LButton::setAllowAnimation(const bool state) { this->allowHoverAnimation = state; } void LButton::render() { /* If the button is destroyed... */ if (this == nullptr) { return; } if (this->buttonVisible) { if (this->isMouseInside()) { if (this->buttonEnabled && this->buttonVisible) { this->buttonTexture.setColor(this->buttonHighlightColor); if (!this->playedSoundHighlight && this->allowSound) { SFXManager::playSFX("btn_over"); this->playedSoundHighlight = true; } if (this->getX() < this->animationMaxButtonX && this->allowHoverAnimation) { this->setX(this->getX() + 2); } } } else { this->buttonTexture.resetBaseColor(); this->playedSoundHighlight = false; if (this->getX() > this->animationOriginalX&& this->allowHoverAnimation) { this->setX(this->getX() - 2); } } this->buttonTexture.render(); if (this->buttonTextStr != "") { this->buttonText.render(); } } }
true
c9dc3f84ad760bf200d6bb54e8f723753a7803cd
C++
Fikretatr/CSE-241-OBJECT-ORIENTED-PROGRAMMING
/ps 6/ps6_part2.cpp
UTF-8
1,410
3.65625
4
[]
no_license
#include<iostream> using namespace std; class CharPair{ public: CharPair(); CharPair(int x); CharPair(int x,char a[]); int get_size(){return size;}; char& operator[](int index); private: char arry[100]; int size; }; int main(){ CharPair a; int bsize,csize; cout<<"Displays the values of object b:\n"; for(int i=0;i<a.get_size();i++) cout<<a[i]<<endl; cout<<"Enter size of array:"; cin>>bsize; cout<<endl; CharPair b(bsize); cout<<"Displays the values of object b:"<<endl; for(int i=0;i<b.get_size();i++) cout<<b[i]<<endl; char array1[20]; cout<<"Enter the size of array:"; cin>>csize; cout<<endl; CharPair c(csize,array1); cout<<"Displays the array1 values:\n"; if(c.get_size()<=sizeof(array1)) for(int i=0;i<c.get_size();i++) cout<<array1[i]<<endl; else{ cout<<"\nIndex out of range"; exit(0); } cin.get(); return 0; } CharPair::CharPair():size(10){ for(int i=0;i<size;i++) arry[i]='#'; } CharPair::CharPair(int n):size(n){ for(int i=0;i<size;i++) arry[i]='#'; } CharPair::CharPair(int x,char arr[]){ size=x; for(int i=0;i<size;i++){ arry[i]='#'; } for(int i=0;i<size;i++){ arr[i]=arry[i]; } } char& CharPair::operator[](int index){ if(index>=size){ cout<<"Illegal index value.\n"; exit(0); } return arry[index]; }
true
a5c72f81126e741f2170b35eb1e929fd06493649
C++
jvgille/Path-Tracer
/src/camera.hpp
UTF-8
2,230
3.125
3
[]
no_license
#ifndef CAMERA #define CAMERA #include <glm/glm.hpp> #include "constants.hpp" using glm::mat3, glm::vec3, glm::vec2, glm::normalize; const vec2 OFFSET{2*EPSILON, EPSILON}; // slightly offset to avoid alignment lightning bugs class Camera { vec3 pos; vec2 rot; mat3 rot_matrix; float focal_length; bool dirty = true; void update_rotation_matrix() { float cx = cos(-rot.x); float sx = sin(-rot.x); float cy = cos(-rot.y); float sy = sin(-rot.y); rot_matrix = mat3(cy,0,sy,0,1,0,-sy,0,cy)* // y mat3(1,0,0,0,cx,-sx,0,sx,cx); // x } public: Camera() : pos() , rot() , focal_length(SCREEN_HEIGHT) { update(); } Camera(vec3 _pos, vec2 _rot, float _focal_length) : pos(_pos) , rot(_rot + OFFSET) , focal_length(_focal_length) { update(); } void rotate(float dx, float dy) { if (dx == 0 && dy == 0) return; rot.x += dx; rot.y += dy; dirty = true; } void move(float dx, float dy, float dz) { if (dx == 0 && dy == 0 && dz == 0) return; pos.x += dx*cos(-rot.y) - dz*sin(-rot.y); pos.z += dx*sin(-rot.y) + dz*cos(-rot.y); pos.y += dy; dirty = true; } const vec3 & get_position() const { return pos; } const vec2 & get_rotation() const { return rot; } const mat3 & get_rotation_matrix() const { return rot_matrix; } float get_focal_length() const { return focal_length; } bool update() { if (dirty) { dirty = false; update_rotation_matrix(); rot.x = glm::clamp(rot.x, float(-M_PI_2), float(M_PI_2)); while (rot.y > 2*M_PI) rot.y -= 2*M_PI; while (rot.y < 0) rot.y += 2*M_PI; return true; } else { return false; } } vec3 get_forward() const { return rot_matrix*vec3(0,0,1); } vec3 get_downward() const { return rot_matrix*vec3(0,1,0); } vec3 get_right() const { return rot_matrix*vec3(1,0,0); } }; #endif // CAMERA
true
a5505bbf13ce6c2f35d1adda305d1bd6905b781c
C++
aryabartar/BSc-HWc
/Fundamental Programming/HW3/6-2.cpp
UTF-8
432
3.125
3
[]
no_license
#include <iostream> #include <cstring> using namespace std ; int main() { const int aMaxSize = 70 ; char a[aMaxSize] ; int whiteCount = 1 ; cin.get (a ,80) ; if ( strtok (a , " ") == NULL) cout << "No word !" ; else { while (strtok (NULL , " ") != NULL){ whiteCount++ ; } cout << whiteCount << " words!" ; } return 0 ; }
true
0508703db0ee58f70af1143521cb30e62afa11b5
C++
radif/mcbPlatformSupport
/mcbPlatformSupport/utils/mcbAnimationSprite.h
UTF-8
2,899
2.53125
3
[ "MIT" ]
permissive
// // mcbAnimationSprite.h // PlatformSupport // // Created by Radif Sharafullin on 7/24/13. // // #ifndef __mcb__utils__AnimationSprite__ #define __mcb__utils__AnimationSprite__ #include "cocos2d.h" namespace mcb{ namespace PlatformSupport{ class AnimationSprite : public cocos2d::CCSprite{ typedef cocos2d::CCSprite super; bool _isAnimating=false; public: AnimationSprite(){} virtual ~AnimationSprite(){} static AnimationSprite* create(const char *pszFileName); class AnimationData{ typedef std::vector<cocos2d::CCTexture2D *> p_oTextures; float _frameDelay=1.f/24.f; int _currentFrameNumber=0; p_oTextures _texures; void reset(){_currentFrameNumber=0;} std::function<void()> _cycleCompletion; void bumpAnimationFrame(){ _currentFrameNumber++; if(_currentFrameNumber>=_texures.size()){ _currentFrameNumber=0; if (_cycleCompletion) _cycleCompletion(); } } cocos2d::CCTexture2D * textureForCurrentFrame(){return _texures.at(_currentFrameNumber);} float _dt=0.f; void addDeltaTime(const float & dt){ if (_frameDelay>0.f) { _dt+=dt; while (_dt>_frameDelay) { _dt-=_frameDelay; bumpAnimationFrame(); } } } friend AnimationSprite; public: AnimationData(){}; virtual ~AnimationData(); void addTexture(cocos2d::CCTexture2D * tex); void setFrameDelay(float frameDelay){_frameDelay=frameDelay;} static std::shared_ptr<AnimationData> create(){return std::make_shared<AnimationData>();} }; typedef std::shared_ptr<AnimationData> pAnimationData; void setAllAnimationFrameDelay(float frameDelay); void setAnimationDataForKey(pAnimationData animData, const std::string & key); void setAnimationFrameDelayForAnimationKey(float frameDelay, const std::string & key); void playAnimationForKey(const std::string & key, const std::function<void()> & cycleCompletion=nullptr, bool reset=true); void startCurrentAnimation(){_isAnimating=true;} void stopAnimation(){_isAnimating=false;} protected: virtual void onEnter() override; virtual void onExit() override; virtual void update(float dt) override; private: pAnimationData _currentAnimation=nullptr; std::map<std::string, pAnimationData> _animations; }; }} #endif /* defined(__mcb__utils__AnimationSprite__) */
true
ae9f74ea9c7f92ba03df3f65ab6a7d4d2c11ca8f
C++
yeyintlwin/learn-cpp
/CH-16 GENERIC ALGORITHMS/ex1601.cpp
UTF-8
976
3.921875
4
[]
no_license
// Listing 16.1: Using adjacent_find() function #include <iostream> #include <set> #include <algorithm> using namespace std; int main() { // Create the set of object. multiset<int, less<int>> intSet; intSet.insert(10); intSet.insert(3); intSet.insert(1); intSet.insert(3); intSet.insert(8); intSet.insert(8); intSet.insert(5); // Display the contents of the set. cout << "\n\tContents of set:\n"; multiset<int, less<int>>::iterator it = intSet.begin(); for (int x = 0; x < intSet.size(); x++) cout << '\t' << *it++ << endl; cout << endl; // Find the first pair of equal values. cout << "\n\tFirst matching pair:\n"; it = adjacent_find(intSet.begin(), intSet.end()); cout << '\t' << *it++ << endl; cout << '\t' << *it << endl; // Find the second pair of equal values. cout << "\n\tSecond matching pair:\n"; it = adjacent_find(it, intSet.end()); cout << '\t' << *it++ << endl; cout << '\t' << *it << endl; return 0; }
true
2597ce657ccad4b8eaeab4fc0eacb0b3d77a63d2
C++
utnapischtim/polygon
/server/unittests/test_TwoOptMoves.cpp
UTF-8
6,675
2.796875
3
[ "MIT" ]
permissive
#include "easylogging++.h" #include "catch.hpp" #include "../src/TwoOptMoves.cpp" bool map_compare(const auto &lhs, const auto &rhs) { auto pred = [](const auto& a, const auto &b) { return a.first == b.first && a.second == b.second; }; return std::equal(lhs.begin(), lhs.end(), rhs.begin(), pred); } TEST_CASE("test TwoOptMoves") { el::Loggers::setVerboseLevel(9); SECTION("to_key") { cgal::Segment_2 s_1 = {{10,20}, {39,22}}, s_2 = {{39,22}, {68,19}}; std::string key = to_key(s_1, s_2); std::string real = "10.000000,20.000000-39.000000,22.000000-39.000000,22.000000-68.000000,19.000000"; CHECK( (key == real) ); } SECTION("calcualteIntersection real world example") { std::vector<cgal::Segment_2> segments = { {{329.41, 755.9}, {1233.45, 71.1812}}, // 0 {{1233.45, 71.1812}, {736.707, 67.7942}},// 1 {{736.707, 67.7942}, {844.895, 122.46}}, // 2 {{844.895, 122.46}, {158.626, 338.007}}, // 3 {{158.626, 338.007}, {233.614, 369.587}},// 4 {{233.614, 369.587}, {263.873, 619.035}},// 5 {{263.873, 619.035}, {189.972, 603.056}},// 6 {{189.972, 603.056}, {80.2051, 153.456}},// 7 {{80.2051, 153.456}, {961.668, 612.329}},// 8 {{961.668, 612.329}, {329.41, 755.9}}}; // 9 auto intersection = calculateIntersections(segments); Intersections real_inters; real_inters[to_key(segments[0], segments[8])] = {segments[0], segments[8]}; real_inters[to_key(segments[3], segments[8])] = {segments[3], segments[8]}; CHECK( (map_compare(intersection, real_inters)) ); } SECTION("calculateIntersections") { //pl::PointList point_list = {{1,11},{33,15},{10,20},{21,10},{39,22},{48,9},{20,41}}; std::vector<cgal::Segment_2> segments = { {{1,11},{33,15}}, // 0 {{33,15},{10,20}},// 1 {{10,20},{21,10}},// 2 {{21,10},{39,22}},// 3 {{39,22},{48,9}}, // 4 {{48,9},{20,41}}, // 5 {{20,41},{1,11}} // 6 }; auto intersection = calculateIntersections(segments); Intersections real_inters; real_inters[to_key(segments[0], segments[2])] = {segments[0], segments[2]}; real_inters[to_key(segments[0], segments[3])] = {segments[0], segments[3]}; real_inters[to_key(segments[3], segments[5])] = {segments[3], segments[5]}; real_inters[to_key(segments[1], segments[3])] = {segments[1], segments[3]}; CHECK( (map_compare(intersection, real_inters)) ); } // SECTION("resolve Intersections real world example") { // pl::PointList point_list = {{329.41, 755.9}, {1233.45, 71.1812}, {736.707, 67.7942}, {844.895, 122.46}, {158.626, 338.007}, {233.614, 369.587}, {263.873, 619.035}, {189.972, 603.056}, {80.2051, 153.456}, {961.668, 612.329}}; // std::vector<cgal::Segment_2> segments; // pl::convert(point_list, segments); // auto intersections = calculateIntersections(segments); // resolveIntersections(segments, intersections); // pl::PointList final_list = calculateFinalList(segments); // CHECK( (final_list.size() == (point_list.size() + 1)) ); // CHECK( (calculateIntersections(segments).size() == 0) ); // } // SECTION("resolveIntersections") { // pl::PointList point_list = {{1,11},{33,15},{10,20},{21,10},{39,22},{48,9},{20,41}}; // std::vector<cgal::Segment_2> segments; // pl::convert(point_list, segments); // auto intersections = calculateIntersections(segments); // resolveIntersections(segments, intersections); // pl::PointList final_list = calculateFinalList(segments); // // ATTENTION // // equality is not possible to check because of the random // // selector in the resolveIntersections method // // pl::PointList real_list = {{1,11},{10,20},{21,10},{33,15},{48,9},{39,22},{20,41},{1,11}}; // // CHECK( (final_list == real_list) ); // // but we could check that all elements are used, and the size is // // correct ... // CHECK( (final_list.size() == (point_list.size() + 1)) ); // // ... and we have a simple polygon! // CHECK( (calculateIntersections(segments).size() == 0) ); // } SECTION("calculateFinalList source->target") { std::vector<cgal::Segment_2> segments = {{{10,20}, {39,22}}, {{39,22}, {68,19}}, {{68,19}, {48,9}}, {{48,9}, {21,10}}, {{21,10}, {1,11}}, {{1,11}, {10,20}}}; pl::PointList real = {{10,20}, {39,22}, {68,19}, {48,9}, {21,10}, {1,11}, {10,20}}; pl::PointList list = calculateFinalList(segments); // for (const auto &l : list) // VLOG(3) << "l: " << l; CHECK( (real == list) ); } SECTION("calculateFinalList misc") { std::vector<cgal::Segment_2> segments = {{{10,20}, {39,22}}, {{1,11}, {21,10}}, {{68,19}, {48,9}}, {{48,9}, {21,10}}, {{68,19}, {39,22}}, {{1,11}, {10,20}}}; pl::PointList real = {{10,20}, {39,22}, {68,19}, {48,9}, {21,10}, {1,11}, {10,20}}; pl::PointList list = calculateFinalList(segments); CHECK( (real == list) ); } SECTION("calculateFinalList twisted") { std::vector<cgal::Segment_2> segments = {{{10,20}, {39,22}}, {{68,19}, {39,22}}, {{48,9}, {68,19}}, {{21,10}, {48,9}}, {{1,11}, {21,10}}, {{10,20}, {1,11}}}; pl::PointList real = {{10,20}, {39,22}, {68,19}, {48,9}, {21,10}, {1,11}, {10,20}}; pl::PointList list = calculateFinalList(segments); CHECK( (real == list) ); } SECTION("calculateFinalList hm") { std::vector<cgal::Segment_2> segments = {{{1,11},{10,20}}, {{33,15},{21,10}}, {{10,20},{21,10}}, {{20,41},{39,22}}, {{39,22},{48,9}}, {{20,41},{1,11}}, {{48,9},{33,15}}}; pl::PointList real = {{1,11},{10,20},{21,10},{33,15},{48,9},{39,22},{20,41},{1,11}}; pl::PointList list = calculateFinalList(segments); CHECK( (real == list) ); } }
true
ef1e0ea473a2d756ed78d4f33cb1bcea44f98729
C++
Abigail-Verhelle/CS120
/RI.cpp
UTF-8
620
4.3125
4
[]
no_license
#include <iostream> using namespace std; //function to round int round (int number,int unit) { int digit = number % unit; number = number - digit; return number; } // place * 10 at some point int main (){ //input int a = 0, place= 10; cout << "Enter an integer: "; cin >> a; cout << endl; //ten cout << "Round to ten: " << round(a,place) << endl; place = place*10; //hundred cout << "Round to hundred: " << round(a,place) << endl; place = place*10; //thousand cout << "Round to thousand: " << round(a,place) << endl; }
true
e46d152f32ca2ee7fc042bb1771e060dbeeec65b
C++
agnusmaximus/GPU_W2V
/preprocess/wikipedia/create_graph_from_corpus.cpp
UTF-8
1,375
2.78125
3
[]
no_license
#include <iostream> #include <fstream> #include <map> #include <sstream> #include <deque> using namespace std; #define WINDOW 20 #define LIMIT -1 int main(int argc, char *argv[]) { ifstream in(argv[1]); map<int, map<int, int> > graph; map<string, int> word_to_id; deque<int> window; string cur_word; int id_count = 1; int iteration = 0; int n_edges = 0; while (in >> cur_word) { if (LIMIT >= 0 && iteration >= LIMIT) break; iteration++; if (word_to_id.find(cur_word) == word_to_id.end()) { word_to_id[cur_word] = id_count++; } int id = word_to_id[cur_word]; if (window.size() >= WINDOW) { window.pop_front(); } for (int i = 0; i < window.size(); i++) { if (id != window[i]) { graph[id][window[i]]++; graph[window[i]][id]++; } } window.push_back(id); } ofstream out_map("word_id_map"); for (auto const &x : word_to_id) { out_map << x.first << " " << x.second << endl; } out_map.close(); in.close(); ofstream out(argv[2]); string output = ""; for (int i = 1; i < id_count; i++) { for (auto const &x : graph[i]) { output += to_string(x.first) + " " + to_string(x.second) + " "; n_edges++; } output += "\n"; } cout << n_edges << endl; out << id_count-1 << " " << n_edges/2 << " " << "001" << endl; out << output << endl; out.close(); }
true
d306dac610b13bde7cbdd1d6db75ba7b2d984f76
C++
JCvegaDangel/Funciones
/funciones/Programa 3 tarea - mayor que en 3 datos.cpp
UTF-8
622
3.921875
4
[]
no_license
//Vega Del angel Juan Carlos - 2AV6 //Ejercicio 3 Funciones - mayor que en 3 numeros #include<iostream> using namespace std; int max(int a, int b); int main(){ int n1, n2, n3; cout << ("Introduce el valor del primer valor: ") << endl; cin >> n1; cout << ("Introduce el valor del segundo valor: ") << endl; cin >> n2; cout << ("Introduce el valor del tercer valor: ") << endl; cin >> n3; int max1 = max(n1, n2); int max2 = max(max1, n3); cout << "El numero mayor es: " << max2 << endl; return 0; } int max(int a, int b){ int c; if (a>b) {c = a; } else { c = b; } return c; }
true
280bda46c682c324c86e119574c4969cb5eb05a7
C++
marcosrodriigues/ufop
/conteudo/Introdução à Programação (Prática)/Exercicios/P03_Marcos_Rodrigues/Exercício 92.cpp
UTF-8
1,893
3.53125
4
[]
no_license
/* Numa universidade cada aluno possui os seguintes dados: - Renda pessoal; - Renda familiar; - Total gasto com alimentação; - Total gasto com outras despesas; Criar um programa que imprima a porcentagem dos alunos que gasta acima de R$ 200,00 com outras despesas, o número de alunos com renda pessoal maior que renda familiar e a porcentagem gasta com alimentação e outras despesas em relação às rendas pessoal e familiar. O programa acaba quando se digita 0 para a renda pessoal. */ #include <iostream> using namespace std; int main() { double rendaPessoal, rendaFamilia, gastoAlimentacao, gastoDespesas, porcentagem200 = 0.0, porcentagem = 0.0; int numAlunos, count = 0, count200 = 0, countRenda = 0; cout << "Digite a renda pessoal do aluno: \n"; cin >> rendaPessoal; while (rendaPessoal != 0.0) { count++; cout << "Digite a renda familiar do aluno: \n"; cin >> rendaFamilia; cout << "Digite o total de gasto com a alimentacao: \n"; cin >> gastoAlimentacao; cout << "Digite o total de gasto com a outras despesas: \n"; cin >> gastoDespesas; if (gastoDespesas > 200.00) count200++; if (rendaPessoal > rendaFamilia) countRenda++; porcentagem = ((gastoDespesas + gastoAlimentacao) / (rendaFamilia + rendaPessoal)) * 100; cout << "A porcentagem gasta com alimentacao e outras despesas em relacao as rendas pessoal e familiar eh " << porcentagem << "%\n\n"; cout << "Digite a renda pessoal do aluno: \n"; cin >> rendaPessoal; } porcentagem200 = ((double)count200 / count) * 100; cout << "A porcentagem dos alunos que possuem gasto acima de R$ 200,00 com outras despesas eh: " << porcentagem200 << "%\n"; cout << "O numero de alunos que posusem a renda pessoal superior a renda familiar eh: " << countRenda << "\n"; return 0; }
true
4fc00fe84a246334273b1b62b331265827096f7a
C++
lizhengdao/imooc_ds
/ds/SelectionSort.h
UTF-8
596
2.796875
3
[]
no_license
// // SelectionSort.h // ds // // Created by Ruby on 2021/5/12. // #ifndef SelectionSort_h #define SelectionSort_h using namespace std; template <typename T> void selectionSort(T a[], int n) { for (int i = 0; i < n; i++) { int minIndex = i; for (int j = i + 1; j < n; j++) { if (a[j] < a[minIndex]) { minIndex = j; } } swap(a[minIndex], a[i]); } } template <typename T> void selectionSortAndPrint(T a[], int n) { selectionSort(a, n); SortTestHelper::printArray(a, n); } #endif /* SelectionSort_h */
true
4444087f93c0fb3ffb58b32ba960bb3cecb3eb85
C++
rheehot/BS_Engine
/Engine/Memory/MemoryManager.cpp
UTF-8
473
2.75
3
[ "MIT" ]
permissive
#include "MemoryManager.h" #include <cstdlib> namespace BE { void MemoryManager::Init(std::initializer_list<SizeType> memorySizes) { check(memorySizes.size() == 5); auto sizes{ memorySizes.begin() }; managerMemory.Init (sizes[0]); componentMemory.Init(sizes[1]); resourceMemory.Init (sizes[2]); oneFrameMemory.Init (sizes[3]); heapMemory.Init (sizes[4]); } void MemoryManager::Release() noexcept { heapMemory.Release(); free(curMemory); } }
true
834b9fc58a9b32f6d06d0efab6d2ad5c25992d02
C++
zhaojidabao/MGCode
/Dot.cpp
GB18030
3,327
3.015625
3
[]
no_license
// DotB.cpp: implementation of the CDot class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Dot.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CDot::CDot() { m_bScale = FALSE; x = y = z = 0; } CDot::~CDot() { } CDot::CDot(CPoint &pt) { x=pt.x; y=pt.y; z=0; } CDot::CDot(POINT pt) { x=pt.x; y=pt.y; z=0; } CDot::CDot(double xValue, double yValue) { x=xValue; y=yValue; z=0; } void CDot::operator =(const DOT & src) { x=src.x; y=src.y; z=src.z; } void CDot::operator =(const CDot & src) { x=src.x; y=src.y; z=src.z; } BOOL CDot::operator ==(const CDot & src) { if((fabs(x - src.x) < EPSINON) && (fabs(y - src.y) < EPSINON)) { return TRUE; } else { return FALSE; } } void CDot::operator *=(double mul) { x*=mul; y*=mul; } CDot::operator CPoint() { CPoint pt; pt.x=(int)x; pt.y=(int)y; return pt; } void CDot::XChangeY() { double tx; tx = x; x = y; y = tx; } void CDot::Scale(CDot center,double ratioX, double ratioY) { if (fabs(ratioX) < EPSINON) ratioX = 0.000000001; if (fabs(ratioY) < EPSINON) ratioY = 0.000000001; double tx(0),ty(0); tx=x-center.x; x=ratioX*tx+center.x; ty=y-center.y; y=ratioY*ty+center.y; return; } void CDot::SetOffset(double xf,double yf) { x+=xf; y+=yf; } void CDot::Move(double moveX, double moveY) { x+=moveX; y+=moveY; } void CDot::LogToTrue() { x=(x-LCENTER)/DPMM; y=(LCENTER-y)/DPMM; } void CDot::TrueToLog() { x=x*DPMM+LCENTER; y=LCENTER-y*DPMM; } void CDot::Rotate(CDot center, double angle) { double dbx,dby,r,Araf; dbx=x-center.x; dby=y-center.y; r=sqrt(dbx*dbx+dby*dby); if(dbx!=0) { Araf=atan(dby/dbx); if(dbx<0) Araf+=PAI; } else { Araf=PAI/2; if(dby<0) Araf=-PAI/2; } Araf+=angle*PAI/180; x=center.x+r*cos(Araf); y=center.y+r*sin(Araf); } /***************************************************************************** : жָǷ߶ : p1 --- ߶㡡p2 --- ߶յ ֵ ߶ TRUE 򷵻FALSE ******************************************************************************/ BOOL CDot::IsDotInLine(CDot& p1 , CDot& p2 ) { // жϵǷӾηΧ if ( x < min(p1.x ,p2.x) || x > max(p1.x ,p2.x) || y < min(p1.y ,p2.y) || y > max(p1.y ,p2.y)) { return FALSE; } // double dblMulti = (double)((x - p1.x) * (p2.y - p1.y) - (p2.x - p1.x) * (y - p1.y)); if ( fabs(dblMulti) < EPSINON ) { return TRUE; } else { return FALSE; } } // double CDot::DistanceFromDot(CDot dot) { return pow(pow(x-dot.x,2)+pow(y-dot.y,2),0.5); } void CDot::Round(int digit) { double temp1 = pow(double(10), digit); if (x>=0) x = int((x*temp1+0.5))/temp1; else x = -int((-x*temp1+0.5))/temp1; if (y>=0) y = int((y*temp1+0.5))/temp1; else y = -int((-y*temp1+0.5))/temp1; } CDot CDot::Center(const CDot &dot1, const CDot &dot2) { CDot dotCenter; dotCenter.x = (dot1.x + dot2.x)/2; dotCenter.y = (dot1.y + dot2.y)/2; return dotCenter; }
true
25ced2c14086a7b26037d52cce5f0e89b259840e
C++
tz01x/Algorithm
/Singel_source_Bellman_fore_.cpp
UTF-8
2,797
2.671875
3
[ "MIT" ]
permissive
#include<bits/stdc++.h> using namespace std; int infinity=numeric_limits<int>::max(); //class node{ //public: // int key; // int weight; // node(){ // key=0; // weight=0; // } // node(int key,int weight){ // this->key=key; // this->weight=weight; // // } //}temp; //class Edge{ //public: // int u,v; // int weight; // Edge(){ // u=0; // v=0; // weight=0; // } // Edge(int u,int v,int weight){ // this->u=u; // this->v=v; // this->weight=weight; // // } //}edge; struct node{ int key,weight; }temp; struct Edge{ int u,v,weight; }edge; int Bellman_ford(vector<Edge>e,int n,int s){ long long int d[n],p[n]; for(int i=0;i<n;i++){ d[i]=infinity; p[i]= -1; } d[s]=0; for(int i=0;i<n;i++){ if (d[i]==infinity) printf("infinity "); else cout<<d[i] << " "; }cout<<endl; //for (int j=0;j<e.size();j++){ // edge=e[j]; // cout<<edge.u<<" "<<edge.weight<< " w "; //} cout<<endl; for(int i=0;i<n-1;i++){ for (int j=0;j<e.size();j++){ edge=e[j]; if((d[edge.u]+edge.weight<d[edge.v])){ printf("node {%d} -> node {%d} and weight is %d\n",edge.u,edge.v,edge.weight); cout<< "dis of u "<<d[edge.u]<<endl; printf("dis of v %d\n",d[edge.v]); d[edge.v]=d[edge.u]+edge.weight; ///Relaxing cout<<"Relaxing.."<<endl; printf("node {%d} -> node {%d} and weight is %d\n",edge.u,edge.v,edge.weight); cout<< "dis of u "<<d[edge.u]<<endl; printf("dis of v %d\n",d[edge.v]); p[edge.v]=edge.u; } } } for(int i=0;i<n;i++){ if (d[i]==infinity) printf("infinity "); else cout<<d[i] << " "; // printf("prante is %d \n",p[i]); }cout<<endl; for (int j=0;j<e.size();j++){ edge=e[j]; if(d[edge.u]+edge.weight<d[edge.v]){ return 0; } } return 1; } int main(){ int n,en; bool is_directed=true; cin>>n; vector<node>g[n]; vector<Edge>e; cin>>en; for(int i=0;i<en;i++){ int row,col,weight; cin>>row>>col>>weight; ///graph input temp.key=col; temp.weight=weight; g[row].push_back(temp); ///edge edge.u=row; edge.v=col; edge.weight=weight; e.push_back(edge); if (!is_directed){ temp.key=row; g[col].push_back(temp); edge.u=col; edge.v=row; e.push_back(edge); } } int source=2; if (Bellman_ford(e,n,source)){ cout<<"works perfectly "<<endl; } else{ cout<<"neg or positive cycle found "<<endl; } }
true
87929c55fc529fb8e14eb4aae7cdf1da07f02653
C++
Falcon20/Data-Structures-and-Algorithms
/Tree/count_leaves_in_a_binary_tree_iterative.cpp
UTF-8
791
3.875
4
[]
no_license
// Problem link - https://practice.geeksforgeeks.org/problems/count-leaves-in-binary-tree/1 /* A binary tree node has data, pointer to left child and a pointer to right child struct Node { int data; Node* left; Node* right; }; */ /* Should return count of leaves. For example, return value should be 2 for following tree. 10 / \ 20 30 */ // Iterative solution int countLeaves(Node* root) { if(root == NULL) return 0; int res = 0; queue<Node *>q; q.push(root); while(!q.empty()) { Node *u = q.front(); q.pop(); if(u->left == NULL && u->right == NULL) { res++; continue; } if(u->left) q.push(u->left); if(u->right) q.push(u->right); } return res; }
true
adbf9462478e1451afbbc298893eadc662bbacd6
C++
omarshawky15/Data-Structures-and-Algorithms-solutions-Coursera-
/Strings/Week 2/bwmatching/bwmatching.cpp
UTF-8
3,536
3.234375
3
[]
no_license
#include <algorithm> #include <cstdio> #include <iostream> #include <string> #include <vector> using namespace std; static const int noCh = 5; int chartoidx(char ch) { switch (ch) { case 'A' : return 0; case 'C' : return 1; case 'G' : return 2; case 'T' : return 3; default: return 4; } } void PreprocessBWT(const string &bwt, vector<int> &firstocc, vector<vector<int>> &arr) { vector<int> v(bwt.size() + 1, 0); vector<int> lastocc(noCh, 0); int sz = bwt.size(), sz1 = sz - 1; for (int i = 0; i < sz; i++) { int idx = chartoidx(bwt[i]); arr[i + 1][idx] = 1; v[i] = lastocc[idx]++; for (int j = 0; j < noCh; j++)arr[i + 1][j] += arr[i][j]; } firstocc[0] = 1; for (int i = 1; i < 4; i++) { firstocc[i] = lastocc[i - 1] + firstocc[i - 1]; } /* string text = "$"; int x = 0; for (int i = 0; i < sz1; i++) { text += bwt[x]; x = firstocc[chartoidx(bwt[x])] + v[x]; } reverse(text.begin(), text.end()); return text; */ } // Preprocess the Burrows-Wheeler Transform bwt of some text // and compute as a result: // * starts - for each character C in bwt, starts[C] is the first position // of this character in the sorted array of // all characters of the text. // * occ_count_before - for each character C in bwt and each position P in bwt, // occ_count_before[C][P] is the number of occurrences of character C in bwt // from position 0 to position P inclusive. // Compute the number of occurrences of string pattern in the text // given only Burrows-Wheeler Transform bwt of the text and additional // information we get from the preprocessing stage - starts and occ_counts_before. int CountOccurrences(const string &pattern, const string &bwt, const vector<int> &firstocc, const vector<vector<int>> &arr) { int top = 0, bottom = bwt.size()-1; for (int i = pattern.size() - 1; i >= 0; i--) { int idx = chartoidx(pattern[i]); top = firstocc[idx] + arr[top][idx]; bottom = firstocc[idx] + arr[bottom + 1][idx] - 1; if (bottom < top)return 0; } return bottom - top + 1; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); string bwt; cin >> bwt; int pattern_count; cin >> pattern_count; // Start of each character in the sorted list of characters of bwt, // see the description in the comment about function PreprocessBWT vector<int> firstocc(noCh, 0); vector<vector<int>> arr(bwt.size() + 1, vector<int>(noCh, 0)); //map<char, int> starts; // Occurrence counts for each character and each position in bwt, // see the description in the comment about function PreprocessBWT //map<char, vector<int> > occ_count_before; // Preprocess the BWT once to get starts and occ_count_before. // For each pattern, we will then use these precomputed values and // spend only O(|pattern|) to find all occurrences of the pattern // in the text instead of O(|pattern| + |text|). PreprocessBWT(bwt, firstocc, arr); for (int pi = 0; pi < pattern_count; ++pi) { string pattern; cin >> pattern; int occ_count = CountOccurrences(pattern, bwt, firstocc, arr); printf("%d ", occ_count); } printf("\n"); return 0; }
true
4997e916b940ba5b4c27a9d1190b518f0f035fea
C++
imefisto/catchcmake-modular
/src/PersonModule/src/Person.cpp
UTF-8
421
2.96875
3
[ "MIT" ]
permissive
#include "PersonModule/Person.h" std::string PersonModule::Person::getFullName() { std::string fullName = _name; if(_name.length() > 0 && _surname.length() > 0) { fullName += " "; } fullName += _surname; return fullName; } void PersonModule::Person::setName(const std::string & name) { _name = name; } void PersonModule::Person::setSurname(const std::string & surname) { _surname = surname; }
true
302ac00a2df2485fd5915fdf254d56cfcac71c4c
C++
AlexMaz99/WDI
/lab9,10/zad15.cpp
UTF-8
1,254
3.875
4
[]
no_license
#include <iostream> using namespace std; struct node { int w; node *next; }; bool repeated(node *first, node *p) { while (first != NULL) { if (first != p && first->w == p->w) return true; first = first->next; } return false; } // 3 3 2 1 6 1 9 // 3 2 1 6 9 void remove(node *first) { if (first == NULL) return; node *p = first; while (p->next != NULL) { if (repeated(first, p->next)) { node *q = p->next; p->next = q->next; delete q; } else p = p->next; } } void insert_last(node *&first, int n) //dodawanie elementu na koniec listy { node *p = new node; p->w = n; p->next = NULL; if (first == NULL) first = p; else { node *r = first; while (r->next != NULL) { r = r->next; } r->next = p; } } int main() { node *first = new node; first = NULL; insert_last(first, 3); insert_last(first, 3); insert_last(first, 2); insert_last(first, 1); insert_last(first, 6); insert_last(first, 1); insert_last(first, 9); remove(first); while (first != NULL) { cout << first->w << " "; first = first->next; } return 0; }
true
3a3c25a509c9030b9d375f7ee159145fcad29eb9
C++
olinrobotics/edwin_stereo
/src/rectifier.cpp
UTF-8
2,230
2.5625
3
[ "MIT" ]
permissive
#include <string> #include <iostream> #include "edwin_stereo/rectifier.h" Mat get_matrix(const YAML::Node& node){ int cols = node["cols"].as<int>(); int rows = node["rows"].as<int>(); auto m_base = Mat_<float>(rows,cols); std::vector<float> data; //data.reserve(cols*rows); for (const auto& d : node["data"]){ data.push_back(d.as<float>()); } auto m = Mat(rows,cols,CV_32F); memcpy(m.data, data.data(), data.size() * sizeof(float)); return m; } void get_matrices(const YAML::Node& config, Mat& m, Mat& d, Mat& r, Mat& p){ m = get_matrix(config["camera_matrix"]); d = get_matrix(config["distortion_coefficients"]); r = get_matrix(config["rectification_matrix"]); p = get_matrix(config["projection_matrix"]); } Rectifier::Rectifier(const string& param_l, const string& param_r){ YAML::Node config_l = YAML::LoadFile(param_l); YAML::Node config_r = YAML::LoadFile(param_r); Mat m_l, d_l, r_l, p_l, \ m_r, d_r, r_r, p_r; get_matrices(config_l, m_l, d_l, r_l, p_l); get_matrices(config_r, m_r, d_r, r_r, p_r); int width = config_l["image_width"].as<int>(); int height = config_l["image_height"].as<int>(); double fx = p_l.at<float>(0,0); double cx = p_l.at<float>(0,2); double cy = p_l.at<float>(1,2); double fy = p_l.at<float>(1,1); double Tx = p_r.at<float>(0,3) / p_r.at<float>(0,0); double rcx = p_r.at<float>(0,2); //printf("fx: %f; cx: %f; cy: %f; fy: %f; Tx: %f; rcx: %f\n", fx,cx,cy,fy,Tx,rcx); Q = (Mat_<double>(4,4,CV_64F) << \ fy*Tx, 0, 0, -fy*cx*Tx, \ 0, fx*Tx, 0, -fx*cy*Tx, \ 0, 0, 0, fx*fy*Tx, \ 0, 0, -fy, fy*(cx-rcx)); cv::initUndistortRectifyMap(m_l,d_l,r_l,p_l,Size(width,height),CV_32F, c_l_m1, c_l_m2); cv::initUndistortRectifyMap(m_r,d_r,r_r,p_r,Size(width,height),CV_32F, c_r_m1, c_r_m2); } void Rectifier::apply(const Mat& l, const Mat& r, Mat& rect_l, Mat& rect_r){ remap(l,rect_l,c_l_m1,c_l_m2,INTER_LINEAR); remap(r,rect_r,c_r_m1,c_r_m2,INTER_LINEAR); } void Rectifier::convert(const Mat& disp, Mat& dist){ Mat disp_f; disp.convertTo(disp_f,CV_32F, 1/16., 0.0); cv::reprojectImageTo3D(disp_f, dist, Q, true, CV_32F); } //int main(){ // // Rectifier r( // "./left_camera.yaml", // "./right_camera.yaml" // ); // // return 0; //}
true
775379ea83e17fbea0e3d7f8e4ae54597855e77d
C++
sunny-aguilar/lab3
/Die.hpp
UTF-8
1,067
3.359375
3
[ "MIT" ]
permissive
/********************************************************************* ** Author: Sandro Aguilar ** Date: Jan 2019 ** Description: This dice class creates an object that has a ** member function that returns a random integer from ** 1 to N (this function is over ridden by the ** LoadedDie class). Includes setter/getters for N. ** Die class is the base class for LoadedDie class. *********************************************************************/ #ifndef DIE_HPP #define DIE_HPP #include <iostream> #include <ctime> #include <vector> using std::vector; class Die { public: Die(); // default constructor Die(int num); // 1-arg constructor int randomInt(); // returns a random integer void setSides(int sides); // setter that sets die sides int getSides(); // getter that returns die sides protected: int N; // number of sides on the die }; #endif
true
e375017d1fe0f10c7f2868258aea1e4b6ad691cb
C++
StevenHickson/CreateNormals
/CreateNormals.h
UTF-8
2,368
2.640625
3
[ "MIT" ]
permissive
#include <iostream> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> bool ReadParameters(const std::string &filename, std::vector<float> *camera_params, std::vector<float> *normal_params, std::vector<bool> *flat_labels); void CreateNormals(const std::vector<float> &camera_params, const std::vector<float> &normal_params, const std::vector<bool> &flat_labels, const cv::Mat &depth, const cv::Mat &labels, cv::Mat *output); void CreateNormalsPython(float *camera_params, int camera_params_length, float *normal_params, int normal_params_length, int* flat_labels, int flat_labels_length, int width, int height, unsigned short int *depth, unsigned short int *labels, float *output); bool CreateNormals(const std::vector<float> &camera_params, const std::vector<float> &normal_params, const std::vector<bool> &flat_labels, const std::string &depth_file, const std::string &labels_file, const std::string &output_file); extern "C" { void CalculateNormals(float *camera_params, int camera_params_length, float *normal_params, int normal_params_length, int* flat_labels, int flat_labels_length, int width, int height, unsigned short int *depth, unsigned short int *labels, float *output) { return CreateNormalsPython(camera_params, camera_params_length, normal_params, normal_params_length, flat_labels, flat_labels_length, width, height, depth, labels, output); } }
true
fcddf2e10d4027084209f0c25f798b5794576de7
C++
chriskatnic/CPSC301
/C-string and arrays/cString.cpp
UTF-8
4,574
3.765625
4
[]
no_license
// Chris Katnic // 09.30.13 // C-strings and arrays #include <cstring> #include <iostream> using namespace std; int welcome(); // welcome(): Prints out a welcome page and returns the number of books that the user wants to enter void readInfo(int, char[][70], char[][70]); // readInfo(): Takes in the information that the user types in into arrays char getSelection(); // getSelection(): Gets the user's choice of how to sort the books void sort(char, char [][70], char [][70], int); // sort(): Using the user's choice, choose sorting method void selectionSort(int, char[][70]); // selectionSort(): Using selection sort, change the order of the books in the array, as per the user's chosen method void swap(char[70], char[70]); // swap(): Utilized within function selectionSort(), swaps the positions of two cstrings in an array void display(int, char[][70]); // display(): Prints out the now ordered list, to the specifications of the user int main() { char nameTitle[20][70], titleName[20][70]; // 20 for the amount of books, 60 characters; char sentinel = 'c'; int numBooks = welcome(); // Get the number of books readInfo(numBooks, nameTitle, titleName); // Read in book info while(sentinel != 'q' && sentinel != 'Q') // While loop to sort until the user says to quit 'q' { sentinel = getSelection(); // Check to see how the user would like to sort sort(sentinel, nameTitle, titleName, numBooks); // Sort function starts all other functions within it } return 0; } int welcome() { cout << "Welcome to the CS Library program \nPlease enter the number of books:\t"; int x; cin >> x; return x; } void readInfo(int numBooks, char nameTitle[][70], char titleName[][70]) { char lname[15], fname[15], title[30], temp[70]; // C-Strings to hold names, title, and one temporary to hold all cout << "Enter the first name, last name, and book title:\n"; for(int i=0;i<numBooks;i++) // While the user has not typed in [number of books] titles, first names, and last names { // Continue to read in titles, and concatenate them to one large temporary c-string cin >> fname >> lname; cin.ignore(1); //ignore whitespace between comma and title cin.getline(title, 999, '\n'); strcpy_s(temp, lname); strcat_s(temp, ", "); strcat_s(temp, fname); strcat_s(temp, ", "); strcat_s(temp, title); strcpy_s(nameTitle[i], temp); // Take temporary c-string and copy to the appropriate array // Then, overwrite the temporary string to create a new order strcpy_s(temp,title); strcat_s(temp, ", "); strcat_s(temp, lname); strcat_s(temp, ", "); strcat_s(temp, fname); strcpy_s(titleName[i], temp); // Take temporary c-string and copy to the appropriate array cout << endl; } } char getSelection() { cout << "The program will display all books sorted according to your choice.\n" << "Please enter your one letter choice as follows:\n" << "A: sort the books by the last names of the authors\n" << "T: sort the books by the titles\n" << "Q: quit this program\n" << endl; char x; cin >> x; return x; } void sort(char sentinel, char nameTitle[][70], char titleName[][70], int numBooks) { switch(sentinel) // Switch statement depending on the character inputted by the user { case 'a': case 'A': { selectionSort(numBooks, nameTitle); // Sort by last name first if choice is 'a' or 'A' display(numBooks, nameTitle); // Display newly sorted array cout << endl; break; } case 't': case 'T': { selectionSort(numBooks, titleName); // Sort by title first if choice is 't' or 'T' display(numBooks, titleName); // Display newly sorted array cout << endl; break; } case 'q': case 'Q': { break; } } } void selectionSort(int numBooks, char x[][70]) { int i, j, lowIndex; char lowCString[70]; for(i=0; i<numBooks; i++) { lowIndex = i; strcpy_s(lowCString, 70, x[i]); for(j=i+1; j<numBooks; j++) { if(strcmp(lowCString, x[j]) > 0) { strcpy_s(lowCString, x[j]); lowIndex = j; } } swap(x[i], x[lowIndex]); } } void swap(char cstring1[70], char cstring2[70]) { char temp[70]; strcpy_s(temp, cstring1); strcpy_s(cstring1, 70, cstring2); strcpy_s(cstring2, 70, temp); } void display(int numBooks, char x[][70]) { for(int i=0; i<numBooks; i++) { cout << x[i] << endl; } }
true
c798e598ca5e8f47fda655a4797e7e4a2e70611c
C++
atran126/Musical-Mechanical-Calculator
/Button.h
UTF-8
401
2.828125
3
[ "MIT" ]
permissive
/* Buffer.h Header file for the button class */ /* Ensures no errors if user includes the class twice */ #ifndef Button_h #define Button_h class Button { public: Button(int mult, int pin); int press_button(int val); int get_val(); int get_pin(); int reset(); private: int times_pressed; int multiplier; int pin_num; }; #endif
true
bf27e8120f0138fead47bd656dd70c6ca679b819
C++
GilM04/C-Users-Francisco-Desktop-lorenys-documentos
/PROYECTO FINAL.cpp
UTF-8
810
3.125
3
[ "MIT" ]
permissive
#ifdef __MSDOS__ #include <iostream.h> #include <stdlib.h> #else #include <iostream> #include <cstdlib> using namespace std; #endif int main (void) { float cuotas, interes, pago_por_cuota, prestamo; cout << "Ingrese el valor de prestamo: "; cin >> prestamo; cuotas=3; if(prestamo>5000) cuotas=5; if(prestamo<1000) cuotas=1; if(prestamo>=1000&&prestamo<=3000) cuotas=2; interes=prestamo<4000?prestamo*0.1:prestamo*0.12; pago_por_cuota=(prestamo+interes)/cuotas; cout << "Valor de cuotas: " << cuotas << endl; cout << "Valor de interes: " << interes << endl; cout << "Valor de pago por cuota: " << pago_por_cuota << endl; cout << endl; system ("pause"); return EXIT_SUCCESS; }
true
8e70d13707ed6e0887cc1000e04eef865012dca9
C++
gghcode/practice-problem-solving
/src/lavida/1727.cpp
UTF-8
557
3.015625
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; bool cmp(const pair<int, float>& o1, const pair<int, float>& o2) { return o1.second > o2.second; } int main() { int TC; scanf("%d", &TC); while (TC--) { pair<int, float> arr[3]; for (int i = 0; i < 3; i++) { float x, y; scanf("%d %d", &x, &y); arr[i] = {i + 1, y / x}; } sort(arr, arr + 3, cmp); printf("%d\n", arr[0].first); } }
true
cf023976902238062df0f4457a6c7a4329384cad
C++
2534537w/Data-Structure
/14-hash-table/main.cpp
UTF-8
1,179
2.90625
3
[]
no_license
#include "hash_table.hpp" #include "file_ops.hpp" #include <ctime> vector<string> words; int main() { cout << "test hash" << endl; // 我们使用文本量更小的共产主义宣言进行试验:) //string filename = "communist.txt"; string filename = "pride-and-prejudice.txt"; //string filename = "a-tale-of-two-cities.txt"; if( FileOps::readFile(filename, words) ) { cout << "words size = " << words.size() << endl; } HashTable<string, int>* s = new HashTable<string, int>(); clock_t start1 = clock(); for(auto i : words) { if(s->contain(i) == true) s->set(i, s->get(i)+1); else s->add(i, 1); } for(auto i : words) assert(s->contain(i) == true); for(int i = 0; i < 30; i++) s->remove("words[i]"); ///assert(s->size() == 0); ///assert(s->empty() == true); clock_t end1 = clock(); cout << "hash-table" << " takes " << (double)(end1-start1) / CLOCKS_PER_SEC << " s" << endl; cout << "hash-table" << " count = " << s->size() << endl; cout << "#################################################" << endl; return 0; }
true
e59d212060aaa25ad273158fd9ff126d9aba3e0e
C++
nrey/eulerProject
/eu0062/eu0062.cpp
UTF-8
1,443
2.828125
3
[]
no_license
#include"eu0062.h" void eu0062 :: solucion(){ // ---------------------------------------------------- // tstart = (double)clock()/CLOCKS_PER_SEC; // ---------------------------------------------------- // output = 0; // ---------------------------------------------------- // std::map<long,int> cubos; std::map<long,unsigned long long> primercubo; // FIXME Read the code tem_1d_1 = new unsigned long long[12]; tem_1d_2 = new unsigned long long[10]; for( unsigned long long j=4642; j<=9999; j++ ){ temp_11 = pow(j,3); //464 digits(&temp_11,12,tem_1d_1); for( unsigned long long i=0; i<10; i++ ){ // Borra contador tem_1d_2[i] = 0; } for( unsigned long long i=0; i<12; i++ ){ // Hace el mapping tem_1d_2[tem_1d_1[i]]++; } temp_12 = 0; for( unsigned long long i=0; i<10; i++ ){ // Crea el key temp_12 = temp_12 + pow(10,i)*tem_1d_2[i]; } ++cubos[temp_12]; if(cubos[temp_12]==1){ // Si es el primer cubo primercubo[temp_12] = temp_11; } if(cubos[temp_12]==5){ output = primercubo[temp_12]; break; } } // ---------------------------------------------------- // tstop = (double)clock()/CLOCKS_PER_SEC; ttime = tstop-tstart; // ---------------------------------------------------- // } void eu0062 :: printsolution(){ std::cout << "Euler 0062\n"; std::cout << "Time: " << ttime << "\n"; std::cout << output; }
true
5338d828fd91a1ec2eee7d4b80070311ea19d94f
C++
huangguojun/cmake
/clang-blueprint/src/main.cpp
UTF-8
400
2.96875
3
[]
no_license
/// \file #include <bits/stdint-intn.h> #include <cstdint> #include <cstdlib> #include <iostream> #include "fact/factorial.h" /// Program entry point. int32_t main(const int32_t /*argc*/, const char** /*argv[]*/) { const int32_t n = 7; const int32_t result = fact::factorial(n); std::cout << "Hello, World! factorial(" << n << ") = " << result << std::endl; return int32_t(0); }
true
78e7ee30c88fa48196470b0e84be6712a6a0c28e
C++
AtlasGooo/Infantry_code
/infantry_serial/include/Packet.hpp
UTF-8
2,165
2.65625
3
[]
no_license
#ifndef PACKET_HPP #define PACKET_HPP #include "StreamBytesBuffer.hpp" namespace stream { class PacketBehaviorProto; enum class StreamType { PacketStreamType = 1, BytesStreamType = 2, }; template<StreamType type> class Stream; template<class PacketProtoType> class PacketTypeList { public: static PacketTypeList* Instance() { static PacketTypeList instance; return &instance; } ~PacketTypeList() { ; } void AddType(PacketProtoType*) { ; } private: PacketTypeList() { ; } std::vector<PacketProtoType*> m_packet_type_list; }; class PacketModelProto { friend class StreamBytesBuffer; friend class PacketBehaviorProto; public: PacketModelProto(uint16_t _id,uint8_t _data_length) :m_id(_id) , m_data_length(_data_length){ ; } ~PacketModelProto() { ; } std::vector<DataUnitProto*>* GetUnitList() { return &m_unit_list; } protected: uint16_t m_id; uint8_t m_data_length; std::vector<DataUnitProto*> m_unit_list; }; class PacketBehaviorProto { public: PacketBehaviorProto(PacketModelProto* _unit_list) :m_model(_unit_list),m_update_flag(false),m_used_flag(false) { ; } ~PacketBehaviorProto() { ; } PacketBehaviorProto& operator<<(PacketBehaviorProto&); PacketBehaviorProto& operator>>(PacketBehaviorProto&); virtual void ToStream(Stream<StreamType::PacketStreamType>*) = 0; virtual void ToStream(Stream<StreamType::BytesStreamType>*); void ToStream(PacketBehaviorProto*); virtual void FromStream(Stream<StreamType::PacketStreamType>*) = 0; virtual void FromStream(Stream<StreamType::BytesStreamType>*); void FromStream(PacketBehaviorProto*); void SetUpdateFlag(bool _set) { m_update_flag = _set; } bool GetUpdateFlag() { return m_update_flag; } void SetUsedFlag(bool _set) { m_used_flag = _set; } bool GetUsedFlag() { return m_used_flag; } uint16_t GetID() { return m_model->m_id; } void SetDataLength(uint8_t _set){m_model->m_data_length = _set;} uint8_t GetDataLength(){return m_model->m_data_length;} PacketModelProto* GetModel() { return m_model; } protected: PacketModelProto* m_model; bool m_update_flag; bool m_used_flag; }; } #endif
true
993f0cfd1ba26d0f077bb3185562326a53e2823d
C++
sgc109/algorithm_practice
/ssm1.cpp
UTF-8
1,964
2.59375
3
[]
no_license
#include <cstdio> #include <iostream> #include <cstring> #include <cmath> #include <vector> #include <utility> #include <algorithm> using namespace std; typedef long long ll; const int mod = 1e9 + 7; const int inf = 0x3c3c3c3c; const long long infl = 0x3c3c3c3c3c3c3c3c; class Rumor { public: int N; int got[17][2]; int gave[17][2]; int tgot[17][2]; int tgave[17][2]; int getMinimum(string knowledge, vector<string> graph) { N = (int)knowledge.size(); int ans = inf; for (int mask = 0; mask < (1 << N); mask++) { memset(got, 0, sizeof(got)); memset(gave, 0, sizeof(gave)); for (int i = 0; i < N; i++) if (knowledge[i] == 'Y') got[i][0] = got[i][1] = 1; int i; for (i = 0; i < N + 2; i++) { int ok = 1; for (int j = 0; j < N; j++) if (!got[j][0] || !got[j][1]) ok = 0; if (ok) break; for (int j = 0; j < N; j++) { for (int k = 0; k < 2; k++) { tgave[j][k] = gave[j][k]; tgot[j][k] = got[j][k]; } } for (int j = 0; j < N; j++) { int o = (mask & (1 << j)) != 0; int cur = 0; if (gave[j][o]) cur = !o; else cur = o; if (!got[j][cur] || gave[j][cur]) continue; for (int k = 0; k < N; k++) { if (graph[j][k] == 'N') continue; tgot[k][cur] = 1; } tgave[j][cur] = 1; } for (int j = 0; j < N; j++) { for (int k = 0; k < 2; k++) { gave[j][k] = tgave[j][k]; got[j][k] = tgot[j][k]; } } } int ok = 1; for (int j = 0; j < N; j++) if (!got[j][0] || !got[j][1]) ok = 0; if (!ok) continue; ans = min(ans, i); } if (ans == inf) ans = -1; return ans; } }; int main() { Rumor obj; cout << obj.getMinimum( "NNNNNNNYYY", {"NYNNYNNYNN" , "NNYNYNNNNY" , "YYNNNYNNNN" , "YNNNYNYNNN" , "NNYNNYNNYN" , "NNNNYNNNYY" , "NYNYNYNNNN" , "NNNNNNYNYY" , "NNNYNNNYNY" , "NYYNNNNYNN"} ); return 0; }
true
ba91e057148d36252f9477e5d90cbdd8b74a98ab
C++
Ayushtytripatha/Placement-Questions
/sorting/Merge.cpp
UTF-8
1,094
3.125
3
[]
no_license
#include<iostream> using namespace std; void merge(int arr[],int lb,int mid,int ub){ int i = lb; int j = mid+1; int k = lb; int b[ub+1]; while(i<=mid && j<=ub){ if(arr[i]<=arr[j]){ b[k] = arr[i]; k++; i++; } else{ b[k] = arr[j]; k++; j++; } } if(i>mid){ while(j<=ub){ b[k] = arr[j]; k++; j++; } } else{ while(i<=mid){ b[k] = arr[i]; i++; k++; } } for(int i=lb;i<k;i++){ arr[i] = b[i]; } } void mergesort(int arr[],int lb,int ub){ if(lb<ub){ int mid = (lb+ub)/2; mergesort(arr,lb,mid); mergesort(arr,mid+1,ub); merge(arr,lb,mid,ub); } } int main(){ int n; cin>>n; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } mergesort(arr,0,n-1); for(int i=0;i<n;i++){ cout<<arr[i]<<" "; } }
true
2cda5c14de0bf671096ced4afa9031c50130049c
C++
camdenvaughan/Algorithm-Visualization
/src/utility/Button.h
UTF-8
1,147
2.609375
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> #include <iostream> enum class SceneState; class Button : public sf::Drawable { public: Button(std::string text, sf::Vector2f position, SceneState sceneState, unsigned int fontSize = 25, sf::IntRect defaultTextureCoords = sf::IntRect(0, 0, 192, 64), sf::IntRect clickTextureCoords = sf::IntRect(0, 64, 192, 64), sf::IntRect hoverTextureCoords = sf::IntRect(192, 0, 192, 64), sf::Color textColor = sf::Color::White); void draw(sf::RenderTarget& target, sf::RenderStates state) const override; void ClickButton(); void SetFont(sf::Font& font); void SetDefaultTexCoords(sf::IntRect texCoords); void SetClickTexCoords(sf::IntRect texCoords); void SetHoverTexCoords(sf::IntRect texCoords); void SetTextFillColor(sf::Color color); void SetPosition(sf::Vector2f position); bool MouseIsOver(sf::Vector2i mousePos); SceneState GetSceneState() const; public: const std::string name; bool hasBeenClicked = false; private: SceneState m_SceneState; sf::IntRect m_DefaultTexCoord; sf::IntRect m_ClickTexCoord; sf::IntRect m_HoverTexCoord; sf::Sprite m_Sprite; sf::Text m_Text; };
true
07c9a2e177fc794ef61be02c2125967ff3e84605
C++
MariyanMomchilov/HuffmanCoding
/HuffmanCodingProject/include/HuffmanTree.h
UTF-8
1,463
2.859375
3
[]
no_license
#ifndef __HUFFMAN #define __HUFFMAN #include "PriorityQueue.h" #include <string> #include <stack> class HuffmanTree { private: Node *root; friend std::ostream &operator<<(std::ostream &os, HuffmanTree &tree); friend std::istream &operator>>(std::istream &is, HuffmanTree &tree); void clear(Node *node); std::string search(Node *node, char s, bool &valid) const; void toScheme(std::ostream &os, Node *node) const; Node *fromSchemeRec(std::istream &is); Node *clone(Node *from) const; public: HuffmanTree(); HuffmanTree(const HuffmanTree &other); HuffmanTree(HuffmanTree &&rval) noexcept; HuffmanTree &operator=(const HuffmanTree &other); HuffmanTree &operator=(HuffmanTree &&rval) noexcept; HuffmanTree(PriorityQueue &queue); std::string getEncoded(char s) const; char getDecoded(const char *&s) const; char getDecoded(std::string &s) const; void toScheme(std::ostream &os) const; void fromScheme(std::istream &is); void toGraphViz(std::ofstream &os) const; void toGraphViz(std::ofstream &os, Node *node) const; ~HuffmanTree(); class Iterator { private: std::stack<Node *> s; Node *prev; public: Iterator(Node *start = nullptr); Iterator &operator++(); bool operator!=(const Iterator &rh) const; Node *operator*(); ~Iterator() = default; }; Iterator begin(); Iterator end(); }; #endif
true
3507a3e74d1e934c11cf7d31b23ae12788cef7a2
C++
bancamaria/POO-Lists
/List.h
UTF-8
1,672
3.671875
4
[]
no_license
#ifndef LIST_H_INCLUDED #define LIST_H_INCLUDED using namespace std; ///creating a class for the list class List { ///declaring a structure for node elements struct node{ int value; node *next; }*first, *last; public: ///public type for accessing node elements typedef node* pNode; ///initializing the first and last element with NULL List(): first(NULL), last(NULL) {} ///copy-constructor + destructor List(const List &object); ~List(); ///function for adding a node anywhere in the list void addNode(int n); pNode getfirst() const; pNode getlast() const; ///function for displaying the list void show(ostream& out, pNode first) const; ///function for deleting an element void deleteNode(int val); void reset(); ///function for searching an element pNode searching(int x) const; ///function for counting the elements int size() const; ///operator overloading pNode operator[](int x) const; List operator=(const List& object); List operator+(const List& object) const; List operator*(int number); bool operator<(const List& object) const; bool operator>(const List& object) const; friend ostream& operator<<(ostream& out, const List& object); friend istream& operator>>(istream& in, List& object); ///function for calculating the sum of the elements int elementSum() const; ///function for mirror void mirror(); ///functions for minimum and maximum pNode maxim() const; pNode minim() const; }; #endif // LIST_H_INCLUDED
true
75ede131b3992b0c5249105661d4b433a051ce1f
C++
Bhutanisachin19/C-and-C-College-Codes
/assignment5.cpp
UTF-8
3,647
3.75
4
[]
no_license
// input 10 intergers /* #include<fstream> #include<iostream> using namespace std; int main() { ofstream outfile("cppfile"); if((outfile.good())==0) // to check whether an error has occured or not cout<<"Unable to open file\n"; int c; int i=1; cout<<"Enter 10 numbers :"<<endl; while (i<=10) { cin>>c; outfile<<c<<"\n"; i++; } outfile.close(); ifstream infile("cppfile"); i=1; while(i<=10) { infile>>c; cout<<c; i++; } infile.close(); } */ //store text /* #include<fstream> #include<iostream> using namespace std; int main() { ofstream outfile("cpfile"); if((outfile.good())==0) // to check whether an error has occured or not cout<<"Unable to open file\n"; char c[10]; int i=1; cout<<"Enter 5 names :"<<endl; while (i<=5) { cin>>c; outfile<<c<<"\n"; i++; } outfile.close(); ifstream infile("cpfile"); i=1; cout<<"Names you entered are :"<<endl; while(i<=5) { infile>>c; cout<<c<<endl; i++; } infile.close(); } */ //display from a existing file /* #include<fstream> #include<iostream> using namespace std; int main() { char c; ifstream obj; obj.open("student"); while(obj) { obj.getline(c); cout<<c; } } */ /* #include<iostream> #include<fstream> using namespace std; class bill { int bill_no,bill_amount; public: void get() { cout<<"Enter bill number and bill amount :"<<endl; cin>>bill_no>>bill_amount; } void put() { cout<<bill_no<<endl<<bill_amount; } }; int main() { bill bb[5]; int i; ofstream outfile("hell"); for(i=0;i<=4;i++) { outfile.write((char *) &bb[i],sizeof(bb[i])); bb[i].get(); } outfile.close(); ifstream infile("hell"); for(i=0;i<=4;i++) { infile.read((char *) &bb[i],sizeof(bb[i])); bb[i].put(); } infile.close(); } */ //template /* #include<iostream> using namespace std; template < class tp > void maxm(tp a,tp b) { if(a>b) cout<<"A is greater "<<endl; else cout<<"B is greater "<<endl; } int main() { int a, b; cout<<"Enter a and b "<<endl; cin>>a>>b; maxm(a,b); float x,y; cout<<"Enter x and y "<<endl; cin>>x>>y; maxm(x,y); } */ //overload template function /* #include<iostream> using namespace std; template < class T > void disp(T a) { cout<<endl<<"Template function "<<endl<<a; } void disp(int a) { cout<<endl<<"Function without template "<<endl<<a; } int main() { disp(10);//integer value disp(19.9);//float value } */ //sort array using template #include<iostream> using namespace std; template < class T > void sort_arr(T arr[]) { int i,j; T a; for (i = 0; i < 5; ++i) { for (j = i + 1; j < 5; ++j) { if (arr[i] > arr[j]) { a = arr[i]; arr[i] = arr[j]; arr[j] = a; } } } cout<<"Sorted array is :"<<endl; for(i=0;i<5;i++) { cout<<arr[i]<<endl; } } int main() { int arr[]={9,3,10,0,8}; sort_arr(arr); float arrf[]={1.5,5.9,55,40.1,1.1}; sort_arr(arrf); } //exception handling /* #include<iostream> using namespace std; int main() { int a,b; cout<<"Enter values of A and B : "<<endl; cin>>a>>b; int x=a-b; try { if(x!=0) cout<<"Result (a/x) ="<<a/x<<endl; else throw(x); } catch(int i) { cout<<"Exception caught"; } } */
true
11e292399b286f4df6f95a22550c880c099be289
C++
FMMazur/CppTuiGameEngine
/src/Engine/Transform.cpp
UTF-8
1,695
3.078125
3
[]
no_license
#include "Transform.hpp" #include <sstream> Transform::Transform() : Component() , m_position() , m_scale(Vector3f::one()) , m_rotation() {} Transform::Transform(Vector3f position) : Component() , m_position(position) , m_scale(Vector3f::one()) , m_rotation() {} Transform::Transform(Vector3f position, Vector3f rotation) : Component() , m_position(position) , m_scale(Vector3f::one()) , m_rotation(rotation) {} Transform::Transform(Vector3f position, Vector3f rotation, Vector3f scale) : Component() , m_position(position) , m_scale(scale) , m_rotation(rotation) {} Transform::Transform(GameObject* parent) : Component(parent) , m_position() , m_scale(Vector3f::one()) , m_rotation() {} Transform::Transform(GameObject* parent, Vector3f position) : Component(parent) , m_position(position) , m_scale(Vector3f::one()) , m_rotation() {} Transform::Transform(GameObject* parent, Vector3f position, Vector3f rotation) : Component(parent) , m_position(position) , m_scale(Vector3f::one()) , m_rotation(rotation) {} Transform::Transform(GameObject* parent, Vector3f position, Vector3f rotation, Vector3f scale) : Component(parent) , m_position(position) , m_scale(scale) , m_rotation(rotation) {} Transform::~Transform() {} std::string Transform::inspect() { std::stringstream ss; ss << this->class_name() << " is at " << this->m_position.inspect() << " with scale " << this->m_scale.inspect() << " rotated to " << this->m_rotation.inspect(); return ss.str(); } std::string Transform::class_name() { return "Transform"; }
true
8c0e6caf8aa49ccf67d229a8e096928d33ab8d1c
C++
Coderdu/linux-hook-api
/elf_parser_api_x64/elf_parser.cc
UTF-8
6,055
2.671875
3
[]
no_license
/* * elf_parser.cc * * Created on: Aug 11, 2010 * Author: fify */ #include <iostream> #include <string> #include <string.h> #include <fstream> #include <algorithm> #include "elf_parser.h" using std::string; using std::fstream; using std::cout; using std::endl; namespace ElfParser { int getAllSectionHeader(vector<MyElf64_Shdr> &vec, fstream &fs) { int old_offset = fs.tellg(); vec.clear(); Elf64_Ehdr e_hdr; MyElf64_Shdr s_hdr; MyElf64_Sym sym; char *sec_name_str_table; fs.seekg(fs.beg); // ------------ Part I: ELF header ------------ // // Read program file header. fs.read((char *) &e_hdr, sizeof(Elf64_Ehdr)); // printf("%lf\n", -1.0 * (e_hdr.e_phoff - e_hdr.e_shoff) / sizeof(Elf64_Phdr)); // ------------ Part II: Program header ------------ // // ------------ Part III: Section header table ------------ // fs.seekg(e_hdr.e_shoff + e_hdr.e_shstrndx * sizeof(Elf64_Shdr), std::ios::beg); // Read information about "Section Name String Table" fs.read((char *) &s_hdr, e_hdr.e_shentsize); fs.seekg(s_hdr.sh_offset, std::ios::beg); // Read in "Section Name String Table". sec_name_str_table = new char[s_hdr.sh_size + 1]; fs.read(sec_name_str_table, s_hdr.sh_size); fs.seekg(e_hdr.e_shoff, std::ios::beg); int count = 0; for (int i = 0; i < e_hdr.e_shnum; i++) { fs.read((char *) &s_hdr, e_hdr.e_shentsize); s_hdr.name = string(sec_name_str_table + s_hdr.sh_name); vec.push_back(s_hdr); count ++; } fs.seekg(old_offset); sort(vec.begin(), vec.end()); return count; } int getAllSym(vector<MyElf64_Sym> &vec, fstream &fs) { int old_offset = fs.tellg(); vec.clear(); Elf64_Ehdr e_hdr; Elf64_Shdr s_hdr; MyElf64_Sym sym; Elf64_Off SymTblFileOffset; int SymTblNum; Elf64_Off SymNamStrTblFileOffset; Elf64_Xword SymNamStrTblSize; char *SymNamStrTable; char *sec_name_str_table; fs.seekg(fs.beg); // ------------ Part I: ELF header ------------ // // Read program file header. fs.read((char *) &e_hdr, sizeof(Elf64_Ehdr)); // printf("%lf\n", -1.0 * (e_hdr.e_phoff - e_hdr.e_shoff) / sizeof(Elf64_Phdr)); // ------------ Part II: Program header ------------ // // ------------ Part III: Section header table ------------ // fs.seekg(e_hdr.e_shoff + e_hdr.e_shstrndx * sizeof(Elf64_Shdr), std::ios::beg); // Read information about "Section Name String Table" fs.read((char *) &s_hdr, e_hdr.e_shentsize); fs.seekg(s_hdr.sh_offset, std::ios::beg); // Read in "Section Name String Table". sec_name_str_table = new char[s_hdr.sh_size + 1]; fs.read(sec_name_str_table, s_hdr.sh_size); fs.seekg(e_hdr.e_shoff, std::ios::beg); for (int i = 0; i < e_hdr.e_shnum; i++) { fs.read((char *) &s_hdr, e_hdr.e_shentsize); if (strcmp(sec_name_str_table + s_hdr.sh_name, ".dynsym") == 0) { SymTblFileOffset = s_hdr.sh_offset; SymTblNum = (s_hdr.sh_size) / (s_hdr.sh_entsize); } if (strcmp(sec_name_str_table + s_hdr.sh_name, ".dynstr") == 0) { SymNamStrTblFileOffset = s_hdr.sh_offset; SymNamStrTblSize = s_hdr.sh_size; } } fs.seekg(SymNamStrTblFileOffset, std::ios::beg); SymNamStrTable = new char[SymNamStrTblSize + 1]; fs.read(SymNamStrTable, SymNamStrTblSize); fs.seekg(SymTblFileOffset, std::ios::beg); // If the given API was not found, then return -1 or else return 0. int ret = 0; for (int i = 0; i < SymTblNum; i++) { fs.read((char *) &sym, sizeof(Elf64_Sym)); sym.name = string(SymNamStrTable + sym.st_name); vec.push_back(sym); ret ++; } delete sec_name_str_table; fs.seekg(old_offset, fs.cur); sort(vec.begin(), vec.end()); return ret; } int getElfHeader(Elf64_Ehdr &hdr, fstream &fs) { int old_addr = fs.tellg(); fs.seekg(fs.beg); fs.read((char *) &hdr, sizeof(Elf64_Ehdr)); fs.seekg(old_addr, fs.cur); if(hdr.e_ident[1] == 'E' && hdr.e_ident[2] == 'L' && hdr.e_ident[3] == 'F') { return 0; } else { cout << "Illegal ELF file!" << endl; return -1; } } /* * sym: output Elf64_Sym * name: API name * fs: Elf file */ int getSymByName(Elf64_Sym &sym, string name, fstream &fs) { int old_offset = fs.tellg(); Elf64_Ehdr e_hdr; Elf64_Shdr s_hdr; Elf64_Off SymTblFileOffset; int SymTblNum; Elf64_Off SymNamStrTblFileOffset; Elf64_Xword SymNamStrTblSize; char *SymNamStrTable; char *sec_name_str_table; fs.seekg(fs.beg); // ------------ Part I: ELF header ------------ // // Read program file header. fs.read((char *) &e_hdr, sizeof(Elf64_Ehdr)); // printf("%lf\n", -1.0 * (e_hdr.e_phoff - e_hdr.e_shoff) / sizeof(Elf64_Phdr)); // ------------ Part II: Program header ------------ // // ------------ Part III: Section header table ------------ // fs.seekg(e_hdr.e_shoff + e_hdr.e_shstrndx * sizeof(Elf64_Shdr), std::ios::beg); // Read information about "Section Name String Table" fs.read((char *) &s_hdr, e_hdr.e_shentsize); fs.seekg(s_hdr.sh_offset, std::ios::beg); // Read in "Section Name String Table". sec_name_str_table = new char[s_hdr.sh_size + 1]; fs.read(sec_name_str_table, s_hdr.sh_size); fs.seekg(e_hdr.e_shoff, std::ios::beg); for (int i = 0; i < e_hdr.e_shnum; i++) { fs.read((char *) &s_hdr, e_hdr.e_shentsize); if (strcmp(sec_name_str_table + s_hdr.sh_name, ".dynsym") == 0) { SymTblFileOffset = s_hdr.sh_offset; SymTblNum = (s_hdr.sh_size) / (s_hdr.sh_entsize); } if (strcmp(sec_name_str_table + s_hdr.sh_name, ".dynstr") == 0) { SymNamStrTblFileOffset = s_hdr.sh_offset; SymNamStrTblSize = s_hdr.sh_size; } } fs.seekg(SymNamStrTblFileOffset, std::ios::beg); SymNamStrTable = new char[SymNamStrTblSize + 1]; fs.read(SymNamStrTable, SymNamStrTblSize); fs.seekg(SymTblFileOffset, std::ios::beg); // If the given API was not found, then return -1 or else return 0. int found = -1; for (int i = 0; i < SymTblNum; i++) { fs.read((char *) &sym, sizeof(Elf64_Sym)); if(strcmp(SymNamStrTable + sym.st_name, name.c_str()) == 0) { found = 0; break; } } delete sec_name_str_table; fs.seekg(old_offset, fs.cur); return found; } } // End of namespace ElfParser
true
d189b186ea35a44e3d11efd2368bdcd5550f18c3
C++
Jaspr2020/Machi-Koro
/Machi Koro/Player.h
UTF-8
785
2.921875
3
[]
no_license
#ifndef PLAYER_H #define PLAYER_H #include "Establishment.h" #include "Landmark.h" #include <iostream> #include <string> #include <vector> using namespace std; class Player { public: Player(); Player(string name); string GetName(); int GetCoins(); vector<Establishment> GetEstablishments(); vector<Landmark> GetLandmarks(); vector<int> GetEstablishmentNums(); void SetName(string name); void SetCoins(int numCoins); void FillLandmarks(); void PrintLandmarks(); void PrintEstablishments(); void AddEstablishment(Establishment establishment); void ChangeLandmarkStatus(string name, bool value); void Print(); private: string m_name; int m_numCoins; vector <Establishment> m_establishments; vector <Landmark> m_landmarks; vector <int> m_numEstablishments; }; #endif
true
754c2c9ccd3c717edbf256cc8a50831ce56d2f2a
C++
elderfd/BeeTracker
/BeeTracker/Experiment.cpp
UTF-8
1,534
2.875
3
[]
no_license
#include "Experiment.h" #include <QMap> Experiment::Experiment() {}; Experiment::Experiment(const ExperimentDesign& design) : _design(design) {} Experiment::~Experiment() {} void Experiment::addEvent(const ExperimentEvent& evt) { events.push_back(evt); } void Experiment::addEvent(ExperimentEvent::Time time, ExperimentEvent::Type type, unsigned x, unsigned y, const QString& visitId) { events.append(ExperimentEvent( time, type, x, y, visitId, _design.xyToPlotID(x, y) )); } const ExperimentDesign Experiment::design() const { return _design; } void Experiment::analyseEvents() { QMap<QString, Visit> visitMap; visits.clear(); for (auto& evt : events) { auto id = evt.visitId; Visit* visit; // This should be fine as long as only one thread accessing the visitmap at once if (visitMap.contains(id)) { visit = &visitMap[id]; } else { visitMap[id] = Visit(); visit = &visitMap[id]; visit->id = id; } if (evt.type == ExperimentEvent::Type::ARRIVE) { visit->start = evt.time; } else if (evt.type == ExperimentEvent::Type::LEAVE) { visit->end = evt.time; } // TODO: Handle undos (also need to add GUI for this) } // Sort the visits by start time for (auto it = visitMap.begin(); it != visitMap.end(); ++it) { unsigned insertAt = visits.size(); for (unsigned i = (visits.size() - 1); i >= 0; ++i) { if (visits[i].start > it->start) { insertAt = i; break; } } it->duration = it->end - it->start; visits.insert(insertAt, *it); } }
true
3b03eba7dc734e54e869feaf8482c76ee3efa56b
C++
gtraines/robot1
/sketches/libraries/Indicator/Indicator.h
UTF-8
844
2.71875
3
[ "MIT" ]
permissive
#ifndef ROBOT1_INDICATOR_H #define ROBOT1_INDICATOR_H class Indicator { public: static void turnOnLed(int pinNumber); static void turnOffLed(int pinNumber); static void momentaryLedOn(int pinNumber); static void momentaryLedOn(int pinNumber, int delay); static void strobeLed(int pinNumber, int delay, int numberTimes); static void alertBlink(int pinNumber); static void alertBlinkFast(int pinNumber); static void alertBlinkSlow(int pinNumber); static void alertStrobe(int pinNumber); static void alertStrobeFast(int pinNumber); static void alertStrobeSlow(int pinNumber); static void strobeSlow(int pinNumber, int numberTimes); static void strobeMedium(int pinNumber, int numberTimes); static void strobeFast(int pinNumber, int numberTimes); }; #endif // ROBOT1_INDICATOR_H
true
8f21282551be2e739f42de666f7c6c42475c97db
C++
kimgea/BusinessObject3
/source/examples/business/User.h
UTF-8
454
2.53125
3
[]
no_license
#pragma once #include "BusinessTable.h" #include "AbstractPerson.h" #include "AbstractPassword.h" #include "Place.h" // class User : public AbstractPerson, public AbstractPassword, public BusinessObject { protected: Place place; // Foregin relation.... must find a better way to do this. Must be able to remove this public: CharColumn UserName; CharColumn BirthPlace; Place* BirthPlaceFK(); // Like this, or using FK from column? User(); };
true
ce23d9805522e557b61dcee2ef0f4543319cf37c
C++
devonhollowood/dailyprog
/2015-05-22/truth_table.cpp
UTF-8
987
3.625
4
[ "MIT" ]
permissive
#include <iostream> #include <iomanip> #include <string> #include <type_traits> template <typename T> typename std::enable_if<std::is_convertible<T, bool>::value, const char*>::type truthiness(T t) { return t ? "True" : "False"; } template <typename T> typename std::enable_if<!std::is_convertible<T, bool>::value, const char*>::type truthiness(T) { return "Not convertible"; } template <typename T> void test_truthiness(std::string repr, T t) { std::cout << std::setw(15) << repr << ": " << truthiness(t) << std::endl; } struct my_struct{}; int main(){ test_truthiness("\"Hello World\"", "Hello World"); test_truthiness("\"\"", ""); test_truthiness("\'0\'", '0'); test_truthiness("1", 1); test_truthiness("0", 0); test_truthiness("0.0", 0.0); test_truthiness("nullptr", nullptr); test_truthiness("&main", &main); test_truthiness("true", true); test_truthiness("false", false); test_truthiness("Empty Struct", my_struct{}); }
true
76a81fe478131937107a7b56f9c1f085ee4a8e27
C++
KendrickAng/competitive-programming
/codeforces/760div3/b/missingbigram.cpp
UTF-8
492
2.5625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; string s = ""; for (int i = 0; i < n-2; i++) { string tmp; cin >> tmp; if (s == "") { s += tmp; } else if (s.back() == tmp[0]) { s += tmp[1]; } else { s += tmp; } } while (s.size() < n) { s += "a"; } cout << s << endl; } int main() { int t; cin >> t; while (t--) { solve(); } }
true
b9301281e4b03317f42c85ce9049b1a323627bb3
C++
manuel-fischer/LP-Solver
/src/lp-model-transform.hpp
UTF-8
1,821
2.84375
3
[ "MIT" ]
permissive
#pragma once #include "lp-model.hpp" #include "lp-model-classify.hpp" #include <algorithm> // -> std::partition void make_negative(linear_var_t& linear_var) { linear_var.coefficient *= -1; } void make_negative(linear_t& linear) { for(auto& t : linear.terms) { make_negative(t); } } lp_model_t standard_form(lp_model_t model) { // Enshure maximization function if(model.objective_function.objective == MIN) { make_negative(model.objective_function.objective_var); model.objective_function.objective = MAX; make_negative(model.objective_function.objective_linear); } return std::move(model); } // canonical form == normal form lp_model_t canonical_form(lp_model_t model) { // TODO: check standard_form // Add slack variables std::vector<var_t> slack_variables; char buffer[sizeof(size_t)*3 + 2]; // *3 could be *log10(256) ~= 2.40824, 2 for 's', '\0' for(auto& limit : model.limits) { if(is_non_negativity_condition(limit)) continue; // TODO: handle GEQ and EQ limits std::sprintf(buffer, "s%zu", slack_variables.size()+1); var_t slack_var = model.vars.put(std::string_view(buffer), SLACK); slack_variables.push_back(slack_var); limit.func.terms.push_back({1, slack_var}); limit.comp = EQ; } std::stable_partition(model.limits.begin(), model.limits.end(), is_non_negativity_condition); // Add non-negativity condition for slack variables model.limits.reserve(model.limits.size() + slack_variables.size()); for(auto& var : slack_variables) { limit_t limit; limit.func = {{{1, var}}}; limit.comp = GEQ; limit.limit = 0; model.limits.push_back(std::move(limit)); } return std::move(model); }
true
1f0c7ec5709e8688b3b1ec8c615d7bf6419af139
C++
BrianErikson/jenkins-notifications
/src/jnotify/UrlHook.cpp
UTF-8
1,713
2.703125
3
[ "MIT" ]
permissive
#include <utility> #include <curl/curl.h> #include <cassert> #include <iostream> #include "UrlHook.h" using namespace url_notify; UrlHook::UrlHook(std::string url, UrlHookCallback callback, long long poll_rate) : poll_rate(poll_rate), next_execution(TimeType::now() + std::chrono::milliseconds(poll_rate)), callback(std::move(callback)), url(std::move(url)) { this->curl_handle = curl_easy_init(); assert(this->curl_handle); curl_easy_setopt(this->curl_handle, CURLOPT_URL, this->url.c_str()); curl_easy_setopt(this->curl_handle, CURLOPT_WRITEFUNCTION, &UrlHook::write_callback); curl_easy_setopt(this->curl_handle, CURLOPT_WRITEDATA, this->write_buf); curl_easy_setopt(this->curl_handle, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(this->curl_handle, CURLOPT_TIMEOUT, 5L); } UrlHook::~UrlHook() { curl_easy_cleanup(this->curl_handle); delete this->write_buf; } size_t UrlHook::write_callback(char *ptr, size_t size, size_t nmemb, void *userdata) { auto *data = static_cast<std::string*>(userdata); assert(size == 1); data->append(ptr, nmemb); return nmemb; } std::string UrlHook::try_get() { CURLcode res = curl_easy_perform(this->curl_handle); if (res != CURLE_OK) { std::cerr << "GET failed: " << curl_easy_strerror(res) << " for URL " << this->url << std::endl; } std::string data = *this->write_buf; this->write_buf->clear(); return data; } bool UrlHook::execute() { auto data = this->try_get(); this->next_execution = TimeType::now() + std::chrono::milliseconds(this->poll_rate); if (data.empty()) { return false; } return this->callback(data); } TimePoint UrlHook::get_next_execution() { return this->next_execution; }
true
81bbb4539b28d48844885c55983ceb2fbadbc052
C++
isglobal-brge/BigDataStatMeth
/src/hdf5_getSDandMean.cpp
UTF-8
14,064
2.890625
3
[]
no_license
#include "include/hdf5_getSDandMean.h" using namespace Rcpp; // Get mean and corrected sd from each column in dataset in the case of n<<m, this information is used // to normalize data, center or scale. int get_HDF5_mean_sd_by_column_ptr(H5File* file, DataSet* dataset, Eigen::MatrixXd& normalize ) { IntegerVector dims_out = get_HDF5_dataset_size(*dataset); try { // Turn off the auto-printing when failure occurs so that we can handle the errors appropriately Exception::dontPrint(); int block_size = 500; IntegerVector stride = IntegerVector::create(1, 1); IntegerVector block = IntegerVector::create(1, 1); IntegerVector offset = IntegerVector::create(0, 0); IntegerVector count = IntegerVector::create(0, 0); count[1] = dims_out[1]; if( block_size < dims_out[0] ) count[0] = block_size; else count[0] = dims_out[0]; // Read data in blocks of 500 columns for(int i=0; (i < floor(dims_out[0]/block_size)) || i==0; i++) { if(i>0){ offset[0] = offset[0] + block_size; if( offset[0] + block_size <= dims_out[0] ) { count[0] = block_size; }else { count[0] = dims_out[0] - offset[1]+block_size; } } Eigen::MatrixXd X = GetCurrentBlock_hdf5(file, dataset, offset[0], offset[1], count[0], count[1]); Eigen::VectorXd mean = X.rowwise().mean(); Eigen::VectorXd std = ((X.colwise() - mean).array().square().rowwise().sum() / (X.cols() - 1)).sqrt(); normalize.block( 0, offset[0] , 1, mean.size()) = mean.transpose(); normalize.block( 1, offset[0], 1, std.size()) = std.transpose(); } } catch(FileIException& error) { // catch failure caused by the H5File operations ::Rf_error( "c++ exception get_HDF5_mean_sd_by_column_ptr (File IException)" ); return -1; } catch(DataSetIException& error) { // catch failure caused by the DataSet operations ::Rf_error( "c++ exception get_HDF5_mean_sd_by_column_ptr (DataSet IException)" ); return -1; } catch(GroupIException& error) { // catch failure caused by the Group operations ::Rf_error( "c++ exception get_HDF5_mean_sd_by_column_ptr (Group IException)" ); return -1; } catch(DataSpaceIException& error) { // catch failure caused by the DataSpace operations ::Rf_error( "c++ exception get_HDF5_mean_sd_by_column_ptr (DataSpace IException)" ); return -1; } catch(DataTypeIException& error) { // catch failure caused by the DataSpace operations ::Rf_error( "c++ exception get_HDF5_mean_sd_by_column_ptr (Data TypeIException)" ); return -1; } return(0); // successfully terminated } // Get mean and corrected sd from each row in dataset int get_HDF5_mean_sd_by_row_ptr(H5File* file, DataSet* dataset, Eigen::MatrixXd& normalize ) { IntegerVector dims_out = get_HDF5_dataset_size(*dataset); try { // Turn off the auto-printing when failure occurs so that we can handle the errors appropriately Exception::dontPrint(); int block_size = 500; IntegerVector stride = IntegerVector::create(1, 1); IntegerVector block = IntegerVector::create(1, 1); IntegerVector offset = IntegerVector::create(0, 0); IntegerVector count = IntegerVector::create(0, 0); count[0] = dims_out[0]; if( block_size < dims_out[1] ) { count[1] = block_size; } else{ count[1] = dims_out[1]; } // Read data in blocks of 500 columns for(int i=0; (i < floor(dims_out[1]/block_size)) || i==0; i++) { if(i>0){ offset[1] = offset[1] + block_size; if( offset[1] + block_size <= dims_out[1] ) { count[1] = block_size; }else { count[1] = dims_out[1] - offset[0] + block_size; } } Eigen::MatrixXd X = GetCurrentBlock_hdf5(file, dataset, offset[0], offset[1], count[0], count[1]); Eigen::RowVectorXd mean = X.colwise().mean(); Eigen::RowVectorXd std = ((X.rowwise() - mean).array().square().colwise().sum() / (X.rows() - 1)).sqrt(); normalize.block( 0, offset[1], 1, mean.size()) = mean; normalize.block( 1, offset[1], 1, std.size()) = std; } } catch(FileIException& error) { // catch failure caused by the H5File operations ::Rf_error( "c++ exception get_HDF5_mean_sd_by_row_ptr (File IException)" ); return -1; } catch(DataSetIException& error) { // catch failure caused by the DataSet operations ::Rf_error( "c++ exception get_HDF5_mean_sd_by_row_ptr (DataSet IException)" ); return -1; } catch(GroupIException& error) { // catch failure caused by the Group operations ::Rf_error( "c++ exception get_HDF5_mean_sd_by_row_ptr (Group IException)" ); return -1; } catch(DataSpaceIException& error) { // catch failure caused by the DataSpace operations ::Rf_error( "c++ exception get_HDF5_mean_sd_by_row_ptr (DataSpace IException)" ); return -1; } catch(DataTypeIException& error) { // catch failure caused by the DataSpace operations ::Rf_error( "c++ exception get_HDF5_mean_sd_by_row_ptr (Data TypeIException)" ); return -1; } return(0); // successfully terminated } //' Get sd and Mean by Rows or Columns //' //' This functions gets Standard Deviation (sd) or Mean by Rows or Columns and //' store results in hdf5 dataset inside the file //' //' @param filename string file name where dataset to normalize is stored //' @param group string Matrix //' @param dataset string Matrix //' @param sd logical (default = TRUE) if TRUE, standard deviation is computed //' @param mean logical (default = TRUE) if TRUE, mean is computed //' @param byrows logical (default = FALSE) if TRUE, sd and mean are computed //' by columns, if byrows=TRUE then sd and mean are computed by Rows. //' @param wsize integer (default = 1000), file block size to read to //' perform calculus exitexit //' @param force, boolean if true, previous results in same location inside //' hdf5 will be overwritten. //' @return hdf5 data file containing a dataset with sd, and mean //' @examples //' //' library(BigDataStatMeth) //' # devtools::reload(pkgload::inst("BigDataStatMeth")) //' //' # Prepare data and functions //' set.seed(123) //' Y <- matrix(rnorm(100), 10, 10) //' X <- matrix(rnorm(10), 10, 1) //' //' # Create hdf5 data file with data (Y) //' bdCreate_hdf5_matrix_file("test.hdf5", Y, "data", "Y", force = TRUE) //' bdAdd_hdf5_matrix( X, "test.hdf5", "data", "X", force = TRUE) //' //' # Get mean and sd //' bdgetSDandMean_hdf5(filename = "test.hdf5", group = "data", dataset = "Y", //' sd = TRUE, mean = TRUE,byrows = TRUE) //' //' @export // [[Rcpp::export]] void bdgetSDandMean_hdf5( std::string filename, const std::string group, std::string dataset, Rcpp::Nullable<bool> sd = R_NilValue, Rcpp::Nullable<bool> mean = R_NilValue, Rcpp::Nullable<bool> byrows = R_NilValue, Rcpp::Nullable<int> wsize = R_NilValue, Rcpp::Nullable<int> force = false) { bool bsd, bmean, bforce, bbyrows; int blocksize; std::string strgroupout; IntegerVector stride = IntegerVector::create(1, 1); IntegerVector block = IntegerVector::create(1, 1); Eigen::MatrixXd datanormal; H5File* file = nullptr; DataSet* pdatasetin = nullptr; try { if( mean.isNull()) { bmean = true; } else { bmean = Rcpp::as<bool> (mean); } if( sd.isNull()) { bsd = true; } else { bsd = Rcpp::as<bool> (sd); } if( byrows.isNull()) { bbyrows = false; } else { bbyrows = Rcpp::as<bool> (byrows); } if( force.isNull()) { bforce = true; } else { bforce = Rcpp::as<bool> (force); } if(!ResFileExist(filename)) { Rcpp::Rcout<<"\nFile not exits, create file before get mean and sd\n"; return void(); } file = new H5File( filename, H5F_ACC_RDWR ); if(exists_HDF5_element_ptr(file, group)==0) { Rcpp::Rcout<<"\nGroup not exits, create file and dataset before get mean and sd\n"; file->close(); return void(); } else { if(!exists_HDF5_element_ptr(file, group + "/" + dataset)) { Rcpp::Rcout<<"\n Dataset not exits, create dataset before get mean and sd \n"; file->close(); return void(); } } strgroupout = "mean_sd/" + group; if(exists_HDF5_element_ptr(file, strgroupout + "/" + dataset) && bforce == false) { Rcpp::Rcout<<"\n Mean and sd exists please set force = TRUE to overwrite\n"; file->close(); return void(); } else if( exists_HDF5_element_ptr(file, strgroupout) && bforce == true) { remove_HDF5_element_ptr(file, strgroupout + "/" + dataset); remove_HDF5_element_ptr(file, strgroupout + "/mean." + dataset); remove_HDF5_element_ptr(file, strgroupout + "/sd." + dataset); } pdatasetin = new DataSet(file->openDataSet(group + "/" + dataset)); IntegerVector dims_out = get_HDF5_dataset_size_ptr(pdatasetin); if( bbyrows == false) { // Define blocksize atending number of elements in rows and cols if( wsize.isNull()) { if(dims_out[1] > maxElemBlock){ blocksize = 1; } else { int maxsize = std::max( dims_out[0], dims_out[1]); blocksize = std::ceil( maxElemBlock / maxsize); } } else { if(dims_out[1] > maxElemBlock){ blocksize = 1; } else { blocksize = Rcpp::as<int> (wsize); } } datanormal = Eigen::MatrixXd::Zero(2,dims_out[0]); // Get data to normalize matrix (mean and sd by column) get_HDF5_mean_sd_by_column_ptr( file, pdatasetin, datanormal); } else { // Define blocksize atending number of elements in rows and cols if( wsize.isNull()) { if(dims_out[0] > maxElemBlock) { blocksize = 1; } else { int maxsize = std::max( dims_out[0], dims_out[1]); blocksize = std::ceil( maxElemBlock / maxsize); } } else { if(dims_out[0] > maxElemBlock) { blocksize = 1; } else { blocksize = Rcpp::as<int> (wsize); } } datanormal = Eigen::MatrixXd::Zero(2,dims_out[1]); // Get data to normalize matrix (mean and sd by column) get_HDF5_mean_sd_by_row_ptr( file, pdatasetin, datanormal); } // if not exists -> create output group if(exists_HDF5_element_ptr(file, strgroupout) == 0) { create_HDF5_groups_ptr( file, strgroupout); } // Store center and scale for each column write_HDF5_matrix_ptr(file, strgroupout + "/mean," + dataset, wrap(datanormal.row(0))); write_HDF5_matrix_ptr(file, strgroupout + "/sd." + dataset, wrap(datanormal.row(1))); } catch( FileIException& error ) { // catch failure caused by the H5File operations pdatasetin->close(); file->close(); ::Rf_error( "c++ exception bdgetSDandMean_hdf5 (File IException)" ); return void(); } catch( DataSetIException& error ) { // catch failure caused by the DataSet operations pdatasetin->close(); file->close(); ::Rf_error( "c++ exception bdgetSDandMean_hdf5 (DataSet IException)" ); return void(); } catch( DataSpaceIException& error ) { // catch failure caused by the DataSpace operations pdatasetin->close(); file->close(); ::Rf_error( "c++ exception bdgetSDandMean_hdf5 (DataSpace IException)" ); return void(); } catch( DataTypeIException& error ) { // catch failure caused by the DataSpace operations pdatasetin->close(); file->close(); ::Rf_error( "c++ exception bdgetSDandMean_hdf5 (DataType IException)" ); return void(); }catch(std::exception &ex) { pdatasetin->close(); file->close(); Rcpp::Rcout<< ex.what(); return void(); } pdatasetin->close(); file->close(); } /****R library(BigDataStatMeth) # devtools::reload(pkgload::inst("BigDataStatMeth")) setwd("/Users/mailos/DOCTORAT_Local/BigDataStatMeth/") # Prepare data and functions set.seed(123) Y <- matrix(rnorm(100), 10, 10) X <- matrix(rnorm(10), 10, 1) # Create hdf5 data file with data (Y) bdCreate_hdf5_matrix_file("test.hdf5", Y, "data", "Y", force = TRUE) bdAdd_hdf5_matrix( X, "test.hdf5", "data", "X", force = TRUE) bdgetSDandMean_hdf5(filename = "test.hdf5", group = "data", dataset = "Y", sd = TRUE, mean = TRUE,byrows = TRUE) */
true
b9dc27002ca65649c7fb6cdfe6fc4e9e24fb509a
C++
PunkyIANG/ASDC
/lab4/directAccess.cpp
UTF-8
3,126
3.34375
3
[]
no_license
#include <iostream> #include <math.h> /* pow */ #include <cstdarg> template <typename T> class DirectAccess { private: T *arr = NULL; int *bounds = NULL; int n = 0; bool isRand = true; int GetD(int i) { if (isRand) { if (i == n-1) return 1; return (bounds[2 * i + 1] - bounds[2 * i] + 1) * GetD(i + 1); } else { if (i == 0) return 1; return (bounds[2 * i + 1] - bounds[2 * i] + 1) * GetD(i - 1); } } int GetTotalDim() { int res = 1; for (int i = 0; i < n; i++) res *= bounds[2 * i + 1] - bounds[2 * i] + 1; return res; } public: DirectAccess() {} DirectAccess(bool isRand, int n, ...) { this->isRand = isRand; this->n = n; bounds = new int[2*n]; va_list args; va_start(args, n); std::cout << "Bounds: "; for (int i = 0; i < 2*n; i++) { bounds[i] = va_arg(args, int); std::cout << bounds[i] << " "; } std::cout << '\n'; va_end(args); for (int i = 0; i < n; i++) { std::cout << "Dimension " << i << ": " << GetD(i) << '\n'; } arr = new T[GetTotalDim()]; std::cout << "Total dim: " << GetTotalDim() << '\n'; } ~DirectAccess() { delete[] bounds; delete[] arr; } T* GetAddr(int pos[]) { T *res = arr; T *oldres = arr; int firstSum = 0; for (int i = 0; i < n; i++) { firstSum += bounds[i * 2] * GetD(i); } int secondSum = 0; for (int i = 0; i < n; i++) { secondSum += pos[i] * GetD(i); } std::cout << "sums " << firstSum << " " << secondSum << "\n"; // res -= (int) pow(sizeof(T), firstSum); // res += (int) pow(sizeof(T), secondSum); res -= sizeof(T) * firstSum; res += sizeof(T) * secondSum; std::cout << "diff: " << res - oldres << "\n"; return res; } T Get(int firstPos, ...) { int pos[n]; pos[0] = firstPos; va_list args; va_start(args, firstPos); for (int i = 1; i < n; i++) pos[i] = va_arg(args, int); va_end(args); return *GetAddr(pos); } void Set(T value, ...) { int pos[n]; va_list args; va_start(args, value); for (int i = 0; i < n; i++) pos[i] = va_arg(args, int); va_end(args); *GetAddr(pos) = value; } }; int main() { DirectAccess<int> test(false, 3, 0, 1, 0, 1, 0, 1); for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) test.Set(i * 4 + j * 2 + k, i, j, k); for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) std::cout << "addr " << i << j << k << ": " << test.Get(i, j, k) << "\n"; }
true
9fb27667aa694e06517b295d007302b66d27f982
C++
BeamMW/beam
/bvm/unittest/doc_test.cpp
UTF-8
1,270
2.59375
3
[ "Apache-2.0" ]
permissive
#include <iomanip> #include "../bvm2.h" int g_failedTests = 0; class DocProcessor: public beam::bvm2::ProcessorManager { public: void SelectContext(bool bDependent, uint32_t nChargeNeeded) override { } void TestQuotedText(const char* what, const std::string& expected) { std::ostringstream stream; m_pOut = &stream; DocQuotedText(what); const auto result = stream.str(); if (stream.str() != expected) { if (g_failedTests) std::cout << std::endl; std::cout << "TestQuotedText failed: " << "\n\tinput: " << what << "\n\tresult: " << result << "\n\texpected: " << expected; g_failedTests++; } } }; int main() { DocProcessor processor; processor.TestQuotedText("hello", "\"hello\""); processor.TestQuotedText("\"", R"("\"")"); processor.TestQuotedText("\\", R"("\\")"); for(char ch = 1; ch <= 0x1F; ++ch) { char input[2] = {ch, 0}; std::ostringstream expect; expect << "\"\\u" << std::setfill('0') << std::setw(4) << std::hex << static_cast<int>(ch) << "\""; processor.TestQuotedText(input, expect.str()); } return g_failedTests ? -1 : 0; }
true
e0edcf804f243206cf2b84013665645cee3e804f
C++
lunatikub/lunatris
/tests/unit/eval/test_eval_homogeneous.cc
UTF-8
1,203
2.671875
3
[ "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
#include "test_eval.hh" TEST_F(Eval, DeltaLine) { uint32_t dl = 0; EXPECT_EQ(eval_delta_line(wall), dl); // 0 - X......... wall_set(wall, 0, 0); ++dl; EXPECT_EQ(eval_delta_line(wall), dl); // 1 - X.X.X.X.X. wall_set(wall, 1, 0); wall_set(wall, 1, 2); wall_set(wall, 1, 4); wall_set(wall, 1, 6); wall_set(wall, 1, 8); dl += 9; EXPECT_EQ(eval_delta_line(wall), dl); // 2 - XXXXX..... SetLine(2, 0, 5); ++dl; EXPECT_EQ(eval_delta_line(wall), dl); // 3 - .XX....... SetLine(3, 1, 2); dl += 2; EXPECT_EQ(eval_delta_line(wall), dl); } TEST_F(Eval, DeltaCol) { uint32_t dc = 0; EXPECT_EQ(eval_delta_col(wall), dc); // 1 - .......... // 0 - X......... wall_set(wall, 0, 0); ++dc; EXPECT_EQ(eval_delta_col(wall), dc); // 1 - XXXXXXXXX. // 0 - X......... SetLine(1, 0, 8); dc = 17; EXPECT_EQ(eval_delta_col(wall), dc); // 2 - X......... // 1 - XXXXXXXXX. // 0 - X......... wall_set(wall, 2, 0); dc = 17; EXPECT_EQ(eval_delta_col(wall), dc); // 3 - .XX....... // 2 - X......... // 1 - XXXXXXXXX. // 0 - X......... wall_set(wall, 3, 1); wall_set(wall, 3, 2); dc += 4; EXPECT_EQ(eval_delta_col(wall), dc); }
true
d7c6db17f0bb33a75acd4069e0e9540b76944a06
C++
dajoh/Antumbra
/Client/Renderer/Texture2D.cpp
UTF-8
2,309
2.890625
3
[]
no_license
#include <exception> #include "Texture2D.hpp" namespace Antumbra { Texture2D::Texture2D() : m_filled(false) { glGenTextures(1, &m_texture); } Texture2D::~Texture2D() { glDeleteTextures(1, &m_texture); } void Texture2D::Fill(const void *data, int width, int height, GLenum format) { GLenum formatType; GLenum basicFormat; switch(format) { case GL_RGB8: case GL_SRGB8: formatType = GL_UNSIGNED_BYTE; basicFormat = GL_RGB; break; case GL_RGBA8: case GL_SRGB8_ALPHA8: formatType = GL_UNSIGNED_BYTE; basicFormat = GL_RGBA; break; case GL_R16F: formatType = GL_FLOAT; basicFormat = GL_RED; break; case GL_RG16F: formatType = GL_FLOAT; basicFormat = GL_RG; break; case GL_DEPTH_COMPONENT24: formatType = GL_UNSIGNED_BYTE; basicFormat = GL_DEPTH_COMPONENT; break; default: throw std::exception("Unsupported texture format."); } glBindTexture(GL_TEXTURE_2D, m_texture); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, basicFormat, formatType, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); m_filled = true; } bool Texture2D::IsFilled() const { return m_filled; } void Texture2D::SetParameter(GLenum name, GLint value) { glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, name, value); } void Texture2D::SetParameter(GLenum name, GLfloat value) { glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameterf(GL_TEXTURE_2D, name, value); } void Texture2D::Bind(int textureUnit) { if(!m_filled) { throw std::exception("Tried to bind unfilled texture."); } glActiveTexture(GL_TEXTURE0 + textureUnit); glBindTexture(GL_TEXTURE_2D, m_texture); } void Texture2D::GenerateMipmaps() { if(!m_filled) { throw std::exception("Tried to generate mipmaps for unfilled texture."); } glBindTexture(GL_TEXTURE_2D, m_texture); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } }
true
0ca0b9bc78d9adb27d5ad35d782afff5a6ed14b3
C++
BSkin/Boat
/Boat/Boat.cpp
UTF-8
2,594
2.625
3
[]
no_license
#include "Boat.h" Ocean * Boat::ocean = NULL; list<GameObject *> * Boat::oceanHeightModObjects = NULL; Boat::Boat(string m, string t, string s, glm::vec3 position, glm::vec3 direction, glm::vec3 up, string path) : PropObject(m, t, s, position, direction, up, path) { oceanHeightModObjects->push_back(this); turnRate = 0.0f; setMass(10000.0f); setFriction(2.0f); body->setDamping(0.9f, 0.9f); setGravity(0,-19.62f*2,0); //body->setAngularFactor(1.0f); collisionType = "vehicle"; buoyancyPoints.push_back(BuoyancyPoint(0.0f, -1.0f, 26.85f)); buoyancyPoints.push_back(BuoyancyPoint(0.0f, -1.0f, -26.85f)); buoyancyPoints.push_back(BuoyancyPoint(9.0f, -1.0f, 0.0f)); buoyancyPoints.push_back(BuoyancyPoint(-9.0f, -1.0f, 0.0f)); buoyancyPoints.push_back(BuoyancyPoint(9.0f, -1.0f, 14.0f)); buoyancyPoints.push_back(BuoyancyPoint(-9.0f, -1.0f, 14.0f)); buoyancyPoints.push_back(BuoyancyPoint(9.0f, -1.0f, -14.0f)); buoyancyPoints.push_back(BuoyancyPoint(-9.0f, -1.0f, -14.0f)); for (list<BuoyancyPoint>::iterator it = buoyancyPoints.begin(); it != buoyancyPoints.end(); it++) (it)->update(&body->getWorldTransform()); } Boat::~Boat() { oceanHeightModObjects->remove(this); } int Boat::update(long elapsedTime) { body->activate(true); if (ocean != NULL) { for (list<BuoyancyPoint>::iterator it = buoyancyPoints.begin(); it != buoyancyPoints.end(); it++) { btVector3 pos = (it)->update(&body->getWorldTransform()); float waterLevel = ocean->getHeight(pos.x(), pos.z()); if (pos.y() < waterLevel) { float buoyantForce = elapsedTime*196.2f/buoyancyPoints.size()*(-pos.y() + waterLevel); body->applyImpulse(btVector3(0, buoyantForce, 0), (it)->getLocalPosition()); } } } //if (turnRate > 0) turnRate -= elapsedTime*0.001f*1.0f; //else if (turnRate < 0) turnRate += elapsedTime*0.001f*1.0f; //body->setAngularVelocity(btVector3(0,turnRate,0)); return RigidObject::update(elapsedTime); } int Boat::render(long totalElapsedTime) { return RigidObject::render(totalElapsedTime); } void Boat::applyImpulseForward(float x, long elapsedTime) { btVector3 forwardVector = body->getWorldTransform() * btVector3(0,0,-1); forwardVector.setY(body->getCenterOfMassPosition().y()); //forwardVector = forwardVector.normalized(); body->applyCentralImpulse(x*elapsedTime*(forwardVector-body->getCenterOfMassPosition())); } void Boat::turn(float x, long elapsedTime) { //turnRate += x*elapsedTime*0.001f; //body->applyTorque(btVector3(0,elapsedTime*10000,0)); body->activate(true); body->applyTorqueImpulse(btVector3(0, x*elapsedTime, 0)); }
true
359a6e626e699a34f1ffeb30bd238651fb2500e2
C++
ue-sho/Library
/algorithm/Graph/MST_prim.hpp
UTF-8
1,477
3.765625
4
[]
no_license
// 最小全域木(minimum spanning tree) // プリム法 // 重み付き連結グラフの最小全域木のコストを求める #include <queue> #include <vector> using namespace std; struct Edge { int destination; //到達点 int cost; //移動コスト Edge() = default; Edge(int destination, int cost) : destination(destination), cost(cost) {} bool operator>(const Edge &edge) const { return cost > edge.cost; } }; int Prim(const vector<vector<Edge>> &graph, int num_vertex) { vector<bool> visited(num_vertex, false); // 訪れたかどうかを記録する priority_queue<Edge, vector<Edge>, greater<Edge>> pri_queue; // コストが小さい順に格納する pri_queue.emplace(0, 0); // 初期値は 頂点 0 から始める(頂点 0 に行くまでのコストは 0) int total_cost = 0; // 最小全域木のコストの総和 while (!pri_queue.empty()) { Edge current_edge = pri_queue.top(); pri_queue.pop(); if (visited[current_edge.destination]) { continue; // すでに訪問済み } visited[current_edge.destination] = true; total_cost += current_edge.cost; for (const Edge next_edge : graph[current_edge.destination]) { if (!visited[next_edge.destination]) { pri_queue.emplace(next_edge); } } } return total_cost; }
true
7bed712200d986059ec57c190fa41bf095858f7f
C++
sariq90/GIP1819
/P12/P12_01_FilledRect/MyFilledRectangle.h
UTF-8
211
2.546875
3
[]
no_license
#pragma once #include "MyRectangle.h" class MyFilledRectangle : public MyRectangle { public: MyFilledRectangle(int x1 = 0, int y1 = 0, int x2 = 20, int y2 = 20) : MyRectangle{ x1,y1,x2,y2 } {} void draw(); };
true
c5db572a5f8b6ba3166f67e99932823a7eab5361
C++
syoyo/tinyusdz
/src/handle-allocator.hh
UTF-8
2,382
2.828125
3
[ "MIT", "MIT-0", "Zlib", "BSD-3-Clause", "ISC", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
// SPDX-License-Identifier: Apache 2.0 // Copyright 2022-Present Light Transport Entertainment Inc. #pragma once #include <cstdint> #include <algorithm> //#include <iostream> //#include <cassert> #include <limits> #include <vector> namespace tinyusdz { /// /// Simple handle resource manager /// Assume T is an unsigned integer type. /// TODO(LTE): Allocate handle for a given value range. e.g. [minVal, maxVal) /// template<typename T = uint32_t> class HandleAllocator { public: // id = 0 is reserved. HandleAllocator() : counter_(static_cast<T>(1)){} //~HandleAllocator(){} /// Allocates handle object. bool Allocate(T *dst) { if (!dst) { return false; } T handle = 0; if (!freeList_.empty()) { // Reuse last element. handle = freeList_.back(); freeList_.pop_back(); // Delay sort until required dirty_ = true; (*dst) = handle; return true; } handle = counter_; if ((handle >= static_cast<T>(1)) && (handle < (std::numeric_limits<T>::max)())) { counter_++; //std::cout << "conter = " << counter_ << "\n"; (*dst) = handle; return true; } return false; } /// Release handle object. bool Release(const T handle) { if (handle == counter_ - static_cast<T>(1)) { if (counter_ > static_cast<T>(1)) { counter_--; } else { return false; } } else { if (handle >= static_cast<T>(1)) { freeList_.push_back(handle); // Delay sort until required dirty_ = true; } else { // invalid handle return false; } } return true; } bool Has(const T handle) const { if (dirty_) { std::sort(freeList_.begin(), freeList_.end()); dirty_ = false; } if (handle < 1) { return false; } // Do binary search. if (std::binary_search(freeList_.begin(), freeList_.end(), handle)) { return false; } if (handle >= counter_) { return false; } return true; } int64_t Size() const { return counter_ - freeList_.size() - 1; } private: // TODO: Use unorderd_set or unorderd_map for efficiency? // worst case complexity is still c.size() though. mutable std::vector<T> freeList_; // will be sorted in `Has` call. T counter_{}; mutable bool dirty_{true}; }; } // namespace tinyusdz
true
93059d9842ec6c0c2aca54c241bce87da48714cd
C++
pratyush220498/Data_Structure-CPP
/basic/PassByValue.cpp
UTF-8
497
3.328125
3
[]
no_license
#include<iostream> using namespace std; void swap(int,int); int main() { int i,j,k; cout<<"enter first no. :- "; cin>>i; cout<<"enter second no. :- "; cin>>j; cout<<"before swspping no's are :- "<<endl; cout<<"i = "<<i<<endl; cout<<"j = "<<j<<endl; swap(i,j); cout<<"after swspping no's are :- "<<endl; cout<<"i = "<<i<<endl; cout<<"j = "<<j<<endl; cout<<endl; return 0; } void swap(int i,int j) { int temp; temp=i; i=j; j=temp; cout<<"i = "<<i<<endl; cout<<"j = "<<j<<endl; }
true
e74e7cae23e281672184c7c70f96e4edf4340444
C++
tech-holic/hello-world
/findnum/main.cpp
GB18030
614
3.125
3
[]
no_license
#include <iostream> using namespace std; int binaryFind(int a[],int target,int maxlenth) { int left=0; int right=maxlenth-1; int mid; while(left<right) { mid=(left+right)/2; if(a[mid]==target) return mid; else if(a[mid]>target) right=mid; else if(a[mid]<target) left=mid; } if(left==right) { if(a[left]==target) return left; } return -1; } int main() { int N[20]; for(int i=0;i<20;i++) N[i]=i+1; // cout << "" <<binaryFind(N,0,20)<<endl; for(int i=0;i<20;i++) cout << "" <<binaryFind(N,i,20)<<endl; return 0; }
true
26239e365b8bfcad89afbcf8d38fe27f6d75faf0
C++
hempnall/codeexamples
/cpp/yara/yara/main.cpp
UTF-8
1,142
2.515625
3
[]
no_license
#include <iostream> #include <yara.h> #include <cstring> using namespace std; int callback_function( int message, void* message_data, void* user_data) { YR_STRING* s; if (CALLBACK_MSG_RULE_MATCHING == message) { YR_RULE* rule = static_cast<YR_RULE*>(message_data); yr_rule_strings_foreach(rule, s) { YR_MATCH* match; /* string is a YR_STRING object */ yr_string_matches_foreach(s, match) { std::cout << "base=" << match->base << " offset=" << match->offset << " length=" << match->length << " data=" << (char*) match->data << "\n"; } } } return CALLBACK_CONTINUE; } int main() { yr_initialize(); YR_RULES *rules; yr_rules_load("/Users/James/dev/src/yara-python/rule.yarac", &rules); const char* data = "asdasdasd HOT ashdkajshdkashdkashd HOT ashdkjashkdhaskj HOT sahdjahdk"; yr_rules_scan_mem(rules, (uint8_t*) data, strlen(data), 0, callback_function, 0, 0); yr_finalize(); // /Users/James/dev/src/yara-python cout << "Hello World!" << endl; return 0; }
true
4af03c51098f62651e69ab2c8b515470a476b8f5
C++
Pradeep-Gopal/Path_Planning_DepthFirstSearch_CPP14
/rwa3/LandBasedWheeled/LandBasedWheeled.h
UTF-8
2,021
3.28125
3
[]
no_license
// // Created by prade on 4/22/2020. // #pragma once #include <string> #include <memory> #include "../LandBasedRobot/LandBasedRobot.h" #include <iostream> namespace rwa3 { class LandBasedWheeled : public LandBasedRobot { public: //--method prototypes virtual void GoUp(int x_, int y_) override; //Move the robot up in the maze virtual void GoDown(int x_, int y_) override; //Move the robot down in the maze virtual void TurnLeft(int x_, int y_) override; //Move the robot left in the maze virtual void TurnRight(int x_, int y_) override; //Move the robot right in the maze virtual void PickUp(std::string& pick) override; //Arm picks up an object virtual void Release(std::string& release) override; //Arm releases an object virtual int get_x() const override;//--get the x coordinate of a robot virtual int get_y() const override;//--get the y coordinate of a robot virtual void set_x(int x) override; //--set the x coordinate of a robot virtual void set_y(int y) override ; //--set the y coordinate of a robot // Deep copy constructor LandBasedWheeled(const LandBasedWheeled &source):LandBasedWheeled( source.name_, source.x_, source.y_, source.wheel_number, *source.wheel_type ){} //--Constructor LandBasedWheeled(std::string name="None", int x=0, int y=0, int w_number=2, std::string w_type="round") : LandBasedRobot(name, x , y), wheel_number{w_number}, wheel_type{nullptr}{ std::shared_ptr<std::string> wheel_type {new std::string {w_type}}; } //--Destructor virtual ~LandBasedWheeled(){ } protected: // --attributes int wheel_number; //Number of wheels mounted on the robot std::shared_ptr<std::string> wheel_type; //Type of wheels mounted on the robot. };//--class LandBasedWheeled }//--namespace rwa3
true
8e27c0651445b62fe294f859bdc5f935e1a60c39
C++
noobcoder1137/data_structures_c-
/doubly_linked_list.cpp
UTF-8
5,994
3.8125
4
[]
no_license
// NoobCoder.com // source code for video tutorial series found here // https://www.youtube.com/playlist?list=PLvTjg4siRgU02UgV08owYouXQSZO1a5W3 #include <iostream> using namespace std; class Node{ public : int data; Node *next; Node *prev; Node(int data){ this->data = data; next = NULL; prev = NULL; } }; class LinkedList{ private : Node *header; Node *tail; int size; public : LinkedList(){ header = NULL; tail = NULL; size = 0; } ~LinkedList(){ Node *next; while(header != NULL){ next = header->next; delete header; header = next; } } void append(int data){ // Create node to be inserted Node *n = new Node(data); // Case 1: check if list is empty if(header == NULL){ header = n; tail = n; } // Case 2: check if list is not empty else{ tail->next = n; n->prev = tail; tail = n; } size++; } void prepend(int data){ // create node to be inserted Node *n = new Node(data); // case 1: check if list is empty if(header == NULL){ header = n; tail = n; } // case 2: check if list is not empty else{ header->prev = n; n->next = header; header = n; } // increment the size size++; } int getSize(){ return size; } void removeLast(){ // Case 1: check if list has 1 node if(header->next == NULL){ // delete the node delete header; // set header and tail to NULL header = NULL; tail = NULL; size--; } // Case 2: check if list has more than 1 node else if(header != NULL){ // advance tail pointer to previous node before it tail = tail->prev; // delete the previous last node delete tail->next; // set the current last node next pointer to NULL tail->next = NULL; // decrement the size size--; } } void removeAt(int pos){ //Case 1: check if position is a valid position if(pos < 1 || pos > size) return; //Case 2: check if position is first node else if(pos == 1) removeFirst(); //Case 3: check if position is last node else if(pos == size) removeLast(); //Case 4: check if position is between first and last node else if(header != NULL){ Node *cur = header; for(int i = 1; i < pos; i++) cur = cur->next; cur->prev->next = cur->next; cur->next->prev = cur->prev; delete cur; size--; } } void toString(){ // Create a temp pointer // that points to first Node Node *temp = header; // Create Loop That stops when pointer is NULL while(temp != NULL){ // Print data cout << temp->data << " "; // Advance Pointer to next node temp = temp->next; } cout << endl; } void toStringReverse(){ // Create a temp pointer that points to the tail Node *n = tail; // Create a loop that keeps executing till pointer is NULL while(n != NULL){ // print data cout << n->data << " "; // advance pointer to next node n = n->prev; } cout << endl; } void removeFirst(){ // check if only one node within list if(header->next == NULL){ delete header; header = NULL; tail = NULL; size--; } // check if more than one node within list else if(header != NULL){ header = header->next; delete header->prev; header->prev = NULL; size--; } } // insert node at a certain position void insertAt(int pos,int data){ // Case 1: Check to see if valid position if(pos < 1 || pos > size + 1) return; // Case 2: Check if insertion is in the beginning of the list else if(pos == 1) prepend(data); // Case 3: Check if insertion is at the end of the list else if(pos == size + 1) append(data); // Case 4: If position is between the beginning and end of the list else if(header != NULL){ Node *n = new Node(data); Node *cur = header; for(int i = 1; i < pos; i++) cur = cur->next; cur->prev->next = n; n->prev = cur->prev; n->next = cur; cur->prev = n; size++; } } }; int main(){ LinkedList list; list.append(1); list.append(2); list.append(3); list.append(4); list.append(5); list.insertAt(3,20); list.toString(); }
true
4f6f96a5932c9d2c172414ebd7ad6ad0e64abbac
C++
shota-yamashita/atcoder
/contests/abc120/abc120_b.cpp
UTF-8
366
2.9375
3
[]
no_license
// B - K-th Common Divisor // https://atcoder.jp/contests/abc120/tasks/abc120_b #include <iostream> using namespace std; int main() { int a, b, k; cin >> a >> b >> k; int count; for(int i=min(a, b); i>=1; i--) { if ((a%i==0) && (b%i==0)) count++; if (count == k) { cout << i << endl; return 0; } } }
true