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
f4dd865bf565af64427a197611b75b02e11d6c03
C++
xjhahah/file_transfer
/ftpServer/Mysql.cpp
UTF-8
2,742
2.75
3
[]
no_license
#include "Mysql.h" #include <string.h> #include <sys/types.h> #include <sys/stat.h> bool Mysql::InitSql(string& host, const string& user, const string& pwd, const string& sqlName){ //连接数据库 //连接成功返回MYSQL*连接句柄,即sql服务器 if(!mysql_real_connect(_mysql, host.c_str(), user.c_str(), pwd.c_str(), sqlName.c_str(), 0, nullptr, 0)){ cout << "sql connect fail!,error message: " << mysql_error(_mysql); exit(-1); }else{ cout << "sql connected success..." << endl; } return true; } //退出关闭数据库描述符 bool Mysql::ExeSql(const string& sql){ //执行失败 if(mysql_query(_mysql, sql.c_str())){ //执行指定以NULL终结的字符串查询的SQL语句,返回一个结果表 //成功可调用mysql_num_rows() 来查看对应于SELECT 语句返回了多少行 cout << "sql query fail! error message: " << mysql_error(_mysql); exit(-1); }else{ //获取结果集 _result = mysql_store_result(_mysql); //检索完整的结果保存至客户端 int fieldNums = mysql_num_fields(_result); //返回结果集中的字段数,失败返回 false for(int i = 0; i < fieldNums; ++i){ _row = mysql_fetch_row(_result); // 从结果集中获取下一行,成功返回一个数组,值大于0 if(!_row){ break; } for(int j = 0; j < fieldNums; ++j){ cout << _row[j] << "\t\t"; } cout << endl; } //mysql_free_result(_result); } return true; } void Mysql::CheckFile(){ cout << "star check filepath is ok or no ok" << endl; const char *path = "/home/xjh/file_transfer"; //Linux下遍历目录: 打开目录---》读取内容 ---》 关闭目录 DIR *dp; struct dirent *entry; //定义文件操作句柄 if((dp = opendir(path)) == NULL){ cerr << "cannot open server file..." << endl; return ; }else{ cout << "open it success" << endl; } while((entry = readdir(dp)) != NULL){ cout << entry->d_name << endl; if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0){ continue; } char path_file[100] = "/home/xjh/file_transfer"; char name[100] = ""; sprintf(name, "%s", entry->d_name); strcat(path_file, name); cout << path_file << endl; struct stat stbuf; int res = stat(path_file, &stbuf); printf("%8ld %s\n", stbuf.st_size, name); AddFile(stbuf.st_size, name); } closedir(dp); } void Mysql::AddFile(long long size, char* name){ char cmd[1024] = ""; sprintf(cmd, "INSERT INTO ftpData values('%s','%d');", name, size); puts(cmd); if(mysql_real_query(_mysql, cmd, strlen(cmd)));{ cerr << "0 query fail, message: " << mysql_error(_mysql); return ; } }
true
2060f016885658625b901b3b8197ae4fc54f223d
C++
Noplace/NesEmu
/Code/graphics/gdi.h
UTF-8
1,893
2.765625
3
[]
no_license
#ifndef UISYSTEM_GRAPHICS_GDI_H #define UISYSTEM_GRAPHICS_GDI_H #include <windows.h> #include <algorithm> #define _USE_MATH_DEFINES #include <math.h> #include "graphics.h" namespace graphics { class GDI : public Graphics { public: GDI(); ~GDI(); void Initialize(HWND window_handle, int width, int height); void Deinitialize(); void Render(); void Clear(RGBQUAD color); void SetClippingArea(int x, int y, int width, int height); void BeginFill(RGBQUAD color, double alpha); void BeginGradientFill(const RGBQUAD* colors,const double* alphas, const double* ratios, int count, FillMode mode); void EndFill(); void DrawRectangle(int x, int y, int width, int height); void DrawCircle(int x, int y, int radius); void DrawTriangle(int x0, int y0, int x1, int y1, int x2, int y2); void DrawLine(int x0, int y0, int x1, int y1); RGBQUAD* frame_buffer() const { return frame_buffer_; } RGBQUAD* back_buffer() const { return back_buffer_; } private: bool TestBoundry(int x,int y) { return ( x >= clip_.x && y >= clip_.y && x < clip_.width && y < clip_.height ); } void SetPixel(int x, int y, RGBQUAD color) { back_buffer_[x+(y*display_width_)] = color; } void FillPixel(int x, int y, double xs, double ys) { int index = x+(y*display_width_); if (fill_.mode == kSolid) { //Solid Fill back_buffer_[index] = interpolate_color(back_buffer_[index],fill_.colors[0],fill_.alphas[0]); } else if (fill_.mode == kGradientHorizontal) { RGBQUAD c = interpolate_color(fill_.colors[0],fill_.colors[1],xs); back_buffer_[index] = interpolate_color(back_buffer_[index],c,fill_.alphas[0]); } } void ClearFill() { } BITMAPINFO bitmap_info; HBITMAP hbmp; HDC window_dc_; RGBQUAD* back_buffer_; RGBQUAD* frame_buffer_; Fill fill_; Clip clip_; //std::queue<Command> command_queue_; }; } #endif
true
db9c9eed8c93802be942456497cbd593e5a6dec7
C++
xiaobaiyey/DexRewrite
/external/libbase/cxx_helper.h
UTF-8
1,188
2.8125
3
[ "Apache-2.0" ]
permissive
#ifndef waa_BASE_CXX_HELPER_H_ #define waa_BASE_CXX_HELPER_H_ #include <cstdlib> #include "primitive_types.h" template<typename U, typename T> U ForceCast(T *x) { return (U) (uintptr_t) x; } template<typename U, typename T> U ForceCast(T &x) { return *(U *) &x; } template<typename T> struct Identity { using type = T; }; template<typename R> static inline R OffsetOf(uintptr_t ptr, size_t offset) { return reinterpret_cast<R>(ptr + offset); } template<typename R> static inline R OffsetOf(intptr_t ptr, size_t offset) { return reinterpret_cast<R>(ptr + offset); } template<typename R> static inline R OffsetOf(ptr_t ptr, size_t offset) { return (R) (reinterpret_cast<intptr_t>(ptr) + offset); } template<typename T> static inline T MemberOf(ptr_t ptr, size_t offset) { return *OffsetOf<T *>(ptr, offset); } static inline size_t DistanceOf(ptr_t a, ptr_t b) { return static_cast<size_t>( abs(reinterpret_cast<intptr_t>(b) - reinterpret_cast<intptr_t>(a)) ); } template<typename T> static inline void AssignOffset(ptr_t ptr, size_t offset, T member) { *OffsetOf<T *>(ptr, offset) = member; } #endif // waa_BASE_CXX_HELPER_H_
true
fa34e3ef1b0a0355c93feb3710950007a1f6d5af
C++
shawnmolga/CPP-rock-paper-scissors
/EX2/AICell.cpp
UTF-8
808
2.859375
3
[]
no_license
#include "AICell.h" AICell::AICell(char playerPiece, bool isPieceJoker) { Cell(playerPiece, isPieceJoker); initAIFields(); } AICell::AICell() { Cell(); initAIFields(); } void AICell::initAIFields() { this->flagProbability = FLAGS_NUM / TOTAL_PIECES_NUM; this->isJokerKnown = false; this->isMovingPieceKnown = false; } void AICell::updateCellKnowlage(AICell & cell,const AICell & fromCell) { cell.flagProbability = fromCell.flagProbability; cell.isJokerKnown = fromCell.isJokerKnown; cell.isMovingPieceKnown = fromCell.isMovingPieceKnown; cell.isMovingPiece = fromCell.isMovingPiece; } bool AICell::isMyPiece(int myPlayerNum){ char piece = getPiece(); if (piece == 0 || piece == '#') return false; return myPlayerNum == 1 ? isupper(piece) : islower(piece); }
true
b6ed5df0c3f9b5bc8e82257c31c935d962d10f70
C++
Boraz/CSCI-2270
/CS_HW_3/graph.cpp
UTF-8
4,258
3.171875
3
[]
no_license
#include "graph.h" using namespace std; // default constructor at work here; pretty cute! graph::graph() { } // destructor is easy, we just clear our vertex vector and our edge map graph::~graph() { vertices.clear(); // vertex edges.clear(); // maps } // add a vertex to the graph by adding it to the vector void graph::add_vertex(const vertex& v) { vertices.push_back(v); } // add an edge to the graph as long as it's under the distance limit void graph::add_edge(vertex* v, vertex* u, double limit) { double dist = 0; dist = great_circle_distance(*v, *u); if(dist <= limit) { // edges[v].push_back(u); // edge v or u? both? edges[u].push_back(v); // add_edge(v, u, great_circle_distance); } // compute distance, evaluate if you add an edge } // compute distance from one lat/long to another as the crow flies double graph::great_circle_distance(const vertex& v, const vertex& u) const { double PI = 3.1415926535897932; double lat1, lat2, long1, long2, dist; lat1 = ((double) v.get_latitude_degrees()) + (((double) v.get_latitude_minutes()) / 60.0); lat1 *= PI/180.0; long1 = ((double) v.get_longitude_degrees()) + (((double) v.get_longitude_minutes()) / 60.0); long1 *= PI/180.0; lat2 = ((double) u.get_latitude_degrees()) + (((double) u.get_latitude_minutes()) / 60.0); lat2 *= PI/180.0; long2 = ((double) u.get_longitude_degrees()) + (((double) u.get_longitude_minutes()) / 60.0); long2 *= PI/180.0; // from http://www.meridianworlddata.com/Distance-Calculation.asp // result in km dist = 6378.7 * acos((sin(lat1) * sin(lat2)) + (cos(lat1) * cos(lat2) * cos(long2 - long1))); return dist; } // read in 120 cities and their latitude/longitude // cities within limit km of each other are connected by edges void init_graph_from_file(graph& g, const string& filename, double limit) { string line; string city_name; string tempstr; int lat1, lat2, long1, long2; ifstream file_to_read; char compass_dir_NS; char compass_dir_EW; // open the data file of cities open_for_read(file_to_read, filename); unsigned int k = 0; while(k < 120) { do { //getline(tempstr, city_name, ':'); //getline(tempstr, lat1, ) file_to_read >> tempstr; city_name += tempstr; } while(tempstr[tempstr.length()-1] != ':'); file_to_read >> lat1; file_to_read >> lat2; file_to_read >> compass_dir_NS; if(compass_dir_NS == 'S') { lat1 *= -1; lat2 *= -1; } file_to_read >> long1; file_to_read >> long2; file_to_read >> compass_dir_EW; if(compass_dir_EW == 'W') { long1 *= -1; long2 *= -1; } // string find, starting position + position of the : // multuply by -1 to get S latitude break at N or S // then break on E or W // add_vertex(vector<v>); // need to add the data to the vector vertex city(city_name, lat1, lat2, long1, long2); // constructor call g.add_vertex(city); // this code just puts this vertex at the end of our vertices array ++k; } file_to_read.close(); // add the edges for(unsigned int i = 0; i < k; ++i) { for (unsigned int j = 0; j < k; ++j) { if(i != j) { g.add_edge(&g.vertices[i], &g.vertices[j], limit); // seems to work } } } } // function defined by Michael Main for input data void open_for_read(ifstream& f, string filename) { f.open(filename); if (f.fail()) { cerr << "Could not open input file." << endl; exit(0); } } // function defined by Michael Main for input data bool is_more_stuff_there(ifstream& f) { return (f && (f.peek() != EOF)); } bool depth_first_search(vertex* u,map<vertex*, bool>& visited, deque<vertex*>& yet_to_explore, map<vertex*, vertex*>& path); { if(!yet_to_explore.empty()) { vertex* w = yet_to_explore.back(); // use .front to find the front yet_to_explore.pop_back(); if(w->get_city_name() == u->get_city_name()) { return true; } vector<vertex*>::iterator it; for(it = edges[w].begin(); it != edges[w].end(); ++it) { vertex* neighbor = *it; if(visited[neighbor] == false) { yet_to_explore.push_back(neighbor); visited[neighbor] = true; path[neighbor] = w; } } return depth_first_search(u, visited, yet_to_explore, path); } else return false; // depth first. for breth add from the other sides }
true
bcccc72283bded549bc07efb742ceb3aee4ad158
C++
Scinopode/MaterialProperties
/src/Functions/cViscosityCO2Fenghour.cpp
UTF-8
1,521
2.5625
3
[]
no_license
/************************************************** * * cViscosityCO2Fenghour.cpp * Created on: 15.08.2017 * _ _ _____ * Author: | \ | || __ \ * Norbert | \| || | \/ * Grunwald | . ` || | __ * | |\ || |_\ \_ * \_| \_(_)____(_) * *************************************************/ #include "cViscosityCO2Fenghour.h" #include <cmath> ViscosityCO2Fenghour::ViscosityCO2Fenghour(cComponent* c) : _component (c), _a { 0.235156, -0.491266, 0.05211155, 0.05347906, -0.01537102}, _d {0.4071119e-02, 0.7198037e-04, 0.2411697e-16, 0.2971072e-22, -0.1627888e-22} { std::cout << "ViscosityCO2Fenghour():Fenghour-Wakeham-Vesovic-Correlation for CO2-viscosity used.\n"; } double ViscosityCO2Fenghour::getValue(PropertyType, VariableArray const &vars) { const double T_red = vars[VariableName::T]/_component->getEpsilonK(); const double rho = vars[VariableName::rho_CG]; const double rho_pow_2 = rho*rho; const double rho_pow_6 = rho_pow_2 * rho_pow_2 * rho_pow_2; const double rho_pow_8 = rho_pow_6 * rho_pow_2; double psi (0.); for (size_t i=0; i<_a.size(); i++) psi += _a[i] * std::pow(std::log(T_red),i); const double eta_0 = 1.00697*std::sqrt(T_red)/std::exp(psi); const double eta_d = _d[0]*rho + _d[1]*rho_pow_2 + _d[2]*rho_pow_6/T_red + _d[3]*rho_pow_8 + _d[4]*rho_pow_8/T_red; const double eta = (eta_0 + eta_d) / 1.e6; std::cout << "Fenghour-Wakeham-Vesovic-Correlation returns " "a viscosity of " << eta << "\n"; return eta; }
true
e3a1071828d7aeb26ab94458bfbbe7331d93f7ba
C++
ehaengel/compsk2
/src/main.cpp
UTF-8
1,768
2.53125
3
[]
no_license
#include <stdlib.h> #include <stdio.h> // COMPSK library #include "communication_server.h" int main(int argc, char** argv) { LogFileManager* logfile_manager = new LogFileManager; logfile_manager->VerboseModeOn(); CommunicationServer* communication_server = new CommunicationServer; communication_server->SetLogFileManager(logfile_manager); if(argc > 1) { int port_number = -1; sscanf(argv[1], "%d", &port_number); communication_server->SetPortNumber(port_number); } if(communication_server->Initialize() == false) { logfile_manager->WriteErrorMessage("main", "Could not initialize communication server"); return 1; } if(communication_server->RunCommunicationServer() == false) { logfile_manager->WriteErrorMessage("main", "Could not run communication server"); return 1; } /*AudioServer* audio_server = new AudioServer; audio_server->SetLogFileManager(logfile_manager); if(audio_server->Initialize() == false) { logfile_manager->WriteErrorMessage("main", "Could not initialize audio server"); return 1; } SignalModulator* signal_modulator = new SignalModulator; signal_modulator->SetPortAudioData(audio_server->GetPortAudioData()); signal_modulator->SetLogFileManager(logfile_manager); if(signal_modulator->Initialize() == false) { logfile_manager->WriteErrorMessage("main", "Could not initialize signal modulator"); return 1; } signal_modulator->ModulateStringData("hello world!"); //audio_server->GetPortAudioData()->audio_output_fifo->SaveToFile("data/cyclic_fifo.dat"); PortAudioData* pa_data = audio_server->GetPortAudioData(); while(pa_data->play_audio != 2) { printf("Enter a number:\n"); scanf("%d", &pa_data->play_audio); } delete audio_server; delete signal_modulator;*/ return 0; }
true
0ca2c8fe3c030aa553005be9c437b72b4fabf42e
C++
jegor377/Flow
/src/tests/cases/point2.hpp
UTF-8
3,657
3.453125
3
[ "MIT" ]
permissive
// Non-assign operators // Point2 and Point2 operators CASE("Point2 + Point2 operator works correctly"){ flow::Point2 a(2, 5); flow::Point2 b = a + a; EXPECT(b.x == 4 && b.y == 10); }, CASE("Point2 - Point2 operator works correctly"){ flow::Point2 a(7, 4); flow::Point2 b(4, 3); flow::Point2 c = a - b; EXPECT(c.x == 3 && c.y == 1); }, CASE("Point2 * Point2 operator works correctly"){ flow::Point2 a(2, 5); flow::Point2 b(3, 4); flow::Point2 c = a * b; EXPECT(c.x == 6 && c.y == 20); }, CASE("Point2 / Point2 operator works correctly"){ flow::Point2 a(50, 15); flow::Point2 b(2, 3); flow::Point2 c = a / b; EXPECT(c.x == 25 && c.y == 5); }, // Point2 and double operators CASE("Point2 + double operator works correctly"){ flow::Point2 a(2, 5); double val = 3; flow::Point2 b = a + val; EXPECT(b.x == 5 && b.y == 8); }, CASE("double + Point2 operator works correctly"){ flow::Point2 a(2, 5); double val = 3; flow::Point2 b = val + a; EXPECT(b.x == 5 && b.y == 8); }, CASE("Point2 - double operator works correctly"){ flow::Point2 a(4, 5); double val = 3; flow::Point2 b = a - val; EXPECT(b.x == 1 && b.y == 2); }, CASE("Point2 * double operator works correctly"){ flow::Point2 a(2, 5); double val = 3; flow::Point2 b = a * val; EXPECT(b.x == 6 && b.y == 15); }, CASE("double * Point2 operator works correctly"){ flow::Point2 a(2, 5); double val = 3; flow::Point2 b = val * a; EXPECT(b.x == 6 && b.y == 15); }, CASE("Point2 / double operator works correctly"){ flow::Point2 a(6, 18); double val = 3; flow::Point2 b = a / val; EXPECT(b.x == 2 && b.y == 6); }, // Assign operators // Point2 and Point2 operators CASE("Point2 += Point2 operator works correctly"){ flow::Point2 a(2, 5); flow::Point2 b(3, 5); a += b; EXPECT(a.x == 5 && a.y == 10); }, CASE("Point2 -= Point2 operator works correctly"){ flow::Point2 a(2, 5); flow::Point2 b(3, 5); a -= b; EXPECT(a.x == -1 && a.y == 0); }, CASE("Point2 *= Point2 operator works correctly"){ flow::Point2 a(2, 5); flow::Point2 b(3, 5); a *= b; EXPECT(a.x == 6 && a.y == 25); }, CASE("Point2 /= Point2 operator works correctly"){ flow::Point2 a(10, 5); flow::Point2 b(2, 5); a /= b; EXPECT(a.x == 5 && a.y == 1); }, // Point2 and double operators CASE("Point2 += double operator works correctly"){ flow::Point2 a(10, 30); double val = 2; a += val; EXPECT(a.x == 12 && a.y == 32); }, CASE("Point2 -= double operator works correctly"){ flow::Point2 a(10, 30); double val = 2; a -= val; EXPECT(a.x == 8 && a.y == 28); }, CASE("Point2 *= double operator works correctly"){ flow::Point2 a(10, 30); double val = 2; a *= val; EXPECT(a.x == 20 && a.y == 60); }, CASE("Point2 /= double operator works correctly"){ flow::Point2 a(10, 30); double val = 2; a /= val; EXPECT(a.x == 5 && a.y == 15); }, // equal operators CASE("Point2 == Point2 operator works correctly"){ flow::Point2 a(10, 20); flow::Point2 b(10, 20); flow::Point2 c(20, 10); EXPECT(a == b); EXPECT( !(a == c) ); }, CASE("Point2 == double operator works correctly"){ flow::Point2 a(20, 20); double b = 20; double c = 30; EXPECT(a == b); EXPECT( !(a == c) ); }, CASE("Point2 != Point2 operator works correctly"){ flow::Point2 a(10, 20); flow::Point2 b(20, 10); flow::Point2 c(10, 20); EXPECT(a != b); EXPECT( !(a != c) ); }, CASE("Point2 != double operator works correctly"){ flow::Point2 a(20, 20); double b = 30; double c = 20; EXPECT(a != b); EXPECT( !(a != c) ); }, // methods CASE("Point2 to_string method works returns correct results"){ flow::Point2 a(10, 30); EXPECT(a.to_string() == ("Point2{x: "+std::to_string(10.0)+", y: "+std::to_string(30.0)+"}") ); },
true
46d497791fb7e409fe6301afe618a1cae5c2f72a
C++
SJD095/Programming-Learning
/C++/eden/InstanceOf [lab]/instance.h
UTF-8
773
3.203125
3
[]
no_license
#ifndef INSTANCE_H #define INSTANCE_H #include <iostream> using namespace std; class Object { public: virtual string name() = 0; }; class Animal: public Object { public: virtual string name() { return "Animal"; } }; class Dog: public Animal { virtual string name() { return "Dog"; } }; class Cat: public Animal { public: virtual string name() { return "Cat"; } }; class Vehicle: public Object { public: virtual string name() { return "Vehicle"; } }; class Bus: public Vehicle { public: virtual string name() { return "Bus"; } }; class Car: public Vehicle { public: virtual string name() { return "Car"; } }; string instanceOf(Object* other) { return other == NULL ? "NULL" : other -> name(); } #endif
true
46d8dd1a2ae95d4386921dd620ef09656e66b0a4
C++
ABHISHEK-G0YAL/Competitive-Programming
/practice/codechef/COOK111B/CKWLK.cpp
UTF-8
568
3.046875
3
[]
no_license
// https://www.codechef.com/problems/CKWLK #include <bits/stdc++.h> using namespace std; typedef long long ll; bool divisibleBy10rN(ll n) { while(n % 10 == 0) n /= 10; return n == 1; } bool isNDollarsAchievable(ll n) { if(divisibleBy10rN(n)) return true; while(n % 20 == 0) { n /= 20; if(divisibleBy10rN(n)) return true; } return n == 1; } int main() { int t; ll n; cin >> t; while(t--) { cin >> n; cout << (isNDollarsAchievable(n) ? "Yes" : "No") << endl; } }
true
ed8b8ff2927f4036a493ed2317f8b2fc1df71d1f
C++
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
/Contests/Weekly Contest 112/Most Stones Removed with Same Row or Column.cpp
UTF-8
922
3.140625
3
[ "MIT" ]
permissive
// Question Link ---> https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/ class Solution { public: int removeStones(vector<vector<int>>& stones) { queue<pair<int, int>> nodes; int largestPossibleNumOfMoves = 0, curMaxMoves; for (int i = 0; i < stones.size(); i++) { if (stones[i][0] != -1) { nodes.push({ stones[i][0], stones[i][1] }); stones[i][0] = -1; // Mark As Visited } curMaxMoves = 0; while (!nodes.empty()) { auto cur = nodes.front(); nodes.pop(); for (int i = 0; i < stones.size(); i++) { int nx = stones[i][0], ny = stones[i][1]; if (nx != -1 && (nx == cur.first || ny == cur.second)) { nodes.push({ stones[i][0], stones[i][1] }); stones[i][0] = -1; // Mark as visited curMaxMoves += 1; } } } largestPossibleNumOfMoves += curMaxMoves; } return largestPossibleNumOfMoves; } };
true
b8a6ea15afd21dc880fe1d79970a8846523c7665
C++
aaroncvega123/LibrarySystem
/g++Versions/withDocumentation/Fiction.h
UTF-8
2,729
3.078125
3
[]
no_license
//--------------------------------------------------------------------------- // Fiction.cpp // Class representing book of fiction // Author: Aaron Vega //--------------------------------------------------------------------------- // Fiction class: Represents books of fiction // -- Allows for storing book information // -- Allows to be used for searching ResourceList // -- Allows to create hash code for object // // Assumptions: // -- Assumes input is correct format //--------------------------------------------------------------------------- #pragma once #include "Publication.h" #include <string> #include <iostream> #include <fstream> using namespace std; class Fiction : public Publication { public: //--------------------------------------------------------------------------- // Default constructor // Pre: None // Post: Sets genre to 'F'. Fiction(); //friend istream& operator>>(istream& is, Fiction& F); //--------------------------------------------------------------------------- // hash // Outputs number based on attributes // Pre: None // Post: Returns integer int hash() const; //--------------------------------------------------------------------------- // create // For creating Fiction Object // Pre: None // Post: Returns new Fiction object Resource* create() const { return new Fiction; }; //--------------------------------------------------------------------------- // getGenre // Pre: None // Post: Returns genre char getGenre() const { return genre; }; //--------------------------------------------------------------------------- // operator== // For comparing two Fiction objects // Pre: input must be of type fiction // Post: True, if all attributes (except year) are the same bool operator==(const Resource& other) const; //--------------------------------------------------------------------------- // setSearchData // For when need a dummy Fiction object for searching the ResourceList // Pre: None // Post: Sets author's last name, first name, title, and format istream& setSearchData(istream& is); //--------------------------------------------------------------------------- // printInfo // Pre: None // Post: prints author's name, title, and year virtual void printInfo(); //--------------------------------------------------------------------------- // Deconstructor // Pre: None // Post: None ~Fiction(); private: //--------------------------------------------------------------------------- // getInput // Pre: Input formatted corrected // Post: sets attributes for this object istream& getInput(istream& is); string authorFirstName; string authorLastName; protected: //bool equals(const Resource& other) const; };
true
af320fa0a0b6177ba480aaa1e50f039af1e25dfd
C++
alantany/cpprep
/ar.cpp
UTF-8
216
2.84375
3
[]
no_license
#include<iostream> void ar(int(&ar)[10]) { for (auto r : ar) if (r) std::cout << r << std::endl; } void arc(const int a[10]) { for (size_t i = 0; i != 10; i++) if (a[i]) std::cout << a[i] << std::endl; }
true
6f474013c91e47a983d1b2366e78337e5f548bff
C++
bhanupriyanka2/MRND_Summer_2019
/DAY2/fibonacci.cpp
UTF-8
2,879
3.515625
4
[]
no_license
#include <stdio.h> #include<stdlib.h> #include <unordered_map> using namespace std; long fibonacci(long n){ if (n == 0){ return 0; } if (n == 1){ return 1; } return fibonacci(n - 1) + fibonacci(n - 2); } long fibonacci_memorized(int n, std::unordered_map <int, int>& fib){ if (n < 0) return 0; if (n == 1 || n == 0) return 1; if (fib[n - 1] && fib[n - 2]) { return fib[n - 1] + fib[n - 2]; } else if (fib[n - 1] && !fib[n - 2]) { return fib[n - 1] + fibonacci_memorized(n - 2, fib); } else if (!fib[n - 1] && fib[n - 2]) { return fibonacci_memorized(n - 1, fib) + fib[n - 2]; } else if (!fib[n - 1] && !fib[n - 2]) { return fibonacci_memorized(n - 1, fib) + fibonacci_memorized(n - 2, fib); } } int **matrix_space_allocation(int rows, int cols){ int **matrix = (int **)malloc(sizeof(int *)*rows); for (int row = 0; row < rows; row++){ matrix[row] = (int *)malloc(sizeof(int)*cols); } return matrix; } int **matrix_multiplication(int **matrix_A, int **matrix_B, int row_A, int col_B, int col_A){ int **result = matrix_space_allocation(row_A, col_B); for (int row = 0; row < row_A; row++){ for (int col = 0; col < col_B; col++){ result[row][col] = 0; } } for (int row = 0; row < row_A; row++){ for (int col = 0; col < col_B; col++){ for (int index = 0; index < col_A; index++){ result[row][col] += matrix_A[row][index] * matrix_B[index][col]; } } } return result; } int **matrix_exponentiation(int n, int **matrix_A){ if (n == 2){ return matrix_multiplication(matrix_A, matrix_A, 2, 2, 2); } if (n % 2 == 0){ return matrix_multiplication(matrix_exponentiation(n / 2, matrix_A), matrix_exponentiation(n / 2, matrix_A),2,2,2); } return matrix_multiplication(matrix_A, matrix_multiplication(matrix_exponentiation(n / 2, matrix_A), matrix_exponentiation(n / 2, matrix_A), 2, 2, 2), 2, 2, 2); } int **fibonacci_matrix_exponentiation(int n, int **matrix_A, int **matrix_fib){ matrix_fib = matrix_multiplication(matrix_exponentiation(n, matrix_A), matrix_fib,2,1,2); return matrix_fib; } /*int main(){ long n = 8; int row_A = 2, row_B = 2, col_A = 2, col_B = 1; int **matrix_A =matrix_space_allocaion(row_A,col_A); int **matrix_B = matrix_space_allocation(row_B,col_B); printf("Enter matrix_A:\n"); for (int i = 0; i < row_A; i++){ for (int j = 0; j < col_A; j++){ scanf("%d", &matrix_A[i][j]); } } fflush(stdin); printf("Enter matrix_B:\n"); for (int i = 0; i < row_B; i++){ for (int j = 0; j < col_B; j++){ scanf("%d", &matrix_B[i][j]); } } fflush(stdin); int **result = fibonacci_matrix_exponentiation(n, matrix_A, matrix_B); long fib=fibonacci(n); printf("%d",fib); printf("fibonacci number :%d", result[0][0]); getchar(); return 0; }*/
true
e29af33cd1f6f21a0fb1f0ad473a363069c5b571
C++
pavluchenko/CppTetris
/CppTetris/game.cpp
UTF-8
1,961
2.984375
3
[]
no_license
// // Created by Helga on 2019-08-08. // #include "game.h" Game::Game(Board *pBoard, Pieces *pPieces, int pScreenHeight, IO* pIO) { mScreenHeight = pScreenHeight; mBoard = pBoard; mPieces = pPieces; mIO = pIO; initGame(); } void Game::initGame() { // Init random numbers srand ((unsigned int) time(NULL)); // First piece mPiece = getRand (0, 6); mRotation = getRand (0, 3); mPosX = (BOARD_WIDTH / 2) + mPieces->getXInitialPosition (mPiece, mRotation); mPosY = mPieces->getYInitialPosition (mPiece, mRotation); // Next piece mNextPiece = getRand (0, 6); mNextRotation = getRand (0, 3); mNextPosX = BOARD_WIDTH + 5; mNextPosY = 5; } int Game::getRand (int pA, int pB) { return rand () % (pB - pA + 1) + pA; } void Game::createNewPiece() { mPiece = mNextPiece; mRotation = mNextRotation; mPosX = (BOARD_WIDTH / 2) + mPieces->getXInitialPosition (mPiece, mRotation); mPosY = mPieces->getYInitialPosition (mPiece, mRotation); // Random next piece mNextPiece = getRand (0, 6); mNextRotation = getRand (0, 3); } void Game::drawPiece(int pX, int pY, int pPiece, int pRotation) { color mColor; // Color of the block int mPixelsX = mBoard->getXPosInPixels (pX); int mPixelsY = mBoard->getYPosInPixels (pY); for (int i = 0; i < PIECE_BLOCKS; i++) { for (int j = 0; j < PIECE_BLOCKS; j++) { switch (mPieces->getBlockType (pPiece, pRotation, j, i)) { case 1: mColor = GREEN; break; // For each block of the piece except the pivot case 2: mColor = BLUE; break; // For the pivot } } } } void Game::drawScene () { } void Game::drawBoard () { int mX1 = BOARD_POSITION - (BLOCK_SIZE * (BOARD_WIDTH / 2)) - 1; int mX2 = BOARD_POSITION + (BLOCK_SIZE * (BOARD_WIDTH / 2)); int mY = mScreenHeight - (BLOCK_SIZE * BOARD_HEIGHT); }
true
24e512938558bee8f37925b78d29cb9a38300c39
C++
therbsty/Operating_System_Simulator
/Operating_System_Simulator/BlockTable.cpp
UTF-8
1,377
3.015625
3
[ "MIT" ]
permissive
#include <iterator> #include <map> #include <vector> #include "Block.hpp" #include "BlockTable.hpp" using namespace std; BlockTable::BlockTable(vector<int> blocksizes) { int currentPos = 0; int newID = 0; for (auto currentSize = blocksizes.begin(); currentSize != blocksizes.end(); ++currentSize) { Block newBlock(newID, currentPos, currentPos + *currentSize - 1); this->blockTable.insert({ newBlock.getBlockID(),newBlock }); currentPos += *currentSize; newID++; } } map<int, Block>* BlockTable::getBlockTable() { return &(this->blockTable); } Block* BlockTable::findBestFitFreeBlock(int jobSize){ Block* bestFitFreeBlock = nullptr; for (auto iterator = blockTable.begin(); iterator != blockTable.end(); ++iterator) { int currentSize = iterator->second.getSize(); int sizeDifference = currentSize - jobSize; if (sizeDifference >= 0 && bestFitFreeBlock == nullptr && iterator->second.getBusy() == false) { bestFitFreeBlock = &(iterator->second); } else if (bestFitFreeBlock == nullptr) { continue; } else if (sizeDifference >= 0 && iterator->second.getBusy() == false && currentSize < bestFitFreeBlock->getSize()) { bestFitFreeBlock = &(iterator->second); } } return bestFitFreeBlock; } void BlockTable::assignBlock(Block* block) { block->setBusy(true); } void BlockTable::freeBlock(Block* block) { block->setBusy(false); }
true
fc16759b9d0fa2ecfd7ac8d98733a3e23ee0384c
C++
smalltong02/keras-liber-monitor
/StaticPEManager/InfoBuilder/BaseInfoBuilder.h
UTF-8
4,035
2.5625
3
[ "MIT" ]
permissive
#pragma once #include "InfoBuilder.h" #include "utils.h" namespace fs = std::filesystem; namespace cchips { class CBaseInfoBuilder : public CInfoBuilder { public: CBaseInfoBuilder() { UpdateInfoType(CJsonOptions::_info_type::info_type_base); } ~CBaseInfoBuilder() = default; bool Initialize(std::unique_ptr<CJsonOptions>& json_options) { if (!json_options) return false; if (!json_options->GetOptionsInfo(GetInfoType(), std::pair<unsigned char*, size_t>(reinterpret_cast<unsigned char*>(&m_options_info), sizeof(m_options_info)))) return false; return true; } bool Scan(fs::path& file_path, CFileInfo& file_info) { try { std::unique_ptr<cchips::CRapidJsonWrapper> json_result; json_result = std::make_unique<cchips::CRapidJsonWrapper>("{}"); if (!json_result) return false; if (fs::is_regular_file(file_path)) { if (m_options_info.bfilename) { json_result->AddTopMember("filename", cchips::RapidValue(file_path.filename().string().c_str(), json_result->GetAllocator())); } if (m_options_info.blocation) { json_result->AddTopMember("filepath", cchips::RapidValue(file_path.parent_path().string().c_str(), json_result->GetAllocator())); } if (m_options_info.bfiletype) { json_result->AddTopMember("filetype", cchips::RapidValue(file_info.GetFileType().c_str(), json_result->GetAllocator())); } if (m_options_info.bfilesize) { json_result->AddTopMember("filesize", cchips::RapidValue(fs::file_size(file_path))); } if (m_options_info.bfileattribute) { std::string attributes = GetAttributes(file_path.string()); json_result->AddTopMember("fileattributes", cchips::RapidValue(attributes.c_str(), json_result->GetAllocator())); } } file_info.SetJsonBaseInfo(std::move(json_result)); return true; } catch (const std::exception& e) { } return false; } private: std::string GetAttributes(const std::string& path) const { DWORD attrs = GetFileAttributes(path.c_str()); std::string attrs_str; auto set_attrs_func = [](std::string& attrs_str, const std::string& attr) { if (attrs_str.length()) { attrs_str += std::string(" | ") + attr; return; } attrs_str = attr; }; if (attrs & FILE_ATTRIBUTE_ARCHIVE) { set_attrs_func(attrs_str, "Archive"); } if (attrs & FILE_ATTRIBUTE_COMPRESSED) { set_attrs_func(attrs_str, "Compressed"); } if (attrs & FILE_ATTRIBUTE_ENCRYPTED) { set_attrs_func(attrs_str, "Encrypted"); } if (attrs & FILE_ATTRIBUTE_HIDDEN) { set_attrs_func(attrs_str, "Hidden"); } if (attrs & FILE_ATTRIBUTE_NORMAL) { set_attrs_func(attrs_str, "Normal"); } if (attrs & FILE_ATTRIBUTE_READONLY) { set_attrs_func(attrs_str, "Readonly"); } if (attrs & FILE_ATTRIBUTE_SYSTEM) { set_attrs_func(attrs_str, "System"); } if (attrs & FILE_ATTRIBUTE_TEMPORARY) { set_attrs_func(attrs_str, "Temporary"); } if (!attrs_str.length()) attrs_str = "Unknown"; return attrs_str; } CJsonOptions::_base_info m_options_info; }; } // namespace cchips
true
6d0b9e860b93f9822572b47b2f66d41473f3ec14
C++
Hitonoriol/Methan0l
/src/lang/core/File.cpp
UTF-8
1,175
3
3
[]
no_license
#include "File.h" #include <interpreter/Interpreter.h> #include <util/util.h> namespace mtl::core { /* * Expands `path aliases`: * `$:` - expands into interpreter home directory * `#:` - expands into script run directory * And prepends the result to the rest of the `pathstr` * Example: `$:/modules/ncurses` becomes: `/path/to/binary/modules/ncurses` * Or expands relative paths into absolute ones via the std::filesystem::absolute if no aliases are present in the `pathstr` */ std::string absolute_path(Interpreter &context, const std::string &pathstr) { auto alias = std::string_view(pathstr).substr(0, 2); std::string retpath = pathstr; if (alias == PathPrefix::RUNDIR) replace_all(retpath, alias, context.get_home_dir()); else if (alias == PathPrefix::SCRDIR) replace_all(retpath, alias, context.get_scriptdir()); else retpath = std::filesystem::absolute(retpath).string(); return retpath; } std::string path(Interpreter &context, const std::string &pathstr) { auto alias = std::string_view(pathstr).substr(0, 2); if (alias == PathPrefix::RUNDIR || alias == PathPrefix::SCRDIR) return absolute_path(context, pathstr); return pathstr; } }
true
62e1f58d10bcc8778c68da42ceae8636f99c8dc8
C++
zcfelix/LeetCode
/BinaryTreeMaximumPathSum.h
UTF-8
675
3.375
3
[]
no_license
/* Author: Felix Zhou, zcfelix.zhou@gmail.com Date: Jul 11th, 2015 Problem: Binary Tree Maximum Path Sum Difficulty: Hard Source: https://leetcode.com/problems/binary-tree-maximum-path-sum/ Notes: Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example: Given the below binary tree, 1 / \ 2 3 Return 6. Solution: */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxPathSum(TreeNode* root) { } };
true
faf693f4ab604b857179f8939cbf479dff4926fb
C++
amashrabov/fivt-993-elements-of-programming
/test/persistent_trie_test.cpp
UTF-8
2,058
3.125
3
[]
no_license
#include <gtest/gtest.h> #include <iostream> #include <vector> #include <algorithm> #include <cstdlib> #include <iterator> #include <string> #include "persistent_trie.h" namespace pds { std::vector<char> string2vector(const std::string& s) { std::vector<char> res; std::copy(s.begin(), s.end(), std::back_inserter(res)); return res; } TEST(persistent_trie, simple) { Trie<char> trie; trie.add_word(string2vector("abcde")); trie.add_word(string2vector("xyz")); trie.add_word(string2vector("abcer")); ASSERT_EQ(trie.contains(string2vector("abcde")), true); ASSERT_EQ(trie.contains(string2vector("ab")), false); trie.add_word(string2vector("ab")); ASSERT_EQ(trie.contains(string2vector("ab")), true); ASSERT_EQ(trie.contains(string2vector("xyz")), true); ASSERT_EQ(trie.contains(string2vector("abcde")), true); } TEST(persistent_trie, save_version) { Trie<char> trie; trie.add_word(string2vector("abcde")); ASSERT_EQ(trie.contains(string2vector("abcde")), true); ASSERT_EQ(trie.contains(string2vector("ab")), false); ASSERT_EQ(trie.contains(string2vector("xyz")), false); Trie<char> trie2(trie); trie2.add_word(string2vector("xyz")); ASSERT_EQ(trie.contains(string2vector("abcde")), true); ASSERT_EQ(trie.contains(string2vector("ab")), false); ASSERT_EQ(trie.contains(string2vector("xyz")), false); ASSERT_EQ(trie2.contains(string2vector("abcde")), true); ASSERT_EQ(trie2.contains(string2vector("ab")), false); ASSERT_EQ(trie2.contains(string2vector("xyz")), true); } TEST(persistent_trie, different_key_type) { Trie<std::string> trie; std::vector<std::string> v1; v1.push_back("abc"); v1.push_back("xyz"); v1.push_back("xyz"); ASSERT_EQ(trie.contains(v1), false); trie.add_word(v1); trie.add_word(v1); ASSERT_EQ(trie.contains(v1), true); } }
true
224cb386e318ef37d3c7662a98af2f71a5c74b7b
C++
adriane0523/Bridge2Africa
/Arduino_software/bridge2Africa_1/bridge2Africa/bridge2Africa.ino
UTF-8
1,341
3.046875
3
[]
no_license
int latchPin = 5; int clockPin = 6; int dataPin = 4; int latchPin2 = 8; int dataPin2 = 7; byte leds = 0; byte leds2 = 0; char one = 'a'; char two = 'd'; char count = one; int first = 1; void setup() { Serial.begin(9600); // set the baud rate Serial.println("Ready"); // print "Ready" pinMode(latchPin, OUTPUT); pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(latchPin2, OUTPUT); pinMode(dataPin2, OUTPUT); } void loop() { char inByte = ' '; if(Serial.available()){ // only send data back if data has been sent char inByte = Serial.read(); // read the incoming data Serial.println(inByte); // send the data back in a new line so that it is not all one long line if (first == 1) { leds = inByte; first = 0; } else { leds2 = inByte; first = 1; //leds = 6; //sets the 1st IC segment to have a byte value of 6 so this value is the input that should be received updateShiftRegister1(); delay(200); //leds2 = 9; updateShiftRegister2(); } } } void updateShiftRegister1() { digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, LSBFIRST, leds); digitalWrite(latchPin, HIGH); } void updateShiftRegister2() { digitalWrite(latchPin2, LOW); shiftOut(dataPin2, clockPin, LSBFIRST, leds2); digitalWrite(latchPin2, HIGH); }
true
13260e52bcbc2afb06a93c099b83e656f4cd373d
C++
mlpack/mlpack
/src/mlpack/methods/random_forest/random_forest_main.cpp
UTF-8
12,856
2.703125
3
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
/** * @file methods/random_forest/random_forest_main.cpp * @author Ryan Curtin * * A program to build and evaluate random forests. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #include <mlpack/core.hpp> #undef BINDING_NAME #define BINDING_NAME random_forest #include <mlpack/core/util/mlpack_main.hpp> #include <mlpack/methods/random_forest/random_forest.hpp> using namespace mlpack; using namespace mlpack::util; using namespace std; // Program Name. BINDING_USER_NAME("Random forests"); // Short description. BINDING_SHORT_DESC( "An implementation of the standard random forest algorithm by Leo Breiman " "for classification. Given labeled data, a random forest can be trained " "and saved for future use; or, a pre-trained random forest can be used for " "classification."); // Long description. BINDING_LONG_DESC( "This program is an implementation of the standard random forest " "classification algorithm by Leo Breiman. A random forest can be " "trained and saved for later use, or a random forest may be loaded " "and predictions or class probabilities for points may be generated." "\n\n" "The training set and associated labels are specified with the " + PRINT_PARAM_STRING("training") + " and " + PRINT_PARAM_STRING("labels") + " parameters, respectively. The labels should be in the range [0, " "num_classes - 1]. Optionally, if " + PRINT_PARAM_STRING("labels") + " is not specified, the labels are assumed " "to be the last dimension of the training dataset." "\n\n" "When a model is trained, the " + PRINT_PARAM_STRING("output_model") + " " "output parameter may be used to save the trained model. A model may be " "loaded for predictions with the " + PRINT_PARAM_STRING("input_model") + "parameter. The " + PRINT_PARAM_STRING("input_model") + " parameter may " "not be specified when the " + PRINT_PARAM_STRING("training") + " parameter" " is specified. The " + PRINT_PARAM_STRING("minimum_leaf_size") + " parameter specifies the minimum number of training points that must fall " "into each leaf for it to be split. The " + PRINT_PARAM_STRING("num_trees") + " controls the number of trees in the random forest. The " + PRINT_PARAM_STRING("minimum_gain_split") + " parameter controls the minimum" " required gain for a decision tree node to split. Larger values will " "force higher-confidence splits. The " + PRINT_PARAM_STRING("maximum_depth") + " parameter specifies " "the maximum depth of the tree. The " + PRINT_PARAM_STRING("subspace_dim") + " parameter is used to control the " "number of random dimensions chosen for an individual node's split. If " + PRINT_PARAM_STRING("print_training_accuracy") + " is specified, the " "calculated accuracy on the training set will be printed." "\n\n" "Test data may be specified with the " + PRINT_PARAM_STRING("test") + " " "parameter, and if performance measures are desired for that test set, " "labels for the test points may be specified with the " + PRINT_PARAM_STRING("test_labels") + " parameter. Predictions for each " "test point may be saved via the " + PRINT_PARAM_STRING("predictions") + "output parameter. Class probabilities for each prediction may be saved " "with the " + PRINT_PARAM_STRING("probabilities") + " output parameter."); // Example. BINDING_EXAMPLE( "For example, to train a random forest with a minimum leaf size of 20 " "using 10 trees on the dataset contained in " + PRINT_DATASET("data") + "with labels " + PRINT_DATASET("labels") + ", saving the output random " "forest to " + PRINT_MODEL("rf_model") + " and printing the training " "error, one could call" "\n\n" + PRINT_CALL("random_forest", "training", "data", "labels", "labels", "minimum_leaf_size", 20, "num_trees", 10, "output_model", "rf_model", "print_training_accuracy", true) + "\n\n" "Then, to use that model to classify points in " + PRINT_DATASET("test_set") + " and print the test error given the labels " + PRINT_DATASET("test_labels") + " using that model, while saving the " "predictions for each point to " + PRINT_DATASET("predictions") + ", one " "could call " "\n\n" + PRINT_CALL("random_forest", "input_model", "rf_model", "test", "test_set", "test_labels", "test_labels", "predictions", "predictions")); // See also... BINDING_SEE_ALSO("@decision_tree", "#decision_tree"); BINDING_SEE_ALSO("@hoeffding_tree", "#hoeffding_tree"); BINDING_SEE_ALSO("@softmax_regression", "#softmax_regression"); BINDING_SEE_ALSO("Random forest on Wikipedia", "https://en.wikipedia.org/wiki/Random_forest"); BINDING_SEE_ALSO("Random forests (pdf)", "https://link.springer.com/content/pdf/10.1023/A:1010933404324.pdf"); BINDING_SEE_ALSO("RandomForest C++ class documentation", "@src/mlpack/methods/random_forest/random_forest.cpp"); PARAM_MATRIX_IN("training", "Training dataset.", "t"); PARAM_UROW_IN("labels", "Labels for training dataset.", "l"); PARAM_MATRIX_IN("test", "Test dataset to produce predictions for.", "T"); PARAM_UROW_IN("test_labels", "Test dataset labels, if accuracy calculation is " "desired.", "L"); PARAM_FLAG("print_training_accuracy", "If set, then the accuracy of the model " "on the training set will be predicted (verbose must also be specified).", "a"); PARAM_INT_IN("num_trees", "Number of trees in the random forest.", "N", 10); PARAM_INT_IN("minimum_leaf_size", "Minimum number of points in each leaf " "node.", "n", 1); PARAM_INT_IN("maximum_depth", "Maximum depth of the tree (0 means no limit).", "D", 0); PARAM_MATRIX_OUT("probabilities", "Predicted class probabilities for each " "point in the test set.", "P"); PARAM_UROW_OUT("predictions", "Predicted classes for each point in the test " "set.", "p"); PARAM_DOUBLE_IN("minimum_gain_split", "Minimum gain needed to make a split " "when building a tree.", "g", 0); PARAM_INT_IN("subspace_dim", "Dimensionality of random subspace to use for " "each split. '0' will autoselect the square root of data dimensionality.", "d", 0); PARAM_INT_IN("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0); PARAM_FLAG("warm_start", "If true and passed along with `training` and " "`input_model` then trains more trees on top of existing model.", "w"); /** * This is the class that we will serialize. It is a pretty simple wrapper * around DecisionTree<>. In order to support categoricals, it will need to * also hold and serialize a DatasetInfo. */ class RandomForestModel { public: // The tree itself, left public for direct access by this program. RandomForest<> rf; // Create the model. RandomForestModel() { /* Nothing to do. */ } // Serialize the model. template<typename Archive> void serialize(Archive& ar, const uint32_t /* version */) { ar(CEREAL_NVP(rf)); } }; PARAM_MODEL_IN(RandomForestModel, "input_model", "Pre-trained random forest to " "use for classification.", "m"); PARAM_MODEL_OUT(RandomForestModel, "output_model", "Model to save trained " "random forest to.", "M"); void BINDING_FUNCTION(util::Params& params, util::Timers& timers) { // Initialize random seed if needed. if (params.Get<int>("seed") != 0) RandomSeed((size_t) params.Get<int>("seed")); else RandomSeed((size_t) std::time(NULL)); // Check for incompatible input parameters. if (!params.Has("warm_start")) { RequireOnlyOnePassed(params, { "training", "input_model" }, true); } else { // When warm_start is passed, training and input_model must also be passed. RequireNoneOrAllPassed(params, {"warm_start", "training", "input_model"}, true); } ReportIgnoredParam(params, {{ "training", false }}, "print_training_accuracy"); ReportIgnoredParam(params, {{ "test", false }}, "test_labels"); RequireAtLeastOnePassed(params, { "test", "output_model", "print_training_accuracy" }, false, "the trained forest model will not " "be used or saved"); if (params.Has("training")) { RequireAtLeastOnePassed(params, { "labels" }, true, "must pass labels when " "training set given"); } RequireParamValue<int>(params, "num_trees", [](int x) { return x > 0; }, true, "number of trees in forest must be positive"); ReportIgnoredParam(params, {{ "test", false }}, "predictions"); ReportIgnoredParam(params, {{ "test", false }}, "probabilities"); RequireParamValue<int>(params, "minimum_leaf_size", [](int x) { return x > 0; }, true, "minimum leaf size must be greater " "than 0"); RequireParamValue<int>(params, "maximum_depth", [](int x) { return x >= 0; }, true, "maximum depth must not be negative"); RequireParamValue<int>(params, "subspace_dim", [](int x) { return x >= 0; }, true, "subspace dimensionality must be nonnegative"); RequireParamValue<double>(params, "minimum_gain_split", [](double x) { return x >= 0.0; }, true, "minimum gain for splitting must be nonnegative"); ReportIgnoredParam(params, {{ "training", false }}, "num_trees"); ReportIgnoredParam(params, {{ "training", false }}, "minimum_leaf_size"); RandomForestModel* rfModel; // Input model is loaded when we are either doing warm-started training or // else we are making predictions only or both. if (params.Has("input_model")) rfModel = params.Get<RandomForestModel*>("input_model"); // Handles the case when we are training new forest from scratch. else rfModel = new RandomForestModel(); if (params.Has("training")) { timers.Start("rf_training"); // Train the model on the given input data. arma::mat data = std::move(params.Get<arma::mat>("training")); arma::Row<size_t> labels = std::move(params.Get<arma::Row<size_t>>("labels")); // Make sure the subspace dimensionality is valid. RequireParamValue<int>(params, "subspace_dim", [data](int x) { return (size_t) x <= data.n_rows; }, true, "subspace " "dimensionality must not be greater than data dimensionality"); const size_t numTrees = (size_t) params.Get<int>("num_trees"); const size_t minimumLeafSize = (size_t) params.Get<int>("minimum_leaf_size"); const size_t maxDepth = (size_t) params.Get<int>("maximum_depth"); const double minimumGainSplit = params.Get<double>("minimum_gain_split"); const size_t randomDims = (params.Get<int>("subspace_dim") == 0) ? (size_t) std::sqrt(data.n_rows) : (size_t) params.Get<int>("subspace_dim"); MultipleRandomDimensionSelect mrds(randomDims); Log::Info << "Training random forest with " << numTrees << " trees..." << endl; const size_t numClasses = arma::max(labels) + 1; // Train the model. rfModel->rf.Train(data, labels, numClasses, numTrees, minimumLeafSize, minimumGainSplit, maxDepth, params.Has("warm_start"), mrds); timers.Stop("rf_training"); // Did we want training accuracy? if (params.Has("print_training_accuracy")) { timers.Start("rf_prediction"); arma::Row<size_t> predictions; rfModel->rf.Classify(data, predictions); const size_t correct = arma::accu(predictions == labels); Log::Info << correct << " of " << labels.n_elem << " correct on training" << " set (" << (double(correct) / double(labels.n_elem) * 100) << ")." << endl; timers.Stop("rf_prediction"); } } if (params.Has("test")) { arma::mat testData = std::move(params.Get<arma::mat>("test")); timers.Start("rf_prediction"); // Get predictions and probabilities. arma::Row<size_t> predictions; arma::mat probabilities; rfModel->rf.Classify(testData, predictions, probabilities); // Did we want to calculate test accuracy? if (params.Has("test_labels")) { arma::Row<size_t> testLabels = std::move(params.Get<arma::Row<size_t>>("test_labels")); const size_t correct = arma::accu(predictions == testLabels); Log::Info << correct << " of " << testLabels.n_elem << " correct on test" << " set (" << (double(correct) / double(testLabels.n_elem) * 100) << ")." << endl; timers.Stop("rf_prediction"); } // Save the outputs. params.Get<arma::mat>("probabilities") = std::move(probabilities); params.Get<arma::Row<size_t>>("predictions") = std::move(predictions); } // Save the output model. params.Get<RandomForestModel*>("output_model") = rfModel; }
true
934c9e3f5f97add36379b8ea9a6bf89c1acf76f5
C++
Pater1/NeumontArchive
/CPP/CPP 1/Projects/Battle Arena/Battle Arena/Character.cpp
UTF-8
3,060
2.796875
3
[]
no_license
#include<string> #include<iostream> #include"Character.h" #include"RandUtils.h" #include"Attack.h" #include "DeleteProtectionWrapper.h" void Character::ConvenienceBaseClone(Character * from, Character * to){ to->characterName = from->characterName; } Character* Character::DeleteProtect(Character* from){ return new DeleteProtectionWrapper(from); } Character::Character(int HP_max) : maxHP(HP_max), curHP(maxHP){ money = new Currency(10, 0, 0, 0); } Character::~Character() { if (attacks.size() > 0) { for (int i = (int)attacks.size() - 1; i >= 0; i--) { delete attacks[i]; } } } double Character::XPDrop(){ return level * ((wins<1? 1: wins)/(double)(losses<1? 1: losses)); } void Character::XPPickup(double xp){ curXP += xp; if (curXP >= xpToNextLevel) { curXP -= xpToNextLevel; xpToNextLevel *= 2; level++; LevelUp(level); } } Currency & Character::GetMoney(){ return *money; } int Character::GetEditWins(int delta){ wins += delta; return wins; } int Character::GetEditLosses(int delta){ losses += delta; return losses; } void Character::Revive(std::vector<Character*>* , std::vector<Character*>* , std::ostream* ) { curHP = maxHP; } bool Character::ThrowAttack(int atkIndex, std::vector<Character*>* allys, std::vector<Character*>* targets, std::ostream* out){ if (PeekDead()) { if (out != nullptr) *FullName(out) << " is dead, and will do nothing this turn.\n"; return false; } if (atkIndex < 0) atkIndex = RandInt((int)attacks.size()); return (attacks[atkIndex]->Throw(this, allys, targets, out)); } int Character::AlterHP(double HPDelta, std::ostream* out) { if (hidden && HPDelta < 0) { if (out != NULL) *FullName(out) << " avoids damage by hiding.\n"; return 0; } else { int delta = (int)(HPDelta * maxHP); if ((delta < 0 ? delta*-1 : delta) < 1) { delta = (delta < 0 ? 1 : -1); } if (out != NULL) *FullName(out) << (delta < 0 ? " loses " : " heals ") << (delta < 0 ? delta*-1 : delta) << "hp!\n"; TurnDelta_HP += delta; return delta; } } int Character::AlterHP(int delta, std::ostream* out) { if (hidden && delta < 0) { if (out != NULL) *FullName(out) << " avoids damage by hiding.\n"; return 0; }else{ if (out != NULL) *FullName(out) << (delta < 0 ? " loses " : " heals ") << (delta < 0 ? delta*-1 : delta) << "hp!\n"; TurnDelta_HP += delta; return TurnDelta_HP; } } std::ostream* Character::FullName(std::ostream* out){ if (out == NULL || out == nullptr) return out; return &(*out << characterName << ", the " << className); } bool Character::CheckDead(std::vector<Character*>* , std::vector<Character*>* , std::ostream* out){ curHP += TurnDelta_HP; TurnDelta_HP = 0; if (curHP > maxHP) curHP = maxHP; if (curHP < 0) curHP = 0; bool b = (curHP <= 0); if(out != NULL){ if (b) { *out << characterName << " is Dead!\n"; } else { *out << characterName << " has " << curHP << "hp!\n"; } } return b; } bool Character::PeekDead() { return ((curHP + TurnDelta_HP) <= 0); } int Character::PeekHP() { return curHP; }
true
e48d99638d1deb88b76b0bfcc8e55f98c6bd8fd1
C++
Solcito25/CCOMP
/4 Examen/exam/main.cpp
UTF-8
857
3.25
3
[]
no_license
#include <iostream> using namespace std; /*int a,b,c=1,d=1,f,e; cin>>a,f; cin>>b,e; if (b*2==a) cout<<b<<endl; else if (a*2==b) cout<<a<<endl; else{ while((c<=b)&&(c<=a)){ if ((f%c==0)&&(e%c==0)){ d=d*c; f=a/c; e=b/c; c++; } else c++; } cout<<d<<endl; }*/ int pares (int &d){ if (d%2==0) return d; return 0; } int impares (int &d){ if (d%2!=0) return d; return 0; } int main(){ int a,b,c,d=0; cout<<"desde"<<endl; cin>>a; cout<<"hasta"<<endl; cin>>b; cout<<"incremento"<<endl; cin>>c; for(a;a<=b;a=a+c){ //cout<<a<<endl; cout<<"es par "<<pares(a)<<endl; cout<<"es impar"<<impares(a)<<endl; } }
true
e9d26b67727ab88fb3e049d9d20d8a5e1bff9d41
C++
CaseyYang/LeetCode
/LeetCode/Minimum_Path_Sum/Main.cpp
UTF-8
597
2.890625
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: int minPathSum(vector<vector<int> > &grid) { if (grid.size() == 0) return 0; int height = grid.size(); int width = grid[0].size(); for (int i = 0; i < grid.size(); ++i){ for (int j = 0; j < grid[i].size(); ++j){ if (i == 0){ if (j != 0) grid[i][j] += grid[i][j - 1]; } else{ if (j == 0) grid[i][j] += grid[i - 1][j]; else grid[i][j] += min(grid[i][j - 1], grid[i - 1][j]); } } } return grid[height - 1][width - 1]; } }; int main(){ return 0; }
true
6d9698d97d235088a874b927efd1de68e8a71dcc
C++
zamansabbir/DataStructure
/LeetCode/LongestWord.cpp
UTF-8
613
3.328125
3
[ "MIT" ]
permissive
#include<iostream> #include<vector> #include <string> #include<algorithm> #include<unordered_set> using namespace std; string longestWord(vector<string> &words){ string result=""; sort(words.begin(),words.end()); unordered_set <string> check; for(string &s:words){ if(s.length()==1||check.find(s.substr(0,s.length()-1))!=check.end()){ if(s.length()>result.length()) result=s; check.insert(s);; } } return result; } int main(){ vector<string> w={"a","banana","app","appl","ap","apply","apple"}; cout<< longestWord(w)<<endl; return 0; }
true
94e46ad133f7e7a9beac5aaa480b3415cb14c4cf
C++
qq260327056/lua-studio
/LuaStudio/src/Lua.h
UTF-8
3,116
2.625
3
[ "MIT" ]
permissive
#pragma once #include <boost/noncopyable.hpp> #include <boost/scoped_ptr.hpp> #include <boost/function.hpp> //#include <boost/function/function1.hpp> #include <exception> #include <vector> typedef std::vector<unsigned char> ProgBuf; struct lua_exception : public std::exception { lua_exception(const char* msg) : exception(msg) {} }; namespace lua_details { struct State; } class Lua : boost::noncopyable { public: Lua(); ~Lua(); enum Event { Start, Running, NewLine, Finished }; void SetCallback(const boost::function<void (Event, int)>& fn); // load file (parse, do not execute) void LoadFile(const char* file_path); bool LoadFile(const char* file_path, const char*& msg); // 'load' string // bool LoadBuffer(const char* source, const char*& msg); // dump current program into the buffer (as executable byte codes) void Dump(ProgBuf& program, bool debug); // execute int Call(); // execute single line (current one) following calls, if any void StepInto(); // execute current line, without entering any functions void StepOver(); // start execution (it runs in a thread) void Run(); // run till return from the current function void StepOut(); std::string Status() const; bool IsRunning() const; // is Lua program running now? (if not, maybe it stopped at the breakpoint) bool IsFinished() const; // has Lua program finished execution? bool IsStopped() const; // if stopped, it can be resumed (if not stopped, it's either running or done) // toggle breakpoint in given line bool ToggleBreakpoint(int line); // stop running program void Break(); // get current call stack std::string GetCallStack() const; enum ValType { None= -1, Nil, Bool, LightUserData, Number, String, Table, Function, UserData, Thread }; struct Value // value on a virtual stack or elsewhere { Value() : type(None), type_name(0) {} ValType type; const char* type_name; std::string value; // simplified string representation of value }; struct Var { std::string name; // variable's identifier Value v; }; // get local vars of function at given 'level' bool GetLocalVars(std::vector<Var>& out, int level= 0) const; struct Field // table entry { Value key; Value val; }; typedef std::vector<Field> TableInfo; // get global vars bool GetGlobalVars(TableInfo& out, bool deep) const; typedef std::vector<Value> ValueStack; // read all values off virtual value stack bool GetValueStack(ValueStack& stack) const; struct StackFrame { StackFrame(); void Clear(); const char* SourcePath() const; enum Entry { Err, LuaFun, MainChunk, CFun, TailCall } type; std::string source; std::string name_what; int current_line; // 1..N or 0 if not available // where it is defined (Lua fn) int line_defined; int last_line_defined; }; // typedef std::vector<StackFrame> CallStack; // get function call stack bool GetCallStack(CallStack& stack) const; // info about current function and source file (at the top of the stack) bool GetCurrentSource(StackFrame& top) const; private: boost::scoped_ptr<lua_details::State> state_; };
true
ab191c88593e62bcc8a6fbff73155404658f6138
C++
KIIIKIII/hello-world
/EdgeSort.cpp
UTF-8
842
2.9375
3
[]
no_license
#include<stdio.h> #include<iostream> #include<algorithm> using namespace std; struct Road { int u; int v; int l; int t; int w; int c; int f; }; Road road[10000]; bool cmp(const Road &r1, const Road &r2) { if (r1.l != r2.l) return r1.l<r2.l; else if (r1.t != r2.t) return r1.t<r2.t; else if (r1.w != r2.w) return r1.w<r2.w; else if (r1.c != r2.c) return r1.c<r2.c; else return r1.f<r2.f; } int main() { int num, n; scanf("%d", &num); for (int i = 0; i<num; i++) scanf("%d %d %d %d %d %d %d", &road[i].v, &road[i].u, &road[i].l, &road[i].t, &road[i].w, &road[i].c, &road[i].f); sort(road, road + num, cmp); scanf("%d", &num); for (int i = 0; i<num; i++) { scanf("%d", &n); n--; printf("%d %d %d %d %d %d %d\n", road[n].v, road[n].u, road[n].l, road[n].t, road[n].w, road[n].c, road[n].f); } return 0; }
true
451ef31d8ec07225078edde1b2a6c5ad4e86fca6
C++
Garfield-Chen/jet-game-engine
/Include/Jet/Core/CoreMeshObject.hpp
UTF-8
3,952
2.53125
3
[]
no_license
/* * Copyright (c) 2010 Matt Fichman * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #pragma once #include <Jet/Core/CoreTypes.hpp> #include <Jet/Core/CoreEngine.hpp> #include <Jet/Core/CoreNode.hpp> #include <Jet/Resources/Material.hpp> #include <Jet/Resources/Mesh.hpp> #include <Jet/Resources/Texture.hpp> #include <map> namespace Jet { //! This class is used to display an instanced mesh on the screen. //! @class MeshObject //! @brief Displays an instanced mesh. class CoreMeshObject : public MeshObject { public: inline CoreMeshObject(CoreEngine* engine, CoreNode* parent) : engine_(engine), parent_(parent), cast_shadows_(true) { } //! Destructor. virtual ~CoreMeshObject() {} //! Returns the parent of this object. inline CoreNode* parent() const { return parent_; } //! Returns the material used to render this object. inline Material* material() const { return material_.get(); } //! Returns the mesh used to render this object. inline Mesh* mesh() const { return mesh_.get(); } //! Returns true if this object casts shadows. inline bool cast_shadows() const { return cast_shadows_; } //! Returns the shader parameter at the given location. //! @param name the param name inline const boost::any& shader_param(const std::string& name) { return shader_param_[name]; } //! Sets the material used to render this object. //! @param material a pointer to the material inline void material(Material* material) { material_ = material; } //! Sets the mesh used to render this object. //! @param mesh the mesh inline void mesh(Mesh* mesh) { mesh_ = mesh; } //! Sets whether or not this object casts shadows. //! @param shadows true if the object should cast shadows inline void cast_shadows(bool shadows) { cast_shadows_ = shadows; } //! Sets the material used to render this object by name. //! @param name the name of the material inline void material(const std::string& name) { material(engine_->material(name)); } //! Sets the mesh used to render this object by name. //! @param name the name of the mesh inline void mesh(const std::string& name) { mesh(engine_->mesh(name)); } //! Sets the shader parameter at the given location. //! @param name the param name //! @param param the parameter inline void shader_param(const std::string& name, const boost::any& param) { shader_param_[name] = param; } private: CoreEngine* engine_; CoreNode* parent_; MaterialPtr material_; MeshPtr mesh_; std::map<std::string, boost::any> shader_param_; bool cast_shadows_; }; }
true
4c6740d7b6dae74b5081206ce1a24299decd7ed8
C++
nkersting/Code
/findPythagoreanTriples.cpp
UTF-8
1,739
3.4375
3
[]
no_license
//If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120. //{20,48,52}, {24,45,51}, {30,40,50} //For which value of p ≤ 1000, is the number of solutions maximised? // This code shows the answer is p=840, with 8 solutions #include <string> #include <string.h> #include <map> #include <set> #include <vector> #include <iostream> using namespace std; //////////////////////// /////////////////////// int main() { map<int, vector<vector<int> > > solution_map; int max_p = 0; int max_sols = 0; for (int p = 1000; p >= 3; --p) { for (int c = p - 2; c >= 2; --c) { for (int a = p - c - 1; a >= 1; --a) { int b = p - c - a; if (a >= b && // avoids double-counting a*a + b*b == c*c) { vector<int> triple = vector<int>{a,b,c}; solution_map[p].push_back(triple); } } } if (solution_map[p].size() > max_sols) { max_sols = solution_map[p].size(); max_p = p; } } cout << "Maximum number for perimeter of " << max_p << ", in which case " << max_sols << " solutions." << endl << endl; for (map<int, vector<vector<int> > >::iterator iter = solution_map.begin(); iter != solution_map.end(); ++iter){ std::cout << iter->first << " "; for (vector<vector<int> >::iterator iter2 = (iter->second).begin(); iter2 != (iter->second).end(); ++iter2){ for (vector<int>::iterator iter3 = (*iter2).begin(); iter3 != (*iter2).end(); ++iter3){ std::cout << *iter3 << " "; } std::cout << ", "; } std::cout << std::endl; } return 1; }
true
313c2706e91fc4b4d87b5e745e8c21460b1b18f6
C++
kentoo-zbcast/people_detect_pi
/acf/ACFFeaturePyramid.h
UTF-8
2,967
2.921875
3
[]
no_license
/* * ACFFeaturePyramid.h */ #pragma once #include "ChannelFeatures.h" class ACFFeaturePyramid { public: ACFFeaturePyramid(const cv::Mat &source_image, int _scales_per_oct, cv::Size minSize, float shrink, const std::array<double, 3>& lambdas, int pad_width, int pad_height); void update(const cv::Mat &source_image); virtual ~ACFFeaturePyramid(); int getAmount() { return this->layers.size(); } ChannelFeatures* getLayer(int L) { if (L < this->layers.size()) { return this->layers[L]; } else { std::cerr << "Requesting unknown layer ..." << std::endl; exit(1); } } cv::Size2d get_scale_xy(int i) { cv::Size2d scale; scale.width = this->scaled_sizes.at(i).width / (double) image_size.width; scale.height = this->scaled_sizes.at(i).height / (double) image_size.height; return scale; } double get_scale(int i) { cv::Size2d scale_xy = get_scale_xy(i); return (scale_xy.width + scale_xy.height) / 2; } void print_scale(int i) { std::cout << "[" << i << " " << this->scaled_sizes.at(i).width << "x" << this->scaled_sizes.at(i).height << "]"; } void print_duration() { std::cout << "Pre: " << pre_duration << std::endl; int sum_layer_init = 0; int sum_layer_smooth = 0; int sum_layer_pad = 0; for (int i = 0; i < layers.size(); i++) { std::cout << "Layer " << i << ": "; if (layers[i] == NULL) { std::cout << "NULL"; } else { sum_layer_init += layers[i]->init_duration; sum_layer_smooth += layers[i]->smooth_duration; sum_layer_pad += layers[i]->pad_duration; int sum = layers[i]->init_duration + layers[i]->smooth_duration + layers[i]->pad_duration; std::cout << "(" << layers[i]->color_duration << " + " << layers[i]->mag_duration << " + " << layers[i]->hist_duration << " = " << layers[i]->init_duration << ") + " << layers[i]->smooth_duration << " + " << layers[i]->pad_duration << " = " << sum; } std::cout << std::endl; } std::cout << "Calc: " << calc_duration << " / (" << sum_layer_init << " + " << sum_layer_smooth << " + " << sum_layer_pad << ")" << std::endl; } int pre_duration; int calc_duration; protected: std::vector<ChannelFeatures*> layers; // amount of scales in each octave (so between halving each image dimension ) int scales_per_oct; // Minimum size an image can have (size of the model) cv::Size minSize; cv::Size image_size; std::vector<cv::Size> scaled_sizes; };
true
3bcd3c5c5e47d4cd122a81d177bcfa7d1a4f5e25
C++
maximaximal/SFML-Sidescroller-Revived
/include/CMenu/CContainer.h
UTF-8
1,047
2.609375
3
[]
no_license
#ifndef CCONTAINER_H #define CCONTAINER_H #include <SFML/Graphics.hpp> namespace CMenuNew { class CContainerManager; enum type { button, slider, label, image }; class CContainer : public sf::Drawable, public sf::NonCopyable { public: CContainer(); virtual ~CContainer(); CContainerManager *containerManager; virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; virtual void update(float frametime); virtual void handleEvent(sf::Event *event); virtual void handleMouseMove(sf::Vector2i pos); virtual void setPosition(sf::Vector2f pos); int getType() {return type;} int getID() {return ID;} void (*onClick)(void); void (*onHover)(void); void (*onHoverLeave)(void); void (*onUpdate)(float frametime); protected: int type; int ID; }; } #endif // CCONTAINER_H
true
e618e6a61b2c535821ccc0aaf78d154a5491bd21
C++
mccurtyn/obelisk
/src/monster.h
UTF-8
553
2.96875
3
[]
no_license
#include <string> #include "entity.h" #pragma once using namespace std; struct monster{ private: entity e; int damage; public: void setMonsterHealth(int h){ e.setEntHealth(h); } int getMonsterHealth(){ return e.getEntHealth(); } void setMonsterAlive(bool a){ e.setEntAlive(a); } bool getMonsterAlive(){ return e.getEntAlive(); } void setMonsterName(string n){ e.setEntName(n); } string getMonsterName(){ return e.getEntName(); } void setMonsterDamage(int d){ damage = d; } int getMonsterDamage(){ return damage; } };
true
27e09f630e4e43aecf804c03766bef59e60cc29d
C++
mghnm/PracticalApplications1
/Step1Task9.cpp
UTF-8
2,120
3.859375
4
[]
no_license
//----------------------------------------------------------------------- // File: Step1Task9.cpp // Summary: Reads the change of growth of investment over 4 years. // Returns the final result of investment in SEK // Version: 1.0 // Owner: Mohamad Ghanem //----------------------------------------------------------------------- //Preprocesssor directives #include <iostream> #include <iomanip> #include <math.h> using namespace std; //Prototype function void calcStockInvestment(); int main() { char answer; do { calcStockInvestment(); cout << "Would you like to calculate again? (Y/N)"; cin >> answer; } while (answer == 'Y' || answer == 'y'); return 0; } //----------------------------------------------------------------- // void calcStockInvestment() // // Summary: Reads the stock value changes over 4 years and gives the user the final value on their investment in SEK // Returns: - //----------------------------------------------------------------- void calcStockInvestment() { //Array of doubles for the investment values double changes[] = { 0.0, 0.0, 0.0, 0.0 }; //The initial invetment the user did double investment = 0.0; //The output value double finalInvestmentValue = 0.0; //Read the temperature in celsius cout << "Enter the initial investment in SEK: "; cin >> investment; //Read the wind speed m/s cout << "Enter the changes over the past 4 year in percentage (separated by spaces): "; cin >> changes[0] >> changes[1] >> changes[2] >> changes[3]; //Use a for loop to calculate the final output finalInvestmentValue = investment; //Here we are essentially doing each multiplication for each year and assigning the new input to the output of the previous year. for (int i = 0; i < 4; i++) { finalInvestmentValue *= ( 1 + (changes[i] / 100.0)); } // Display result with 1 decimals cout << fixed << showpoint << setprecision(2); //Putting it all together for the user cout << "Your initial investment of " << investment << " SEK 4 years ago is now worth " << finalInvestmentValue << " SEK"<< endl; }
true
29428bf350f030fa9bfc6783c2b5ae3f6c28e190
C++
jkevin1/lang
/lex.cpp
UTF-8
1,752
3.234375
3
[]
no_license
#include "lex.hpp" #include <ctype.h> #include <string> Lexer::Lexer(const char* filename) : owned(true), lastChar(' ') { file = fopen(filename, "r"); } Lexer::Lexer(FILE* source) : owned(false), lastChar('0') { file = source; } Lexer::~Lexer() { if (owned) fclose(file); } Token Lexer::getNextToken() { while (isspace(lastChar)) lastChar = nextChar(); if (isalpha(lastChar) || lastChar == '_') { std::string value; do { value += lastChar; lastChar = nextChar(); } while (isalnum(lastChar) || lastChar == '_'); printf("Identifier: %s\n", value.c_str()); return TOK_IDENTIFIER; } if (isdigit(lastChar) || lastChar == '.') { std::string value; do { value += lastChar; lastChar = nextChar(); } while (isdigit(lastChar) || lastChar == '.'); printf("Number: %lf\n", strtod(value.c_str(), nullptr)); return TOK_NUMBER; } if (lastChar == '"') { std::string value; while ((lastChar = nextChar()) != '"' && lastChar != EOF) value += lastChar; lastChar = nextChar(); printf("String: '%s'\n", value.c_str()); return TOK_STRING; } if (lastChar == EOF) return TOK_EOF; if (lastChar == '/') { lastChar = nextChar(); if (lastChar == '/') { while (lastChar != EOF && lastChar != '\n' && lastChar != '\r') lastChar = nextChar(); printf("Comment ignored\n"); if (lastChar != EOF) return getNextToken(); } } if (lastChar == EOF) return TOK_EOF; char tok = lastChar; lastChar = nextChar(); printf("Unknown Character: %c\n", tok); return lastChar; } char Lexer::nextChar() { return getc(file); } int main(int argc, char* argv[]) { Lexer lexer(argv[1]); while (lexer.getNextToken() != TOK_EOF); }
true
00bda0ed3c3d5cf2af3f7ae3992e480ecf54c9c7
C++
viragkiss/CS
/Data Structures/Assignment 1/CStudent.hpp
UTF-8
1,155
3
3
[]
no_license
#ifndef CStudent_hpp #define CStudent_hpp #include <iostream> #include <cstdlib> using namespace std ; #include <string> #include <stdio.h> #include "CCourse.hpp" class CCourse; class CStudent { private: // --- add attributes here char* name; int id; int maxCourses; int maxExams; int nbCourses; CCourse** courses; int **grades; public: //Memory management methods // --- constr, desctructor add Memory management methods here CStudent(); CStudent(char* vname, int vid) ; ~CStudent() ; friend ostream& operator<<(ostream &o, const CStudent &s); friend class CCourse; friend class CDept; public: // --- add getters and setters here int getNbCourses(); public: // --- add grades methods here void setCourseGrades(int courseIndex, int* scores); void setExamGrade(int courseIndex, int examIndex, int score); void printGrades(); public: // --- add other methods here bool enroll(CCourse* c); int isEnrolled(CCourse* c); void displayInfo(); void displayCourses(); int* calcAverages(); int calcAverage(CCourse* c); } ; #endif
true
3d630f7f2d5a4de81b522d472c26919cecdca3ce
C++
redmonjp/ac_procedure
/headers/mce_setup.hpp
UTF-8
10,904
3.328125
3
[]
no_license
#ifndef mce_setup_h #define mce_setup_h #include "bk.hpp" #include <cstdlib> #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <set> using namespace std; /************************************************************** Function: read_file Description: This function is used to read in a user provided file that will be passed in argv[1]. The function expects the file to be laid out in a manner that the first line is the number of vertices in graph and every line after that is an edge in the graph. The function reads the given file in, line by line, and then pushes each line onto the pairs vector. The first element of the vector is popped off and used to create the size of the membership_array. From that point each edge in pairs vector is manipulated and packed into the correct data structures Dictionary of Variables: membership_array- type: vector <vector <bool> > Description: input to function, contains the matrix representation of the graph description file - ie what edges are valid edge_vector- type: vector <vector <int> > Description:input to function, contains each edge that is descibed in the graph description file primal_edge_vector- type:vector< pair<int, int> > Description: input to function, contains the primal pairs of each edge in the graph description file vertices- type:vector<int> Description: input to function, contains the number of vertices i,j,k,l,z,start,x,y - type:int Description: local to function, counters in some manner num_of_vertices type:int Description: local to function, contains the int value of the number of vertices described in the graph description file num_of_tuples type:int Description: local to function, contains the int value of the number of tuples (edges) described in the graph description file pair_exists type:bool Description: local to function, tells weather the inverse of the pair exists - prevents duplicates edge- type:vector<int> Description: local to function, contains the vector of the single edge we are working with primal_edge_pair type:pair<int,int> Description: local to function, contains the single pair we are working with pairs- type:vector<string> Description: local to function, contains the vector of each edge in the file readfile(argv[1])- type:ifstream Description: local to function, used to read in the file data convert- type:stringstream Description: local to function, stringstream variable used as the buffer to convert graph_str- type:str Description: local to function, used to hold the single string that we are working with *********************************************************************/ //read in the included file and parse it into data structures void read_file(vector< vector<bool> > &membership_array, vector< vector<int> > &edge_vector, vector< pair<int, int> > &primal_edge_vector, vector<int>&vertices, int argc, const char *argv[]){ int i=0; int j=0; int k=0; int l=0; int z=0; int start=0; int x=0; int y=0; int num_of_vertices=0; int num_of_tuples=0; bool pair_exists = false; set<int>set_of_edge; vector<int>edge; pair<int, int>primal_edge_pair; vector<string>pairs; ifstream read_file(argv[1]); stringstream convert; string graph_str; //check the number of arguments - if the number is not correct then let 'em know //and get out of here if (argc != 2) { cout<<"Incorrect number of arguments given to program"<<endl; exit(1); } //read the graph description file //push it back onto a vector if (read_file){ while (!read_file.eof()) { getline (read_file,graph_str); pairs.push_back(graph_str); } } else{ cout << "Couldn't open file\n"; read_file.close(); exit(1); } //get the string that represents the number of vertices //stuff it into an int convert<<pairs.at(z); convert>>num_of_vertices; convert.clear(); //cout<<endl<<"Number of vertices: "<<num_of_vertices<<endl; //Call CreateSetofVertices from bk.hpp CreateSetofVertices(num_of_vertices, vertices); //resize the array to match the number of vertices and set it all to false membership_array.resize(num_of_vertices+1, vector<bool>(num_of_vertices+1, false)); num_of_tuples = (int)pairs.size(); //as long as we still have tuples //z is the index into the vector holding tuples //increment to get the next tuple and loop until we are at the end while (true) { set_of_edge.clear(); //get the next tuple z++; i=0; //check to see if we are at the end 'z+1' to account for zero index if (z>= num_of_tuples) { break; } //take the tuple and put it into a sting to work with graph_str = pairs.at(z); //move past new lines and brackets if(graph_str.at(i) == '{') { i++; } j=i; start=i; while (graph_str.at(i) != '}') { //check to see if we are sitting on a comma if (graph_str.at(i) == ',') { i++; } //set the pointer to where we are sitting k=i; //as long as it isnt a comma or } loop while (graph_str.at(k)!=','&&graph_str.at(k)!='}') { k++; } //make a substring of the number convert<<graph_str.substr(i,k-i); convert>>x; convert.clear(); //since k was incremented to the end - bring i to k i=k; //set j to the start of the {} j=start; while (graph_str.at(j) != '}'&&graph_str.at(j) != '\n') { //reset our flag pair_exists = false; //set everything to the start of {} l=j; //move past the comma while (graph_str.at(l)!=','&&graph_str.at(l)!='}') { l++; } //make a substring of the number convert<<graph_str.substr(j,l-j); convert>>y; convert.clear(); //check to make sure these places exist if (x>num_of_vertices) { cout<<"The value "<<x<<" for x is invalid"<<endl; cout<<"Check the graph description file for errors"<<endl; exit(1); } if (y>num_of_vertices) { cout<<"The value "<<y<<" for y is invalid"<<endl; cout<<"Check the graph description file for errors"<<endl; exit(1); } //check to see if the values are the same //if they are then dont add the pair to keep out loops //else add it if (x != y) { membership_array[x][y] = true; //insert each value into the edge - if it is already there is wont show up edge.push_back(x); edge.push_back(y); //check to make sure the (x,y) and (y,x) never show up for (int q=0 ; q<primal_edge_vector.size(); q++) { if (membership_array[y][x] == true) { pair_exists = true; } } //if (y,x) is not in the membership array then put it in as an edge if (!pair_exists) { primal_edge_pair = make_pair(x, y); primal_edge_vector.push_back(primal_edge_pair); } } else if (x ==y){ edge.push_back(x); edge.push_back(y); } //since l was incremented to the end - bring j to l j=l; if (graph_str.at(j) == ',') { j++; } } } sort( edge.begin(), edge.end() ); edge.erase( unique( edge.begin(), edge.end() ), edge.end() ); //before we start the next iteration push the new edge onto the vector edge_vector.push_back(edge); //empty the edge for the next loop edge.clear(); } } //nested for loops to print the membership array void print_matrix(vector< vector<bool> > &membership_array){ cout<<endl<<"Membership Array:"; for (int i = 1; i < membership_array.size(); i++){ cout<<endl; for (int j = 1; j < membership_array.size(); j++){ cout << membership_array[i][j]<<" "; } } cout<<endl; } //nested for loops to print the hyperedges void print_edge_vector(vector< vector<int> > &edge_vector){ vector<int>::iterator it; vector<int>edge; cout<<endl<<"User Input Cliques"<<endl; //print the hyperedges we found! for (int i=0; i<edge_vector.size(); i++) { edge = edge_vector[i]; cout<<"{"; for (it=edge.begin(); it!=edge.end(); ++it){ if (it != edge.begin()){ cout << ","; } cout<<*it; } cout<<"}"<<endl; } } //nested for loops to print the primal edges of the membership array void print_primal_edge_vector(vector< pair<int, int> > &primal_edge_vector){ pair<int, int>pair; cout<<endl<<"Primal Edges:"<<endl; //print the hyperedges we found! for (int i=0; i<primal_edge_vector.size(); i++) { pair = primal_edge_vector.at(i); cout<<"{"; cout<<pair.first <<","<<pair.second; cout<<"}"<<endl; } } //nested for loops to print the hyperedges void print_maximal_cliques(vector< vector<int> > &maximal_cliques){ vector<int>::iterator it; vector<int>edge; //sort the edges! for(int i=0; i<maximal_cliques.size(); i++){ sort(maximal_cliques[i].begin(), maximal_cliques[i].end()); } sort(maximal_cliques.begin(), maximal_cliques.end()); cout<<endl<<"Maximal Cliques in Graph"<<endl; //print the hyperedges we found! for (int i=0; i<maximal_cliques.size(); i++) { edge = maximal_cliques[i]; cout<<"{"; for (it=edge.begin(); it!=edge.end(); ++it){ if (it != edge.begin()){ cout << ","; } cout<<*it; } cout<<"}"<<endl; } } //nested for loops to print the hyperedges void print_clique(vector<int> clique){ vector<int>::iterator it; cout<<"{"; for (it=clique.begin(); it!=clique.end(); ++it){ if (it != clique.begin()){ cout << ","; } cout<<*it; } cout<<"}"; } #endif /* mce_setup_h */
true
307a83ea5359ab6d95ed05a4083b531712b17da7
C++
happiie/CPlusPlus
/tuto2/tuto2 Q2/main.cpp
UTF-8
14,697
3.125
3
[]
no_license
#include <iostream> #include <cstdlib> #include <ctime> #include <windows.h> #include "Mouse.h" #include "Snake.h" using namespace std; int xSize=20,ySize=20; void printMap(char gameMap[20][20]) { for(int x=0;x<xSize;x++) { cout<<"+---"; // Top line } cout<<"+"<<endl; // Final plus for(int y=0;y<ySize;y++) { for(int x=0;x<xSize;x++) { cout<<"| "<<gameMap[y][x]<<" "; // Places array inside grid } cout<<"|"<<endl; for(int x=0;x<xSize;x++) { cout<<"+---"; // Draws last lines } cout<<"+"<<endl; // Final plus } } int main() { //random the program on every runtime srand(time(0)); //initiate all map to - char gameMap[20][20]; for(int i=0;i<20;i++) { for(int j=0;j<20;j++) { gameMap[i][j]='-'; } } //declare array of class of snake and mouse Snake snake[1000]; Mouse mouse[2000]; //array to store place of snake and mouse int syPlace[1000]; int sxPlace[1000]; int myPlace[2000]; int mxPlace[2000]; //initiate original number of snake and mouse int s=10; int m=50; int ssurvive=10; int msurvive=50; //to check whether snake or mouse has success to breed int soriginal=0; int sbreed=0; int moriginal=0; int mbreed=0; //initiate snake and mouse place for(int i=0;i<s;i++) { syPlace[i]=rand()%20; sxPlace[i]=rand()%20; while(gameMap[syPlace[i]][sxPlace[i]]!='-') { syPlace[i]=rand()%20; sxPlace[i]=rand()%20; } gameMap[syPlace[i]][sxPlace[i]]='X'; } for(int j=0;j<m;j++) { myPlace[j]=rand()%20; mxPlace[j]=rand()%20; while(gameMap[myPlace[j]][mxPlace[j]]!='-') { myPlace[j]=rand()%20; mxPlace[j]=rand()%20; } gameMap[myPlace[j]][mxPlace[j]]='O'; } printMap(gameMap); cout<<"Initial MAP"<<endl; cout<<"Time Step: 0"<<endl; cout<<"Snake survive: "<<ssurvive<<endl; cout<<"Mouse survive: "<<msurvive<<endl; cout<<endl; cout<<"Press ENTER to move"<<endl; system("PAUSE"); system("CLS"); //start of the game, time step = 20 for(int z=0;z<20;z++) { //check number of breed of both snake and mouse if(sbreed!=soriginal) { s=s+sbreed; sbreed=soriginal; } if(mbreed!=moriginal) { m=m+mbreed; mbreed=moriginal; } //part of snake for(int i=0;i<s;i++) { if(snake[i].getSurvive()==true) { int newy,newx; int moves; int test; int randomCall=rand()%8+1; if(randomCall==1) test=snake[i].checkMouse1(gameMap,syPlace[i],sxPlace[i]); else if(randomCall==2) test=snake[i].checkMouse2(gameMap,syPlace[i],sxPlace[i]); else if(randomCall==3) test=snake[i].checkMouse3(gameMap,syPlace[i],sxPlace[i]); else if(randomCall==4) test=snake[i].checkMouse4(gameMap,syPlace[i],sxPlace[i]); else if(randomCall==5) test=snake[i].checkMouse5(gameMap,syPlace[i],sxPlace[i]); else if(randomCall==6) test=snake[i].checkMouse6(gameMap,syPlace[i],sxPlace[i]); else if(randomCall==7) test=snake[i].checkMouse7(gameMap,syPlace[i],sxPlace[i]); else test=snake[i].checkMouse8(gameMap,syPlace[i],sxPlace[i]); if(test==0) { snake[i].send(rand()%4+1); moves=snake[i].get(); } else moves=test; if(moves==1) { newy=syPlace[i]; newx=sxPlace[i]-1; } else if(moves==2) { newy=syPlace[i]-1; newx=sxPlace[i]; } else if(moves==3) { newy=syPlace[i]; newx=sxPlace[i]+1; } else { newy=syPlace[i]+1; newx=sxPlace[i]; } while(gameMap[newy][newx]=='X'||newy<0||newx<0||newy>=20||newx>=20) { snake[i].send(rand()%4+1); moves=snake[i].get(); if(moves==1) { newy=syPlace[i]; newx=sxPlace[i]-1; } else if(moves==2) { newy=syPlace[i]-1; newx=sxPlace[i]; } else if(moves==3) { newy=syPlace[i]; newx=sxPlace[i]+1; } else { newy=syPlace[i]+1; newx=sxPlace[i]; } if(snake[i].checkAll()==true) break; } if(snake[i].checkAll()!=true) { gameMap[syPlace[i]][sxPlace[i]]='-'; syPlace[i]=newy; sxPlace[i]=newx; if(gameMap[syPlace[i]][sxPlace[i]]=='O') snake[i].setZeroStarve(); else snake[i].setStarve(); gameMap[syPlace[i]][sxPlace[i]]='X'; } else gameMap[syPlace[i]][sxPlace[i]]='X'; snake[i].reset(); if(snake[i].getStarve()==3) { snake[i].die(); gameMap[syPlace[i]][sxPlace[i]]='-'; } snake[i].setBreed(); if(snake[i].getBreed()==5) { int newplace; snake[i].send(rand()%4+1); newplace=snake[i].get(); if(newplace==1) { syPlace[s+sbreed]=syPlace[i]; sxPlace[s+sbreed]=sxPlace[i]-1; } else if(newplace==2) { syPlace[s+sbreed]=syPlace[i]-1; sxPlace[s+sbreed]=sxPlace[i]; } else if(newplace==3) { syPlace[s+sbreed]=syPlace[i]; sxPlace[s+sbreed]=sxPlace[i]+1; } else { syPlace[s+sbreed]=syPlace[i]+1; sxPlace[s+sbreed]=sxPlace[i]; } while(gameMap[syPlace[s+sbreed]][sxPlace[s+sbreed]]!='-') { snake[i].send(rand()%4+1); newplace=snake[i].get(); if(newplace==1) { syPlace[s+sbreed]=syPlace[i]; sxPlace[s+sbreed]=sxPlace[i]-1; } else if(newplace==2) { syPlace[s+sbreed]=syPlace[i]-1; sxPlace[s+sbreed]=sxPlace[i]; } else if(newplace==3) { syPlace[s+sbreed]=syPlace[i]; sxPlace[s+sbreed]=sxPlace[i]+1; } else { syPlace[s+sbreed]=syPlace[i]+1; sxPlace[s+sbreed]=sxPlace[i]; } if(snake[i].checkAll()==true) break; } if(snake[i].checkAll()!=true) { sbreed++; gameMap[syPlace[s+sbreed]][sxPlace[s+sbreed]]='X'; } snake[i].reset(); if(syPlace[s+sbreed]>=20||sxPlace[s+sbreed]>=20) snake[s+sbreed].die(); } } } //part of mouse for(int j=0;j<m;j++) { if(gameMap[myPlace[j]][mxPlace[j]]=='X') mouse[j].die(); if(mouse[j].getSurvive()==true) { int newy,newx; int moves; mouse[j].send(rand()%4+1); moves=mouse[j].get(); if(moves==1) { newy=myPlace[j]; newx=mxPlace[j]-1; } else if(moves==2) { newy=myPlace[j]-1; newx=mxPlace[j]; } else if(moves==3) { newy=myPlace[j]; newx=mxPlace[j]+1; } else { newy=myPlace[j]+1; newx=mxPlace[j]; } while(gameMap[newy][newx]!='-'||newy<0||newx<0||newy>=20||newx>=20) { mouse[j].send(rand()%4+1); moves=mouse[j].get(); if(moves==1) { newy=myPlace[j]; newx=mxPlace[j]-1; } else if(moves==2) { newy=myPlace[j]-1; newx=mxPlace[j]; } else if(moves==3) { newy=myPlace[j]; newx=mxPlace[j]+1; } else { newy=myPlace[j]+1; newx=mxPlace[j]; } if(mouse[j].checkAll()==true) break; } if(mouse[j].checkAll()!=true) { gameMap[myPlace[j]][mxPlace[j]]='-'; myPlace[j]=newy; mxPlace[j]=newx; gameMap[myPlace[j]][mxPlace[j]]='O'; } else gameMap[myPlace[j]][mxPlace[j]]='O'; mouse[j].reset(); mouse[j].setBreed(); if(mouse[j].getBreed()==2) { int newplace; mouse[j].send(rand()%4+1); newplace=mouse[j].get(); if(newplace==1) { myPlace[m+mbreed]=myPlace[j]; mxPlace[m+mbreed]=mxPlace[j]-1; } else if(newplace==2) { myPlace[m+mbreed]=myPlace[j]-1; mxPlace[m+mbreed]=mxPlace[j]; } else if(newplace==3) { myPlace[m+mbreed]=myPlace[j]; mxPlace[m+mbreed]=mxPlace[j]+1; } else { myPlace[m+mbreed]=myPlace[j]+1; mxPlace[m+mbreed]=mxPlace[j]; } while(gameMap[myPlace[m+mbreed]][mxPlace[m+mbreed]]!='-') { mouse[j].send(rand()%4+1); newplace=mouse[j].get(); if(newplace==1) { myPlace[m+mbreed]=myPlace[j]; mxPlace[m+mbreed]=mxPlace[j]-1; } else if(newplace==2) { myPlace[m+mbreed]=myPlace[j]-1; mxPlace[m+mbreed]=mxPlace[j]; } else if(newplace==3) { myPlace[m+mbreed]=myPlace[j]; mxPlace[m+mbreed]=mxPlace[j]+1; } else { myPlace[m+mbreed]=myPlace[j]+1; mxPlace[m+mbreed]=mxPlace[j]; } if(mouse[j].checkAll()==true) break; } if(mouse[j].checkAll()!=true) { mbreed++; gameMap[myPlace[m+mbreed]][mxPlace[m+mbreed]]='O'; } mouse[j].reset(); if(myPlace[m+mbreed]>=20||mxPlace[m+mbreed]>=20) mouse[m+mbreed].die(); } } } //1 time step end printMap(gameMap); ssurvive=0; msurvive=0; for(int y=0;y<ySize;y++) { for(int x=0;x<xSize;x++) { if(gameMap[y][x]=='X') ssurvive++; if(gameMap[y][x]=='O') msurvive++; } } cout<<"Time Step: "<<z+1<<endl; cout<<"Snake survive: "<<ssurvive<<endl; cout<<"Mouse survive: "<<msurvive<<endl; cout<<endl; cout<<"Press ENTER to move"<<endl; system("PAUSE"); system("CLS"); } //20 time steps end cout<<"Game End"<<endl; string winner; if(ssurvive>msurvive) winner="Snake"; else winner="Mouse"; cout<<winner<<" WIN"<<endl; return 0; }
true
644e96df517ec664247756d0597f9ab34b383982
C++
potatolylc/SmartHomeArduinoTemplates
/Sensors/TiltSensor/TiltSensor.ino
UTF-8
737
3.28125
3
[]
no_license
/* This code is for detecting whether a tilt signal is catched. If the signal is catched, then led is on. */ int ledPin = 13; // Connect LED to pin 13 int switcher = 3; // Connect Tilt sensor to Pin3 void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); // Set digital pin 13 to output mode pinMode(switcher, INPUT); // Set digital pin 3 to input mode } void loop() { Serial.println(digitalRead(switcher)); if(digitalRead(switcher)==HIGH) //Read sensor value { digitalWrite(ledPin, HIGH); // Turn on LED when the sensor is tilted } else { digitalWrite(ledPin, LOW); // Turn off LED when the sensor is not triggered } }
true
3b4897b41a99c830e3b52cc7024d78e4a04de8e9
C++
cowlicks/library-mathematics
/include/Library/Mathematics/Geometry/3D/Objects/Plane.hpp
UTF-8
14,636
2.796875
3
[ "MPL-2.0", "BSL-1.0", "Apache-2.0" ]
permissive
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @project Library/Mathematics /// @file Library/Mathematics/Geometry/3D/Objects/Plane.hpp /// @author Lucas Brémond <lucas@loftorbital.com> /// @license Apache License 2.0 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __Library_Mathematics_Geometry_3D_Objects_Plane__ #define __Library_Mathematics_Geometry_3D_Objects_Plane__ #include <Library/Mathematics/Geometry/3D/Objects/Segment.hpp> #include <Library/Mathematics/Geometry/3D/Objects/Ray.hpp> #include <Library/Mathematics/Geometry/3D/Objects/Line.hpp> #include <Library/Mathematics/Geometry/3D/Objects/PointSet.hpp> #include <Library/Mathematics/Geometry/3D/Objects/Point.hpp> #include <Library/Mathematics/Geometry/3D/Object.hpp> #include <Library/Mathematics/Objects/Vector.hpp> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace library { namespace math { namespace geom { namespace d3 { namespace objects { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using library::math::obj::Vector3d ; using library::math::geom::d3::Object ; using library::math::geom::d3::objects::Point ; using library::math::geom::d3::objects::PointSet ; using library::math::geom::d3::objects::Line ; using library::math::geom::d3::objects::Ray ; using library::math::geom::d3::objects::Segment ; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Plane /// /// A plane is a flat, two-dimensional surface that extends infinitely far. /// /// @ref https://en.wikipedia.org/wiki/Plane_(geometry) class Plane : public Object { public: /// @brief Constructor /// /// @code /// Plane plane({ 0.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0 }) ; /// @endcode /// /// @param [in] aPoint A point /// @param [in] aNormalVector A normal vector Plane ( const Point& aPoint, const Vector3d& aNormalVector ) ; /// @brief Clone plane /// /// @return Pointer to cloned plane virtual Plane* clone ( ) const override ; /// @brief Equal to operator /// /// @code /// Plane({ 0.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0 }) == Plane({ 0.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0 }) ; // True /// @endcode /// /// @param [in] aPlane A plane /// @return True if planes are equal bool operator == ( const Plane& aPlane ) const ; /// @brief Not equal to operator /// /// @code /// Plane({ 0.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0 }) != Plane({ 0.0, 0.0, 1.0 }, { 0.0, 0.0, 1.0 }) ; // True /// @endcode /// /// @param [in] aPlane A plane /// @return True if planes are not equal bool operator != ( const Plane& aPlane ) const ; /// @brief Check if plane is defined /// /// @code /// Plane({ 0.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0 }).isDefined() ; // True /// @endcode /// /// @return True if plane is defined virtual bool isDefined ( ) const override ; /// @brief Check if plane intersects point /// /// @code /// Plane plane = ... ; /// Point point = ... ; /// plane.intersects(point) ; /// @endcode /// /// @param [in] aPoint A point /// @return True if plane intersects point bool intersects ( const Point& aPoint ) const ; /// @brief Check if plane intersects point set /// /// @code /// Plane plane = ... ; /// PointSet pointSet = ... ; /// plane.intersects(pointSet) ; /// @endcode /// /// @param [in] aPointSet A point set /// @return True if plane intersects point set bool intersects ( const PointSet& aPointSet ) const ; /// @brief Check if plane intersects line /// /// @code /// Plane plane = ... ; /// Line line = ... ; /// plane.intersects(line) ; /// @endcode /// /// @param [in] aLine A line /// @return True if plane intersects line bool intersects ( const Line& aLine ) const ; /// @brief Check if plane intersects ray /// /// @code /// Plane plane = ... ; /// Ray ray = ... ; /// plane.intersects(ray) ; /// @endcode /// /// @param [in] aRay A ray /// @return True if plane intersects ray bool intersects ( const Ray& aRay ) const ; /// @brief Check if plane intersects segment /// /// @code /// Plane plane = ... ; /// Segment segment = ... ; /// plane.intersects(segment) ; /// @endcode /// /// @param [in] aSegment A segment /// @return True if plane intersects segment bool intersects ( const Segment& aSegment ) const ; /// @brief Check if plane contains point /// /// @code /// Plane plane = ... ; /// Point point = ... ; /// plane.contains(point) ; /// @endcode /// /// @param [in] aPoint A point /// @return True if plane contains point bool contains ( const Point& aPoint ) const ; /// @brief Check if plane contains point set /// /// @code /// Point plane = ... ; /// PointSet pointSet = ... ; /// plane.contains(pointSet) ; /// @endcode /// /// @param [in] aPointSet A point set /// @return True if plane contains point set bool contains ( const PointSet& aPointSet ) const ; /// @brief Check if plane contains line /// /// @code /// Point plane = ... ; /// Line line = ... ; /// plane.contains(line) ; /// @endcode /// /// @param [in] aLine A line /// @return True if plane contains line bool contains ( const Line& aLine ) const ; /// @brief Check if plane contains ray /// /// @code /// Point plane = ... ; /// Ray ray = ... ; /// plane.contains(ray) ; /// @endcode /// /// @param [in] aRay A ray /// @return True if plane contains ray bool contains ( const Ray& aRay ) const ; /// @brief Check if plane contains segment /// /// @code /// Point plane = ... ; /// Segment segment = ... ; /// plane.contains(segment) ; /// @endcode /// /// @param [in] aSegment A segment /// @return True if plane contains segment bool contains ( const Segment& aSegment ) const ; /// @brief Get plane point /// /// @code /// Plane({ 0.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0 }).getPoint() ; // [0.0, 0.0, 0.0] /// @endcode /// /// @return Plane point Point getPoint ( ) const ; /// @brief Get plane normal vector /// /// @code /// Plane({ 0.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0 }).getNormalVector() ; // [0.0, 0.0, 1.0] /// @endcode /// /// @return Plane normal vector Vector3d getNormalVector ( ) const ; /// @brief Compute intersection of plane with point /// /// @param [in] aPoint A point /// @return Intersection of plane with point Intersection intersectionWith ( const Point& aPoint ) const ; /// @brief Compute intersection of plane with point set /// /// @param [in] aPointSet A point set /// @return Intersection of plane with point set Intersection intersectionWith ( const PointSet& aPointSet ) const ; /// @brief Compute intersection of plane with line /// /// @param [in] aLine A line /// @return Intersection of plane with line Intersection intersectionWith ( const Line& aLine ) const ; /// @brief Compute intersection of plane with ray /// /// @param [in] aRay A ray /// @return Intersection of plane with ray Intersection intersectionWith ( const Ray& aRay ) const ; /// @brief Compute intersection of plane with segment /// /// @param [in] aSegment A segment /// @return Intersection of plane with segment Intersection intersectionWith ( const Segment& aSegment ) const ; /// @brief Print plane /// /// @param [in] anOutputStream An output stream /// @param [in] (optional) displayDecorators If true, display decorators virtual void print ( std::ostream& anOutputStream, bool displayDecorators = true ) const override ; /// @brief Apply transformation to plane /// /// @param [in] aTransformation A transformation virtual void applyTransformation ( const Transformation& aTransformation ) override ; /// @brief Constructs an undefined plane /// /// @code /// Plane plane = Plane::Undefined() ; // Undefined /// @endcode /// /// @return Undefined plane static Plane Undefined ( ) ; private: Point point_ ; Vector3d normal_ ; } ; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } } } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
true
293bd841348d3c648906c322af8edb63165982e9
C++
Asoelter/wui
/wui/containers/signal.h
UTF-8
953
2.875
3
[]
no_license
#ifndef SIGNAL_H #define SIGNAL_H #include <functional> #include <utility> #include <vector> #include "typelist.h" #include "slot.h" template<typename ...Args> class Signal { public: Signal() = default; void connect(const std::function<void(Args...)>& func); void connect(const Slot<Args...>& slot); void connect(Slot<Args...>&& slot); void disconnect(const Slot<Args...>& slot); void emit(Args... args); private: std::vector<Slot<Args...>> functions_; }; //Utility functions for similarities with qt template<typename ...Args> void connect(Signal<Args...>& signal, Slot<Args...> slot) { signal.connect(std::move(slot)); } template<typename ...Args, typename ...Args2> void emit(Signal<Args...>& signal, Args2... args) { static_assert(AreSimilar<TypeList<Args...>, TypeList<Args2...>>, "Incompatible arguments passed to signal"); signal.emit(args...); } #include "signal.hpp" #endif //SIGNAL_H
true
e273123146662b51ec6742cbc2460b0c7d910da7
C++
frankhart2017/CPP-NEW-CONCEPTS
/udl/udl_1.cpp
UTF-8
554
3.40625
3
[]
no_license
// udl_1.cpp // Source: https://www.geeksforgeeks.org/user-defined-literals-cpp/ // 14th November 2019 #include <iostream> #include <iomanip> using namespace std; long double operator"" _kg(long double x) { return x * 1000; } long double operator"" _g(long double x) { return x; } long double operator"" _mg(long double x) { return x / 1000; } int main() { long double weight = 3.6_kg; cout<<weight<<endl; cout<<setprecision(8)<<(weight + 2.3_mg)<<endl; cout<<(32.3_kg / 2.0_g)<<endl; cout<<(32.3_mg * 2.0_g)<<endl; return 0; }
true
aa50b2e0334cae8d2dee008a3b37f39f9d1d60d9
C++
KrystianSarowski/AI-Games-Project1
/AI-Games-Project1/Board.h
UTF-8
5,855
3.28125
3
[]
no_license
#pragma once #include "Tile.h" #include "Piece.h" #include "MyMath.h" #include <array> #include <queue> class Board { public: /// @brief Constructor of the Board. /// /// Calls various function to create all instances of Tile and connect them with each other /// and then create the pieces for each side of the board. /// @param t_windoSize the size of the window in which the board will be placed. Board(sf::Vector2u t_windoSize); /// @brief Gets the pointer to the Tile that contains the passed in position. /// /// Tries to find and return the pointer to the Tile that contains the passed in position. /// If there is no Tile found that contains the position it returns nullptr. /// @param t_mousePos the position within the game world for which a Tile is searched. /// @return a pointer to the Tile that contains the passed in position. Tile* selectTile(sf::Vector2f t_mousePos); /// @brief Draws all the tiles on screen. /// /// Creates a fake tile circle shape that it draws in every tile position. /// It then calls the Piece::render(sf::RenderWindow& t_window) to draw itself. /// @param t_window reference to the window in which everything will be drawn. void render(sf::RenderWindow& t_window); /// @brief Gets all the pieces of the passed in PieceType in a vector. /// /// Gets all the pieces of the passed in PieceType in a vector by converting /// the PieceType to integer and indexing into m_pieces. /// @param t_type the PieceType of the pieces to return. /// @return a vector of all the pieces of the passed in PieceType. std::vector<Piece*> getPieces(PieceType t_type); /// @brief Calculates the value of advantage over the other player. /// /// Calculates the value of each Piece position of a certain PieceType /// varsus the position of the other pieces. If the number is a negative /// the opponent has an advantage otherwise the player controlling the passed /// in PieceType has an advantage. /// @param t_type the PieceType of the player for who we are checking the advantage. /// @return the value of the advantage either positive or negative. int calculateValue(PieceType t_type); /// @brief A bool for if the passed in PieceType has won. /// /// Checks if all the pieces of the passed in PieceType are in the opposing player's /// starting locations if yes that player has won then. /// @param t_type the PieceType of the player for who we are checking if the won. /// @return bool for if all the opposing PieceType tiles are occupied by the passed in PieceType. bool checkForWin(PieceType t_type); /// @brief Resets the position of all pieces in the Board to the starting positions. /// /// Sets all the pieces contained in Board to null Tile and then moves them to /// the starting tiles. void restart(); private: /// @brief Creates a grid of tiles using to triangular patterns. /// /// Creates a grid of tiles using the a pattern of two triangles. The second triangle /// is flipped upsided down and every Tile that overlapse the created tiles is deleted. /// The top 10 and bottom 10 tiles as set as the goal tiles for each PieceType. /// The starting position of each triangle is such that the pattern is centred with the passed /// in size. At the end it calls the function to connect the tiles and setup the goal costs to /// the furthest goal tiles (the very top and the very bottom). /// @param t_windowSize the size of the windown in which the gird will be centered. /// @see connectTiles(), generateDistanceCosts(std::vector<Tile*> t_furthestGoalTiles) void createGrid(sf::Vector2u t_windowSize); /// @brief Connects each tile with it's adjecant neighbours. /// /// Connects each tile within the grid with all the tiles that are with a certain deistance. /// @see createGrid(sf::Vector2u t_windowSize) void connectTiles(); /// @brief Generates the cost from each tile to each of the furthest goals. /// /// Generates the distance cost from each Tile to the each of the furthest goal /// tiles that are passed into this function. /// @param t_furthestGoalTiles a vector that contains the pointest to the furthest goal tiles. /// @see createGrid(sf::Vector2u t_windowSize) void generateDistanceCosts(std::vector<Tile*> t_furthestGoalTiles); /// @brief Creates a Piece within each of the Tile in the m_goalTiles vectors. /// /// Creates a pointer to a Piece for each Tile within the m_goalTiles vectors setting /// it PieceType by converting the index used to traves the vector. void createPieces(); /// @brief Vector of all Tile pointers that make up the Board. /// /// Vector that contains all the Tile pointers that are within the Board and /// are inter connected with one another. /// @see Tile std::vector<Tile*> m_grid; /// @brief Vector of vectors that contains pointer to each of the goal tiles. /// /// Vector of vectors that contains within each vector goal tiles for each of /// the PieceTypes. The index used to traves is the same as the index of each PieceType. /// @see Tile, PieceType std::vector<std::vector<Tile*>> m_goalTiles; /// @brief Vector of vectors that contains pointer to each of the pieces. /// /// Vector of vectors that contains within each vector pieces for each of /// the PieceTypes. The index used to traves is the same as the index of each PieceType. /// @see Tile, PieceType std::vector<std::vector<Piece*>> m_pieces; /// @brief The radius of the Tile. /// /// The radius of the Tile used for calucaltion and rendering. const float m_TILE_RADIUS{ 15.0f }; /// @brief The number of tiles within the largest row with the triangle grids. /// /// The number of tiles within the largest row with the triangle grids. This /// is only used when making of the grid. /// @see createGrid(sf::Vector2u t_windowSize) const int m_MAX_ROW_LENGTH{ 13 }; };
true
d77c259e6f29cf5d794d1362827b51c800b48648
C++
torunxxx001/BookCollectionSystem
/Hardware/src/hard/rpi_gpio.hpp
UTF-8
1,522
2.609375
3
[ "MIT" ]
permissive
/* 参考PDF[BCM2835-ARM-Peripherals.pdf] */ /* RaspberryPI用GPIO操作プログラム */ /* 対応表 PIN NAME 0 GPIO 2(SDA) 1 GPIO 3(SCL) 2 GPIO 4(GPCLK0) 3 GPIO 7(CE1) 4 GPIO 8(CE0) 5 GPIO 9(MISO) 6 GPIO 10(MOSI) 7 GPIO 11(SCLK) 8 GPIO 14(TXD) 9 GPIO 15(RXD) 10 GPIO 17 11 GPIO 18(PCM_CLK) 12 GPIO 22 13 GPIO 23 14 GPIO 24 15 GPIO 25 16 GPIO 27(PCM_DOUT) 17 GPIO 28 18 GPIO 29 19 GPIO 30 20 GPIO 31 */ #ifndef __RPI_GPIO_HPP__ #define __RPI_GPIO_HPP__ /* バスアクセス用物理アドレス(Page.6 - 1.2.3) */ #define PHADDR_OFFSET 0x20000000 /* GPIOコントロールレジスタへのオフセット(Page.90 - 6.1) */ #define GPIO_CONTROL_OFFSET (PHADDR_OFFSET + 0x200000) /* GPFSEL0からGPLEVまでのサイズ */ #define GPCONT_SIZE 0x3C /* 各レジスタへのオフセット */ #define GPFSEL_OFFSET 0x00 #define GPSET_OFFSET 0x1C #define GPCLR_OFFSET 0x28 #define GPLEV_OFFSET 0x34 /* モード定義 */ #define GPIO_INPUT 0 #define GPIO_OUTPUT 1 #define GPIO_ALT0 4 #define GPIO_ALT1 5 #define GPIO_ALT2 6 #define GPIO_ALT3 7 #define GPIO_ALT4 3 #define GPIO_ALT5 2 #define HIGH 1 #define LOW 0 extern const char* PINtoNAME[]; //GPIOコントロール用クラス class gpio { private: //GPIOマッピング用ポインタ static volatile unsigned int* gpio_control; static int instance_count; public: gpio(); ~gpio(); void mode_write(int pin, int mode); void mode_read(int pin, int* mode); void data_write(int pin, int data); void data_read(int pin, int* data); }; #endif
true
1370f360f5fa8b2fd1089509541a13bc4fc20f82
C++
wCmJ/KB
/lc/672.cc
UTF-8
2,261
3.078125
3
[]
no_license
#include <iostream> #include <unordered_set> #include <unordered_map> using namespace std; class Solution { public: static int cnt; int flipLights(int n, int m) { //first: open //int op[4]; //将m分配到4组操作中, int op[4] = {0}; string base(n + 1, '1'); std::cout<<"base is: "<<base<<std::endl; unordered_set<string> record; unordered_map<string, unordered_set<int>> finished;//memorize flipLights(base, m, record, finished); /*for(auto it = record.begin(); it != record.end();++it){ std::cout<<*it<<std::endl; }*/ return record.size(); } void flipLights(string base, int m, unordered_set<string> &record, unordered_map<string, unordered_set<int>>& finished){ ++cnt; if(m == 0){ record.insert(base); return; } if(finished.count(base) && finished[base].count(m)){//memorize return;//memorize } //op1 string op1 = base; for(int i = 1;i<op1.size();++i){ if(op1[i] == '0')op1[i] = '1'; else if(op1[i] == '1')op1[i] = '0'; } flipLights(op1, m - 1, record, finished); //op2 op1 = base; for(int i = 1;i<op1.size();i+=2){ if(op1[i] == '0')op1[i] = '1'; else if(op1[i] == '1')op1[i] = '0'; } flipLights(op1, m - 1, record, finished); //op3 op1 = base; for(int i = 2;i<op1.size();i+=2){ if(op1[i] == '0')op1[i] = '1'; else if(op1[i] == '1')op1[i] = '0'; } flipLights(op1, m - 1, record, finished); //op4 op1 = base; for(int i = 1;i<op1.size();i+=3){ if(op1[i] == '0')op1[i] = '1'; else if(op1[i] == '1')op1[i] = '0'; } flipLights(op1, m - 1, record, finished); finished[base].insert(m); } }; int Solution::cnt = 0; int main(){ Solution so; std::cout<<"so.flipLights(2,2): "<<so.flipLights(2,2)<<std::endl; std::cout<<so.cnt<<std::endl; std::cout<<"so.flipLights(4,100): "<<so.flipLights(4,100)<<std::endl; std::cout<<so.cnt<<std::endl; return 0; }
true
dbd31775d0e24810e7e5c92c3deba904ecba9b40
C++
vishalsalgond/Data-Structures-Algorithms
/Bit Manipulation/subsets.cpp
UTF-8
652
3.140625
3
[]
no_license
//https://leetcode.com/problems/subsets/ class Solution { public: vector <vector<int>> ans; void filterNums(int n, vector <int> nums) { vector <int> temp; int j = 0; while(n > 0) { int last_bit = n & 1; if(last_bit) { temp.push_back(nums[j]); } j++; n = n >> 1; } ans.push_back(temp); } vector<vector<int>> subsets(vector<int>& nums) { int n = nums.size(); for(int i = 0; i < (1 << n); i++) { filterNums(i, nums); } return ans; } };
true
042a6c6dc417bca46ba386485a02325cc2a5090f
C++
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-Fortress117
/src/examples/03_module/04_for_ranged/for_ranged.cpp
UTF-8
877
3.8125
4
[ "MIT" ]
permissive
#include "for_ranged.h" #include<iostream> #include<vector> using std::vector; /* Write code for loop_string_w_index that accepts a string parameter. The function uses an indexed for loop to iterate and display the characters in the string as follows: for string test displays t e s t */ /* Write code for loop_string_w_index that accepts a string parameter. The function uses a for ranged loop using auto to iterate and display the characters in the string as follows: for string test displays t e s t */ void loop_string_w_auto(std::string str) { //not modifiable for (auto ch : str) { ch = 'j'; std::cout << ch << "\n"; } //modifiable for (auto &ch : str) { ch = 'j'; std::cout << ch << "\n"; } } void loop_vector_w_index() { vector<int> nums = {9, 10, 99, 5,67 }; for (int i = 0; i < nums.size(); ++i) { std::cout << nums[i] << "\n"; } }
true
2cc6b20e0a63098d1f4bc844f5d0925b41ea800b
C++
dsudheerdantuluri/leetcode
/algorithms/cpp/19.cc
UTF-8
1,136
2.984375
3
[]
no_license
// lt19.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { if ((head == nullptr) || (n <= 0)) { return head; } ListNode *p_node = head; for (auto i = 1; i <= n; ++i) { if (!p_node) { return head; } p_node = p_node->next; } ListNode *p_nthNodeFromEnd = head; ListNode *p_prev = nullptr; while (p_node != nullptr) { p_node = p_node->next; p_prev = p_nthNodeFromEnd; p_nthNodeFromEnd = p_nthNodeFromEnd->next; } if (p_prev != nullptr) { p_prev->next = p_nthNodeFromEnd->next; delete p_nthNodeFromEnd; } else { ListNode *temp = head; head = head->next; delete temp; return head; } return head; } }; int main() { return 0; }
true
d7dca07b393535e15df7ce34fc5d2b5f44d9a559
C++
bg1bgst333/Sample
/designpattern/pm/pm/src/pm/model.h
UTF-8
1,037
2.59375
3
[ "MIT" ]
permissive
// 二重インクルード防止 #ifndef __MODEL_H_ #define __MODEL_H_ // 独自のヘッダ #include "subject.h" // interface_subject #include "presentation_model.h" // class_presentation_model // 前方宣言 class class_presentation_model; // クラスclass_model class class_model : public interface_subject{ // 非公開メンバ private: // 非公開メンバ変数 interface_observer *observer_; // interface_observerポインタobserver_. // 公開メンバ public: // 公開メンバ関数 // コンストラクタとデストラクタ class_model(){}; // コンストラクタclass_model virtual ~class_model(){}; // デストラクタ~class_model // メンバ関数 void func(); // メンバ関数func virtual void set_observer(interface_observer *observer); // メンバ関数set_observer virtual void notify(); // メンバ関数notify void set_presentation_model(class_presentation_model *presentation_model); // メンバ関数set_presentation_model }; #endif
true
3185d1428d3527ca2de3b65266fb65c4ef6836d7
C++
apache/impala
/be/src/util/cache/cache-test.h
UTF-8
3,915
2.734375
3
[ "Apache-2.0", "OpenSSL", "bzip2-1.0.6", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "LicenseRef-scancode-google-patent-license-webrtc", "PSF-2.0", "BSD-3-Clause", "dtoa", "MIT", "LicenseRef-scancode-mit-modification-obligations", "Minpack", "BSL-1.0", "LicenseRef-s...
permissive
// Some portions Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "util/cache/cache.h" #include <memory> #include <string> #include <vector> #include <gtest/gtest.h> #include "kudu/util/coding.h" #include "kudu/util/faststring.h" #include "kudu/util/mem_tracker.h" #include "kudu/util/slice.h" namespace impala { // Conversions between numeric keys/values and the types expected by Cache. static std::string EncodeInt(int k) { kudu::faststring result; kudu::PutFixed32(&result, k); return result.ToString(); } static int DecodeInt(const Slice& k) { CHECK_EQ(4, k.size()); return kudu::DecodeFixed32(k.data()); } // Cache sharding policy affects the composition of the cache. Some test // scenarios assume cache is single-sharded to keep the logic simpler. enum class ShardingPolicy { MultiShard, SingleShard, }; // CacheBaseTest provides a base test class for testing a variety of different cache // eviction policies (LRU, LIRS, FIFO). It wraps the common functions to simplify the // calls for tests and to use integer keys and values, so that tests can avoid using // Slice types directly. It also maintains a record of all evictions that take place, // both the keys and the values. // NOTE: The structures are not synchronized, so this is only useful for single-threaded // tests. class CacheBaseTest : public ::testing::Test, public Cache::EvictionCallback { public: explicit CacheBaseTest(size_t cache_size) : cache_size_(cache_size) { } size_t cache_size() const { return cache_size_; } // Implementation of the EvictionCallback interface. This maintains a record of all // evictions, keys and values. void EvictedEntry(Slice key, Slice val) override { evicted_keys_.push_back(DecodeInt(key)); evicted_values_.push_back(DecodeInt(val)); } // Lookup the key. Return the value on success or -1 on failure. int Lookup(int key, Cache::LookupBehavior behavior = Cache::NORMAL) { auto handle(cache_->Lookup(EncodeInt(key), behavior)); return handle ? DecodeInt(cache_->Value(handle)) : -1; } // Insert a key with the give value and charge. Return whether the insert was // successful. bool Insert(int key, int value, int charge = 1) { std::string key_str = EncodeInt(key); std::string val_str = EncodeInt(value); auto handle(cache_->Allocate(key_str, val_str.size(), charge)); // This can be null if Allocate rejects something with this charge. if (handle == nullptr) return false; memcpy(cache_->MutableValue(&handle), val_str.data(), val_str.size()); auto inserted_handle(cache_->Insert(std::move(handle), this)); // Insert can fail and return nullptr if (inserted_handle == nullptr) return false; return true; } void Erase(int key) { cache_->Erase(EncodeInt(key)); } protected: // This initializes the cache with the specified 'eviction_policy' and // 'sharding_policy'. Child classes frequently call this from the SetUp() method. // For example, there are shared tests that apply to all eviction algorithms. This // function is used during SetUp() to allow those shared tests to be parameterized to // use various combinations of eviction policy and sharding policy. void SetupWithParameters(Cache::EvictionPolicy eviction_policy, ShardingPolicy sharding_policy); const size_t cache_size_; // Record of all evicted keys/values. When an entry is evicted, its key is put in // evicted_keys_ and its value is put in evicted_values_. These are inserted in // the order they are evicted (i.e. index 0 happened before index 1). std::vector<int> evicted_keys_; std::vector<int> evicted_values_; std::shared_ptr<kudu::MemTracker> mem_tracker_; std::unique_ptr<Cache> cache_; }; } // namespace impala
true
322538ca410df466d927da2d8f11e84ef1a6b3fb
C++
DevTaeho/ps
/swea/[모의 SW 역량테스트] 보물상자 비밀번호_5658.cpp
UTF-8
1,571
2.546875
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <queue> #define ll long long using namespace std; int N, K, rot; char d[4][10]; vector<string> v; deque<char> in; ll conv(string s) { ll res = 0; ll g = 1; for (int i = s.size() - 1; i >= 0; i--) { char t = s[i]; int x; if ('0' <= t && t <= '9') x = t - '0'; else { switch (t) { case 'A': x = 10; break; case 'B' : x = 11; break; case 'C' : x = 12; break; case 'D' : x = 13; break; case 'E' : x = 14; break; case 'F' : x = 15; break; default: break; } } res += g * x; g *= 16; } return res; } void rot_insert(int r) { if (r == 0) { for (int i = 0; i < 4; i++) { for (int k = 0; k < rot; k++) { d[i][k] = in[i*rot + k]; } } for (int i = 0; i < 4; i++) { v.push_back(d[i]); } } else { char b = in.back(); in.pop_back(); in.push_front(b); for (int i = 0; i < 4; i++) { for (int k = 0; k < rot; k++) { d[i][k] = in[i*rot + k]; } } for (int i = 0; i < 4; i++) { v.push_back(d[i]); } } } int main() { ios::sync_with_stdio(0); cin.tie(0); int testc; cin >> testc; for (int tc = 1; tc <= testc; tc++) { v.clear(); in.clear(); cin >> N >> K; in.resize(N); rot = N / 4; for (int i = 0; i < N; i++) { char t; cin >> in[i]; } for (int i = 0; i < rot; i++) { rot_insert(i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); reverse(v.begin(), v.end()); cout << '#' << tc << ' ' << conv(v[K-1]) << '\n'; } return 0; }
true
2d8fa09d9019e944f89ee50956e9199e8911f8d6
C++
pllefevre/seakgChrysocyonParser
/cccQt/cccVar.h
UTF-8
972
3.0625
3
[]
no_license
#ifndef __CCCVAR_H__ #define __CCCVAR_H__ #include "cccContent.h" class cccVar { public: cccVar() {}; cccVar(cccVar &var) { m_Value = var.getValue(); }; cccVar(cccContent &content) { m_Value = content; }; cccVar(const cccVar &var) { m_Value = var.getValue(); }; //cccVar(const cccContent &content) { m_Value = cccContent(content); }; cccContent getValue() const { return m_Value; }; void setValue(cccContent &content) { m_Value = content; }; void operator = (cccVar& var) { m_Value = var.getValue(); }; //void operator = (const cccVar& var) { m_Value = var.getValue(); }; //void operator = (cccContent& content) { m_Value = content; }; virtual cccVar operator + (cccVar& var) { cccContent content; content.setContent(var.getValue().getContent() + m_Value.getContent()); return cccVar(content); }; virtual void operator ++ () {}; virtual void operator - () {}; private: cccContent m_Value; }; #endif // __CCCVAR_H__
true
39e3dc5752b4f7b8a29dc3ff3f89f449fcb24042
C++
furkanyildiz/Data_Glass_Project_Bil396
/Old Versions/tick_v1/Pong/mythread.cpp
UTF-8
2,068
2.6875
3
[]
no_license
// mythread.cpp #include <QtWidgets> #include <QtCore> #include <iostream> #include<QtBluetooth> #include "mythread.h" QByteArray data1; QByteArray data2; int MyThread::gyro1 = 100; int MyThread::gyro2 = 100; MyThread::MyThread(QBluetoothSocket *socket,int id,QBluetoothSocket* secondSocket) { this->thread_id = id; this->socket = socket; this->secondSocket = secondSocket; } void MyThread::run() { qDebug() << "THREAD RUNNING";/* int a= rand()%89+10; int b= rand()%89+10; int c= rand()%890+100; int d= rand()%89+10; std::string f = std::to_string(a);*/ sleep(5); //while(1){ connect(socket, SIGNAL(readyRead()), this, SLOT(readWrite()),Qt::DirectConnection); connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()),Qt::DirectConnection); //std::cout << f.c_str() << std::endl; //socket->write(f.c_str()); //socket->write(std::to_string(a)+","+std::to_string(b)+","+std::to_string(c)+","+std::to_string(d)); //sleep(1); /* if(socket->isReadable()){ rec = socket->read(2); qDebug() << rec; rec.clear(); socket->write("1"); }*/ //} // make this thread a loop exec(); } void MyThread::readWrite() { QBluetoothSocket *socket = qobject_cast<QBluetoothSocket *>(sender()); //silincede calısıyor. if (!socket) return; while (socket->canReadLine()) { QByteArray line = socket->readLine().trimmed(); qDebug() << " This message receiving from data glass : " << this->thread_id << line; //secondSocket->write(line); if (thread_id == 1){ gyro1 = line.toInt(); infos.gyro = gyro2; } if (thread_id == 2){ gyro2 = line.toInt(); infos.gyro = gyro1; } infos.topx = 32; infos.topy = 64; socket->write(infos); } // QByteArray text = message.toUtf8() + '\n'; // string to Qbyte array } void MyThread::disconnected() { }
true
b2a097157fef9c736c50a6feb00a0228ffc55e30
C++
GabeOchieng/ggnn.tensorflow
/program_data/PKU_raw/40/2787.c
UTF-8
489
2.625
3
[]
no_license
double mianji(double a,double b,double c,double d,double jiao) { double result,hu,s,panduan; hu=jiao/180*PI/2; s=(a+b+c+d)/2; panduan=(s-a)*(s-b)*(s-c)*(s-d)-a*b*c*d*cos(hu)*cos(hu); if(panduan<0) result=-1; else result=sqrt(panduan); return result; } int main() { double a,b,c,d,jiao,shuchu; scanf("%lf%lf%lf%lf%lf",&a,&b,&c,&d,&jiao); shuchu=mianji(a,b,c,d,jiao); if(shuchu==-1) printf("Invalid input"); else printf("%.4lf",shuchu); return 0; }
true
06ae77f72e59d623cf7959bf91a4cfec20db2524
C++
walchko/ParticleFilter
/src/logReader.cpp
UTF-8
1,556
2.75
3
[]
no_license
#include <particleFilter.h> #include <fstream> #include <sstream> #include <vector> #include <string> using namespace std; vector<string>& split(const string &s, char delim, vector<string> &elems) { stringstream ss(s); string item; while (getline(ss, item, delim)) { elems.push_back(item); } return elems; } vector<string> split(const string &s, char delim) { vector<string> elems; split(s, delim, elems); return elems; } void ParticleFilter::readLog() { string line; ifstream myfile (logName); if (myfile.is_open()) { while ( getline (myfile,line) ) { vector<string> elements = split(line, ' '); if (elements[0] == "O") { OdometryData odom; odom.x = stof(elements[1]); odom.y = stof(elements[2]); odom.theta = stof(elements[3]); odom.ts = stof(elements[4]); logOdometryData.push_back(odom); } else if (elements[0] == "L"){ LaserData laser; laser.x = stof(elements[1]); laser.y = stof(elements[2]); laser.theta = stof(elements[3]); laser.xl = stof(elements[4]); laser.yl = stof(elements[5]); laser.thetal = stof(elements[6]); laser.ts = stof(elements[187]); for (int i = 0; i < 180; i ++){ laser.r[i] = stoi(elements[i+7]); } logLaserData.push_back(laser); timestamps.push_back(laser.ts); } } myfile.close(); } else cout << "Unable to open file " << logName << "\n"; return; };
true
d1399fd5977bb83c7ef6bbd85ee535f55f07ef84
C++
Sanchita99/Computer_Networks_Programs
/stop_wait_ARQ.cpp
UTF-8
735
2.984375
3
[]
no_license
#include<stdio.h> #include<stdlib.h> int recieve(int f, long long int n) { int rack,rf=0,j=0,rd[n]; rack=rand()%2; //printf("%d \n",rack); if(rack!=f) { rf=f; rd[j]=f; j++; printf("\trecieve \t%d\n",f); return rack; } else { printf("drop as rack is %d\n",rack); return rack; } } int send(int d[], long long int n) { int i; int ack; for(i=0;i<n;i++) { ack=recieve(d[i],n); if(ack==d[i]) { i--; continue; } } } int main() { long long int n; printf("Enter number of data bits\n"); scanf("%lld",&n); int i,d[n]; printf("Enter data\n"); for(i=0;i<n;i++) { scanf("%d",&d[i]); } send(d,n); }
true
a3f06eeefc6f70ac4c04e5895f6e347a27e3c119
C++
RedCaplan/Cplusplus
/Games/MegaSuperUltraEpicIncredibleUnbelievable__Game/MegaSuperUltraEpicIncredibleUnbelievable__Game/Player.h
UTF-8
633
2.796875
3
[]
no_license
#pragma once #include <iostream> #include <windows.h> using namespace std; class Player { int PosX; int PosY; char sign = '@'; short color1=3; short color2=15; public: Player ( ); Player (int x , int y) :PosX (x) , PosY (y){} void DrawPlayer (); COORD GetCord ( ) { COORD x = { PosX , PosY }; return x; } void SetColor2 (int _color2){ color2 = _color2; } void SetColor1 (int _color1){ color1 = _color1; } int GetColor1 ( ){ return color1; } void SetSign (char _sign){ sign = _sign; } void SetCord (int x , int y){ PosX = x; PosY = y; } char GetHeroSign ( ){ return sign; } ~Player ( ); };
true
ebc7ad268a8cbbc82e36e67a0d50be2e5b706744
C++
biprodas/OJ-Solutions
/UVa/10035 - Primary Arithmetic.cpp
UTF-8
524
2.828125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int call(int a, int b, int c){ if(a==0 && b==0) return 0; //base case (a%10 + b%10 + c)>9 ? c=1 : c=0; return c+call(a/10, b/10,c); } int main(){ //freopen("in.txt","r",stdin); int a, b; while(scanf("%d%d",&a,&b)==2){ if(a==0 && b==0) break; int res= call(a,b,0); if(res==0) cout<<"No carry operation.\n"; else if(res==1) cout<<"1 carry operation.\n"; else cout<<res<<" carry operations.\n"; } return 0; }
true
48a524c2a9b904e0be3ebad9df3a8a218fb81405
C++
diegoMontesinos/sutcliffeFractal
/src/ofApp.cpp
UTF-8
5,885
2.640625
3
[]
no_license
/* * Implementation of the SutcliffeFractal app with oF. * * Diego Montesinos (diegoa.montesinos at gmail.com) * January, 2015 * * Modificación para pintarlo con ofVboMesh por xumo */ #include "ofApp.h" #include <math.h> void ofApp::setup () { // Set the sides and the radius nSides = 5; radius = 300.0; // Set weight, the factor scale and depth weight = 0.5; fScale = 0.35; depth = 4; // Generate the polygon base generateBasePolygon(); // Set the of params ofSetVerticalSync(true); ofNoFill(); ofSetHexColor(0x000000); ofBackgroundHex(0xffffff); ofEnableAntiAliasing(); // Set the GUI sidesCtrl.addListener(this, &ofApp::sidesChanged); radiusCtrl.addListener(this, &ofApp::radiusChanged); gui.setup(); gui.add(sidesCtrl.setup("Polygon sides", 5, 3, 10)); gui.add(radiusCtrl.setup("Polygon radius", 300.0, 200.0, 500.0)); gui.add(weightCtrl.setup("Middle proportion", 0.5, 0.0, 1.0)); gui.add(fScaleCtrl.setup("Factor scale", 0.35, 0.1, 0.5)); gui.add(depthCtrl.setup("Recursion depth", 4, 1, 6)); gui.add(constantLW.setup("Constant lineWidth", true)); gui.add(invertColors.setup("Invert colors", false)); //Pone el Mesh en modo de pintar lineas. mesh.setMode(OF_PRIMITIVE_LINES); /* Estos son los tipos de pintado que se pueden OF_PRIMITIVE_TRIANGLES, OF_PRIMITIVE_TRIANGLE_STRIP, OF_PRIMITIVE_TRIANGLE_FAN, OF_PRIMITIVE_LINES, OF_PRIMITIVE_LINE_STRIP, OF_PRIMITIVE_LINE_LOOP, OF_PRIMITIVE_POINTS */ } void ofApp::update () { // Get the vars from the gui if(weight != weightCtrl || fScale != fScaleCtrl || depth != depthCtrl) { //regenerar la malla si cambia algún parámetro generateBasePolygon(); } weight = weightCtrl; fScale = fScaleCtrl; depth = depthCtrl; if(invertColors) { ofBackgroundHex(0x000000); ofSetHexColor(0xffffff); } else { ofBackgroundHex(0xffffff); ofSetHexColor(0x000000); } } void ofApp::draw () { // Draw the GUI if(!hGui) { gui.draw(); } // Get the center and render sutcliffe fractal //sutcliffe(basePolygon, center, depth); //Pintar malla en wireframe paraq ue se vean la lineas mesh.drawWireframe(); } void ofApp::keyPressed(int key) { if(key == 'h') { hGui = !hGui; } if(key == 's') { ofSaveFrame(); } } void ofApp::sidesChanged(int & newSides) { nSides = newSides; generateBasePolygon(); } void ofApp::radiusChanged(float & newRadius) { radius = newRadius; generateBasePolygon(); } void ofApp::generateBasePolygon () { // Clear the base polygon basePolygon.clear(); // Calc the angle amount float angleAmt = (2.0 * M_PI) / ((float) nSides); // Set the angle float angle = 0.0; while ( angle <= (2.0 * M_PI) ) { // Create a point float x = (cos(angle) * radius) + (ofGetWidth() / 2.0); float y = (sin(angle) * radius) + (ofGetHeight() / 2.0); ofVec2f point (x, y); // Store in basePolygon.push_back(point); // Increase the angle angle += angleAmt; } //BOrrar el contenido la malla mesh.clear(); //Mandar a rehacer la mall ofVec2f center (ofGetWidth() / 2.0, ofGetHeight() / 2.0); sutcliffe(basePolygon, center, depth); } void ofApp::sutcliffe (std::vector<ofVec2f> polygon, ofVec2f center, int n) { // Get the polygon size int pSize = polygon.size(); // Set the line width if its necessary if(constantLW) { ofSetLineWidth(1.0); } else { ofSetLineWidth(ofMap(n, 0, depth, 1.1, 3.5)); } // Draw the polygon for (int i = 0; i < pSize; i++) { ofVec2f point = polygon[i]; ofVec2f nextPoint = polygon[(i + 1) % pSize]; //añadir dos vertices a la malla, el inicio y el final de la linea. //A la hora de pintar hace lo mismo pero en el GPU. OF_PRIMITIVE_LINES pinta ina linea entre vertices adjacentes, de par en par. mesh.addVertex(ofVec3f(point.x, point.y)); mesh.addVertex(ofVec3f(nextPoint.x, nextPoint.y)); //ofLine(point.x, point.y, nextPoint.x, nextPoint.y); } // If there are more steps if(n > 0) { // Firts create the inner and middle points std::vector<ofVec2f> innerPoints; std::vector<ofVec2f> middlePoints; for (int i = 0; i < pSize; i++) { // Get the point and next point ofVec2f point = polygon[i]; ofVec2f nextPoint = polygon[(i + 1) % pSize]; // Get the middle point in proportion ofVec2f middlePoint = (point * weight) + (nextPoint * (1.0 - weight)); middlePoints.push_back(middlePoint); // Get the direction vector ofVec2f direction; if(pSize == 5) { direction = polygon[(i + 3) % 5] - middlePoint; } else { direction = center - middlePoint; } // Get the radius float r = (center - middlePoint).length(); // Normalize and scale the direction direction.normalize(); direction.scale(r * fScale); // Create and store the inner point ofVec2f innerPoint = middlePoint + direction; innerPoints.push_back(innerPoint); } // Create the inner pentagons for (int i = 0; i < pSize; ++i) { std::vector<ofVec2f> pentagon; // Create a sutfliffe pentagon pentagon.push_back(middlePoints[i]); pentagon.push_back(innerPoints[i]); pentagon.push_back(innerPoints[(i + 1) % pSize]); pentagon.push_back(middlePoints[(i + 1) % pSize]); pentagon.push_back(polygon[(i + 1) % pSize]); // Call recursively with the pentagon this->sutcliffe (pentagon, calcCentroid(pentagon), n - 1); } // Call recursively with the inner points this->sutcliffe (innerPoints, center, n - 1); } } ofVec2f ofApp::calcCentroid (std::vector<ofVec2f> polygon) { // Get the sum of positions float x = 0.0, y = 0.0; for (int i = 0; i < polygon.size(); i++) { x += polygon[i].x; y += polygon[i].y; } // Get the average (centroid) x = x / (float) polygon.size(); y = y / (float) polygon.size(); ofVec2f centroid (x, y); return centroid; }
true
4bcf3c9b9c89afdf8f59085352d34f3be8ec5d5d
C++
Barney666/Coding_Interview
/src/Leetcode/Exercise815.cpp
UTF-8
1,858
3.34375
3
[]
no_license
#include <vector> #include <unordered_map> #include <queue> #include <algorithm> #include <iostream> using namespace std; class Solution { public: int numBusesToDestination(vector<vector<int>>& routes, int source, int target) { if(source == target) return 0; int bus_num = routes.size(); vector<bool> bus_used(bus_num, false); // 记录用过的公交车 unordered_map<int, vector<int>> station_by_bus; // 记录每个站点都有哪些公交车可到达 queue<int> accessible_station; // BFS记录现在可以到达的站点 accessible_station.push(source); int result = 1; // 最小是1,已经把source加到queue中了 for(int i = 0; i < bus_num; i++) for(int station: routes[i]) station_by_bus[station].push_back(i); while (!accessible_station.empty()){ for(int i = accessible_station.size(); i > 0; i--){ // 这样可以不用因为里面会把queue的长度增加,而单独定义一个变量记录长度 int station = accessible_station.front(); accessible_station.pop(); for(auto bus: station_by_bus[station]){ // 这里是关键思想,先根据站点会有哪些公交车,再到routes中看这个公交车还能去哪 if(!bus_used[bus]){ bus_used[bus] = true; for(int next_station: routes[bus]){ if(next_station == target) return result; else accessible_station.push(next_station); } } } } result++; // 一轮完事 } return -1; } };
true
d08a415c9f949858669252a069d383d9d422f7e0
C++
mtao/core
/include/mtao/geometry/mesh/triangle/mesh.h
UTF-8
2,921
2.578125
3
[ "MIT" ]
permissive
#pragma once #include <mtao/types.hpp> #include <numeric> #include <optional> namespace mtao::geometry::mesh::triangle { #ifdef SINGLE using REAL = float; #else /* not SINGLE */ using REAL = double; #endif /* not SINGLE */ struct Mesh { Mesh() = default; Mesh(Mesh&&) = default; Mesh(const Mesh&) = default; Mesh(const mtao::ColVectors<REAL,2> V, const mtao::ColVectors<int,2> E = mtao::ColVectors<int,2>(), const mtao::ColVectors<int,3> F = mtao::ColVectors<int,3>()); Mesh(const std::tuple<mtao::ColVectors<REAL,2> ,mtao::ColVectors<int,2>>& VE); Mesh& operator=(const Mesh& other) = default; Mesh& operator=(Mesh&& other) = default; void fill_attributes(); mtao::ColVectors<REAL,2> V;//vertices mtao::ColVectors<int,2> E;//edges mtao::VectorX<int> VA;//vertex markers mtao::VectorX<int> EA;//edge markers mtao::ColVectors<int,3> F;//faces mtao::ColVectors<REAL,2> H;//Point in a hole std::optional<mtao::ColVectors<REAL,2>> C;//circumcenters mtao::VectorX<bool> verify_delauney() const; void translate(const mtao::Vector<REAL,2>&); void scale(const mtao::Vector<REAL,2>&); void make_circumcenters(); }; Mesh combine(const std::vector<Mesh>& components); template <typename T, typename FuncType> std::tuple<T, std::vector<int>> vector_hstack(const std::vector<Mesh>& data, const FuncType& accessor) { std::vector<int> sizes; std::transform(data.begin(),data.end(), std::back_inserter(sizes), [&](const Mesh& m) -> int{ return accessor(m).cols(); }); std::vector<int> offsets(1,0); std::partial_sum(sizes.begin(),sizes.end(), std::back_inserter(offsets)); T H(accessor(data[0]).rows(),offsets.back()); for(size_t i = 0; i < data.size(); ++i) { auto&& h = accessor(data[i]); H.block(0,offsets[i],h.rows(),h.cols()) = h; } return {H,offsets}; } template <typename T, typename FuncType> std::tuple<T, std::vector<int>> vector_vstack(const std::vector<Mesh>& data, const FuncType& accessor) { std::vector<int> sizes; std::transform(data.begin(),data.end(), std::back_inserter(sizes), [&](const Mesh& m) -> int{ return accessor(m).rows(); }); std::vector<int> offsets(1,0); std::partial_sum(sizes.begin(),sizes.end(), std::back_inserter(offsets)); T H(offsets.back(),accessor(data[0]).cols()); for(size_t i = 0; i < data.size(); ++i) { auto&& h = accessor(data[i]); H.block(offsets[i],0,h.rows(),h.cols()) = h; } return {H,offsets}; } }
true
3a482cc21f4987faafa3a52d5965d0c717b19605
C++
mbeckem/prequel
/include/prequel/container/array.hpp
UTF-8
13,015
3.03125
3
[ "MIT" ]
permissive
#ifndef PREQUEL_CONTAINER_ARRAY_HPP #define PREQUEL_CONTAINER_ARRAY_HPP #include <prequel/anchor_handle.hpp> #include <prequel/binary_format.hpp> #include <prequel/block_index.hpp> #include <prequel/container/allocator.hpp> #include <prequel/container/extent.hpp> #include <prequel/defs.hpp> #include <prequel/handle.hpp> #include <prequel/serialization.hpp> #include <memory> #include <variant> namespace prequel { // TODO: Consistent naming and exporting of anchors for all container types. class raw_array; namespace detail { class raw_array_impl; struct raw_array_anchor { /// Raw block storage. extent::anchor storage; /// Number of elements u64 size = 0; static constexpr auto get_binary_format() { return binary_format(&raw_array_anchor::storage, &raw_array_anchor::size); } }; } // namespace detail using raw_array_anchor = detail::raw_array_anchor; /// The stream allocates new blocks in chunks of the given size. struct linear_growth { linear_growth(u64 chunk_size = 1) : m_chunk_size(chunk_size) { PREQUEL_ASSERT(chunk_size >= 1, "Invalid chunk size."); } u64 chunk_size() const { return m_chunk_size; } private: u64 m_chunk_size; }; /// The stream is resized exponentially (to 2^n blocks). struct exponential_growth {}; /// Specify the growth strategy of a stream. using growth_strategy = std::variant<linear_growth, exponential_growth>; /** * A dynamic array for fixed-size values. * The size of values can be determined at runtime (e.g. through user input) * but must remain constant during the use of an array. * * A array stores a sequence of fixed-size values in contiguous storage on disk. * The stream can reserve capacity ahead of time to prepare for future insertions, * very similar to `std::vector<T>`. */ class raw_array { public: using anchor = raw_array_anchor; public: /** * Accesses a raw array rooted at the given anchor. * `value_size` and `alloc` must be equivalent every time the raw array is loaded. */ explicit raw_array(anchor_handle<anchor> _anchor, u32 value_size, allocator& alloc); ~raw_array(); raw_array(const raw_array&) = delete; raw_array& operator=(const raw_array&) = delete; raw_array(raw_array&&) noexcept; raw_array& operator=(raw_array&&) noexcept; public: engine& get_engine() const; allocator& get_allocator() const; /** * Returns the size of a serialized value on disk. */ u32 value_size() const; /** * Returns the number of serialized values that fit into a single block on disk. */ u32 block_capacity() const; /** * Returns true iff the stream is empty, i.e. contains zero values. */ bool empty() const; /** * Returns the number of values in this stream. */ u64 size() const; /** * Returns the capacity of this stream, i.e. the maximum number of values * that can currently be stored without reallocating the storage on disk. * The stream will allocate storage according to its growth strategy when * an element is inserted into a full stream. * * @note `capacity() * value_size() == byte_size()` will always be true. */ u64 capacity() const; /** * Returns the number of disk blocks currently allocated by the stream. */ u64 blocks() const; /** * Returns the relative fill factor, i.e. the size divided by the capacity. */ double fill_factor() const; /** * Returns the total size of this datastructure on disk, in bytes. */ u64 byte_size() const; /** * Returns the relative overhead of this datastructure compared to a linear file, i.e. * the allocated storage (see capacity()) dividied by the used storage (see size()). */ double overhead() const; /** * Retrieves the element at the given index and writes it into the `value` buffer, * which must be at least `value_size()` bytes large. */ void get(u64 index, byte* value) const; /** * Sets the value at the given index to the content of `value`, which must * have at least `value_size()` readable bytes. */ void set(u64 index, const byte* value); /** * Frees all storage allocated by the stream. * * @post `size() == 0 && byte_size() == 0`. */ void reset(); /** * Removes all objects from this stream, but does not * free the underlying storage. * * @post `size() == 0`. */ void clear(); /** * Resizes the stream to the size `n`. New elements are constructed by * initializing them with `value`, which must be at least `value_size()` bytes long. * @post `size() == n`. */ void resize(u64 n, const byte* value); /** * Resize the underlying storage so that the stream can store at least `n` values * without further resize operations. Uses the current growth strategy to computed the * storage that needs to be allocated. * * @post `capacity() >= n`. */ void reserve(u64 n); /** * Resize the underlying storage so that the stream can store at least `n` *additional* values * without further resize operations. Uses the current growth strategy to computed the * storage that needs to be allocated. * * @post `capacity() >= size() + n` */ void reserve_additional(u64 n); /** * Reduces the storage space used by the array by releasing unused capacity. * * It uses the current growth strategy to determine the needed number of blocks * and shrinks to that value. */ void shrink(); /** * Reduces the storage space used by the array by releasing all unused capacity. * * Releases *all* unused blocks to reduce the storage space to the absolute minimum. * Ignores the growth strategy. */ void shrink_to_fit(); /** * Inserts a new value at the end of the stream. * Allocates new storage in accordance with the current growth strategy * if there is no free capacity remaining. */ void push_back(const byte* value); /** * Removes the last value from this stream. * * @throws bad_operation If the stream is empty. */ void pop_back(); /** * Changes the current growth strategy. Streams support linear and exponential growth. */ void growth(const growth_strategy& g); /** * Returns the current growth strategy. */ growth_strategy growth() const; private: detail::raw_array_impl& impl() const; private: std::unique_ptr<detail::raw_array_impl> m_impl; }; /** * A dynamic array of for instances of type `T`. * * A stream stores a sequence of fixed-size values in contiguous storage on disk. * The stream can reserve capacity ahead of time to prepare for future insertions, * very similar to `std::vector<T>`. */ template<typename T> class array { public: using value_type = T; public: class anchor { raw_array::anchor array; static constexpr auto get_binary_format() { return binary_format(&anchor::array); } friend class array; friend class binary_format_access; }; public: /** * Accesses an array rooted at the given anchor. * alloc` must be equivalent every time the raw array is loaded. */ explicit array(anchor_handle<anchor> _anchor, allocator& alloc) : inner(std::move(_anchor).template member<&anchor::array>(), value_size(), alloc) {} public: engine& get_engine() const { return inner.get_engine(); } allocator& get_allocator() const { return inner.get_allocator(); } /** * Returns the size of a serialized value on disk. */ static constexpr u32 value_size() { return serialized_size<T>(); } /** * Returns the number of serialized values that fit into a single block on disk. */ u32 block_capacity() const { return inner.block_capacity(); } /** * Returns true iff the stream is empty, i.e. contains zero values. */ bool empty() const { return inner.empty(); } /** * Returns the number of values in this stream. */ u64 size() const { return inner.size(); } /** * Returns the capacity of this stream, i.e. the maximum number of values * that can currently be stored without reallocating the storage on disk. * The stream will allocate storage according to its growth strategy when * an element is inserted into a full stream. * * @note `capacity() * value_size() == byte_size()` will always be true. */ u64 capacity() const { return inner.capacity(); } /** * Returns the number of disk blocks currently allocated by the stream. */ u64 blocks() const { return inner.blocks(); } /** * Returns the relative fill factor, i.e. the size divided by the capacity. */ double fill_factor() const { return inner.fill_factor(); } /** * Returns the total size of this datastructure on disk, in bytes. */ u64 byte_size() const { return inner.byte_size(); } /** * Returns the relative overhead of this datastructure compared to a linear file, i.e. * the allocated storage (see capacity()) dividied by the used storage (see size()). */ double overhead() const { return inner.overhead(); } /** * Retrieves the value at the given index. * * @throws bad_argument If the index is out of bounds. */ value_type get(u64 index) const { serialized_buffer<T> buffer; inner.get(index, buffer.data()); return deserialize<value_type>(buffer.data(), buffer.size()); } /** * Equivalent to `get(index)`. */ value_type operator[](u64 index) const { return get(index); } /** * Sets the value at the given index. * * @throws bad_argument If the index is out of bounds. */ void set(u64 index, const value_type& value) { auto buffer = serialize_to_buffer(value); inner.set(index, buffer.data()); } /** * Frees all storage allocated by the stream. * * @post `size() == 0 && byte_size() == 0`. */ void reset() { inner.reset(); } /** * Removes all objects from this stream, but does not * necessarily free the underlying storage. * * @post `size() == 0`. */ void clear() { inner.clear(); } /** * Resizes the stream to the given size `n`. * If `n` is greater than the current size, `value` is used as a default * value for new elements. * * @post `size == n`. */ void resize(u64 n, const value_type& value = value_type()) { auto buffer = serialize_to_buffer(value); inner.resize(n, buffer.data()); } /** * Reserves sufficient storage for `n` values, while respecting the current growth strategy. * Note that the size remains unchanged. * * @post `capacity >= n`. */ void reserve(u64 n) { inner.reserve(n); } /** * Resize the underlying storage so that the stream can store at least `n` *additional* values * without further resize operations. Uses the current growth strategy to computed the * storage that needs to be allocated. * * @post `capacity() >= size() + n` */ void reserve_additional(u64 n) { inner.reserve_additional(n); } /** * Reduces the storage space used by the array by releasing unused capacity. * * It uses the current growth strategy to determine the needed number of blocks * and shrinks to that value. */ void shrink() { inner.shrink(); } /** * Reduces the storage space used by the array by releasing all unused capacity. * * Releases *all* unused blocks to reduce the storage space to the absolute minimum. * Ignores the growth strategy. */ void shrink_to_fit() { inner.shrink_to_fit(); } /** * Inserts a new value at the end of the stream. * Allocates new storage in accordance with the current growth strategy * if there is no free capacity remaining. */ void push_back(const value_type& value) { auto buffer = serialize_to_buffer(value); inner.push_back(buffer.data()); } /** * Removes the last value from this stream. * * @throws bad_operation If the stream is empty. */ void pop_back() { inner.pop_back(); } /** * Changes the current growth strategy. Streams support linear and exponential growth. */ void growth(const growth_strategy& g) { inner.growth(g); } /** * Returns the current growth strategy. */ growth_strategy growth() const { return inner.growth(); } /** * Returns the raw, byte oriented inner stream. */ const raw_array& raw() const { return inner; } private: raw_array inner; }; } // namespace prequel #endif // PREQUEL_CONTAINER_ARRAY_HPP
true
d96355eab3a2d444e581285f1bf2c73e602b5432
C++
Rahul2013396/pointers
/q10.cpp
UTF-8
510
3.84375
4
[]
no_license
// function revString(char*) which reverses the parameter cstring. The function returns nothing. You may use C++ string handling functions in <cstring> in the function if you wish. #include<iostream> #include<cstring> using namespace std; void reverseString(char *a) { // WRITE YOUR CODE HERE cout << "The reverse is "; for(int i=10;i>=0;i--) { cout << *(a+i); } cout << endl; } int main() { char k[10] = "abcde"; reverseString(k); // calling the function return 0; }
true
4b1db18563255697c1a3306e716189c4079ec7d3
C++
mew18/DS-ALGO-plus-plus
/Strings/Excercise/diffrence_ascii_code.cpp
UTF-8
466
2.984375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; void ascii_diff(string s) { for (int i = 0; i < s.length();++i) { if(i==s.length()-1) { cout << s[i]; break; } cout << s[i] << (int)s[i + 1] - s[i]; } } int main() { string s; cin >> s; if(!(s.length()>=2 and s.length()<=1000)) { domain_error("Error"); } ascii_diff(s); return 0; }
true
3da4445166d2de8ab981b8611a9f4810476c79be
C++
allanmc/Spring-brAIn
/lib/dlib/stl_checked/std_vector_c.h
UTF-8
13,032
2.9375
3
[ "BSL-1.0" ]
permissive
// Copyright (C) 2008 Davis E. King (davisking@users.sourceforge.net) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_STD_VECTOr_C_H_ #define DLIB_STD_VECTOr_C_H_ #include <vector> #include <algorithm> #include "../assert.h" #include "std_vector_c_abstract.h" #include "../serialize.h" #include "../is_kind.h" namespace dlib { template < typename T, typename Allocator = std::allocator<T> > class std_vector_c { typedef typename std::vector<T,Allocator> base_type; base_type impl; public: // types: typedef typename Allocator::reference reference; typedef typename Allocator::const_reference const_reference; typedef typename base_type::iterator iterator; // See 23.1 typedef typename base_type::const_iterator const_iterator; // See 23.1 typedef typename base_type::size_type size_type; // See 23.1 typedef typename base_type::difference_type difference_type;// See 23.1 typedef T value_type; typedef Allocator allocator_type; typedef typename Allocator::pointer pointer; typedef typename Allocator::const_pointer const_pointer; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; // 23.2.4.1 construct/copy/destroy: explicit std_vector_c(const Allocator& alloc= Allocator()) : impl(alloc) {} explicit std_vector_c(size_type n, const T& value = T(), const Allocator& alloc= Allocator()) : impl(n, value, alloc) {} template <typename InputIterator> std_vector_c(InputIterator first, InputIterator last, const Allocator& alloc= Allocator()) : impl(first,last,alloc) {} std_vector_c(const std_vector_c<T,Allocator>& x) : impl(x.impl) {} std_vector_c(const std::vector<T,Allocator>& x) : impl(x) {} operator const base_type& () const { return impl; } operator base_type& () { return impl; } std_vector_c<T,Allocator>& operator=(const std_vector_c<T,Allocator>& x) { impl = x.impl; return *this; } std_vector_c<T,Allocator>& operator=(const std::vector<T,Allocator>& x) { impl = x; return *this; } template <typename InputIterator> void assign(InputIterator first, InputIterator last) { impl.assign(first,last); } void assign(size_type n, const T& u) { impl.assign(n,u); } allocator_type get_allocator() const { return impl.get_allocator(); } // iterators: iterator begin() { return impl.begin(); } const_iterator begin() const { return impl.begin(); } iterator end() { return impl.end(); } const_iterator end() const { return impl.end(); } reverse_iterator rbegin() { return impl.rbegin(); } const_reverse_iterator rbegin() const { return impl.rbegin(); } reverse_iterator rend() { return impl.rend(); } const_reverse_iterator rend() const { return impl.rend(); } // 23.2.4.2 capacity: size_type size() const { return impl.size(); } size_type max_size() const { return impl.max_size(); } void resize(size_type sz, T c = T()) { impl.resize(sz,c); } size_type capacity() const { return impl.capacity(); } bool empty() const { return impl.empty(); } void reserve(size_type n) { impl.reserve(n); } // element access: const_reference at(size_type n) const { return impl.at(n); } reference at(size_type n) { return impl.at(n); } // 23.2.4.3 modifiers: void push_back(const T& x) { impl.push_back(x); } void swap(std_vector_c<T,Allocator>& x) { impl.swap(x.impl); } void clear() { impl.clear(); } // ------------------------------------------------------ // Things that have preconditions that should be checked. // ------------------------------------------------------ reference operator[]( size_type n ) { DLIB_CASSERT(n < size(), "\treference std_vector_c::operator[](n)" << "\n\tYou have supplied an invalid index" << "\n\tthis: " << this << "\n\tn: " << n << "\n\tsize(): " << size() ); return impl[n]; } // ------------------------------------------------------ const_reference operator[]( size_type n ) const { DLIB_CASSERT(n < size(), "\tconst_reference std_vector_c::operator[](n)" << "\n\tYou have supplied an invalid index" << "\n\tthis: " << this << "\n\tn: " << n << "\n\tsize(): " << size() ); return impl[n]; } // ------------------------------------------------------ reference front( ) { DLIB_CASSERT(size() > 0, "\treference std_vector_c::front()" << "\n\tYou can't call front() on an empty vector" << "\n\tthis: " << this ); return impl.front(); } // ------------------------------------------------------ const_reference front( ) const { DLIB_CASSERT(size() > 0, "\tconst_reference std_vector_c::front()" << "\n\tYou can't call front() on an empty vector" << "\n\tthis: " << this ); return impl.front(); } // ------------------------------------------------------ reference back( ) { DLIB_CASSERT(size() > 0, "\treference std_vector_c::back()" << "\n\tYou can't call back() on an empty vector" << "\n\tthis: " << this ); return impl.back(); } // ------------------------------------------------------ const_reference back( ) const { DLIB_CASSERT(size() > 0, "\tconst_reference std_vector_c::back()" << "\n\tYou can't call back() on an empty vector" << "\n\tthis: " << this ); return impl.back(); } // ------------------------------------------------------ void pop_back( ) { DLIB_CASSERT(size() > 0, "\tconst_reference std_vector_c::pop_back()" << "\n\tYou can't call pop_back() on an empty vector" << "\n\tthis: " << this ); impl.pop_back(); } // ------------------------------------------------------ iterator insert( iterator position, const T& x ) { DLIB_CASSERT( begin() <= position && position <= end(), "\titerator std_vector_c::insert(position,x)" << "\n\tYou have called insert() with an invalid position" << "\n\tthis: " << this ); return impl.insert(position, x); } // ------------------------------------------------------ void insert( iterator position, size_type n, const T& x ) { DLIB_CASSERT( begin() <= position && position <= end(), "\tvoid std_vector_c::insert(position,n,x)" << "\n\tYou have called insert() with an invalid position" << "\n\tthis: " << this ); impl.insert(position, n, x); } // ------------------------------------------------------ template <typename InputIterator> void insert( iterator position, InputIterator first, InputIterator last ) { DLIB_CASSERT( begin() <= position && position <= end(), "\tvoid std_vector_c::insert(position,first,last)" << "\n\tYou have called insert() with an invalid position" << "\n\tthis: " << this ); impl.insert(position, first, last); } // ------------------------------------------------------ iterator erase( iterator position ) { DLIB_CASSERT( begin() <= position && position < end(), "\titerator std_vector_c::erase(position)" << "\n\tYou have called erase() with an invalid position" << "\n\tthis: " << this ); return impl.erase(position); } // ------------------------------------------------------ iterator erase( iterator first, iterator last ) { DLIB_CASSERT( begin() <= first && first <= last && last <= end(), "\titerator std_vector_c::erase(first,last)" << "\n\tYou have called erase() with an invalid range of iterators" << "\n\tthis: " << this ); return impl.erase(first,last); } // ------------------------------------------------------ }; // ---------------------------------------------------------------------------------------- template <typename T, typename Allocator> bool operator==(const std_vector_c<T,Allocator>& x, const std_vector_c<T,Allocator>& y) { return x.size() == y.size() && std::equal(x.begin(), x.end(), y.begin()); } template <typename T, typename Allocator> bool operator< (const std_vector_c<T,Allocator>& x, const std_vector_c<T,Allocator>& y) { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } template <typename T, typename Allocator> bool operator!=(const std_vector_c<T,Allocator>& x, const std_vector_c<T,Allocator>& y) { return !(x == y); } template <typename T, typename Allocator> bool operator> (const std_vector_c<T,Allocator>& x, const std_vector_c<T,Allocator>& y) { return y < x; } template <typename T, typename Allocator> bool operator>=(const std_vector_c<T,Allocator>& x, const std_vector_c<T,Allocator>& y) { return !(x < y); } template <typename T, typename Allocator> bool operator<=(const std_vector_c<T,Allocator>& x, const std_vector_c<T,Allocator>& y) { return !(y < x); } // specialized algorithms: template <typename T, typename Allocator> void swap(std_vector_c<T,Allocator>& x, std_vector_c<T,Allocator>& y) { x.swap(y); } // ---------------------------------------------------------------------------------------- template <typename T, typename alloc> void serialize ( const std_vector_c<T,alloc>& item, std::ostream& out ) { try { const unsigned long size = static_cast<unsigned long>(item.size()); serialize(size,out); for (unsigned long i = 0; i < item.size(); ++i) serialize(item[i],out); } catch (serialization_error& e) { throw serialization_error(e.info + "\n while serializing object of type std_vector_c"); } } // ---------------------------------------------------------------------------------------- template <typename T, typename alloc> void deserialize ( std_vector_c<T, alloc>& item, std::istream& in ) { try { unsigned long size; deserialize(size,in); item.resize(size); for (unsigned long i = 0; i < size; ++i) deserialize(item[i],in); } catch (serialization_error& e) { throw serialization_error(e.info + "\n while deserializing object of type std_vector_c"); } } // ---------------------------------------------------------------------------------------- template <typename T, typename alloc> struct is_std_vector<std_vector_c<T,alloc> > { const static bool value = true; }; // ---------------------------------------------------------------------------------------- } #endif // DLIB_STD_VECTOr_C_H_
true
ca782d3e80655fe8d78d3dd182d42c3e5a454386
C++
Hattomo/micat-os
/kernel/console.hpp
UTF-8
493
2.765625
3
[]
no_license
#pragma once #include "graphics.hpp" class Console { public: static const int kRows = 35, kColums = 90; Console(const PixelColor &writer, const PixelColor &fg_color); void PutString(const char *s); void SetWriter(PixelWriter *writer); private: void Newline(); void Refresh(); PixelWriter *writer_; const PixelColor fg_color_, bg_color_; char buffer_[kRows][kColums + 1]; int cursor_row_, cursor_column_; int margin_row_, margin_column_; };
true
1d4df9e503480aa362f0ba369b771342450e6037
C++
amixofpersons/c-plus-basics-and-exercises
/loops/for-loops.cpp
UTF-8
864
4.0625
4
[]
no_license
#include <iostream> using namespace std; int main(){ /* for loops are structured to continue looping until a condition is met. for example, we can loop through until we reach a given point*/ int n; /* Above we declare our int, n, and create a for loop centering around the variable. this is relatively common to do and is what you'll be using for loops for. Until a condition is met, keep doing this. You want to be careful with for loop conditions so you don't end up creating an infinite loop which will continue forever since the condition to break out of the loop hasn't been established. */ for(n = 0; n < 10; n++){ /*here for each time we go through this loop, we'll cout the value for n until n is not less than 10 anymore. The final value n should be is nine. */ cout << "The value for n now is " << n << endl; } return 0; }
true
85ffe3b050b54bfb5c3d477b06b4825070fa1467
C++
modakshantanu/raytracer
/vector.h
UTF-8
2,787
3.03125
3
[]
no_license
#ifndef VEC #define VEC #include <cmath> #include <iostream> #include <cstdlib> using namespace std; #define FPMUL(a,b) ((a * b) >> 8) #define FPDIV(a,b) ((a << 8) / b) #define FPSQRT(a) ((int) (sqrt(a << 8))) inline int unitrandom() { return (rand() & 0x7f) - 127; } class Vec { public: int e[3]; Vec() : e{0,0,0} {} Vec(int a, int b, int c) : e{a,b,c} {} Vec operator-() const {return Vec(-e[0],-e[1],-e[2]);} Vec& operator+=(const Vec &v) { e[0] += v.e[0]; e[1] += v.e[1]; e[2] += v.e[2]; return *this; } Vec& operator*=(const int t) { e[0] = FPMUL(e[0], t); e[1] = FPMUL(e[1], t); e[2] = FPMUL(e[2], t); return *this; } Vec& operator/=(const int t) { e[0] = FPDIV(e[0], t); e[1] = FPDIV(e[1], t); e[2] = FPDIV(e[2], t); return *this; } int lsq() const { return FPMUL(e[0],e[0]) + FPMUL(e[1],e[1]) + FPMUL(e[2], e[2]); } // TODO : OPTIMISE THIS? int len() const { return FPSQRT(lsq()); } inline static Vec random() { return Vec(unitrandom(), unitrandom(), unitrandom()); } }; inline std::ostream& operator<<(std::ostream &out, const Vec &v) { return out << v.e[0]/256.0 << ' ' << v.e[1]/256.0 << ' ' << v.e[2]/256.0; } inline Vec operator+(const Vec &u, const Vec &v) { return Vec(u.e[0] + v.e[0], u.e[1] + v.e[1], u.e[2] + v.e[2]); } inline Vec operator-(const Vec &u, const Vec &v) { return Vec(u.e[0] - v.e[0], u.e[1] - v.e[1], u.e[2] - v.e[2]); } inline Vec operator*(const Vec &u, const Vec &v) { return Vec(FPMUL(u.e[0],v.e[0]), FPMUL(u.e[1], v.e[1]), FPMUL(u.e[2] , v.e[2])); } inline Vec operator*(int t, const Vec &v) { return Vec(FPMUL(t,v.e[0]), FPMUL(t,v.e[1]), FPMUL(t,v.e[2])); } inline Vec operator*(const Vec &v, int t) { return t * v; } inline Vec operator/(Vec v, int t) { return FPDIV(256,t) * v; } inline int dot(const Vec &u, const Vec &v) { return FPMUL(u.e[0] , v.e[0]) + FPMUL(u.e[1] , v.e[1]) + FPMUL(u.e[2] , v.e[2]); } inline Vec cross(const Vec &u, const Vec &v) { return Vec(FPMUL(u.e[1] , v.e[2]) - FPMUL(u.e[2] , v.e[1]), FPMUL(u.e[2] , v.e[0]) - FPMUL(u.e[0] , v.e[2]), FPMUL(u.e[0] , v.e[1]) - FPMUL(u.e[1] , v.e[0])); } inline Vec unit_vector(Vec v) { // cerr<<v<<' '<<v.len()<<endl; // cerr<<v / v.len() << endl; return v / v.len(); } Vec random_in_unit_sphere() { while (true) { auto p = Vec::random(); if (p.lsq() >= 250) continue; return p; } } #endif
true
b20300da51f13510c51be589e1324d10442aeafd
C++
JunchenZ/ImageCompressor
/ch-decompress/ReadChFile.cpp
UTF-8
1,744
2.65625
3
[]
no_license
// // ReadChFile.cpp // ReadFile // // Created by Westley Kirkham on 1/30/18. // Copyright © 2018 Westley Kirkham. All rights reserved. // #include "pbmcompress-v1.h" #include <tuple> #include <vector> #include <string> #include <fstream> #include <cassert> #include <iostream> #include <iomanip> #include <sstream> std::tuple<bool, int, int, std::vector<uint8_t> *> read_ch_file(std::string filename) { int width = 0, height = 0; std::vector<uint8_t> *vec_uint = new std::vector<uint8_t>(); char file_type[2]; bool check = false; std::ifstream my_stream (filename); if(!my_stream.good()) { auto tup_ch_file = make_tuple( check, width, height, vec_uint); std::cout << "Error: File Not Found" << std::endl; return tup_ch_file; } my_stream.read(file_type, 2); check = (file_type[0] == 'c') && (file_type[1] == 'h'); if(!check) { auto tup_ch_file = make_tuple( check, width, height, vec_uint); std::cout << "Error: File Type. Expected: ch"; std::cout << ". Received: " << file_type << std::endl; return tup_ch_file; } char num_buff[4]; my_stream.read(num_buff, 4); width = (uint8_t) num_buff[3] << 24 | (uint8_t) num_buff[2] << 16 | (uint8_t) num_buff[1] << 8 | (uint8_t) num_buff[0]; my_stream.read(num_buff, 4); height = (uint8_t) num_buff[3] << 24 | (uint8_t) num_buff[2] << 16 | (uint8_t) num_buff[1] << 8 | (uint8_t) num_buff[0]; uint8_t next_byte = my_stream.get(); while (my_stream.good()) { vec_uint -> push_back(next_byte); next_byte = my_stream.get(); } auto tup_ch_file = make_tuple( check, width, height, vec_uint); return tup_ch_file; }
true
1d6c107af91071597cad1b7d77be3383618c8b14
C++
integrid/light-alarm
/lib/arduino/lightalarm/lightalarm.ino
UTF-8
2,136
2.828125
3
[]
no_license
#include <Adafruit_NeoPixel.h> #define PIN 6 #define MODE_IDLE 0 #define MODE_WAKE 1 Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800); uint32_t startTime; uint32_t duration; uint32_t color; uint8_t mode; String inputString; boolean inputStringComplete = false; void setup() { Serial.begin(9600); inputString.reserve(32); strip.begin(); strip.show(); // Initialize all pixels to 'off' mode = MODE_IDLE; } void loop() { if (inputStringComplete) { if (inputString.startsWith("trigger")) { String r = inputString.substring(7, 10); String g = inputString.substring(10, 13); String b = inputString.substring(13, 16); String l = inputString.substring(16); color = strip.Color(r.toInt(), g.toInt(), b.toInt()); startTime = millis(); duration = l.toInt() * 60000; // minutes to milli mode = MODE_WAKE; } else if (inputString.startsWith("set")) { String r = inputString.substring(3, 6); String g = inputString.substring(6, 9); String b = inputString.substring(9, 12); String brightness = inputString.substring(12, 15); stripSet(strip.Color(r.toInt(), g.toInt(), b.toInt()), brightness.toInt()); strip.show(); mode = MODE_IDLE; } else if (inputString.startsWith("stop")) { stripSet(strip.Color(0, 0, 0), 0); // turn off lights mode = MODE_IDLE; } inputString = ""; inputStringComplete = false; } switch (mode) { case MODE_WAKE: uint32_t curTime = millis() - startTime; stripSet(color, curTime * 255 / duration); break; } delay(5000); } void serialEvent() { while (Serial.available()) { char inChar = (char) Serial.read(); if (inChar == '\n') { // TODO: copy to separate string to avoid potential read/write conflict inputStringComplete = true; break; } else { inputString += inChar; } } } void stripSet(uint32_t c, uint32_t brightness) { for (uint8_t i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, c); } strip.setBrightness(min(255, max(1, brightness))); strip.show(); }
true
f7e6710c40f5a83f84b294144161c44fef41b2b5
C++
conankzhang/ecs-game-engine
/Tools/AssetBuildLibrary/Functions.h
UTF-8
2,123
2.59375
3
[]
no_license
/* This file contains functions used by asset build tools */ #ifndef EAE6320_ASSETBUILD_FUNCTIONS_H #define EAE6320_ASSETBUILD_FUNCTIONS_H // Includes //========= #include <Engine/Results/Results.h> #include <string> // Interface //========== namespace eae6320 { namespace Assets { eae6320::cResult BuildAssets( const char* const i_path_assetsToBuild ); // If an asset ("A") references another asset ("B") // then that reference to B must be converted from a source path to a built path // if it is included in the built A asset eae6320::cResult ConvertSourceRelativePathToBuiltRelativePath( const char* const i_sourceRelativePath, const char* const i_assetType, std::string& o_builtRelativePath, std::string* o_errorMessage = nullptr ); // Error / Warning Output //----------------------- // These functions output asset build errors or warnings in the best way for the platform's build tools // (e.g. for Visual Studio the messages are formatted so that they'll show up in the Error List window) void OutputErrorMessage( const char* const i_errorMessage, ... ); void OutputErrorMessageWithFileInfo( const char* const i_filePath, const char* const i_errorMessage, ... ); void OutputErrorMessageWithFileInfo( const char* const i_filePath, const unsigned int i_lineNumber, const char* const i_errorMessage, ... ); void OutputErrorMessageWithFileInfo( const char* const i_filePath, const unsigned int i_lineNumber, const unsigned int i_columnNumber, const char* const i_errorMessage, ... ); void OutputWarningMessage( const char* const i_warningMessage, ... ); void OutputWarningMessageWithFileInfo( const char* const i_filePath, const char* const i_warningMessage, ... ); void OutputWarningMessageWithFileInfo( const char* const i_filePath, const unsigned int i_lineNumber, const char* const i_warningMessage, ... ); void OutputWarningMessageWithFileInfo( const char* const i_filePath, const unsigned int i_lineNumber, const unsigned int i_columnNumber, const char* const i_warningMessage, ... ); } } #endif // EAE6320_ASSETBUILD_FUNCTIONS_H
true
c2c946f6447cc2a339da7250d842353081f8778b
C++
intelligent-soft-robots/o80
/include/o80/state.hpp
UTF-8
2,908
2.9375
3
[ "BSD-3-Clause" ]
permissive
#pragma once #include <string> #include "o80/interpolation.hpp" namespace o80 { /*! A State represents the state of an actuator, * as well as methods specifying how a state * interpolates toward another. The interpolation * (and finished) method will be used by the BackEnd * to compute at each iteration the current desired * state value for each actuator, based on commands * sent by FrontEnd. E.g. if a command requests the desired * state of an actuator to reach value "target" in 5 seconds, * considering the current state of the actuator is "start", * then the interpolation methods will specified how the * desired state value interpolates between "start" and "target". * By default linear interpolation methods are implemented, but * they may be overriden for better control. The default linear * interpolation will work only if the state value is of native type * (e.g. double, float) and has to be overriden for any other type. * @tparam T value of the state */ template <typename T, class Sub> class State { public: State(T value); State(); T get() const; void set(T value); std::string to_string() const; bool finished(const o80::TimePoint &start, const o80::TimePoint &now, const Sub &start_state, const Sub &current_state, const Sub &previous_desired_state, const Sub &target_state, const o80::Speed &speed) const; Sub intermediate_state(const o80::TimePoint &start, const o80::TimePoint &now, const Sub &start_state, const Sub &current_state, const Sub &previous_desired_state, const Sub &target_state, const o80::Speed &speed) const; Sub intermediate_state(const o80::TimePoint &start, const o80::TimePoint &now, const Sub &start_state, const Sub &current_state, const Sub &previous_desired_state, const Sub &target_state, const o80::Duration_us &duration) const; Sub intermediate_state(long int start_iteration, long int current_iteration, const Sub &start_state, const Sub &current_state, const Sub &previous_desired_state, const Sub &target_state, const o80::Iteration &iteration) const; double to_duration(double speed, const Sub& target_state) const; template <class Archive> void serialize(Archive &archive) { archive(value); } T value; }; #include "state.hxx" } // namespace o80
true
2f85a221bba78759871c3c46a30716bfdb07b34a
C++
vazgriz/OscilloscopeMusic
/src/Line.h
UTF-8
2,698
2.5625
3
[ "MIT" ]
permissive
#pragma once #include <VulkanWrapper/VulkanWrapper.h> #include "Renderer.h" #include <glm/glm.hpp> struct UniformBuffer { glm::mat4 projection; glm::vec4 colorWidth; glm::vec2 screenSize; }; struct Vertex { glm::vec4 positionAlpha; glm::vec4 normalWidth; }; class Line : public IRenderer { public: Line(size_t bufferSize, size_t persistence, Renderer& renderer); Line(const Line& other) = delete; Line& operator = (const Line& other) = delete; Line(Line&& other) = default; Line& operator = (Line&& other) = default; void addPoint(float x, float y); void render(float dt, vk::CommandBuffer& commandBuffer) override; private: struct Transfer { vk::Buffer* buffer; vk::BufferCopy copy; vk::BufferMemoryBarrier barrier; vk::PipelineStageFlags stage; }; size_t m_bufferSize; size_t m_persistance; bool m_dirty; std::vector<glm::vec3> m_points; std::vector<Vertex> m_vertices; std::vector<uint32_t> m_indices; Renderer* m_renderer; vk::Device* m_device; vk::RenderPass* m_renderPass; std::unique_ptr<vk::DescriptorPool> m_descriptorPool; std::unique_ptr<vk::DescriptorSetLayout> m_descriptorSetLayout; std::unique_ptr<vk::DescriptorSet> m_descriptorSet; std::unique_ptr<vk::PipelineLayout> m_pipelineLayout; std::unique_ptr<vk::Pipeline> m_pipeline; std::unique_ptr<vk::Buffer> m_stagingBuffer; std::unique_ptr<vk::Buffer> m_vertexBuffer; std::unique_ptr<vk::Buffer> m_indexBuffer; std::unique_ptr<vk::Buffer> m_uniformBuffer; std::unique_ptr<vk::DeviceMemory> m_stagingBufferMemory; std::unique_ptr<vk::DeviceMemory> m_vertexBufferMemory; std::unique_ptr<vk::DeviceMemory> m_indexBufferMemory; std::unique_ptr<vk::DeviceMemory> m_uniformBufferMemory; std::vector<char> loadFile(const std::string& filename); vk::ShaderModule loadShader(const std::string& filename); char* m_stagingPtr; size_t m_stagingOffset = 0; std::vector<Transfer> m_transfers; UniformBuffer* m_uniformBufferPtr; vk::DeviceMemory allocateMemory(vk::Buffer& buffer, vk::MemoryPropertyFlags required, vk::MemoryPropertyFlags preferred); void createBuffers(); void transferData(size_t size, void* data, vk::Buffer& destinationBuffer, vk::AccessFlags destinationAccess, vk::PipelineStageFlags stage); void handleTransfers(vk::CommandBuffer& commandBuffer); void updateUniformBuffer(); void createMesh(); void createDescriptorPool(); void createDescriptorSetLayout(); void createDescriptor(); void writeDescriptor(); void createPipelineLayout(); void createPipeline(); };
true
44b23ab1b2def146041642efc46039e9b6136d0d
C++
kodamayuto/KODAMA_YUTO
/吉田学園情報ビジネス専門学校 児玉優斗/00_2DSTG[Shooting Game]/ShootingGame/game.cpp
SHIFT_JIS
5,084
2.546875
3
[]
no_license
//***************************************************************************** // // Q[̏[game.cpp] // Author : kodama Yuto // //***************************************************************************** //CN[ht@C #include "game.h" #include "fade.h" #include "pause.h" #include"ranking.h" //============================================================================= // O[oϐ錾 //============================================================================= GAMESTATE g_gamestate = GAMESTATE_NONE; //Q[̏ int g_nCounterGameState; //JE^[ bool g_bPause; //|[Yp true = |[Y //============================================================================= // //============================================================================= void InitGame(void) { InitPause(); //|[Y InitBG(); //wi InitPlayer(); //vC[̃|S InitBullet(); //e InitExplosion(); // InitScore(); //XRA InitLife(); //Ct InitPlayerMode(); //@̏ԕω InitEffect(); //GtFNg InitEnemy(); //G̃|S InitBoss(); //{X InitBossOption(); //{X̃IvV //==============// // GZbg // //==============// // nCntData == s@nCntSetEnemy == for (int nCntData = 0; nCntData < MAX_TYPE_ENEMY / 2; nCntData++) { for (int nCntSetEnemy = 0; nCntSetEnemy < 13; nCntSetEnemy++) { SetEnemy(D3DXVECTOR3(50.0f + (100 * nCntSetEnemy), 200.0f + (-50 * nCntData), 0.0f), D3DXVECTOR3(0.0f,0.0f,0.0f),(nCntData) % 4); } } //O[oϐ̏ g_gamestate = GAMESTATE_NORMAL; g_nCounterGameState = 0; g_bPause = false; PlaySound(SOUND_LABEL_BGM001);// } //============================================================================= // I //============================================================================= void UninitGame(void) { UninitPause(); //|[Y UninitBG(); //wi UninitPlayer(); //|S UninitBullet(); //e UninitExplosion(); // UninitScore(); //XRA UninitLife(); //Ct UninitPlayerMode(); //@̏ԕω UninitEffect(); //GtFNg UninitEnemy(); //G UninitBoss(); //{X UninitBossOption(); } //============================================================================= // XV //============================================================================= void UpdateGame(void) { //|[Y@ON/OFF if (GetKeyboardTrigger(DIK_P) == true) { PauseModeChange(); SerectReset(); DispReset(); if (g_gamestate == GAMESTATE_NORMAL) { PlaySound(SOUND_LABEL_SE_PAUSE);// } } if (g_bPause == false || g_gamestate == GAMESTATE_END || g_gamestate == GAMESTATE_NONE) { UpdateBG(); //wi UpdatePlayer(); //|S UpdateBullet(); //e UpdateExplosion(); // UpdateScore(); //XRA UpdateLife(); //Ct UpdatePlayerMode(); //@̏ԕω UpdateEffect(); //GtFNg UpdateEnemy(); //G UpdateBoss(); //{X UpdateBossOption(); } else if(g_bPause == true && g_gamestate != GAMESTATE_END || g_gamestate != GAMESTATE_NONE) { UpdatePause();//|[Y } switch (g_gamestate) { case GAMESTATE_NORMAL: break; case GAMESTATE_END: BulletErese(); g_nCounterGameState++; if (g_nCounterGameState >= 60) { SetRankScore(GetScore()); SetFade(MODE_RESULT); g_gamestate = GAMESTATE_NONE; //[hݒ } break; } } //============================================================================= // `揈 //============================================================================= void DrawGame(void) { //***eIuWFNg̕`揈*** DrawBG(); //wi DrawBullet(); //e DrawExplosion(); // DrawEffect(); //GtFNg DrawEnemy(); //G DrawLife(); //Ct DrawPlayerMode(); //@̏ԕω DrawScore(); //XRA DrawPlayer(); //@ DrawBoss(); //{X DrawBossOption(); //{X̃IvV if (g_bPause == true && g_gamestate == GAMESTATE_NORMAL) { DrawPause(); //|[Y } } //============================================================================= // Q[̏Ԃ̐ݒ //============================================================================= void SetGameState(GAMESTATE state) { g_gamestate = state; g_nCounterGameState = 0; } //============================================================================= // Q[̏Ԃ̎擾 //============================================================================= GAMESTATE GetGameState(void) { return g_gamestate; } //============================================================================= // |[YԂ̐؂ւ //============================================================================= void PauseModeChange(void) { g_bPause = g_bPause ? false : true; }
true
1558663779d65a57610a8014b8ab8c95131774b6
C++
Ha11ow/CSS343
/Assignment 4/Driver.cpp
UTF-8
1,416
3.203125
3
[]
no_license
#include <iostream> #include <fstream> #include "HashTable.h" #include <string> using namespace std; void removeChar(char s[], char g); int main() { ofstream output; output.open("output1.txt"); ifstream infile("phonebook.txt"); if (!infile) { cout << "File could not be opened." << endl; return 1; } HashTable temp = HashTable(); string input; while (getline(infile,input)) { if (infile.eof()) break; temp.insert(input); } output << temp; } /* int main() { string st = "(425) 285-9940"; int hashValue = 1; int temp = 0; for (int i = 0; i < st.size(); i++) { temp = int(st[i]); if (temp != 0) { hashValue *= temp; } else { hashValue += 11; } } if (hashValue < 0) { hashValue *= -1; } cout << hashValue % 4177; /* st.erase(0, 1); st.erase(3, 2); st.erase(6, 1); int temp = stoi(st); cout << temp << endl; * } */ void removeChar(char s[], char g) { int i, j; for (i = 0; s[i] != 0; ++i) { while (s[i] == g) { j = i; while (s[j] != 0) { s[j] = s[j + 1]; ++j; } } } }
true
6fcc17d200e32435bfc334b48640928020b2a2b1
C++
anmolp14/practice
/codeforces/r388/qA.cpp
UTF-8
293
2.8125
3
[]
no_license
#include<iostream> using namespace std; int main() { int n,coun=0 ; cin >> n; while ( n!=0 && n!=3 ) { coun++; n=n-2; } if( n == 3 ) coun++; cout << coun << endl; if( n==3 ) coun--; for ( int i=0;i< coun ;i++ ) cout << "2 "; if(n==3) cout << 3; return 0; }
true
1aa7abeacda2bbc343b5fd3aa69d6699f6b3f59b
C++
changsongzhu/leetcode
/C++/per_day/07-19-2017/354_h.cpp
UTF-8
1,014
3.296875
3
[]
no_license
/** 354[H]. Russian Doll Envelopes You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope. What is the maximum number of envelopes can you Russian doll? (put one inside other) Example: Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). **/ class Solution { public: int maxEnvelopes(vector<pair<int, int>>& envelopes) { int n=envelopes.size(), res=0; vector<int> dp(n, 1); sort(envelopes.begin(), envelopes.end()); for(int i=0;i<n;i++) { for(int j=0;j<i;j++) { if(envelopes[j].first<envelopes[i].first&&envelopes[j].second<envelopes[i].second) dp[i]=max(dp[i], dp[j]+1); } res=max(res, dp[i]); } return res; } };
true
941b663af7227b7879dc8cf3991c41c6eec4e468
C++
ValentinCamus/GIR-Engine
/Sources/Engine/Shader/Shader.cpp
UTF-8
3,763
2.859375
3
[ "MIT" ]
permissive
#include "Shader.hpp" namespace gir { Shader::Shader(const std::unordered_map<GLenum, std::string> &sources) : OpenGLComponent("Shader") { std::vector<GLuint> stages; m_id = glCreateProgram(); stages.reserve(sources.size()); for (const auto &src : sources) { GLuint id = ParseGLSL(src.first, src.second); stages.push_back(id); glAttachShader(m_id, id); } glLinkProgram(m_id); for (const auto id : stages) { glDeleteShader(id); } GLint success; glGetProgramiv(m_id, GL_LINK_STATUS, &success); if (!success) { GLint length; glGetProgramiv(m_id, GL_INFO_LOG_LENGTH, &length); auto log = std::string(length, ' '); glGetProgramInfoLog(m_id, length, nullptr, &log[0]); Logger::Error("Shader program linking failed with the following: {}", log); } } Shader& Shader::operator=(Shader &&shader) noexcept { m_name = shader.m_name; m_id = shader.m_id; m_isBound = shader.m_isBound; shader.m_id = 0; return *this; } Shader::~Shader() { glDeleteProgram(m_id); } void Shader::Bind() { GIR_ASSERT(m_id > 0, "Invalid program ID"); OpenGLComponent::Bind(); glUseProgram(m_id); } void Shader::Unbind() { OpenGLComponent::Unbind(); glUseProgram(0); } unsigned Shader::ParseGLSL(GLenum shaderType, const std::string &filename) { std::ifstream file {filename}; GLuint id = glCreateShader(shaderType); if (file.is_open()) { std::stringstream stream; stream << file.rdbuf(); std::string src {stream.str()}; ParseIncludes(src); const char *cSource = src.c_str(); glShaderSource(id, 1, &cSource, nullptr); glCompileShader(id); GLint success; glGetShaderiv(id, GL_COMPILE_STATUS, &success); if (!success) { GLint length; glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length); std::string log(length, ' '); glGetShaderInfoLog(id, length, nullptr, &log[0]); Logger::Error("Shader compilation failed with the following: {}", log); } } else { Logger::Error("Could not open file ", filename); } return id; } void Shader::ParseIncludes(std::string &src) const { const std::regex pattern {"#include( )*\"(([A-Z]|[a-z]|[0-9]|_)*\\.glsl)\""}; std::smatch match; auto begin = src.cbegin(); while (regex_search(begin, src.cend(), match, pattern)) { std::ifstream file {PROJECT_SOURCE_DIR + std::string("/Shaders/") + match[2].str()}; std::stringstream stream; stream << file.rdbuf(); src.replace(match.position(), match.length(), stream.str()); begin = src.cbegin() + match.position() + stream.str().length(); } } int Shader::GetUniformLocation(const std::string &name) { GLint location = -1; auto iterator = m_uniforms.find(name); if (iterator != m_uniforms.end()) { location = iterator->second; } else { location = glGetUniformLocation(m_id, name.c_str()); if (location != -1) m_uniforms.emplace(name, location); else Logger::Error("[Program ID={0}] Invalid uniform name: {1}", m_id, name); } return location; } } // namespace gir
true
da4a8070d1d4741ef46e8d8f0a4f907042a9e36c
C++
iliayar/ITMO
/Term2/algo/labs/lab2/taskE.cpp
UTF-8
4,792
2.984375
3
[]
no_license
// Generated at 2020-04-08 23:33:54.920838 // By iliayar #include <iostream> #include <vector> #include <chrono> #include <algorithm> #include <cstdio> #include <map> #include <ctime> #include <cstdlib> using namespace std; #define ON 1 #define OFF 0 #define int long long #define vint vector<int> #ifdef LOCAL #define DBG(x) cout << "DBG: " << x << endl #define DBG_CODE(x) x #else #define DBG(x) #define DBG_CODE(x) #endif //##################CODE BEGIN############# struct Node { int value; int h; int size; Node * left; Node * right; Node(int value, int h = 1) : value(value), h(h), size(1), left(nullptr), right(nullptr) {} }; Node * root = nullptr; const int INF = 1000000001; int h_get(Node *v) { return v == nullptr ? 0 : v->h; } int h_diff(Node *v) { return h_get(v->right) - h_get(v->left); } void h_upd(Node * v) { v->h = max(h_get(v->left), h_get(v->right)) + 1; } void size_upd(Node *v) { v->size = (v->left == nullptr ? 0 : v->left->size) + (v->right == nullptr ? 0 : v->right->size) + 1; // DBG("sum_upd " << v->value << " " << v->sum); } int size(Node * v) { return v == nullptr ? 0 : v->size; } Node *l_rotate(Node *a) { Node *b = a->right; a->right = b->left; b->left = a; h_upd(a); h_upd(b); size_upd(a); size_upd(b); return b; } Node *r_rotate(Node *a) { Node *b = a->left; a->left = b->right; b->right = a; h_upd(a); h_upd(b); size_upd(a); size_upd(b); return b; } Node * balance(Node * v) { if(v == nullptr) return v; h_upd(v); size_upd(v); if(h_diff(v) <= -2) { if(h_diff(v->left) >= 1) { v->left = l_rotate(v->left); } return r_rotate(v); } else if(h_diff(v) >= 2) { if(h_diff(v->right) <= -1) { v->right = r_rotate(v->right); } return l_rotate(v); } return v; } Node * find(int x, Node * v) { if(v == nullptr) return nullptr; if(v->value == x) return v; if(x < v->value) return find(x, v->left); else return find(x, v->right); } Node * insert(int x, Node * v) { if(v == nullptr) { return new Node(x); } else if(x < v->value) { v->left = insert(x, v->left); } else if(x > v->value) { v->right = insert(x, v->right); } return balance(v); } Node * min(Node * v) { if(v->left == nullptr) return v; return min(v->left); } Node * max(Node * v) { if(v->right == nullptr) return v; return min(v->right); } Node * next(int x, Node * v, Node * min = nullptr) { if(v == nullptr) return min; if(v->value > x) return next(x, v->left, v); else return next(x, v->right, min); } Node * prev(int x, Node * v, Node * max = nullptr) { if(v == nullptr) return max; if(v->value < x) return prev(x, v->right, v); else return prev(x, v->left, max); } Node * remove(int x, Node * v) { if(v == nullptr) return v; if(x < v->value) { v->left = remove(x, v->left); } else if(x > v->value) { v->right = remove(x, v->right); } else if(v->left != nullptr && v->right != nullptr) { v->value = next(v->value, root)->value; v->right = remove(v->value, v->right); } else { if(v->left != nullptr) { v = v->left; } else if(v->right != nullptr) { v = v->right; } else { v = nullptr; } } return balance(v); } Node * kth_max(int k, Node * v) { if(size(v->right) == k) return v; if(size(v->right) > k) return kth_max(k, v->right); return kth_max(k - size(v->right) - 1, v->left); } //entry void sol() { int n; cin >> n; for(int i = 0; i < n; ++i) { string op; cin >> op; DBG(op); if(op == "+1" || op == "1") { int t; cin >> t; root = insert(t, root); } else if(op == "-1") { int t; cin >> t; root = remove(t, root); } else { int t; cin >> t; t--; Node * x = kth_max(t, root); cout << x->value << endl; } } } //##################CODE END############### #ifdef LOCAL #undef FILE_IO #undef FILENAME #define FILE_IO ON #define FILENAME "local" #endif signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #if FILE_IO == ON freopen(FILENAME".in", "r", stdin); freopen(FILENAME".out", "w", stdout); #endif #ifdef LOCAL auto start = std::chrono::high_resolution_clock::now(); #endif sol(); #ifdef LOCAL auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); cout << duration.count() << " microseconds" << endl; #endif }
true
8e4c0fa318ee4fe7459f565a28245ce50ab55012
C++
evandrix/UVa
/10331.cpp
UTF-8
1,425
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define maxn 102 #define INF 99999999 #define min(a, b) (a > b ? b : a) int t[maxn][maxn], N; struct ss { int u, v, c; int used; }; ss V[100000]; int tv; void ini() { int i, j; for (i = 1; i <= N; i++) { for (j = i + 1; j <= N; j++) { t[i][j] = t[j][i] = INF; } t[i][i] = 0; } } void Floyd() { int i, j, k; for (k = 1; k <= N; k++) { for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { t[i][j] = min(t[i][j], t[i][k] + t[k][j]); } } } } void Count() { int i, j, k, max = 0; for (i = 1; i < N; i++) { for (j = i + 1; j <= N; j++) { for (k = 0; k < tv; k++) { if (V[k].c > t[V[k].u][V[k].v]) { continue; } if (t[i][V[k].u] + V[k].c + t[V[k].v][j] == t[i][j] || t[i][V[k].v] + V[k].c + t[V[k].u][j] == t[i][j]) { V[k].used++; } if (V[k].used > max) { max = V[k].used; } } } } k = 0; for (i = 0; i < tv; i++) { if (V[i].used == max) { if (k++ > 0) { cout << " "; } cout << i + 1; } } cout << endl; } void Cal() { Floyd(); Count(); } int main() { int m, u, v, c, k = 0; ss dum; while (cin >> N >> m) { ini(); tv = 0; while (m--) { cin >> u >> v >> c; if (t[u][v] > c) { t[u][v] = t[v][u] = c; } dum.u = u; dum.v = v; dum.c = c; dum.used = 0; V[tv++] = dum; } Cal(); } return 0; }
true
e8bb30b97de29e0b3b7573d30a134b719b6f9c5b
C++
JanaSabuj/Coursera-Algorithmic-ToolBox
/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.cpp
UTF-8
1,022
3.125
3
[]
no_license
#include <iostream> using ll = long long; int fibonacci_sum_naive(long long n) { if (n <= 1) return n; long long previous = 0; long long current = 1; long long sum = 1; for (long long i = 0; i < n - 1; ++i) { long long tmp_previous = previous; previous = current; current = tmp_previous + current; sum += current; } return sum % 10; } ll pisano(ll m, ll n) { ll dp[m * m]; dp[0] = 0; dp[1] = 1; ll p; for (ll i = 2 ; i <= m * m + 2; ++i) { /* code */ dp[i] = (dp[i - 1] + dp[i - 2]) % m; if (dp[i - 1] == 0 and dp[i] == 1) { p = i - 2 + 1; break; } } return dp[n % p]; } ll fibonacci_sum_fast(ll n){ ll f = pisano( (ll)10, n+2); return (f-1+10)%10; } int main() { // freopen("input.txt", "r" , stdin); long long n = 0; std::cin >> n; // std::cout << fibonacci_sum_naive(n); std::cout << fibonacci_sum_fast(n); }
true
8c66b56819309be4dc05707178b82013094a033a
C++
Neconspictor/Euclid
/projects/engine/nex/util/Iterator.hpp
UTF-8
634
3.109375
3
[]
no_license
#pragma once namespace nex { template<class Container> struct Range { typename Container::iterator begin; typename Container::iterator end; }; template<class Container> class ConstRange { public: //using iterator = typename Container::const_iterator; using const_iterator = typename Container::const_iterator; explicit ConstRange() {} ConstRange(const Container& container) { mBegin = container.begin(); mEnd = container.end(); } const_iterator begin() const { return mBegin; } const_iterator end() const { return mEnd; } private: const_iterator mBegin; const_iterator mEnd; }; }
true
1c3fa0dae72ef25c0a31e898d8d1c159cf78cd10
C++
didrlgus/algorithm-practice
/codility/lesson5/passingCars.cpp
UTF-8
418
2.578125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; vector<int> east,west; int ret; int solution(vector<int> &v) { for(int i=0;i<(int)v.size();i++) { if(v[i]==0) east.push_back(i); else west.push_back(i); } for(int i=0;i<(int)east.size();i++) { int val=east[i]; ret+=west.end()-upper_bound(west.begin(),west.end(),val); if(ret>1000000000) return -1; } return ret; }
true
9d5a39561ea6066507a2ebb980ce5510cd688e0d
C++
sarvaiyac/geeksalgorithms
/Advanced C++/Assignment4/Isosceles.cpp
UTF-8
1,422
3.25
3
[]
no_license
// // Isosceles.cpp // Assignment4 // // Created by Chintan Sarvaiya on 2014-07-27. // Copyright (c) 2014 ___CHINTANSARVAIYA___. All rights reserved. // #include "Isosceles.h" // Accessor int Isosceles::getHeight() const { return height;} // Mutator void Isosceles::setHeight(int i_height){ height = i_height; } void Isosceles::scale(int n){ // it scales height and base of Isosceles with n, if perticular conidtion matches if (height+n >= 1) { height = height+n; base = 2*height - 1; } } double Isosceles::computeGeometricArea() const{ return (double)height*base/2; } double Isosceles::computeGeometricPerimeter() const{ return (double) base + (2*(sqrt((0.25*base*base) + (height*height)))); } int Isosceles::computeScreenArea() const{ return height*height; } int Isosceles::computeScreenPerimeter() const{ return 4*(height-1); } int Isosceles::computeHorizontalExtents() const{ return base; } int Isosceles::computeVerticalExtents() const{ return height; } // This method draws Isosceles with specified character on specified canvas, and that Isosceles starts with row r and column c void Isosceles::draw(int c,int r, Canvas& canvas, char ch) const{ int start = c; int end = c+base; for (int i = (r+height-1); i>=r; i--) { for (int j=start; j<end; j++) canvas.put(j, i,ch); start++; end--; } }
true
02fd4d848a95a8f08814cd17122943456e377587
C++
sausthapit/uasl_image_acquisition
/test/test_tau2_framerate.cpp
UTF-8
1,826
2.53125
3
[]
no_license
#include "acquisition.hpp" #include "util_signal.hpp" #include "camera_tau2.hpp" #include <opencv2/core/version.hpp> #if CV_MAJOR_VERSION == 2 #include <opencv2/highgui/highgui.hpp> #elif CV_MAJOR_VERSION >= 3 #include <opencv2/highgui.hpp> #endif #include <chrono> #include <vector> #include <string> int main() { cam::SigHandler sig_handle;//Instantiate this class first since the constructor blocks the signal of all future child threads //Class for managing cameras cam::Acquisition acq; acq.add_camera<cam::tau2>("FT2HKAW5"); std::vector<cv::Mat> img_vec;//Vector to store the images dynamic_cast<cam::Tau2Parameters&>(acq.get_cam_params(0)).set_image_roi(0,16,640,480); dynamic_cast<cam::Tau2Parameters&>(acq.get_cam_params(0)).set_pixel_format(CV_8U); unsigned int count = 0; std::chrono::time_point<std::chrono::steady_clock> start, end;//Variable to measure framerate start = std::chrono::steady_clock::now(); acq.start_acq();//Start the acquisition while(sig_handle.check_term_sig() && acq.is_running()) { int ret_acq = acq.get_images(img_vec); if(!ret_acq) { ++count; for(size_t n = 0; n<img_vec.size(); ++n) { std::string image_name_show = "Image_" + std::to_string(n+1); cv::imshow(image_name_show.c_str(), img_vec[n]); /*std::string image_name = "test_pic/" + std::to_string(n+1) + "_" + std::to_string(count) + ".png"; cv::imwrite(image_name.c_str(), img_vec[n]);*/ } cv::waitKey(1); } if(count && count%100 == 0)//Print framerate every 100 frames { end = std::chrono::steady_clock::now(); std::cout << "Framerate : " << 100 * 1000.0 / std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << " fps" << std::endl; start = std::chrono::steady_clock::now(); } } return 0; }
true
8fa66c570d8708e31ccdc593c7741eaef597c744
C++
jigsaw5071/algorithms
/string/string_permutation_generator.cpp
UTF-8
1,731
3.671875
4
[]
no_license
/** @ Shubham Sharma Date:01/01/2017 */ /* ----------------------------String Permutation generator-------------------------------------------------- 1. This algorithm is used to handle the string with duplicates also. 2. The Time complexity is O(n!) 3. The space complexity is O(n) */ #include<bits/stdc++.h> using namespace std; /** utility function to print the array */ void print_string(vector<char>& result){ for(int i=0;i<result.size();++i){ cout<<result[i]<<""; } cout<<endl; } /** utility function to print all the permutations of the given string */ void premute_util(vector<char>& str,vector<int>& count,vector<char>& result,const int level){ if(result.size()==level){ print_string(result); return; } for(int i=0;i<count.size();++i){ if(count[i]==0){ continue; } result[level]=str[i]; count[i]--; premute_util(str,count,result,level+1); count[i]++; } } /** utility function to generate all the lexicographical permutations */ void permute(string& s){ if(s.length()==0){return;} if(s.length()==1){ cout<<s[0]<<endl; return; } int n=s.length(); vector<int> _hash_table(26,0); for(int i=0;i<n;++i){ _hash_table[(int)(s[i]-97)]++; } vector<char> str; vector<int> count; for(int i=0;i<26;++i){ if(_hash_table[i]>0){ str.push_back((char)(i+97)); count.push_back(_hash_table[i]); } } vector<char> result(s.length()); premute_util(str,count,result,0);//0 here indicates the level } int main(void){ string s="abcd"; permute(s); return 0; }
true
0dcb3d9c3bd95605d4d8959893f23becd3ce9b00
C++
ai5/gpsfish
/osl/core/osl/book/openingBook.h
UTF-8
6,841
3.09375
3
[]
no_license
#ifndef _OPENING_BOOK_H #define _OPENING_BOOK_H #include "osl/book/compactBoard.h" #include "osl/basic_type.h" #include "osl/numEffectState.h" #include <fstream> #include <functional> namespace osl { namespace book { class OMove { public: OMove(int i) { value = i; } OMove(Move m) { const Square from = m.from(); const Square to = m.to(); const int bitFrom = (from.isPieceStand() ? 0 : (from.x() << 4 | from.y())); const int bitTo = (to.isPieceStand() ? 0 : (to.x() << 12 | to.y() << 8)); value = (bitFrom | bitTo | static_cast<unsigned int>(m.isPromotion()) << 19 | static_cast<unsigned int>(m.capturePtype()) << 20 | static_cast<unsigned int>(m.ptype()) << 24 | static_cast<int>(m.player()) << 28); } Square from() { if ((value & 0xff) == 0) return Square::STAND(); else return Square((value >> 4) & 0xf, value & 0xf); } Square to() { if (((value >> 8) & 0xff) == 0) return Square::STAND(); else return Square((value >> 12) & 0xf, (value >> 8) & 0xf); } bool isPromotion() { return (value >> 19) & 1; } Ptype capturePtype() { return static_cast<Ptype>((value >> 20) & 0xf); } Ptype ptype() { return static_cast<Ptype>((value >> 24) & 0xf); } Player player() { return static_cast<Player>((value) >> 28); } operator Move() { return Move(from(), to(), ptype(), capturePtype(), isPromotion(), player()); } operator int() { return value; } private: int value; }; struct OBMove { Move move; int state_index; int stateIndex() const { return state_index; } }; /** * StateとOBMoveを保持する. * Stateはvector<OBMove>と黒から見たwinCount, loseCountを保持する * OBMoveはMoveとそのMoveを採用した時のStateのindex * ファイル形式 * state数 - 4byte * State - 16byte * state数 * + 黒のwinCount * + 白のwinCount * + OBMoveの数 * + OBMoveの開始index * OBMove - 8byte * OBMove数 * + Move (4byte) * + Stateのindex */ class WinCountBook { int nStates; std::ifstream ifs; public: WinCountBook(const char *filename); ~WinCountBook(); int winCount(int stateIndex); int loseCount(int stateIndex); std::vector<OBMove> moves(int stateIndex); private: int readInt(); void seek(int offset); }; struct WMove { Move move; int state_index; int weight; int stateIndex() const { return state_index; } void setWeight(const int w) { weight = w; }; }; std::ostream& operator<<(std::ostream&, const WMove& w); std::istream& operator>>(std::istream&, WMove& w); inline bool operator==(const WMove& l, const WMove& r) { return l.move == r.move && l.stateIndex() == r.stateIndex() && l.weight == r.weight; } /** * WMoveのWeightによるsort */ struct WMoveSort : public std::binary_function<WMove, WMove, bool> { bool operator()(const WMove& l, const WMove& r) const { return l.weight > r.weight; } }; /** * WMoveのMoveによるsort */ struct WMoveMoveSort : public std::binary_function<WMove, WMove, bool> { bool operator()(const WMove& l, const WMove& r) const { return l.move.intValue() < r.move.intValue(); } }; /** * WMoveのWeightとMoveによるsort */ struct WMoveWeightMoveSort : public std::binary_function<WMove, WMove, bool> { bool operator()(const WMove& l, const WMove& r) const { if (l.weight != r.weight) return l.weight > r.weight; return l.move.intValue() < r.move.intValue(); } }; /** * StateとWMoveを保持する. * Stateはvector<WMove>を保持する * WMoveはMoveとそのMoveを採用した時のStateのindexと手番から見た * Moveの重み(0-1000)をもつ * ファイル形式 * version番号 - 4byte * state数 - 4byte * move数 - 4byte * 開始state index - 4byte * State - 16byte * state数 * + WMoveの開始index * + WMoveの数 * + 先手の勝数 * + 後手の勝数 * WMove - 12byte * WMove数 * + Move (4byte) * + Stateのindex * + Weight * CompactBoard形式の盤面 - 164byte * state数 */ class WeightedBook { int n_states; int n_moves; int start_state; std::ifstream ifs; public: typedef std::vector<WMove> WMoveContainer; WeightedBook(const char *filename); ~WeightedBook(); /** * Return moves from the state of the stateIndex. If the zero_include is * true, all of the moves are returned. Otherwise, the moves that * have some weights (i.e. non-zero value) are returned. */ WMoveContainer moves(int stateIndex, const bool zero_include = true); int whiteWinCount(int stateIndex); int blackWinCount(int stateIndex); CompactBoard compactBoard(int stateIndex); SimpleState board(int stateIndex); int totalState() const { return n_states; } int startState() const { return start_state; } void validate(); /** * As traversing the 'tree', return all state indices of the state's * parents. * @return state indexes; empty if there is none. */ std::vector<int> parents(const int stateIndex); /** * As traversing the 'tree', find a state index of the state. If * the visit_zero is true zero-weighted moves are visited (in this * case, player is ignored). Otherwise, the palyer's zero-weighted * moves are not visited. * * @param state to find * @param visit_zero * @param player * @return a state index of the state; if it is not found, return -1. */ int stateIndex(const SimpleState& state, const bool visit_zero = true, const Player player = BLACK); /** * As traversing the 'tree', find a state index of the state reached * by applying the moves from the initial state. * Note that zero-weighted moves are visited. * * @param moves to apply * @return state index; if it is not found, return -1. */ int stateIndex(const std::vector<Move>& moves); private: void seek(int offset); static const int HEADER_SIZE = 16; static const int STATE_SIZE = 16; static const int MOVE_SIZE = 12; static const int BOARD_SIZE = 41 * 4; }; } // book using book::CompactBoard; using book::WeightedBook; } // namespace osl #endif // _OPENING_BOOK_H // ;;; Local Variables: // ;;; mode:c++ // ;;; c-basic-offset:2 // ;;; End:
true
832debb4d00f83f440a99106846894f708660bd0
C++
davelasquez12/SimpleShellCpp
/Simple_Shell/Main.cpp
UTF-8
1,505
2.96875
3
[]
no_license
/*David Velasquez Operating Systems - Proj1 - Simple Shell Due: February 14th, 2017*/ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include <io.h> #include <process.h> #include "functions.h" int main() { int i = 0, j, k, numArgs = 0; char ** argArray, ** argArrayFree = NULL; printf("\nWelcome to the Cool Shell\n\n"); char ** pathv = (char**)malloc(64 * sizeof(char*)); //init number of paths (64) for (i = 0; i < 64; i++) //init the path length of each path in the array (128 chars) pathv[i] = (char*)malloc(128); parsePath(pathv); while (1) { char * input = getUserInput(); //prompt function for user input char * savedInput = input; //free this memory allocated at the end char * command; //stores only the command (not the arguments) command = parseCommand(input); //char * fullCmdName = lookupPath(command, pathv); //needed once path searching works for (k = 0; k < strlen(command); k++) //removes command from input and leaves arguments input++; numArgs = getNumArgs(input); if (numArgs > 0) { argArray = getArgArray(input); argArrayFree = argArray; } /*if (strcmp(command, "exit") == 0) exitShell(numArgs);*/ //start child process if (fork() == 0) { execvp(command, argArray); exit(0); //should not reach here } //parent process free(command); free(savedInput); //free(fullCmdName); for (i = 0; i < numArgs; i++) free(argArrayFree[i]); } return 0; }
true
684412692b47c300ba71fea38092e8296bc1cc59
C++
skyliulu/OJ
/dji/ex1.cpp
UTF-8
1,045
2.625
3
[]
no_license
#include <iostream> #include <numeric> #include <sstream> #include <vector> #include <unordered_map> #include <algorithm> #include <iomanip> using namespace std; int n,p; const int start = 0; int end_p = 0; int sumPath = 1<<30,tmpPath = 0; vector<int> visited; vector<vector<int>> matrix; void func(int k) { if(k==end_p) { sumPath = min(tmpPath,sumPath); return; } if(visited[k]) return; visited[k] = 1; for(int i=0;i<n;i++) { if(matrix[k][i]>0) { tmpPath += matrix[k][i]; func(i); tmpPath -= matrix[k][i]; } } visited[k] = 0; } int main() { cin >> n >>p; // vector<int> A(p,0),B(p,0),T(p,0); // vector<vector<int>> matrix(n,vector<int>(n,0)); matrix.assign(n,vector<int>(n,0)); for(int i=0;i<p;i++) { // cin >> A[i] >> B[i] >>T[i]; int a,b,t; cin >> a >>b>>t; matrix[a][b] = t; } cin >> end_p; visited.assign(n,0); func(start); cout << sumPath <<endl; return 0; }
true
71670d9f1400acd546c5386ec613bdc952b13223
C++
denis-gubar/Leetcode
/String/0609. Find Duplicate File in System.cpp
UTF-8
953
2.828125
3
[]
no_license
class Solution { public: vector<string> split(const string& s, char delimeter = ' ') { vector<string> result; istringstream ss(s); for (string token; !ss.eof(); ) { getline(ss, token, delimeter); result.push_back(token); } return result; } vector<vector<string>> findDuplicate(vector<string>& paths) { vector<vector<string>> result; unordered_map<string, vector<string>> M; for (string const& p : paths) { vector<string> S(split(p)); auto update = [&M](string const& p, string const& prefix) { int pos = p.find('('); string_view value(p.c_str(), pos); string_view key(p.c_str() + pos, p.size() - pos); M[string(key)].push_back(prefix + string(value)); }; if (S.size() == 1) update(p, {}); else { for (int i = 1; i < S.size(); ++i) update(S[i], S[0] + '/'); } } for (auto& [key, value] : M) if (value.size() > 1) result.push_back(value); return result; } };
true
49b388da262c5c32571772b64108be899288e997
C++
MikeXuQ/Algorithm
/algorithm_total/101/main.cpp
UTF-8
899
3.6875
4
[]
no_license
#include <iostream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: bool isSymmetric(TreeNode* root) { if (root == NULL) return true; return isSubTreeSymmetric(root->left, root->right); } bool isSubTreeSymmetric(TreeNode* left, TreeNode* right) { if (left == NULL && right == NULL) { return true; } else if (left != NULL && right != NULL) { if (left->val == right ->val) { return isSubTreeSymmetric(left->left, right->right) && isSubTreeSymmetric(right->left, left->right); } else { return false; } } else { return false; } } }; int main() { std::cout << "Hello, World!" << std::endl; return 0; }
true
c63ade35796f577f56609cdbdb8c20121f0a15ac
C++
arvind-murty/CppProgramming
/chap6/prob5/calendar.h
UTF-8
573
3
3
[]
no_license
#ifndef CALENDAR_H_ #define CALENDAR_H_ #include <string> enum Month { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; bool isLeapYear(int year); int daysInMonth(Month month, int year); std::string monthToString(Month month); class Date { public: Date(Month month = JAN, int day = 1, int year = 1900); Date(int day = 1, Month month = JAN, int year = 1900); int getDay() { return d; } Month getMonth() { return m; } int getYear() { return y; } std::string toString(); private: Month m; int d; int y; }; #endif
true
d2549ae6971d106a889cce709d2c5b6ca04701b0
C++
jsfreischuetz/NonEuclidean
/TestProject/PhysicalTest.cpp
UTF-8
3,569
2.609375
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "CppUnitTest.h" #include "..\NonEuclidean\Tunnel.h" #include "..\NonEuclidean\Portal.h" #include "..\NonEuclidean\Physical.h" #include "..\NonEuclidean\Player.h" #include "..\NonEuclidean\Resources.h" #include "..\NonEuclidean\Ground.h" #include "..\NonEuclidean\Engine.h" #include <windows.h> #include <string> #include <iostream> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace TestProject { TEST_CLASS(PhysicalTest) { public: TEST_METHOD(Portal_Hit_Test) { Engine *e = new Engine; glewExperimental = GL_TRUE; glewInit(); std::shared_ptr<Tunnel> tunnel1(new Tunnel(Tunnel::NORMAL)); tunnel1->pos = Vector3(-2.4f, 0, -1.8f); tunnel1->scale = Vector3(1, 1, 4.8f); std::shared_ptr<Tunnel> tunnel2(new Tunnel(Tunnel::NORMAL)); tunnel2->pos = Vector3(2.4f, 0, 0); tunnel2->scale = Vector3(1, 1, 0.6f); std::shared_ptr<Ground> ground(new Ground()); ground->scale *= 1.2f; std::shared_ptr<Portal> portal1(new Portal()); tunnel1->SetDoor1(*portal1); std::shared_ptr<Portal> portal2(new Portal()); tunnel2->SetDoor1(*portal2); std::shared_ptr<Portal> portal3(new Portal()); tunnel1->SetDoor2(*portal3); std::shared_ptr<Portal> portal4(new Portal()); tunnel2->SetDoor2(*portal4); Portal::Connect(portal1, portal2); Portal::Connect(portal3, portal4); Physical p; Assert::IsFalse(p.TryPortal(*portal1)); } TEST_METHOD(Portal_Hit_Test_2) { Engine *e = new Engine; glewExperimental = GL_TRUE; glewInit(); std::shared_ptr<Tunnel> tunnel1(new Tunnel(Tunnel::NORMAL)); tunnel1->pos = Vector3(-2.4f, 0, -1.8f); tunnel1->scale = Vector3(1, 1, 4.8f); std::shared_ptr<Tunnel> tunnel2(new Tunnel(Tunnel::NORMAL)); tunnel2->pos = Vector3(2.4f, 0, 0); tunnel2->scale = Vector3(1, 1, 0.6f); std::shared_ptr<Ground> ground(new Ground()); ground->scale *= 1.2f; std::shared_ptr<Portal> portal1(new Portal()); tunnel1->SetDoor1(*portal1); std::shared_ptr<Portal> portal2(new Portal()); tunnel2->SetDoor1(*portal2); std::shared_ptr<Portal> portal3(new Portal()); tunnel1->SetDoor2(*portal3); std::shared_ptr<Portal> portal4(new Portal()); tunnel2->SetDoor2(*portal4); Portal::Connect(portal1, portal2); Portal::Connect(portal3, portal4); Physical p; p.SetPosition(Vector3(-2.53473f, 1.5f, 2.99862f)); p.prev_pos = Vector3(-2.5347f, 1.5f, 3.00441f); Assert::IsTrue(p.TryPortal(*portal1)); } TEST_METHOD(On_Collide_Test_1) { Engine *e = new Engine; Object o; Physical phy; phy.OnCollide(o, Vector3(10, 10, 10)); Assert::AreNotEqual(phy.pos.x, 0.f); Assert::AreNotEqual(phy.pos.y, 0.f); Assert::AreNotEqual(phy.pos.z, 0.f); } TEST_METHOD(On_Collide_Test_2) { Engine *e = new Engine; Object o; Physical phy; phy.OnCollide(o, Vector3(0, 0, 0)); Assert::AreEqual(phy.pos.x, 0.f); Assert::AreEqual(phy.pos.y, 0.f); Assert::AreEqual(phy.pos.z, 0.f); } TEST_METHOD(Update_Test) { Engine *e = new Engine; Physical p; p.pos = Vector3(0, 0, 0); p.Update(); p.Update(); p.Update(); Assert::AreEqual(p.pos.x, 0.f); Assert::AreNotEqual(p.pos.y, 0.f); Assert::AreEqual(p.pos.z, 0.f); } TEST_METHOD(Reset_Test) { Engine *e = new Engine; Physical p; p.pos = Vector3(0, 0, 0); p.Update(); p.Update(); p.Update(); p.Reset(); Assert::AreEqual(p.pos.x, 0.f); Assert::AreEqual(p.pos.y, 0.f); Assert::AreEqual(p.pos.z, 0.f); } }; }
true
362113341e315bbceb12d0e6d3bc0beceaa53653
C++
wickneber/hexapodFABRIK
/KinematicsEngine.h
UTF-8
2,150
2.71875
3
[]
no_license
// // Created by root on 5/29/20. // #ifndef KINEMATICSENGINE_KINEMATICSENGINE_H #define KINEMATICSENGINE_KINEMATICSENGINE_H #include <vector> #include "DOF3Leg.h" #include "usefulTypedefs.h" namespace KinematicsEngine { /// Implements a hybrid algorithm that consists of FABRIK inverse kinematics and the /// analytic geometric approach to calculate the inverse kinematics values for the /// given robot legs. /// \param x The desired x value for the robot leg(s) to be. /// \param y The desired y value for the robot leg(s) to be. /// \param z The desired z value for the robot leg(s) to be. /// \param robotLegs The set of legs to calculate the leg kinematics for. void doKinematics(double x, double y, double z, std::vector<DOF3Leg*>& robotLegs); /// Given a desired translation on the base reference frame, calculate the /// resulting x, y, and z translations for the robot legs /// \param xTranslation The desired x translation in centimeters /// \param yTranslation The desired y translation in centimeters /// \param zTranslation The desired z translation in centimeters void doTranslation(double xTranslation, double yTranslation, double zTranslation, std::vector<DOF3Leg*>& robotLegs); /// Given the yaw, pitch, and roll in radians, calculate the resulting legs /// goal positions after all the rotations. /// \param yaw The yaw degree to rotate the robot /// \param pitch The pitch degree to rotate the robot /// \param roll The roll degree to rotate the robot void doRotation(double yaw, double pitch, double roll, std::vector<DOF3Leg*>& robotLegs); void testFabrik(DOF3Leg* robotLeg); /// Given a specific leg id number, use the FABRIK algorithm to calculate the IK of the specific robot leg /// \param legId The leg ID number that a calculation is desired static void doFabrik(DOF3Leg* robotLeg); /// Just a testing function to test the FABRIK algorithm /// \param legId the leg to test //void testFabrik(std::shared_ptr<DOF3Leg>& robotLeg); }; #endif //KINEMATICSENGINE_KINEMATICSENGINE_H
true
e96dd006b9cdfa456297e4725e8674dc1037a25a
C++
Richard-coder-Nai/OJ
/practice/0776_1.cpp
UTF-8
203
2.828125
3
[ "Apache-2.0" ]
permissive
#include <iostream> using namespace std; int main(void) { string a, b; cin>>a>>b; if(a.size()<b.size()) swap(a, b); a = a+a; if(a.find(b)!=a.npos) cout<<"true"<<endl; else cout<<"false"<<endl; }
true
b5ef85bdde19fea9c00b8af3d2e92d734a7aa5e5
C++
Baticsute/Tower-Shot-Game
/tower.h
UTF-8
979
2.734375
3
[]
no_license
#ifndef TOWER_H #define TOWER_H #include <QGraphicsPixmapItem> #include <QGraphicsPolygonItem> #include <QGraphicsItem> #include <QPointF> #include <QObject> class Tower:public QObject, public QGraphicsPixmapItem{ // Là lớp kiểu QGraphicsPixmapItem , QObject để chạy timer Q_OBJECT public: Tower(QGraphicsItem * parent=0); // Hàm khởi tạo double distanceTo(QGraphicsItem * item); // khoảng cách đến đối tượng khác virtual void fire(); // phương thức trừu tượng , phát ra đạn khi có mục tiêu public slots: void aquire_target(); // slot được định nghĩa phát hiện mục tiêu protected: QGraphicsPolygonItem * attack_area; // là polygon bao quanh trụ , xác định vùng bắn khi có kẻ thù QPointF attack_dest; // là điểm cần bắn vào mục tiêu bool has_target; // biến binary xác định có/không mục tiêu }; #endif // TOWER_H
true
d6a9fae0db9ea9acaf41271b1c314f91de4d78f2
C++
yashPat98/OpenGL-Using-GLUT
/Line Sizes/LineSizes.cc
UTF-8
1,311
2.640625
3
[]
no_license
#include <GL/gl.h> #include <GL/glut.h> void SetupRC(void){ glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glColor3f(1.0f, 1.0f, 1.0f); } void ChangeSize(GLsizei w, GLsizei h){ GLfloat aspectRatio = (GLfloat)w / (GLfloat)h; if(h == 0) h = 1; glViewport(0, 0, w, h); //Reset coordinate system glMatrixMode(GL_PROJECTION); glLoadIdentity(); if(w <= h) glOrtho(-100.0f, 100.0f, -100.0f / aspectRatio, 100.0f / aspectRatio, -100.0f, 100.0f); else glOrtho(-100.0f * aspectRatio, 100.0f * aspectRatio, -100.0f, 100.0f, -100.0f, 100.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void RenderScene(void){ GLfloat y, step; GLfloat fSizes[2]; GLfloat fCurrSize; glGetFloatv(GL_LINE_WIDTH_RANGE, fSizes); //glGetFloatv(GL_LINE_WIDTH_GRANULARITY, &step); fCurrSize = fSizes[0]; glClear(GL_COLOR_BUFFER_BIT); for(y = -90.0f; y < 90.0f; y += 20.0f){ glLineWidth(fCurrSize); glBegin(GL_LINES); glVertex2f(-80.0f, y); glVertex2f(80.0f, y); glEnd(); fCurrSize += 1.0f; } glutSwapBuffers(); } int main(int argc, char* argv[]){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(1024, 720); glutCreateWindow("Line Sizes"); glutDisplayFunc(RenderScene); glutReshapeFunc(ChangeSize); SetupRC(); glutMainLoop(); return 0; }
true
c1469bf2ff75b6e15e03c246cc154cffe2422d42
C++
shubhapatil154/CP
/InterViewPrep/Bits/bits.cpp
UTF-8
1,075
3.203125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; void showbits(int n){ int k, andmask; for (int i = 15; i >= 0;i--){ andmask = 1 << i; k = n & andmask; if (k == 0) cout << "0"; else { cout << "1"; } } cout << endl; } int main(){ int n,k; cout << "enter n: "; cin>>n; cout << "binary: "; showbits(n); cout << "1's complement: "; k = ~n; cout << k << endl; cout << "binary: "; showbits(k); cout << "right shifted once: "; k = n >> 1; cout << k << endl; cout << "binary: "; showbits(k); cout << "right shifted twice: "; k = n >> 2; cout << k << endl; cout << "binary: "; showbits(k); cout << "left shifted once: "; k = n << 1; cout << k << endl; cout << "binary: "; showbits(k); cout << "left shifted twice: "; k = n << 2; cout << k << endl; cout << "binary: "; showbits(k); cout << endl; return 0; }
true
4b3b6cf508de9e84c7080b2d62b8a078380696a3
C++
longfangsong/glpkxx
/test.cpp
UTF-8
672
2.5625
3
[]
no_license
#include "glpkxx.h" #include <iostream> using namespace std; int main() { LinearProblem problem; Variable x1("x1"), x2("x2"), x3("x3"); Variable a("x1"); x1 >= 0; x2 >= 0; x3 >= 0; problem.addConstraint(x1 + x2 + x3 <= 100); problem.addConstraint(10 * x1 + 4 * x2 + 5 * x3 <= 600); problem.addConstraint(2 * x1 + 2 * x2 + 6 * x3 <= 200); pair<double, map<Variable,double> > result = problem.maximize(10 * x1 + 6 * x2 + 4 * x3); cout << result.first << endl; // 733.333 cout << result.second[x1] << endl; // 33.333 cout << result.second[x2] << endl; // 66.667 cout << result.second[x3] << endl; // 0 return 0; }
true
2313163cf063cc25dd9df91b2785c0112027d8ff
C++
asifbux/Cplusplus_Project
/ENSF_607_Project/CornerCut.cpp
UTF-8
1,479
2.953125
3
[]
no_license
// // CornerCut.cpp // ENSF_607_Project // // Created by Computer on 2020-04-06. // Copyright © 2020 Asif. All rights reserved. // #include "CornerCut.hpp" #include <iostream> #include "cmath" using namespace std; CornerCut::CornerCut(double x, double y, double width, double length, double radius, const char* name): Circle(x, y, radius, name), Rectangle(x, y, width, length, name), Shape(x, y, name) { if(radius > width) { cout<< "Error with CornerCut, radius must be less than or equal to width"<<endl; exit(0); } } //CornerCut::CornerCut( const CornerCut& source): Circle(source),Rectangle(source), Shape(source) //{ // //} CornerCut& CornerCut:: operator = (const CornerCut& rhs) { if( this != &rhs) { destroy(); copy(rhs); side_a = rhs.getSideA(); side_b = rhs.getSideB(); radius = rhs.getRadius(); } return *this; } double CornerCut::area() { return abs((Circle::area()/4) - Rectangle::area()); } double CornerCut::perimeter() { return abs(((2* Circle::getRadius()) - (Circle::perimeter()/4)) - Rectangle::perimeter()); } void CornerCut::display() { cout << "\nCornerCut Name: "<< shapeName << endl; origin.display(); cout << "Width: " << getSideA() << endl; cout << "Length: " << getSideB() << endl; cout << "Radius of the cut: "<< getRadius()<< endl; } CornerCut::~CornerCut() { cout << "Called CornerCut Destructor: " << shapeName << endl; }
true