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
1b569208384eb3df47a44bc5686924d0c56a232f
C++
MikeGus/TP_alg
/mod2/3/heap_sort_local/main.cpp
UTF-8
5,505
3.40625
3
[]
no_license
#include <iostream> #include <assert.h> //3_1. Реклама. //В супермаркете решили оптимизировать показ рекламы. Известно расписание прихода и ухода //покупателей (два целых числа). Каждому покупателю необходимо показать минимум 2 рекламы. //Рекламу можно транслировать только в целочисленные моменты времени. Покупатель может //видеть рекламу от момента прихода до момента ухода из магазина. //В каждый момент времени может показываться только одна реклама. Считается, что реклама //показывается мгновенно. Если реклама показывается в момент ухода или прихода, то считается, //что посетитель успел её посмотреть. Требуется определить минимальное число показов рекламы. struct Customer { int in; int out; int length(); friend std::istream& operator>>(std::istream& input, Customer& data); friend std::ostream& operator<<(std::ostream& output, Customer& data); bool operator<(const Customer& other) const; bool operator>(const Customer& other) const; }; int Customer::length() { return out - in; } std::istream& operator>>(std::istream& input, Customer& data) { input >> data.in >> data.out; return input; } std::ostream& operator<<(std::ostream& output, Customer& data) { output << data.in << " " << data.out << std::endl; return output; } bool Customer::operator<(const Customer& other) const { if (out != other.out) { return out < other.out; } else { return in > other.in; } } bool Customer::operator>(const Customer& other) const { if (out != other.out) { return out > other.out; } else { return in < other.in; } } //functions for work with array namespace my { template<class T> void read_array(T* array, size_t size, std::istream& input) { for (size_t i = 0; i < size; ++i) { input >> array[i]; } } template<class T> void print_array(std::ostream& output, T* array, size_t size) { for (size_t i = 0; i < size; ++i) { output << array[i]; } } template<class T> void copy(T* dest, T* src, size_t size) { for (size_t i = 0; i < size; ++i) { dest[i] = src[i]; } } template<class T> void swap(T& dest, T& src) { T tmp = src; src = dest; dest = tmp; } template<class T> void resize(T*& array, size_t size, const float mult) { size_t new_size = size * mult; T* new_array = new T[new_size]; my::copy(new_array, array, size); delete[] array; array = new_array; } } template<class T> void sift_down(T* data, size_t size, size_t pos) { size_t left = 2 * pos + 1; size_t right = 2 * pos + 2; size_t largest = pos; if (left < size && data[left] > data[pos]) { largest = left; } if (right < size && data[right] > data[largest]) { largest = right; } if (largest != pos) { my::swap(data[pos], data[largest]); sift_down(data, size, largest); } } template<class T> void sift_up(T* data, size_t size, int pos) { while (pos > 0) { int parent = (pos - 1) / 2; if (data[pos] <= data[parent]) { return; } my::swap(data[pos], data[parent]); pos = parent; } } template<class T> void build(T* data, size_t size) { for (int i = (int)size / 2 - 1; i >= 0; --i) { sift_down(data, size, i); } } template<class T> void add(T& elem, T* data, size_t& size) { my::resize(data, size, size + 1); data[size] = elem; sift_up(data, size, size); size++; } template<class T> void sort(T* data, size_t size) { assert(size); while (size) { size--; my::swap(data[size], data[0]); sift_down(data, size, 0); } } size_t get_result(Customer* data, size_t size) { // data is sorted by time out // data with equal time in is sorted by time in //empty array if (size == 0) { return 0; } //not empty array size_t result = 2; //place two points int right_point = data[0].out; int left_point = right_point - 1; for (size_t pos = 1; pos != size; ++pos) { //if both points inside if (left_point >= data[pos].in && right_point <= data[pos].out) { } //if only one point inside else if (right_point >= data[pos].in && right_point <= data[pos].out) { left_point = right_point; right_point = data[pos].out; result += 1; } //if no points inside else { right_point = data[pos].out; left_point = right_point - 1; result += 2; } } return result; } int main(void) { size_t number = 0; std::cin >> number; if (number < 1) { std::cout << 0; return 0; } Customer* data = new Customer[number]; my::read_array(data, number, std::cin); build(data, number); sort(data, number); size_t result = get_result(data, number); std::cout << result; delete[] data; return 0; }
true
88862d0eda763cdb80784923e77c214442e7f879
C++
Wunder9l/algorithms
/annealing_simulation/cpp/annealing.h
UTF-8
2,159
3.140625
3
[]
no_license
#pragma once #include <functional> #include <random> #include <math.h> template<class TState> class IAnnealingSimulator { public: virtual double EnergyCallback(const TState &state) = 0; virtual TState NextStateCallback(const TState &state) = 0; virtual double TemperatureCallback(double curTemperature, uint64_t iteration) = 0; }; template<class TState> class Annealing { public: using OnIterationCallback = std::function<void(uint64_t i, const TState& state, double energy, double temperature)>; explicit Annealing(IAnnealingSimulator<TState>& simulator) : Simulator(simulator) { std::random_device rd; Generator = std::mt19937(rd()); } std::pair<TState, double> Run(double startTemperature, double endTemperature, const TState &startState, uint64_t maxIterations = 1000000, const OnIterationCallback *callback = nullptr) { double t = startTemperature; TState state = startState; for (uint64_t i = 0; i < maxIterations && t > endTemperature; ++i) { auto nextState = Simulator.NextStateCallback(state); double prevEnergy = Simulator.EnergyCallback(state); double nextEnergy = Simulator.EnergyCallback(nextState); if (DoStateChange(prevEnergy, nextEnergy, t)) { state = nextState; prevEnergy = nextEnergy; } t = Simulator.TemperatureCallback(t, i); if (callback) { (*callback)(i, state, prevEnergy, t); } } return std::make_pair(state, Simulator.EnergyCallback(state)); } private: bool DoStateChange(double prevEnergy, double nextEnergy, double temperature) { if (prevEnergy > nextEnergy) { return true; } else { double probability = exp((prevEnergy - nextEnergy) / temperature); return Distribution(Generator) <= probability; } } IAnnealingSimulator<TState>& Simulator; std::mt19937 Generator; std::uniform_real_distribution<double> Distribution = std::uniform_real_distribution<double> (0.0,1.0); };
true
163409d572c1872473f7150577337af4682aff10
C++
WPI-NASA-SRC-P2/capricorn_competition_round
/operations/src/clients/navigation_vision_client.cpp
UTF-8
2,488
2.6875
3
[]
no_license
/* Author BY: Mahimana Bhatt Email: mbhatt@wpi.edu TEAM CAPRICORN NASA SPACE ROBOTICS CHALLENGE This ros node calls an actionlib to take the specified robot near to the given target. This code does not wait for getting the actionlib finished with the task, just sends the goal (waits if server is not available) to actionlib and exits. Command Line Arguments Required: 1. robot_name: eg. small_scout_1, small_excavator_2 2. target object: it can be any object detection class eg. hauler, excavator, scout, processingPlant, repairStation, furnace, hopper, all object detection classes are given in COMMON_NAMES */ #include <operations/NavigationVisionAction.h> // Note: "Action" is appended #include <actionlib/client/simple_action_client.h> #include <utils/common_names.h> typedef actionlib::SimpleActionClient<operations::NavigationVisionAction> g_client; int main(int argc, char **argv) { if (argc < 2) { ROS_ERROR_STREAM("This node must be launched with the robotname and the target object detection class that you want to go passed asfirst and second command line arguments!"); return -1; } std::string robot_name(argv[1]); ros::init(argc, argv, robot_name + COMMON_NAMES::NAVIGATION_VISION_CLIENT_NODE_NAME); // please launch from capricorn namespace g_client client(robot_name + COMMON_NAMES::NAVIGATION_VISION_ACTIONLIB, true); client.waitForServer(); operations::NavigationVisionGoal goal; // desired target object, any object detection class goal.desired_object_label = std::string(argv[2]); goal.mode = std::stoi(argv[3]); geometry_msgs::PoseStamped zero_point; zero_point.pose.position.x = std::stoi(argv[4]); zero_point.pose.position.y = std::stoi(argv[5]); zero_point.header.frame_id = "map"; goal.goal_loc = zero_point; client.sendGoal(goal); bool finished_before_timeout = client.waitForResult(ros::Duration(1.0)); // client.cancelGoal(); if (finished_before_timeout) { actionlib::SimpleClientGoalState state = client.getState(); operations::NavigationVisionResultConstPtr result = client.getResult(); if (result->result == COMMON_NAMES::COMMON_RESULT::INVALID_GOAL) { ROS_INFO("Invalid Object Detection Class or Cannot go to the class"); } ROS_INFO("Action finished: %s", state.toString().c_str()); return 0; } ROS_INFO("Current State: %s\n", client.getState().toString().c_str()); return 0; }
true
2d477bbc4bb192436b724e2516f154b097ca8fe7
C++
quedlin/DataFileStats
/main.cpp
UTF-8
2,985
3.390625
3
[]
no_license
/** DataFileStats main.cpp Purpose: Checks a flat data file, and writes out some statistics to make database import somewhat easier. @author Quedlin @version 1.0 2018.03.23. */ #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <iterator> using namespace std; template<typename Out> void split(const std::string &s, char delim, Out result) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { *(result++) = item; } } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, std::back_inserter(elems)); return elems; } int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "Usage: \t" << argv[0] << " FILENAME DELIMETER" << std::endl; std::cerr << "e.g.:\t" << argv[0] << " FILENAME ," << std::endl; std::cerr << " or:\t" << argv[0] << " FILENAME ;" << std::endl; std::cerr << " or:\t" << argv[0] << " FILENAME \\t" << std::endl; std::cerr << " or:\t" << argv[0] << " FILENAME \\space" << std::endl; return 1; } std::string fileName = argv[1]; std::string delimeter = argv[2]; char delimeterChar; if (delimeter.compare("\\t") == 0) delimeterChar = '\t'; if (delimeter.compare("\\space") == 0) //TODO: Rethink this later or something delimeterChar = ' '; else { if (delimeter.length() != 1) { std::cerr << "Invalid delimeter." << std::endl; return 1; } delimeterChar = delimeter.c_str()[0]; } int maxLineLength = 0; int lineCount = 0; std::vector<std::string> headers; std::vector<int> maxFieldSizes = std::vector<int>(); std::ifstream file(fileName); std::string str; while (std::getline(file, str)) { std::vector<std::string> cells = split(str, delimeterChar); if (lineCount == 0) { headers = cells; for (unsigned int i=0; i<headers.size(); i++) { maxFieldSizes.push_back(0); } } else { int lineLength = str.length(); if (lineLength > maxLineLength) maxLineLength = lineLength; for (unsigned int k=0; k<cells.size(); k++) { int cellSize = cells[k].length(); if (maxFieldSizes[k] < cellSize) maxFieldSizes[k] = cellSize; } } lineCount++; } cout << endl; cout << "Line count: " << lineCount << endl; cout << "Maximum line length: " << maxLineLength << endl; cout << "Number of fields: " << headers.size() << endl; cout << endl; for (unsigned int i=0; i<headers.size(); i++) { cout << "field #" << i << " max size: " << maxFieldSizes[i] << "\t(" << headers[i] << ")" << endl; } return 0; }
true
746b5a73010314016b3b1fc1894ac2c132b8cf3a
C++
teemid/Capstan
/include/Capstan/Math/Vector2f.h
UTF-8
3,321
3.25
3
[ "MIT" ]
permissive
#ifndef CAPSTAN_MATH_VECTOR2F_H #define CAPSTAN_MATH_VECTOR2F_H #include "Capstan/Platform/Intrinsics.h" #include "Capstan/Types.h" namespace Capstan { struct Vector2f { union { Real32 data[2]; struct { Real32 x, y; }; struct { Real32 u, v; }; }; Vector2f (void); Vector2f (Real32 x); Vector2f (Real32 x, Real32 y); inline Vector2f operator +(const Vector2f & rhs); inline Vector2f operator -(const Vector2f & rhs); inline Vector2f operator *(const Vector2f & rhs); inline Vector2f operator /(const Vector2f & rhs); inline Vector2f operator +(const Real32 & scalar); inline Vector2f operator -(const Real32 & scalar); inline Vector2f operator *(const Real32 & scalar); inline Vector2f operator /(const Real32 & scalar); inline Bool32 operator ==(const Vector2f & rhs); }; inline Vector2f Normalize (Vector2f & v); inline Real32 LengthSquared (Vector2f & v); inline Real32 Length (Vector2f & v); inline Real32 Dot (Vector2f & v1, Vector2f & v2); inline Real32 Angle (Vector2f & v1, Vector2f & v2); inline Vector2f Lerp (Vector2f & start, Vector2f & end, Real32 t); //==== Implementation begin ====// inline Vector2f Vector2f::operator +(const Vector2f & rhs) { Vector2f v; v.x = x + rhs.x; v.y = y + rhs.y; return v; } inline Vector2f Vector2f::operator -(const Vector2f & rhs) { Vector2f v; v.x = x - rhs.x; v.y = y - rhs.y; return v; } inline Vector2f Vector2f::operator *(const Vector2f & rhs) { Vector2f v; v.x = x * rhs.x; v.y = y * rhs.y; return v; } inline Vector2f Vector2f::operator /(const Vector2f & rhs) { Vector2f v; v.x = x / rhs.x; v.y = y / rhs.y; return v; } inline Bool32 Vector2f::operator ==(const Vector2f & rhs) { return (x == rhs.x && y == rhs.y); } inline Vector2f Vector2f::operator +(const Real32 & scalar) { return Vector2f(x + scalar, y + scalar); } inline Vector2f Vector2f::operator -(const Real32 & scalar) { return Vector2f(x - scalar, y - scalar); } inline Vector2f Vector2f::operator *(const Real32 & scalar) { return Vector2f(x * scalar, y * scalar); } inline Vector2f Vector2f::operator /(const Real32 & scalar) { return Vector2f(x / scalar, y / scalar); } inline Real32 LengthSquared (Vector2f & v) { return v.x * v.x + v.y * v.y; } inline Real32 Length (Vector2f & v) { return SquareRoot(LengthSquared(v)); } inline Vector2f Normalize (Vector2f & v) { return v / Length(v); } inline Real32 Dot (Vector2f & v1, Vector2f & v2) { return v1.x * v2.x + v1.y * v2.y; } inline Real32 Angle (Vector2f & v1, Vector2f & v2) { return Cos(Dot(v1, v2) / Length(v1) * Length(v2)); } inline Vector2f Lerp (Vector2f & start, Vector2f & end, Real32 t) { return start * (1.0f - t) + end * t; } //==== Implementation end ====// } #endif
true
df25b41d8f3067c64cf08f1550eb34fc3d7733f8
C++
Hollbrok/Akinator
/Akinator/tree_func.cpp
WINDOWS-1251
10,146
3.015625
3
[ "MIT" ]
permissive
#include "tree.h" tree_element::tree_element(data_type data, tree_element* prev, tree_element* left, tree_element* right) : data_(data), prev_(prev), left_(left), right_(right) { assert(this && "You passed nullptr to list_elem construct"); } tree_element::~tree_element() { assert(this && "You passed nullptr to ~tree_element"); data_ = POISON; prev_ = nullptr; left_ = nullptr; right_ = nullptr; if (user_data_) { delete[] user_data_; user_data_ = nullptr; } } tree::tree(const char* name) : cur_size_(0), error_state_(0), name_(name), root_(nullptr), buffer_(nullptr) { assert(this && "You passed nullptr to constructor"); assert(name && "You need to pass name"); } tree::~tree() { assert(this && "nullptr in desctructor"); assert(root_); if (root_) root_->free_all(); if (buffer_) { delete[] buffer_; buffer_ = nullptr; } cur_size_ = -1; error_state_ = -1; name_ = nullptr; root_ = nullptr; } void tree_element::free_all() { assert(this); if (get_left()) left_->free_all(); if (get_right()) right_->free_all(); if (user_data_) delete[] user_data_; if (this) free(this); return; } tree_element* tree::add_to_left(tree_element* x, data_type number) { assert(this && "You passed nullptr tree"); tree_element* tmp = new tree_element; assert(tmp && "Can't calloc memory for tree_element"); if((x == nullptr) && (cur_size_ == 0)) { root_ = tmp; tmp->set_prev(x); tmp->set_right(nullptr); tmp->set_left(nullptr); tmp->set_data(number); cur_size_++; } else if(cur_size_ && tmp) { tmp->set_prev(x); tmp->set_right(nullptr); tmp->set_left(nullptr); tmp->set_data(number); cur_size_++; x->set_left(tmp); } else printf("You must pass x\n"); return tmp; } tree_element* tree::add_to_right(tree_element* x, data_type number) { assert(this && "You passed nullptr tree"); tree_element* tmp = new tree_element; assert(tmp && "Can't calloc memory for tree_element"); if((x == nullptr) && (cur_size_ == 0)) { root_ = tmp; tmp->set_prev(x); tmp->set_right(nullptr); tmp->set_left(nullptr); tmp->set_data(number); cur_size_++; } else if(cur_size_) { tmp->set_prev(x); tmp->set_right(nullptr); tmp->set_left(nullptr); tmp->set_data(number); x->set_right(tmp); cur_size_++; } else printf("You must pass x\n"); return tmp; } void tree::print_tree_info() const { graphviz_dump("dump.dot"); system("iconv.exe -t UTF-8 -f CP1251 < dump.dot > dump_temp.dot"); system("dot dump_temp.dot -Tpdf -o dump.pdf"); system("del dump.dot"); system("ren dump_temp.dot dump.dot"); system("dump.pdf"); return; } void tree::graphviz_dump(const char* dumpfile_name) const { assert(dumpfile_name && "You passed nullptr dumpfile_name"); FILE* dump = fopen(dumpfile_name, "wb"); assert(dump && "Can't open dump.dot"); fprintf(dump, "digraph %s {\n", name_); fprintf(dump, "node [color = Red, fontname = Courier, style = filled, shape=record, fillcolor = purple]\n"); fprintf(dump, "edge [color = Blue, style=dashed]\n"); tree_element* tmp = root_; print_all_elements(tmp, dump); fprintf(dump, "}\n"); fclose(dump); return; } void tree::show_tree() const { graphviz_beauty_dump("beauty_tree.dot"); system("iconv.exe -t UTF-8 -f CP1251 < beauty_tree.dot > beauty_tree_temp.dot"); system("dot beauty_tree_temp.dot -Tpdf -o beauty_dump.pdf"); system("del beauty_tree.dot"); system("ren beauty_tree_temp.dot beauty_tree.dot"); system("beauty_dump.pdf"); return; } void tree::graphviz_beauty_dump(const char* dumpfile_name) const { assert(dumpfile_name && "You passed nullptr dumpfile_name"); FILE* dump = fopen(dumpfile_name, "wb"); assert(dump && "Can't open dump.dot"); fprintf(dump, "digraph %s {\n", name_); fprintf(dump, "node [color = Red, fontname = Courier, style = filled, shape=ellipse, fillcolor = purple]\n"); fprintf(dump, "edge [color = Blue, style=dashed]\n"); tree_element* root = root_; print_all_elements_beauty(root, dump); fprintf(dump, "}\n"); fclose(dump); return; } void tree::fill_tree(const char* name_file) { assert(this && "you passed nullptr to fill_tree"); assert(name_file && "U need to pas FILE* database"); buffer_ = make_buffer(name_file); char* copy_of_buffer = buffer_; while (*buffer_ != '['); buffer_++; root_ = fill_root(); if (root_) build_prev_connections(root_); buffer_ = copy_of_buffer; return; } void tree_element::build_prev_connections(tree_element* root) { assert(root); if(root->get_right()) { if( ((root->get_right())->get_left() == nullptr) && ((root->get_right())->get_right() == nullptr) ) (root->get_right())->set_prev(root); else { (root->get_right())->set_prev(root); build_prev_connections(root->get_right()); } } if(root->get_left()) { if( ((root->get_left())->get_left() == nullptr) && ((root->get_left())->get_right() == nullptr) ) (root->get_left())->set_prev(root); else { (root->get_left())->set_prev(root); build_prev_connections(root->get_left()); } } } tree_element* tree::fill_root() { while(isspace(*buffer_)) buffer_++; if (*buffer_ == '[') buffer_++; while(isspace(*buffer_)) buffer_++; tree_element* tmp_element = new tree_element; assert(tmp_element && "Can't calloc mempry for tmp"); if((*buffer_ == '`') || (*buffer_ == '?')) { buffer_++; int lenght = 0; while((*buffer_ != '?') && (*buffer_ != '`')) { lenght++; buffer_++; } buffer_ -= lenght; tmp_element->data_ = buffer_; tmp_element->length_ = lenght; buffer_ += lenght; tmp_element->set_left(nullptr); tmp_element->set_right(nullptr); tmp_element->set_prev(nullptr); while(isspace(*buffer_)) buffer_++; if(*buffer_ == '?') { buffer_++; tmp_element->set_left(fill_root()); tmp_element->set_right(fill_root()); } } buffer_++; while(isspace(*buffer_)) buffer_++; if (*buffer_ == ']') { buffer_++; return tmp_element; } else { printf("Something bad..\n"); return nullptr; } } void print_all_elements(tree_element* tmp, FILE* dump) { assert(tmp && "tmp is nullptr in print_all_elements"); if (tmp->get_right()) { print_all_elements(tmp->get_right(), dump); fprintf(dump, "\"%p\" -> \"%p\" [label=\"\", fontcolor=darkblue]\n", tmp, tmp->get_right()); fprintf(dump, "\"%p\" -> \"%p\" [label=\"\", fontcolor=darkblue]\n", tmp->get_right(), (tmp->get_right())->get_prev()); } if (tmp->get_left()) { print_all_elements(tmp->get_left(), dump); fprintf(dump, "\"%p\" -> \"%p\" [label=\"\", fontcolor=darkblue]\n", tmp, tmp->get_left()); fprintf(dump, "\"%p\" -> \"%p\" [label=\"\", fontcolor=darkblue]\n", tmp->get_left(), (tmp->get_left())->get_prev()); } if ((tmp->get_right() == nullptr) && (tmp->get_left() == nullptr)) fprintf(dump, "\"%p\" [label = \"<f0> value = [%.*s]|{<f1> left| <here> prev| right}| {<f2> [%p]| [%p]| [%p]}\",style = filled, fillcolor = lightgreen] \n", tmp, tmp->length_, tmp->non_const_get_data(), tmp->get_left(), tmp->get_prev(), tmp->get_right()); else if (tmp->get_prev() == nullptr) fprintf(dump, "\"%p\" [label = \"{<f0> value = [%.*s] |<here> [%p]}|{<f1> right| <here> prev| left}| {<f2> [%p]| [%p]| [%p]}\",style = filled, fillcolor = red] \n", tmp, tmp->length_, tmp->non_const_get_data(), tmp, tmp->get_left(), tmp->get_prev(), tmp->get_right()); else fprintf(dump, "\"%p\" [label = \"{<f0> value = [%.*s] |<here> [%p]}|{<f1> right| <here> prev| left}| {<f2> [%p]| [%p]| [%p]}\",style = filled, fillcolor = purple] \n", tmp, tmp->length_, tmp->non_const_get_data(), tmp, tmp->get_left(), tmp->get_prev(), tmp->get_right()); return; } void print_all_elements_beauty(tree_element* tmp, FILE* dump) { assert(tmp && "tmp is nullptr in print_all_elements"); if (tmp->get_right()) { print_all_elements_beauty(tmp->get_right(), dump); fprintf(dump, "\"%p\" -> \"%p\" [label=\"\", fontcolor=darkblue]\n", tmp, tmp->get_right()); } if (tmp->get_left()) { print_all_elements_beauty(tmp->get_left(), dump); fprintf(dump, "\"%p\" -> \"%p\" [label=\"\", fontcolor=darkblue]\n", tmp, tmp->get_left()); } if ((tmp->get_right() == nullptr) && (tmp->get_left() == nullptr)) fprintf(dump, "\"%p\" [label = \"%.*s\",style = filled, fillcolor = lightgreen] \n", tmp, tmp->length_, tmp->non_const_get_data()); else if (tmp->get_prev() == nullptr) fprintf(dump, "\"%p\" [label = \"%.*s\",style = filled, fillcolor = red] \n", tmp, tmp->length_, tmp->non_const_get_data()); else fprintf(dump, "\"%p\" [label = \"%.*s\",style = filled, fillcolor = purple] \n", tmp, tmp->length_, tmp->non_const_get_data()); return; } tree_element* create_root(char* data, tree_element* left, tree_element* right, tree_element* prev) { tree_element* root = new tree_element; root->set_left(left); if (left) left->set_prev(root); root->set_right(right); if (right) right->set_prev(root); root->set_data(data); root->set_prev(prev); root->user_length_ = strlen(root->data_); root->length_ = root->user_length_; return root; }
true
53eb3ecca8f1ce1169cc0faa0ce275dd12d85c00
C++
zxycode007/Sapphire
/SapphireBase/SapphireSSkinMeshBuffer.h
GB18030
9,610
2.546875
3
[]
no_license
#ifndef _SAPPHIRE_SSKIN_MESH_BUFFER_ #define _SAPPHIRE_SSKIN_MESH_BUFFER_ #include "SapphirePrerequisites.h" #include "SapphireIMeshBuffer.h" #include "SapphireSVertex.h" namespace Sapphire { //! һʱ̶S3DVertex2TCoords, S3DVertex S3DVertexTangents֮ѡ񻺳񻺳 struct SSkinMeshBuffer : public IMeshBuffer { //! ĬϵĹ SSkinMeshBuffer(E_VERTEX_TYPE vt = EVT_STANDARD) : ChangedID_Vertex(1), ChangedID_Index(1), VertexType(vt), MappingHint_Vertex(EHM_NEVER), MappingHint_Index(EHM_NEVER), BoundingBoxNeedsRecalculated(true) { //#ifdef _DEBUG // setDebugName("SSkinMeshBuffer"); //#endif } //! ȡIJ virtual const SMaterial& getMaterial() const { return Material; } //! ȡIJ virtual SMaterial& getMaterial() { return Material; } //! ȡı׼ virtual S3DVertex *getVertex(UINT32 index) { switch (VertexType) { case EVT_2TCOORDS: return (S3DVertex*)&Vertices_2TCoords[index]; case EVT_TANGENTS: return (S3DVertex*)&Vertices_Tangents[index]; default: return &Vertices_Standard[index]; } } //! ȡָ virtual const void* getVertices() const { switch (VertexType) { case EVT_2TCOORDS: return Vertices_2TCoords.cbegin()._Ptr; case EVT_TANGENTS: return Vertices_Tangents.cbegin()._Ptr; default: return Vertices_Standard.cbegin()._Ptr; } } //! ȡָ virtual void* getVertices() { switch (VertexType) { case EVT_2TCOORDS: return Vertices_2TCoords.begin()._Ptr; case EVT_TANGENTS: return Vertices_Tangents.begin()._Ptr; default: return Vertices_Standard.begin()._Ptr; } } //! ȡ virtual UINT32 getVertexCount() const { switch (VertexType) { case EVT_2TCOORDS: return Vertices_2TCoords.size(); case EVT_TANGENTS: return Vertices_Tangents.size(); default: return Vertices_Standard.size(); } } //! ȡ񻺳е /** \return Index type of this buffer. */ virtual E_INDEX_TYPE getIndexType() const { return EIT_16BIT; } //! ȡָ virtual const UINT16* getIndices() const { return Indices.begin()._Ptr; } //! ȡָ virtual UINT16* getIndices() { return Indices.begin()._Ptr; } //! ȡС virtual UINT32 getIndexCount() const { return Indices.size(); } //! ȡײ virtual const AxisAlignedBox& getBoundingBox() const { return BoundingBox; } //! ײ virtual void setBoundingBox(const AxisAlignedBox& box) { BoundingBox = box; } //! ¼AABB virtual void recalculateBoundingBox() { if (!BoundingBoxNeedsRecalculated) return; BoundingBoxNeedsRecalculated = false; switch (VertexType) { case EVT_STANDARD: { if (Vertices_Standard.empty()) BoundingBox.reset(Vector3(0, 0, 0)); else { BoundingBox.reset(Vertices_Standard[0].Pos); for (UINT32 i = 1; i<Vertices_Standard.size(); ++i) BoundingBox.addInternalPoint(Vertices_Standard[i].Pos); } break; } case EVT_2TCOORDS: { if (Vertices_2TCoords.empty()) BoundingBox.reset(Vector3(0, 0, 0)); else { BoundingBox.reset(Vertices_2TCoords[0].Pos); for (UINT32 i = 1; i<Vertices_2TCoords.size(); ++i) BoundingBox.addInternalPoint(Vertices_2TCoords[i].Pos); } break; } case EVT_TANGENTS: { if (Vertices_Tangents.empty()) BoundingBox.reset(Vector3(0, 0, 0)); else { BoundingBox.reset(Vertices_Tangents[0].Pos); for (UINT32 i = 1; i<Vertices_Tangents.size(); ++i) BoundingBox.addInternalPoint(Vertices_Tangents[i].Pos); } break; } } } //! ȡ virtual E_VERTEX_TYPE getVertexType() const { return VertexType; } //! ȡ virtual void convertTo2TCoords() { if (VertexType == EVT_STANDARD) { for (UINT32 n = 0; n<Vertices_Standard.size(); ++n) { S3DVertex2TCoords Vertex; Vertex.Color = Vertices_Standard[n].Color; Vertex.Pos = Vertices_Standard[n].Pos; Vertex.Normal = Vertices_Standard[n].Normal; Vertex.TCoords = Vertices_Standard[n].TCoords; Vertices_2TCoords.push_back(Vertex); } Vertices_Standard.clear(); VertexType = EVT_2TCOORDS; } } //! תΪ߶ virtual void convertToTangents() { if (VertexType == EVT_STANDARD) { for (UINT32 n = 0; n<Vertices_Standard.size(); ++n) { S3DVertexTangents Vertex; Vertex.Color = Vertices_Standard[n].Color; Vertex.Pos = Vertices_Standard[n].Pos; Vertex.Normal = Vertices_Standard[n].Normal; Vertex.TCoords = Vertices_Standard[n].TCoords; Vertices_Tangents.push_back(Vertex); } Vertices_Standard.clear(); VertexType = EVT_TANGENTS; } else if (VertexType == EVT_2TCOORDS) { for (UINT32 n = 0; n<Vertices_2TCoords.size(); ++n) { S3DVertexTangents Vertex; Vertex.Color = Vertices_2TCoords[n].Color; Vertex.Pos = Vertices_2TCoords[n].Pos; Vertex.Normal = Vertices_2TCoords[n].Normal; Vertex.TCoords = Vertices_2TCoords[n].TCoords; Vertices_Tangents.push_back(Vertex); } Vertices_2TCoords.clear(); VertexType = EVT_TANGENTS; } } //! ضiλ virtual const Vector3& getPosition(UINT32 i) const { switch (VertexType) { case EVT_2TCOORDS: return Vertices_2TCoords[i].Pos; case EVT_TANGENTS: return Vertices_Tangents[i].Pos; default: return Vertices_Standard[i].Pos; } } //! ضiλ virtual Vector3& getPosition(UINT32 i) { switch (VertexType) { case EVT_2TCOORDS: return Vertices_2TCoords[i].Pos; case EVT_TANGENTS: return Vertices_Tangents[i].Pos; default: return Vertices_Standard[i].Pos; } } //! ضiķ virtual const Vector3& getNormal(UINT32 i) const { switch (VertexType) { case EVT_2TCOORDS: return Vertices_2TCoords[i].Normal; case EVT_TANGENTS: return Vertices_Tangents[i].Normal; default: return Vertices_Standard[i].Normal; } } //! ضiķ virtual Vector3& getNormal(UINT32 i) { switch (VertexType) { case EVT_2TCOORDS: return Vertices_2TCoords[i].Normal; case EVT_TANGENTS: return Vertices_Tangents[i].Normal; default: return Vertices_Standard[i].Normal; } } //! ضi virtual const Vector2& getTCoords(UINT32 i) const { switch (VertexType) { case EVT_2TCOORDS: return Vertices_2TCoords[i].TCoords; case EVT_TANGENTS: return Vertices_Tangents[i].TCoords; default: return Vertices_Standard[i].TCoords; } } //! ضi virtual Vector2& getTCoords(UINT32 i) { switch (VertexType) { case EVT_2TCOORDS: return Vertices_2TCoords[i].TCoords; case EVT_TANGENTS: return Vertices_Tangents[i].TCoords; default: return Vertices_Standard[i].TCoords; } } //! Ӷǰ virtual void append(const void* const vertices, UINT32 numVertices, const UINT16* const indices, UINT32 numIndices) {} //! 񻺳ǰ virtual void append(const IMeshBuffer* const other) {} //! ȡڶ㻺ĵǰӲӳʾ virtual E_HARDWARE_MAPPING getHardwareMappingHint_Vertex() const { return MappingHint_Vertex; } //! ȡڶ㻺ĵǰӲӳʾ virtual E_HARDWARE_MAPPING getHardwareMappingHint_Index() const { return MappingHint_Index; } //! Ӳӳʾ virtual void setHardwareMappingHint(E_HARDWARE_MAPPING NewMappingHint, E_BUFFER_TYPE Buffer = EBT_VERTEX_AND_INDEX) { if (Buffer == EBT_VERTEX) MappingHint_Vertex = NewMappingHint; else if (Buffer == EBT_INDEX) MappingHint_Index = NewMappingHint; else if (Buffer == EBT_VERTEX_AND_INDEX) { MappingHint_Vertex = NewMappingHint; MappingHint_Index = NewMappingHint; } } //! ı־Ӳ virtual void setDirty(E_BUFFER_TYPE Buffer = EBT_VERTEX_AND_INDEX) { if (Buffer == EBT_VERTEX_AND_INDEX || Buffer == EBT_VERTEX) ++ChangedID_Vertex; if (Buffer == EBT_VERTEX_AND_INDEX || Buffer == EBT_INDEX) ++ChangedID_Index; } virtual UINT32 getChangedID_Vertex() const { return ChangedID_Vertex; } virtual UINT32 getChangedID_Index() const { return ChangedID_Index; } //! AABBҪ¼㣬ڸıⶥλú void boundingBoxNeedsRecalculated(void) { BoundingBoxNeedsRecalculated = true; } //߶б std::vector<S3DVertexTangents> Vertices_Tangents; //б std::vector<S3DVertex2TCoords> Vertices_2TCoords; //׼б std::vector<S3DVertex> Vertices_Standard; // std::vector<UINT16> Indices; UINT32 ChangedID_Vertex; UINT32 ChangedID_Index; //ISkinnedMesh::SJoint *AttachedJoint; Matrix4 Transformation; SMaterial Material; E_VERTEX_TYPE VertexType; AxisAlignedBox BoundingBox; // Ӳӳʾ E_HARDWARE_MAPPING MappingHint_Vertex : 3; E_HARDWARE_MAPPING MappingHint_Index : 3; bool BoundingBoxNeedsRecalculated : 1; }; } #endif
true
d9cb2611a98a838bb826b0b00c1d241aaddb970d
C++
lasthopestars/Code-file-uploads
/callByReference.cpp
UTF-8
508
3.453125
3
[]
no_license
#include<iostream> using namespace std; void addOne(int &y) { cout << y << " " << &y << endl; y = y + 1; } //call by value defines a new variable and copies the value in there, //whilst call by reference sends the address itself, so the address is the same //and there is no process of copying the value in. int main() { int x = 5; cout << x << " " << &x << endl; addOne(x);//6-> the x here and the &y has the same address cout << x << " " << &x << endl; return 0; }
true
4fe1cc934117d50d7340e40ca580a38e5d1b651e
C++
lgenet/Sofia
/Resources/UnitTests/lab_10_test.cpp
UTF-8
6,032
3.234375
3
[]
no_license
#include "gtest/gtest.h" #include <iostream> #include <fstream> #include <sstream> #include "lab_for_testing.cpp" using namespace std; class Lab10Test : public ::testing::Test{}; /**************************************** * Utility Functions */ string trim(string s) { int first = 0; int last = s.length(); string temp = ""; for(int i = 0; i < s.length(); i++) { if(s[i] != ' ' && s[i] != '\n' && s[i] != '\t') { first = i; break; } } for(int i = s.length()-1; i >=0; i--) { if(s[i] != ' ' && s[i] != '\n' && s[i] != '\t') { last = i; break; } } for(int i = first; i <= last; i++) { temp+= s[i]; } return temp; } string sanitize(string s) { s = trim(s); for(int i = 0; i < s.length(); i++) { if(s[i] == '\t') s[i] = ' '; } return s; } string sanitizeComma(string s) { s = trim(s); string a =""; for(int i = 0; i < s.length(); i++) { if(s[i] == '\t') a += ' '; else if( s[i] == ',') ; else a += s[i]; } return a; } string sanitizeExtreme(string s) { s = trim(s); string a =""; for(int i = 0; i < s.length(); i++) { if(s[i] == '\t' || s[i] == '\n') a += ' '; else if( s[i] == ',') ; else a += s[i]; } return a; } bool contains(string s1, string s2) { return strstr(s1.c_str(), s2.c_str()); } /************************* * Specific Test Helpers */ int original[6][6] = { {42, 68, 35, 1 , 70, 25}, {79, 59, 63, 65, 6 , 46}, {82, 28, 62, 92, 96, 43}, {28, 37, 92, 5 , 3 , 54}, {93, 83, 22, 17, 19, 96}, {48, 27, 72, 39, 70, 13} }; void primeArrayForTest() { for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) arr[i][j] = original[i][j]; } /**************************************** * Hard Tests */ TEST_F(Lab10Test, test_fill_array) { // Run Test fill(); // Expect for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) EXPECT_EQ(arr[i][j], original[i][j]); } TEST_F(Lab10Test, test_transpose) { // Setup int transposed[6][6] = { {42, 79, 82, 28, 93, 48}, {68, 59, 28, 37, 83, 27}, {35, 63, 62, 92, 22, 72}, {1 , 65, 92, 5 , 17, 39}, {70, 6 , 96, 3 , 19, 70}, {25, 46, 43, 54, 96, 13} }; primeArrayForTest(); // Run Test transpose(); // Expect for(int i = 0; i < 6; i++) for(int j = 0; j < 6; j++) EXPECT_EQ(arr[i][j], transposed[i][j]); } /**************************************** * Soft Tests */ TEST_F(Lab10Test, test_min) { // Setup A testing::internal::CaptureStdout(); primeArrayForTest(); // Run Test find_min(); // Setup B string output = testing::internal::GetCapturedStdout(); std::transform(output.begin(), output.end(), output.begin(), ::tolower); output = sanitize(output); bool hasMin = contains(output, "minimum") || contains(output, "min") || contains(output, "smallest") || contains(output, "lowest") || contains(output, "low")|| contains(output, "smallest"); bool hasValue = contains(output, "1"); bool hasCorrectPos = contains(output, "0") && contains(output, "3"); bool hasAltPos = contains(output, "1") && contains(output, "4"); bool hasPos = hasCorrectPos || hasAltPos; EXPECT_EQ(hasMin, true) << "Low, Lowest, Smallest, Min or Minimum should appear in output"; EXPECT_EQ(hasValue, true) << "Min should have been 1 at pos 0,3 or 1,4. But got\n"<< output; EXPECT_EQ(hasPos, true) << "Min should have been 1 at pos 0,3 or 1,4. But got\n"<< output; } TEST_F(Lab10Test, test_max) { // Setup A testing::internal::CaptureStdout(); primeArrayForTest(); // Run Test find_max(); // Setup B string output = testing::internal::GetCapturedStdout(); std::transform(output.begin(), output.end(), output.begin(), ::tolower); output = sanitize(output); bool hasMax = contains(output, "maximum") || contains(output, "max") || contains(output, "largest") || contains(output, "highest") || contains(output, "high") || contains(output, "biggest"); bool hasValue = contains(output, "96"); bool hasCorrectPos = contains(output, "2") && contains(output, "4"); bool hasAltPos = contains(output, "3") && contains(output, "5"); bool hasPos = hasCorrectPos || hasAltPos; EXPECT_EQ(hasMax, true) << "Biggest, High, Highest, Max or Maximum should appear in output"; EXPECT_EQ(hasValue, true) << "Min should have been 1 at pos 0,3 or 1,4. But got\n"<< output; EXPECT_EQ(hasPos, true) << "Min should have been 1 at pos 0,3 or 1,4. But got\n"<< output; } TEST_F(Lab10Test, test_print_function) { // Setup A testing::internal::CaptureStdout(); string expected [] = { "42\t68\t35\t1\t70\t25", "79\t59\t63\t65\t6\t46", "82\t28\t62\t92\t96\t43", "28\t37\t92\t5\t3\t54", "93\t83\t22\t17\t19\t96", "48\t27\t72\t39\t70\t13" }; // Run Test print(); // Setup B string output = testing::internal::GetCapturedStdout(); std::transform(output.begin(), output.end(), output.begin(), ::tolower); cout << "User Output looks like" << endl; cout << "================================================" << endl; cout << output << endl; cout << "================================================" << endl; for(int i = 0; i < 6; i++) { bool containsLine = contains(output, expected[i]); EXPECT_EQ(containsLine, true); } } TEST_F(Lab10Test, test_coded_by) { // Setup A testing::internal::CaptureStdout(); // Run Test lab(); // Setup B string output = testing::internal::GetCapturedStdout(); std::transform(output.begin(), output.end(), output.begin(), ::tolower); // Expect bool hasCodedBy = contains(output, "coded by") || contains(output,"programmed by") || contains(output,"program was written by") || contains(output,"program created by") || contains(output,"program was made by"); ASSERT_EQ(hasCodedBy, true); } int main(int argsc, char **argv) { ::testing::InitGoogleTest(&argsc, argv); return RUN_ALL_TESTS(); } /*TO Run g++ -std=c++14 -isystem ./googletest/googletest/include -pthread ./lab_9_test.cpp ./libgtest.a */
true
608b53c4a49a7279fd31f83589217bee88873ee8
C++
alexeylive/C-CPP-Homework
/Bus(4homework)/Bus.cpp
UTF-8
3,439
3.375
3
[]
no_license
using namespace std; #include <iostream> #include <cstring> #include <fstream> #include "Bus.hpp" const int Bus::get_busNumber() const{ return this->bus_number; } const int Bus::get_year() const{ return this->year; } const int Bus::get_mileage() const{ return this->mileage; } const int Bus::get_route() const{ return this->route; } const char* Bus::get_surname() const{ return this->surname; } const char* Bus::get_mark_of_bus() const{ return this->mark_of_bus; } const char* Bus::get_initials()const{ return this->initials; } void Bus::show_name() const { cout << "Name is " << get_surname() <<' '<< get_initials() << '.'<<endl; } void Bus::show_mark_of_bus() const { cout << "Mark of bus is " << get_mark_of_bus() << '.'<<endl; } void Bus::show_busNumber() const { cout << "Bus number is " << get_busNumber()<< '.'<<endl; } void Bus::show_year() const { cout << "Production year: " << get_year()<< '.'<<endl; } void Bus::show_mileage() const { cout << "Mileage: " << get_mileage()<< '.'<<endl; } void Bus::show_route() const { cout << "Route: " << get_route()<< '.'<<endl; } void show_buses_over_10000_km(Bus* List, int N){ int i=0; cout << endl << "Mileage over 10000: " << endl; while(i<N){ if(List[i].get_mileage()>10000) List[i].show_busNumber(); i++; } } void show_old_buses(Bus* List, int N){ int i=0; cout << endl << "Older than 10: " << endl; while(i<N){ if((2017-List[i].get_year()) > 10) List[i].show_busNumber(); i++; } } void show_busNumber_for_route(Bus* List,int route_number, int N){ int i=0; cout << endl << "Your numbers of buses: " << endl; while(i<N){ if(List[i].get_route() == route_number) List[i].show_busNumber(); i++; } } Bus::Bus(){ this->bus_number = 0; this->year = 0; this->mileage = 0; this->route = 0; this->surname = NULL; this->mark_of_bus = NULL; this->initials = NULL; } Bus::~Bus(){ delete[] surname; delete[] mark_of_bus; delete[] initials; } Bus::Bus(const Bus& rhs): year(rhs.year), route(rhs.route), mileage(rhs.mileage), bus_number(rhs.bus_number) { if (rhs.surname){ size_t len =strlen(rhs.surname)+1; this->surname = new char[len]; memcpy(this->surname,rhs.surname,len); } if (rhs.mark_of_bus){ size_t len =strlen(rhs.mark_of_bus)+1; this->mark_of_bus = new char[len]; memcpy(this->mark_of_bus,rhs.mark_of_bus,len); } if (rhs.initials){ size_t len =strlen(rhs.initials)+1; this->initials = new char[len]; memcpy(this->initials,rhs.initials,len); } } void Bus::set_busNumber(const int bus_number){ this->bus_number = bus_number; } void Bus::set_year(const int year){ this->year = year; } void Bus::set_mileage(const int mileage){ this->mileage = mileage; } void Bus::set_route(const int route){ this-> route = route; } void Bus::set_mark_of_bus(const char* mark_of_bus) { if (mark_of_bus){ size_t len =strlen(mark_of_bus)+1; this->mark_of_bus = new char[len]; memcpy(this->mark_of_bus,mark_of_bus,len); } } void Bus::set_surname(const char* surname) { if (surname){ size_t len =strlen(surname)+1; this->surname = new char[len]; memcpy(this->surname,surname,len); } } void Bus::set_initials(const char* initials) { if (initials){ size_t len =strlen(initials)+1; this->initials = new char[len]; memcpy(this->initials,initials,len); } }
true
4b89d0f292300f3425cf9e95e7cd8b61c2232657
C++
srirammarisetty19/VAD-Device
/arduino codes/velostat/velostat.ino
UTF-8
554
3.171875
3
[]
no_license
// Analog input pin that the Velostat is connected to const int analogInPin = A0; // value read from the Velostat int sensorValue = 0; void setup() { // initialize serial communications at 9600 bps: Serial.begin(9600); //init Analog Pin as PULLUP //(meaning it sends out voltage) digitalWrite(analogInPin, HIGH); } void loop() { // read the analog in value: sensorValue = analogRead(analogInPin); // print the results to the serial monitor: //Serial.print("sensor = " ); Serial.println(sensorValue); delay(1000); }
true
ff3429c3ef85bcea69308cbae90b470880433749
C++
kunal-Khulbay/My-programming-practice-works
/c++ programs/Dynamic_Constructor.cpp
UTF-8
709
3.953125
4
[]
no_license
/*Author: ALOK KHULBAY. Date:08-09-2020. Purpose:To self learn. Program to read and display Roll No. to illustrate the concept of Dynmaic Constructor. */ #include <iostream> using namespace std; class abc { int rn; float fees; public: abc(int a, float b) { rn = a; fees = b; } abc(abc &m)//Copy Constructor. { rn = m.rn; fees = m.fees; cout << "\n Copy constructor at Work"; } }; int main() { float x, y; cout << "Enter the Roll No of Student"; cin >> x; cout << "\n Enter the fees of Student"; cin >> y; abc m1(x, y); abc m2(m1); cout << "\n Roll no and fees is:" << x << " and " << y << endl; return 0; }
true
ff5d1be1d8ca03b594759e915e4cbee88859f071
C++
Zhao-Michael/CppUtil
/CppUtil/Cpp14.cpp
GB18030
3,492
3.203125
3
[]
no_license
#include <tuple> #include <map> #include <vector> #include <string> #include <iostream> #include <algorithm> #include <memory> using namespace std; /* * C++ 14: ķƵ lambda lambda ʼ new/delete constexpr Ϸɵ λָ ĬϳԱʼľۺࡣ ģ std::make_unique std::shared_timed_mutex std::shared_lock std::integer_sequence std::exchange std::quoted C++ 17: std::any, std::optional, std::string_view, std::apply, polymorphic allocators, searchers. u8 ַ noexcept Ϊϵͳһ µֵ˳ lambda ʽ *this constexpr ڵ constexpr if constexpr lambda ʽ inline ṹ if switch еijʼ ǿƵĸ ʱʵʻ ģ ۵ʽ ģʵƵ auto ռλķģβ ռ 򻯵Ƕռ using ռ䲻ظ ԣ [[fallthrough]] [[nodiscard]] [[maybe_unused]] __has_include */ int DigitSeparators() { int i = 100'000'000; return i; } void BinaryLiterals() { auto i = 0b01'000'111; } auto AutoReturn() { map<string, int> result; return result; } constexpr int Fibonacci(int n) { switch (n) { case 0: return 0; case 1: return 1; default: return Fibonacci(n - 1) + Fibonacci(n - 2); } } void ConstexprInCompile() { static_assert(Fibonacci(10) == 55); // static_assert(Fibonacci(10) == 2); // compile failed } template<typename T> constexpr T maxValue = T(1000); template<> constexpr double maxValue<double> = 2000; template<> constexpr char maxValue<char> = 'a'; void VariableTemplate() { cout << maxValue<int> << endl; cout << maxValue<double> << endl; cout << maxValue<char> << endl; } [[deprecated("This is deprecated")]] void deprecatedFunc() { cout << "deprecated func" << endl; } void StructBinding() { tuple<double, int> G = { 1.3,2 }; auto& [a, b] = G; cout << a << endl; map<int, string> mapA; auto& [i, j] = mapA.insert({ 1,"bd" }); cout << i->first << i->second << j << endl; for (const auto& [i, j] : mapA) { cout << i << j << endl; } } void GenicLambda() { vector<int> lines = { 8, 1,6,7,3,7,9,3,6 }; sort(begin(lines), end(lines), [](const auto& a, const auto& b) { return a < b; }); cout << lines.front() << endl; } void LambdaMove() { auto a = make_unique<int>(1754); auto lambda = [ptr = move(a)]() { cout << *ptr << endl; }; lambda(); if (a == nullptr) { cout << "a is empty" << endl; } } namespace A { namespace B { } } namespace A::B { } void DefineVariableInIfSwith() { string a = "abc123"; if (const auto it = find(a.begin(), a.end(), 'b'); it != end(a)) { cout << "Find : " << *it << endl; } else { cout << "Not Find : " << *it << endl; } switch (int it = 1; it) { case 0: return; case 1: return; default: return; } } template<typename T> auto length(const T& value) { if constexpr (is_integral<T>::value) { return value; } else { return value.length(); } } struct MyClass { static const int sValue; }; inline int const MyClass::sValue = 777; void RunCpp14() { deprecatedFunc(); VariableTemplate(); StructBinding(); GenicLambda(); LambdaMove(); DefineVariableInIfSwith(); int len1 = length(123); int len2 = length(string("abc")); cin.get(); }
true
5f3db7e3be2dbe93afeaba9c897ff59619a7ba4f
C++
kkpattern/practicing
/TopCoder/SRM/565DIV2/500.cc
UTF-8
1,062
2.984375
3
[]
no_license
#include <stdio.h> #include <algorithm> #include <list> #include <map> #include <string> #include <vector> using std::list; using std::map; using std::string; using std::vector; class MonstersValley2 { public: int backTracing(int i) { if (i >= monster_count_) return 0; long long old_scar = scar_; int min_price = 0; if (scar_ < dread_[i]) { scar_ += dread_[i]; min_price = price_[i]+backTracing(i+1); } else { // try bride scar_ += dread_[i]; int bride_price = price_[i]+backTracing(i+1); // try not bride scar_ -= dread_[i]; int not_bride_price = backTracing(i+1); min_price = std::min(bride_price, not_bride_price); } scar_ = old_scar; return min_price; } int minimumPrice(vector <int> dread, vector <int> price) { monster_count_ = dread.size(); scar_ = 0; dread_ = dread; price_ = price; return backTracing(0); } private: int monster_count_; vector<int> dread_; vector<int> price_; long long scar_; }; int main() { return 0; }
true
2d28b6892304bc468b7c4bf8763eb55db4a3bfe6
C++
leonardoAnjos16/Competitive-Programming
/CSES/rectangle_cutting.cpp
UTF-8
639
2.640625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define long long long int vector<vector<int>> memo; int moves(int a, int b) { if (a == b) return 0; int &ans = memo[a][b]; if (~ans) return ans; ans = INT_MAX; for (int i = 1; i < a; i++) ans = min(ans, moves(i, b) + moves(a - i, b) + 1); for (int i = 1; i < b; i++) ans = min(ans, moves(a, i) + moves(a, b - i) + 1); return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int a, b; cin >> a >> b; memo.assign(a + 5, vector<int>(b + 5, -1)); int ans = moves(a, b); cout << ans << "\n"; }
true
45adaa9bd81e11675ec5dbc177ca092238dec322
C++
EldarGiniyatullin/University
/Semester_1/HW_4/Hometask_3/Hometask_3.cpp
UTF-8
2,845
3.3125
3
[]
no_license
#include <stdio.h> #include "polishstack.h" using namespace std; int main() { printf("Enter an infix-Polish-notation-reformed expression "); Stack wareStack; wareStack.first = NULL; char consoleSymbol; bool isZero = false; bool isRight = false; while ((consoleSymbol = getchar()) != '\n' && !isZero && !isRight) { switch(consoleSymbol) { case '+': if (wareStack.first == NULL || wareStack.first->next == NULL) { isRight = true; break; } else { wareStack.first->next->value = wareStack.first->next->value + wareStack.first->value; removeElementStack(wareStack); break; } case '-': if (wareStack.first == NULL || wareStack.first->next == NULL) { isRight = true; break; } else { wareStack.first->next->value = wareStack.first->next->value - wareStack.first->value; removeElementStack(wareStack); break; } case '*': if (wareStack.first == NULL || wareStack.first->next == NULL) { isRight = true; break; } else { wareStack.first->next->value = wareStack.first->next->value * wareStack.first->value; removeElementStack(wareStack); break; } case '/': if (wareStack.first == NULL || wareStack.first->next == NULL) { isRight = true; break; } else { if (wareStack.first->value == 0) { printf("\nDividing by zero!"); isZero = true; break; } else { wareStack.first->next->value = wareStack.first->next->value / wareStack.first->value; removeElementStack(wareStack); break; } } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': addValueStack((int)consoleSymbol - '0', wareStack); break; } } if (wareStack.first->next != NULL) { isRight = true; } if (isRight && !isZero) { printf("\nInvalid transcription"); } if (!isZero && !isRight) { printf("\n=%d", wareStack.first->value); } delete wareStack.first; }
true
aa6180b8d7ae9ec0dd4a6de443e172f631fedaf0
C++
Stazer/beluga
/source/beluga/tls/tls_client.cpp
UTF-8
3,135
2.734375
3
[ "MIT" ]
permissive
#include <beluga/tls/tls_client.hpp> #include <beluga/tls/tls_reader.hpp> beluga::tls_client::record_event::record_event(const tls_record& record): record(record) { } void beluga::tls_client::record_event::set_record(const tls_record& record) { this->record = record; } beluga::tls_record& beluga::tls_client::record_event::get_record() { return record; } const beluga::tls_record& beluga::tls_client::record_event::get_record() const { return record; } beluga::tls_client::handshake_event::handshake_event(const tls_handshake& handshake): handshake(handshake) { } void beluga::tls_client::handshake_event::set_handshake(const tls_handshake& handshake) { this->handshake = handshake; } beluga::tls_handshake& beluga::tls_client::handshake_event::get_handshake() { return handshake; } const beluga::tls_handshake& beluga::tls_client::handshake_event::get_handshake() const { return handshake; } beluga::tls_client::client_hello_event::client_hello_event(const tls_client_hello& client_hello): client_hello(client_hello) { } void beluga::tls_client::client_hello_event::set_client_hello(const tls_client_hello& client_hello) { this->client_hello = client_hello; } beluga::tls_client_hello& beluga::tls_client::client_hello_event::get_client_hello() { return client_hello; } const beluga::tls_client_hello& beluga::tls_client::client_hello_event::get_client_hello() const { return client_hello; } beluga::tls_client::tls_client(boost::asio::ip::tcp::socket& socket): tcp_client(socket) { initialize(); } beluga::tls_client::tls_client(boost::asio::io_service& io_service): tcp_client(io_service) { initialize(); } void beluga::tls_client::initialize() { std::shared_ptr<dynamic_buffer> buffer = std::make_shared<dynamic_buffer>(); this->on_receive.connect ([this, buffer] (tcp_client::receive_event& event) { buffer->insert(buffer->end(), event.get_buffer().begin(), event.get_buffer().end()); while(true) { tls_reader<dynamic_buffer::const_iterator> reader(*buffer); tls_record record; if(reader.read_record(record)) { reader.set_to(reader.get_iterator() + record.get_length()); record_event event(record); on_record(event); switch(record.get_type()) { case tls_record::HANDSHAKE: handle_handshake(reader); break; } buffer->erase(reader.get_from(), reader.get_to()); } else break; } }); } void beluga::tls_client::handle_handshake(tls_reader<dynamic_buffer::const_iterator>& reader) { tls_handshake handshake; if(reader.read_handshake(handshake)) { handshake_event event(handshake); on_handshake(event); switch(handshake.get_type()) { case tls_handshake::CLIENT_HELLO: handle_client_hello(reader); break; } } } void beluga::tls_client::handle_client_hello(tls_reader<dynamic_buffer::const_iterator>& reader) { tls_client_hello client_hello; if(reader.read_client_hello(client_hello)) { client_hello_event event(client_hello); on_client_hello(event); } }
true
46856e0dadec732951f5390cc673efeadda88d8c
C++
Drakula44/neural_network_cpp
/src/node.cpp
UTF-8
478
2.578125
3
[]
no_license
#include "../headers/node.h" #include<bits/stdc++.h> #define e 2.7182818 using namespace std; void node::init(double v1,int n1){ srand(time(NULL)); v=v1; n=n1; for(int i=0;i<=n;i++){ w[i]=rand()/pow(10,8); //cout<<w[i]<<endl; } } double node::activate(double x){ v=1/(1+pow(e,-x));//zasada je sigmoid return v; } const node& node::operator=(const node &p){ if(&p==this) return *this; v=p.v; n=p.n; b=p.b; for(int i=0;i<n;i++){ w[i]=p.w[i]; } return *this; }
true
ef4dbc3459340b7f80a71ca9f3dfc0ce985f3b0d
C++
bityutskiyAO/Misis-C-
/bitytskiy_a_o/prj.labs/queue/queue.h
UTF-8
492
2.96875
3
[]
no_license
#pragma once #ifndef QUEUE #define QUEUE #include <iostream> class Queue { public: Queue() = default; Queue(const int size); Queue(const Queue &rhs); ~Queue(); Queue &operator=(const Queue &rhs); bool isEmpty(); bool isFull(); void push(const int val); int top(); void pop(); std::ostream &writeTo(std::ostream &ostrm) const; private: int *data_{nullptr}; int size_{ 0 }; int i_first{ 0 }; int i_last{ 0 }; }; #endif;
true
63d8a11f269cfb4a6153aa23a037e1579d149114
C++
RPChavan/USC-EE569---Introduction-to-Digital-Image-Processing
/HW2 - Edge, Boundary Detection/Edge detection-Sobel.cpp
UTF-8
7,356
2.9375
3
[]
no_license
#include <stdio.h> #include <iostream> #include <stdlib.h> #include <random> #include <math.h> #include <fstream> #include <string> using namespace std; int main(int argc, char *argv[]) { // Define file pointer and variables FILE *file; int BytesPerPixel; int Row_Size = 321; int Column_Size = 481; // Check for proper syntax if (argc < 3){ cout << "Syntax Error - Incorrect Parameter Usage:" << endl; cout << "program_name input_image.raw output_image.raw [BytesPerPixel = 1] [Size = 256]" << endl; return 0; } // Check if image is grayscale or color if (argc < 4){ BytesPerPixel = 1; // default is grey image } else { BytesPerPixel = atoi(argv[3]); // Check if size is specified if (argc >= 5){ Row_Size = atoi(argv[4]); Column_Size = atoi(argv[4]); } } // Allocate image data array unsigned char Imagedata[Row_Size][Column_Size][3]; // Read image (filename specified by first argument) into image data matrix if (!(file=fopen(argv[1],"rb"))) { cout << "Cannot open file: " << argv[1] <<endl; exit(1); } fread(Imagedata, sizeof(unsigned char), Row_Size*Column_Size*3, file); fclose(file); ///////////////////////// INSERT YOUR PROCESSING CODE HERE ///////////////////////// //Variable declaration unsigned char Gray[Row_Size+4][Column_Size+4][1]; float xmask[9] = {-1.0/4.0, 0, 1.0/4.0, -2.0/4.0, 0, 2.0/4.0, -1.0/4.0, 0, 1.0/4.0}; float ymask[9] = { 1.0/4.0, 2.0/4.0, 1.0/4.0, 0, 0, 0, -1.0/4.0,-2.0/4.0,-1.0/4.0}; short xgradient[Row_Size][Column_Size][1] ; short ygradient[Row_Size][Column_Size][1] ; unsigned char mag[Row_Size][Column_Size][1]; unsigned char normalised_mag[Row_Size][Column_Size][1]; unsigned char normalised_mag_inv[Row_Size][Column_Size][1]; int i, j, k, l, m, n; int varx[9],vary[9]; int Threshold = 70; unsigned char thres_image[Row_Size][Column_Size][1]; for(i = 0; i < Row_Size+4; i++) { for(j = 0; j < Column_Size+4; j++) { Gray[i][j][0] = 0; } } //Coverting the color image into a gray scale image for(i = 2; i < Row_Size+2; i++) { for(j = 2; j < Column_Size+2; j++) { Gray[i][j][0] = (unsigned char)(((int(Imagedata[i-2][j-2][0])+int(Imagedata[i-2][j-2][1])+int(Imagedata[i-2][j-2][2]))/3.0)+0.5) ; } } //Boundary Extension //top rows for(i = 0; i < 2; i++) { for(j = 2; j < Column_Size+2; j++) { Gray[i][j][0] = (unsigned char)Gray[i+2][j][0]; } //cout<<endl; } //bottom rows for(i=Row_Size+2;i<Row_Size+4;i++) { for(j=2;j<Column_Size+2;j++) { Gray[i][j][0] = (Gray[i-2][j][0]); } cout<<endl; } //left columns for(j = 0;j < 2; j++) { for(i = 2;i < Row_Size+2; i++) { Gray[i][j][0] = (unsigned char)Gray[i][j+2][0]; } cout<<endl; } //Right Columns for(j=Column_Size+2;j<Column_Size+4;j++) { for(i=2;i<Row_Size+2;i++) { Gray[i][j][0] = (unsigned char)Gray[i][j-2][0]; } } //top left corner for(i = 0; i<2; i++){ for (j = 0; j<2; j++){ Gray[i][j][0] = Gray[i+2][j+2][0]; } } //top right corner for(i = 0; i<2; i++){ for (j = Column_Size+2; j<Column_Size+4; j++){ Gray[i][j][0] = (unsigned char)Gray[i+2][j-2][0]; } } //bottom left for(i = Row_Size+2; i<Row_Size+4; i++){ for (j = 0; j<2; j++){ Gray[i][j][0] = (unsigned char)Gray[i-2][j+2][0]; } } //bottom right for(i = Row_Size+2; i<Row_Size+4; i++){ for (j = Column_Size+2; j<Column_Size+4; j++){ Gray[i][j][0] = (unsigned char)Gray[i-2][j-2][0]; } } //Finding the x-gradient and y-gradient values for(i = 2; i < Row_Size+2; i++) { j = 2; for(j = 2; j < Column_Size+2; j++) { xgradient[i-2][j-2][0] = 0; ygradient[i-2][j-2][0] = 0; m = 0; k = 0; l = 0; varx[9] = 0; vary[9] = 0; for(k = i-1; k <= i+1; k++) { for(l = j-1; l <= j+1; l++) { varx[m] = float(Gray[k][l][0]) * xmask[m] ; vary[m] = float(Gray[k][l][0]) * ymask[m] ; m++; } } for(m = 0; m < 9; m++) { xgradient[i-2][j-2][0] = xgradient[i-2][j-2][0] + varx[m]; ygradient[i-2][j-2][0] = ygradient[i-2][j-2][0] + vary[m]; } } } //Normalising the x-gradient and y-gradient for(i = 0; i < Row_Size; i++) { for(j = 0; j < Column_Size; j++) { mag[i][j][0] = (unsigned char)( pow( pow ( float ( xgradient[i][j][0] ), 2 ) + pow ( float ( ygradient[i][j][0] ), 2 ),0.5 ) ); } } float minimum = float(mag[0][0][0]); float maximum = float(mag[0][0][0]); for (int i = 0; i < Row_Size; ++i) { for (int j = 0; j < Column_Size ; ++j) { if (mag[i][j][0] < minimum) { minimum = float(mag[i][j][0]); } if (mag[i][j][0] > maximum) { maximum = float(mag[i][j][0]); } } } cout<<maximum<<endl; cout<<minimum<<endl; for(i = 0; i < Row_Size; i++) { for(j = 0; j < Column_Size; j++) { normalised_mag[i][j][0] = (unsigned char) (int(((float(mag[i][j][0])-minimum)/(maximum-minimum))*255)); } } minimum = float(normalised_mag[0][0][0]); maximum = float(normalised_mag[0][0][0]); for (int i = 0; i < Row_Size; ++i) { for (int j = 0; j < Column_Size ; ++j) { if (normalised_mag[i][j][0] < minimum) { minimum = float(normalised_mag[i][j][0]); } if (normalised_mag[i][j][0] > maximum) { maximum = float(normalised_mag[i][j][0]); } } } cout<<maximum<<endl; cout<<minimum<<endl; //Thresholding cdf method int x,r; int freq[256]; float prob[256],cdf[256],cdf255[256]; float tot =0.0; short ***I_new = new short**[Row_Size]; for (i = 0; i < Row_Size; i++) { I_new[i] = new short*[Column_Size]; for (j = 0; j < Column_Size; j++) { I_new[i][j] = new short[1]; } } for(i = 0; i < Row_Size; i++) { for(j = 0; j < Column_Size;j++) { I_new[i][j][0] = short(normalised_mag[i][j][0]); } } for(r = 0; r < 256; r++) { freq[r] = 0; } //thresolding for(i = 0; i < Row_Size; i++) { for(j = 0; j < Column_Size; j++) { x = I_new[i][j][0]; freq[x] = freq[x]+1; } } cout<<endl; for(k = 0; k < 256; k++) { prob[k] = float(freq[k])/float(154401.0); tot = tot+prob[k]; cdf[k] = tot; cout<<k<<"= "; cout<<cdf[k]<<endl; } for(i = 0; i < Row_Size; i++) { for(j = 0; j < Column_Size; j++) { if(short(normalised_mag[i][j][0]) > 55) { thres_image[i][j][0] = (unsigned char)0; } else { thres_image[i][j][0] = (unsigned char)255; } } } ofstream outfile; outfile.open("sobelpig.csv"); for(i=0;i<256;i++) { outfile << i << "," << cdf[i] << std::endl; } outfile.close(); // Write image data (filename specified by second argument) from image data matrix if (!(file=fopen(argv[2],"wb"))) { cout << "Cannot open file: " << argv[2] << endl; exit(1); } fwrite(thres_image, sizeof(unsigned char), Row_Size+4*Column_Size+4*1, file); fclose(file); return 0; }
true
ef42fba9828db39ea450226b1972e51da8e86bd1
C++
nalzok/Cal61CforFun
/CBasics/peek2comp.cpp
UTF-8
851
3.546875
4
[]
no_license
#include <iostream> #include <bitset> using namespace std; int main() { cout << "I can show you 2's complement representation of an integer ^__^ " << endl; int num; while (42) { try { cout << "Give me a number, or press Ctrl+c to exit: " << endl; cin >> num; // poorly considered overflow protection.. if (num > 127 or num < -128) { throw std::invalid_argument( "overflow! " );; } // hard coded length of rep cuz bitset requires constent length.. // feel free to modify this parameter here // Suggestion on how to accept user input will be apprecaited bitset<8> rep(num); cout << " => " << rep << endl; } catch (exception& e) { cout << e.what() << endl; return 1; } } return 0; }
true
088006c960bed8b6dc63a6dafc88e6ee2d0f737e
C++
nnresearcher/LeetCode_Optimal_Solution
/easy/141/C++/快慢指针/141.cpp
UTF-8
942
3.578125
4
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { // judge null pointer input parameter if (head == NULL || head->next == NULL) { return false; } // use fast and slow pointers ListNode *fast = head->next; ListNode *slow = head; // If the fast pointer catches up with the slow pointer, then there is a loop while (fast != slow) { // If the fast pointer is null, there is no ring if (fast->next == NULL || fast->next->next == NULL) { return false; } // The 'fast pointer' takes two steps and the 'slow pointer' takes one step fast = fast->next->next; slow = slow->next; } return true; } };
true
e74389b862c6a8d8f6a3b31bd87523fcef6c2381
C++
defkevin/s16_Independent_Study
/cs104/HW3/SetStr_Test.cpp
UTF-8
726
3.140625
3
[]
no_license
#include "../../test/logging.h" #include "setstr.h" #include <iostream> using namespace std; void print(const SetStr& set) { const string* s = set.first(); while (s != nullptr) { cout << *s << " "; s = set.next(); } cout << endl; } int main() { BEGIN_TESTS(); SetStr set; CHECK_EQ(set.empty(), true); set.insert("pizza"); set.insert("bagel"); set.insert("donut"); set.insert("burger"); set.insert("burger"); CHECK_EQ(set.size(), 4); print(set); set.remove("bagel"); set.remove("fries"); print(set); CHECK_EQ(*set.first(), "pizza"); CHECK_EQ(*set.next(), "donut"); CHECK_EQ(set.exists("bagel"), false); CHECK_EQ(set.exists("burger"), true); CHECK_EQ(set.empty(), false); }
true
e7d97c74d7cdeca8acfde462554017c3973a2bee
C++
PeterMerkert/symphony
/src/Engine/GameObject.cpp
UTF-8
3,983
2.6875
3
[ "MIT" ]
permissive
#include "GameObject.h" #include <glm/gtc/type_ptr.hpp> #include <iostream> #include <string> #include "SymphonyEngine.h" //TO-DO: <algorithm> is required for the correct use of std::remove used in RemoveChild; // find a way to avoid using this. //#include <algorithm> namespace Symphony { GameObject::GameObject() { parent = nullptr; meshRenderer = nullptr; name = "New GameObject"; isEnabled = true; } GameObject::GameObject(Transform & t) : GameObject() { transform = t; } GameObject::~GameObject() { delete meshRenderer; } void GameObject::ModifyMeshRenderer(Mesh* newMesh, Shader* newShader) { if (meshRenderer) { meshRenderer->mesh = newMesh; meshRenderer->shader = newShader; return; } meshRenderer = new MeshRenderer(newMesh, newShader); } void GameObject::Update(float deltaTime) { if (parent) transform.UpdateWorldMatrix(parent->transform.GetWorldMatrix()); else transform.UpdateWorldMatrix(); /*if (meshRenderer && meshRenderer->OkToRender()) { if (SymphonyEngine::GetKeyboard()->GetKeyHold(SDL_SCANCODE_RIGHT)) { glm::vec3 r = glm::vec3(0, 45, 0) * deltaTime; transform.Rotate(r); } else if (SymphonyEngine::GetKeyboard()->GetKeyHold(SDL_SCANCODE_LEFT)) { glm::vec3 r = glm::vec3(0, -45, 0) * deltaTime; transform.Rotate(r); } if (SymphonyEngine::GetKeyboard()->GetKeyHold(SDL_SCANCODE_UP)) { glm::vec3 r = glm::vec3(45, 0, 0) * deltaTime; transform.Rotate(r); } else if (SymphonyEngine::GetKeyboard()->GetKeyHold(SDL_SCANCODE_DOWN)) { glm::vec3 r = glm::vec3(-45, 0, 0) * deltaTime; transform.Rotate(r); } if (SymphonyEngine::GetKeyboard()->GetKeyHold(SDL_SCANCODE_LCTRL)) { glm::vec3 r = glm::vec3(0, 0, 45) * deltaTime; transform.Rotate(r); } else if (SymphonyEngine::GetKeyboard()->GetKeyHold(SDL_SCANCODE_RCTRL)) { glm::vec3 r = glm::vec3(0, 0, -45) * deltaTime; transform.Rotate(r); } if (SymphonyEngine::GetKeyboard()->GetKeyHold(SDL_SCANCODE_R)) { transform.SetRotation(glm::vec3(0, 0, 0)); } } std::cout << std::endl << "Object: " << name << std::endl << transform << std::endl;*/ for (GameObject* go : children) { if (go->isEnabled) go->Update(deltaTime); } } void GameObject::Render(glm::mat4& viewMatrix, glm::mat4& projMatrix) { if (meshRenderer && meshRenderer->OkToRender()) { (*meshRenderer->shader).Use(); glm::mat4 identity; glUniformMatrix4fv((*meshRenderer->shader)("viewMatrix"), 1, GL_FALSE, glm::value_ptr(viewMatrix)); glUniformMatrix4fv((*meshRenderer->shader)("projMatrix"), 1, GL_FALSE, glm::value_ptr(projMatrix)); glUniformMatrix4fv((*meshRenderer->shader)("modelMatrix"), 1, GL_FALSE, glm::value_ptr(transform.GetWorldMatrix())); meshRenderer->Render(); (*meshRenderer->shader).Release(); } for (GameObject* go : children) { if (go->isEnabled) go->Render(viewMatrix, projMatrix); } } /*void GameObject::RemoveChild(GameObject* c) { children.erase(std::remove(children.begin(), children.end(), c), children.end()); }*/ }
true
922793261d7b38308535d2281fb7ee83dea31ec1
C++
amb-lucas/Competitive-Programming
/Number-Theory/Mobius.cpp
UTF-8
488
3.078125
3
[]
no_license
/* N = p1^k1 * p2^k2 * p3^k3 ... pm^km if there's a ki>=2, then M(N) = 0 else if m%2 = 1, then M(N) = -1 // odd number of primes else M(N) = 1 // even number of primes *** M(1) = 1 *** */ for(int i=1; i<LIM; i++){ mobius[i] = 1; primo[i] = 1; } for(int i=2; i<LIM; i++){ if(primo[i]){ for(int j=i; j<LIM; j+=i){ mobius[j] = -mobius[j]; primo[j] = 0; } if(i<=LIM/i){ for(int j=i*i; j<LIM; j+=(i*i)){ mobius[j] = 0; } } } }
true
b10a8a93d813aa1ad25651ca08d0fb4d69b5e884
C++
haru067/AOJ
/Volume0/0027_What_day_is_today.cpp
UTF-8
409
3.046875
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main(){ int mon, day, week; string ans[7] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; int start_week[13] = {-1, 3, 6, 0, 3, 5, 1, 3, 6, 2, 4, 0, 2}; while(cin >> mon >> day){ if(mon==0 && day==0){ break; } week = start_week[mon]+day-1; week %= 7; cout << ans[week] << endl; } return 0; }
true
446982b9ddca4b56793cc2967579bc8039869dd3
C++
ohlionel/codebase
/13307130248/assignment4/B/src/B.cpp
UTF-8
897
2.84375
3
[]
no_license
#include <cmath> #include <cstdio> #include <cstdlib> #include <iostream> #include <algorithm> #include <stack> #include <vector> using namespace std; int N; void work() { vector<int> A, L(N), R(N); stack<int> S; for(int i = 0; i < N; i++) { int tmp; scanf("%d", &tmp); A.push_back(tmp); } long long ans = -1; for(int i = 0; i < N; i++) { while(!S.empty() && A[S.top()] > A[i]) { R[S.top()] = i - 1; S.pop(); } S.push(i); } while(!S.empty()) { R[S.top()] = N - 1; S.pop(); } for(int i = N - 1; i >= 0; i--) { while(!S.empty() && A[S.top()] > A[i]) { L[S.top()] = i + 1; S.pop(); } S.push(i); } while(!S.empty()) { L[S.top()] = 0; S.pop(); } for(int i = 0; i < N; i++) ans = max(ans, (long long)(R[i] - L[i] + 1) * A[i]); printf("%lld\n", ans); } int main() { while(scanf("%d", &N), N != 0) { work(); } return 0; }
true
8ddb87599b6d4f56b41f5a6eda3781248c4a0c88
C++
r-zareba/Cpp-projects
/qt_arduino1/src/main.cpp
UTF-8
1,566
3.296875
3
[]
no_license
#include <Arduino.h> #include "Button.h" static const uint8_t button1Pin = 51; static const uint8_t button2Pin = 52; static const uint8_t button3Pin = 53; static const uint8_t greenLedPin = 8; static const uint8_t yellowLedPin = 9; static const uint8_t redLedPin = 10; Button button1(button1Pin, LOW); Button button2(button2Pin, LOW); Button button3(button3Pin, LOW); unsigned long currentTime; unsigned long printTime; bool ledState = LOW; void writeLeds(char &led, uint8_t &ledBrightness); void setup(){ Serial.begin(9600); pinMode(greenLedPin, OUTPUT); pinMode(yellowLedPin, OUTPUT); pinMode(redLedPin, OUTPUT); } void loop(){ currentTime = millis(); if (button1.beenClicked()) { ledState = !ledState; digitalWrite(greenLedPin, ledState); } // if (button2.isPressed()) digitalWrite(yellowLedPin, HIGH); // else digitalWrite(yellowLedPin, LOW); // if ((currentTime - printTime) > 200){ // Serial.print(button2.isPressed()); // printTime = currentTime; // } if (Serial.available()){ char ledPin = Serial.read(); uint8_t ledBrightness = Serial.parseInt(); writeLeds(ledPin, ledBrightness); } } void writeLeds(char &led, uint8_t &brightness){ Serial.println("\n\nFUNCTION GETS: "); Serial.print(led); Serial.print(brightness); Serial.println("\n\n"); if (led == 'g') analogWrite(greenLedPin, brightness); if (led == 'y') analogWrite(yellowLedPin, brightness); if (led == 'r') analogWrite(redLedPin, brightness); }
true
5c0f0e29fb6db163f14401dad274d4b05b3a52ff
C++
Israelroze/CatchTheFlag
/BoardFileHandler.h
UTF-8
1,031
2.734375
3
[]
no_license
#pragma once #include <list> #include <string> #include <iostream> #include <fstream> #include <ostream> #include "Cell.h" using namespace std; class BoardFileHandler { private: //string Directory; string FileName; string Violations = ""; char Board[13][13] = { ' ' }; int BoardCounters[8] = { 0 }; enum { s1, s2, s3, s7, s8, s9, Aflags, Bflags }; list<Cell> Cells; void UpdateBoardCounters(char ch); Type GetCellType(char ch); void ValidateBoardCounters(); void GetBoard(); void updateBoard(Cell* (&cells)[13][13]); void toString(string & str, char * arr, int size); public: enum class Player { PlayerA }; BoardFileHandler(string _fileName) : FileName(_fileName) {} void ReadBoard(); void WriteBoard(Cell* (&cells)[13][13]); bool IsViolations() { if (Violations != "") return true; return false; } void SetBoard(char _board[13][13]); string GetViolations() const { return Violations; } string GetBoardFileName() const { return FileName; } list<Cell> GetCellList() const { return this->Cells; } };
true
0eef3a3ce0d44e3b44f6c24822ad66928c8c99cc
C++
nghianghesi/mum
/ParallelPrograming/NumericalIntegration/Source.cpp
UTF-8
2,482
2.984375
3
[]
no_license
#include <stdio.h> #include <omp.h> #include <iostream> #include <chrono> #include <string> #include <cstdlib> #include <ctime> #include <thread> #include <windows.h> using namespace std; using namespace std::chrono; double sum; double t,ft; double w; int sequentialtime, paralleltime; #define n 100000000 #define a 0 #define b 2 int i; clock_t ttime; int max_thread_capacity = std::thread::hardware_concurrency(); double f(double x) { return sqrt(4.0 - x*x); } void sequential() { ttime = clock(); sum = 0.0; w = 1.0 * (b - a) / n; t = a; for (i = 1; i < n; i++) { t += w; sum = sum + f(t); /*Add point to sum*/ } sum = sum + (f(a) + f(b)) / 2; sum = w * sum; sequentialtime = clock() - ttime; printf("sequential: result %f, time %d \n", sum, sequentialtime); } void parallel() { ttime = clock(); sum = 0.0; w = 1.0 * (b - a) / n; omp_set_num_threads(max_thread_capacity); #pragma omp parallel reduction(+:sum) { #pragma omp for for (i = 1; i < n; i++) { sum = sum + f(a + w*i); /*Add point to sum*/ } } sum = sum + (f(a) + f(b)) / 2; sum = w * sum; paralleltime = (clock() - ttime); printf("parallel - reduction: result %f, time %d, speed up %f\n", sum, paralleltime, 1.0*sequentialtime/paralleltime); } void parallelCritical() { ttime = clock(); sum = 0.0; w = 1.0 * (b - a) / n; omp_set_num_threads(max_thread_capacity); #pragma omp parallel private (ft) { #pragma omp for for (i = 1; i < n; i++) { ft = f(a + w*i); #pragma omp critical sum = sum + ft; /*Add point to sum*/ } } sum = sum + (f(a) + f(b)) / 2; sum = w * sum; paralleltime = (clock() - ttime); printf("parallel critical: result %f, time %d, speed up %f\n", sum, paralleltime, 1.0*sequentialtime / paralleltime); } void parallelNoPragmaFor() { ttime = clock(); sum = 0.0; w = 1.0 * (b - a) / n; int steps = n / max_thread_capacity; omp_set_num_threads(max_thread_capacity); #pragma omp parallel private (i, t) reduction(+:sum) { for (i = 0, t = a + w*omp_get_thread_num() * steps; i < steps; i++, t+=w) { sum += f(t); /*Add point to sum*/ } #pragma omp sections { #pragma omp section { sum += (f(a) + f(b)) / 2; } } } sum = w * sum; paralleltime = (clock() - ttime); printf("parallel reduction: result %f, time %d, speed up %f\n", sum, paralleltime, 1.0*sequentialtime / paralleltime); } void main() { sequential(); //parallelCritical(); parallelNoPragmaFor(); std::string str; std::getline(std::cin, str); }
true
0c3832341aa22ddaf3a04585ed9f76654b218a44
C++
AloyseTech/TSE
/examples/TSE_SpaceSelector/planet.h
UTF-8
1,466
2.765625
3
[]
no_license
class Planet { public: const uint8_t *datamat; uint8_t height, width; int16_t xPos, yPos; const char* name; uint8_t nameSize; uint16_t colorA; uint16_t colorB; uint16_t colorC; uint16_t colorD; bool vFlip = 0; Planet() {} Planet(int x, int y, int h, int w, String n, const uint8_t * d, int cA, int cB, int cC, int cD) { xPos = x; yPos = y; height = h; width = w; name = n.c_str(); nameSize=n.length(); datamat = d; colorA = cA; colorB = cB; colorC = cC; colorD = cD; } void draw(long xOffset, long yOffset, uint16_t *buffer, int lines) { int curLine = lines - yPos - yOffset; if ( curLine >= 0 && curLine < height ) { for (int x = 0; x < width; ++x) { int tx = x + xPos + xOffset; if ( tx >= 0 && tx < 128 ) { uint8_t col = vFlip ? datamat[(width - (x + 1)) + (curLine * width)] : datamat[x + (curLine * width)]; if ( col == 0x11 ) { buffer[tx] = colorA; } else if ( col == 0x22 ) { buffer[tx] = colorB; } else if ( col == 0x33 ) { buffer[tx] = colorC; } else if ( col == 0x44 ) { buffer[tx] = colorD; } } } } } };
true
2bc7941ee53df9ce1a31826d9079befff8b58f24
C++
petarbratic/Aplikacija-za-prodaju-vozila
/projekat/Korisnik.hpp
UTF-8
2,527
3.1875
3
[]
no_license
#ifndef KORISNIK_HPP_INCLUDED #define KORISNIK_HPP_INCLUDED #include <vector> #include <fstream> #include <string.h> using namespace std; class Korisnik{ private: std::string ime; std::string prezime; bool kupacIliProd; std::string brojTelefona; std::string korisnickoIme; std::string lozinka; public: Korisnik(std::string i, std::string p, bool kilip, std::string broj, std::string username, std::string password){ ime=i; prezime=p; kupacIliProd=kilip; brojTelefona=broj; korisnickoIme=username; lozinka=password; } string getime()const{ return ime; } string getprezime()const{ return prezime; } string getkorisnickoime()const{ return korisnickoIme; } string getlozinka()const{ return lozinka; } void citajTxt(std::string nazivFajla){ std::string linija; std::ifstream fajl (nazivFajla); if (fajl.is_open()){ while ( getline (fajl,linija) ){ std::cout << linija << '\n'; } fajl.close(); } else std::cout << "Neuspesno otvoren fajl"; } void pisiTxt(std::string nazivFajla,const Korisnik& k22,char mode='w'){ std::ofstream fajl; if (mode=='a'){ fajl.open (nazivFajla, std::ios_base::app); } else{ fajl.open (nazivFajla);} fajl << k22.ime << "," << k22.prezime << "," << k22.kupacIliProd << "," << k22.brojTelefona << "," << k22.korisnickoIme << "," << k22.lozinka <<std::endl; fajl.close(); } void ispisiKorisnik ()const{ std::cout<<"Ime korisnika: " << ime << std::endl; std::cout <<"Prezime korisnika: "<< prezime << std::endl; switch (kupacIliProd){ case 0: std::cout << "Kupac" << std::endl;break; case 1: std::cout << "Prodavac" << std::endl; } std::cout <<"Broj telefona korisnika: "<< brojTelefona << std::endl; std::cout <<"Korisnicko ime: "<< korisnickoIme << std::endl; //std::cout <<"Lozinka: "<< lozinka << std::endl; } }; #endif // KORISNIK_HPP_INCLUDED
true
64722d6fb90c7a00fbdfec21bd3cd7a6a634d68d
C++
jeeminhan/Coding-Practice
/tuple_satisfy.cpp
UTF-8
1,135
3.375
3
[]
no_license
/* 2/2/21 FROM AGGIE COMPETITIVE PROGRAMMING CLUB Given is a positive integer N, How many tuples (A,B,C) of positive integers satisfy A×B+C=N? 3 = 3 100 = 473 3 There are 3 tuples of integers that satisfy A × B + C = 3 : ( A , B , C ) = ( 1 , 1 , 2 ) , ( 1 , 2 , 1 ) , ( 2 , 1 , 1 ) . 1,000,000 = 13,969,985 */ #include <iostream> using namespace std; int main() { int num = 3; int counter = 0; num = num-1; int second_iterator = num-1; while (num != 0) { if (second_iterator > 0 && (num % second_iterator == 0)) { if (num != second_iterator) { counter = counter + 2; second_iterator--; } else { counter = counter + 1; second_iterator--; } } else { if (second_iterator == 0) { } else { second_iterator = second_iterator - 1; } } if (second_iterator == 0) { num = num - 1; second_iterator = num-1; } } cout << counter; return 0; }
true
96ddf0b1b08da39743d6ab1742aacb78106bd4ad
C++
JoshuaFlynn/TLLibrary
/Examples/ImageGen/FileProc.h
UTF-8
5,773
2.75
3
[ "Unlicense" ]
permissive
#ifndef G_FILEPROC_H #define G_FILEPROC_H /* Generated on: 2012-04-02-13.12.01 Version: 2.2 */ /* Notes: Cross-compiler edition (Linux compatibility) Added error check for fclose */ /* Suggestions for improvements: */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include "FlagOps.h" #include "CharArray.h" namespace TL { const bool FileExists(const char FileName[]) { FILE *Check = NULL; Check = fopen(FileName,"r"); if(Check == NULL) { return false; } //Anyone implement error checking for fclose please. if(fclose(Check) != 0) { return false; } return true; } const int GetAccessFlag(FILE * Ptr) { if(Ptr == NULL) { return 0; } #ifdef IS_WINDOWS return Ptr->_flag; #else //Mainly for Linux return Ptr->_flags; #endif } const int GetReadOnly() { #ifdef IS_WINDOWS return _IOREAD; #endif #ifdef IS_LINUX return _IO_NO_WRITES; #endif #ifdef IS_APPLE return __SRD; #elifndef IS_LINUX return _IOREAD;//Other OSes should be added #endif } const bool IsReadOnlyFlag(FILE * Ptr) { if(Ptr == NULL) { return false; } if(AreFlagsEnabled(GetAccessFlag(Ptr),GetReadOnly())) { return true; } return false; } class FileProc { private: protected: FILE *FilePtr; CharArray FileName; CharArray AccessMode; void Clear(){FilePtr = NULL; FileName.Open();} FILE * GetFilePtr(){return FilePtr;} public: void Open(){Clear();} const bool Close() { bool ReturnBool = true; if(FilePtr != NULL) { if(!IsReadOnlyFlag(FilePtr)) { ERRORCLASSFUNCTION(FileProc,Close,fflush(FilePtr),ReturnBool = false;) } ERRORCLASSFUNCTION(FileProc,Close,fclose(FilePtr) != 0,ReturnBool = false;) FilePtr = NULL; } FileName.Close(); return ReturnBool; } const bool Reset() { ERRORCLASSFUNCTION(FileProc,Reset,!Close(),Open(); RETURN_BOOL) Open(); return true; } inline const bool IsValid() const { return (FileName.IsValid() && AccessMode.IsValid() && FilePtr); } inline const bool IsEmpty() const { return (FileName.IsEmpty() && AccessMode.IsEmpty() && !FilePtr); } inline const bool IsReadOnly() const {return IsReadOnlyFlag(FilePtr); } const bool OpenFile(const CharArray &FileN, const CharArray &AccessFlags) { ERRORCLASSFUNCTION(FileProc,OpenFile,FileN.GetSize() < 1, RETURN_BOOL) ERRORCLASSFUNCTION(FileProc,OpenFile,AccessFlags.GetSize() > 4,RETURN_BOOL) ERRORCLASSFUNCTION(FileProc,OpenFile,AccessFlags.GetSize() < 1,RETURN_BOOL) ERRORCLASSFUNCTION(FileProc,OpenFile,!FileName.SetArray(FileN),RETURN_BOOL) ERRORCLASSFUNCTION(FileProc,OpenFile,!AccessMode.SetArray(AccessFlags),RETURN_BOOL) ERRORCLASSFUNCTION(FileProc,OpenFile,!OpenFile(),RETURN_BOOL) return true; } const bool OpenFile() { ERRORCLASSFUNCTION(FileProc,OpenFile,FileName.GetSize() < 1, RETURN_BOOL) ERRORCLASSFUNCTION(FileProc,OpenFile,AccessMode.GetSize() > 4,RETURN_BOOL) ERRORCLASSFUNCTION(FileProc,OpenFile,AccessMode.GetSize() < 1,RETURN_BOOL) ERRORCLASSFUNCTION(FileProc,OpenFile,!(FilePtr = fopen(FileName.GetArray(),AccessMode.GetArray()) ),perror(""); RETURN_BOOL) return true; } FileProc(){Open();} FileProc(const CharArray &FileN, const CharArray &AccessFlags) { ERRORCLASSFUNCTION(FileProc,FileProc,!OpenFile(FileN, AccessFlags),) } ~FileProc(){Close();} const CharArray &GetFileName() const { return FileName; } const CharArray &GetAccessMode() const { return AccessMode; } const bool DuplicateSettings(const FileProc &ItemCopy) { FileProc Temp; ERRORCLASSFUNCTION(FileProc,DuplicateSettings(),!Temp.FileName.SetArray(ItemCopy.FileName),RETURN_BOOL); ERRORCLASSFUNCTION(FileProc,DuplicateSettings(),!Temp.AccessMode.SetArray(ItemCopy.AccessMode),RETURN_BOOL); if(!ItemCopy.FilePtr) { ERRORCLASSFUNCTION(FileProc,DuplicateSettings(),!Temp.OpenFile(),RETURN_BOOL); } FILE * TempFile = NULL; TempFile = Temp.FilePtr; Temp.FilePtr = FilePtr; FileName.Swap(Temp.FileName); AccessMode.Swap(Temp.AccessMode); FilePtr = TempFile; ERRORCLASSFUNCTION(FileProc,DuplicateSettings(),!Temp.Close(),RETURN_BOOL) return true; } void Swap(FileProc &ItemCopy) { FileProc Temp; Temp.Open(); Temp.FilePtr = ItemCopy.FilePtr; Temp.FileName.Swap(ItemCopy.FileName); Temp.AccessMode.Swap(ItemCopy.AccessMode); ItemCopy.FilePtr = FilePtr; ItemCopy.FileName.Swap(FileName); ItemCopy.AccessMode.Swap(AccessMode); FilePtr = Temp.FilePtr; FileName.Swap(Temp.FileName); AccessMode.Swap(Temp.AccessMode); return; } FileProc &operator=(const FileProc &ItemCopy) { ERRORCLASSFUNCTION(FileProc,operator=,!DuplicateSettings(ItemCopy),RETURN_THIS) return *this; } }; } #endif
true
96eb714d04d7671ee5c2ebdc8398961d9ca71d54
C++
AverJing/LeetCode
/LeetCode/121 Best Time to Buy and Sell Stock/solution.h
UTF-8
1,845
3.671875
4
[]
no_license
/* * * *@author: Aver Jing *@description: *@date: * * */ /* Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. Example 1: Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price. Example 2: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0. */ #pragma once #include <vector> #include <stack> using std::vector; using std::stack; class Solution { public: //bad answer /* int maxProfit(vector<int>& prices) { int max = 0; for (auto i = 0; i < prices.size(); ++i) { for(auto j = i + 1; i < prices.size(); ++j) { if (prices[j] > prices[i]) { max = max < prices[j] - prices[i] ? prices[j] - prices[i] : max; } } } return max; } */ /* int maxProfit(vector<int>& prices) { int max = 0; if (prices.size() < 2) return 0; stack<int> s; s.push(prices[0]); for (auto i = 1; i < prices.size(); ++i) { if (prices[i - 1] > prices[i]) { if (s.top() > prices[i]) { s.pop(); s.push(prices[i]); } } auto top = s.top(); max = max < prices[i] - top ? prices[i] - top : max; } return max; } */ //optimization int maxProfit(vector<int>& prices) { int max = 0; if (prices.size() < 2) return 0; int min = prices[0]; for (auto i = 1; i < prices.size(); ++i) { if (prices[i - 1] > prices[i]) { if (min > prices[i]) { min = prices[i]; } } max = max < prices[i] - min ? prices[i] - min : max; } return max; } };
true
02b9055edd8e3f15fdd3398a3e71b582931bafb6
C++
atishayjain20/Graph
/graph/find_path.cpp
UTF-8
956
2.671875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; bool visited[1000][1000]; bool blocked[1000][1000]; int height,width; int adj[1000][1000]; bool valid(int x,int y){ if(x<0||y<0||x>=height||y>=width||visited[x][y]||blocked[x][y]){ return false; } return true; } bool find_path(int x,int y,int ex,int ey){ if(!valid(x,y)) return false; visited[x][y]=1; if(x==ex && y==ey) return true; bool found=false; if(find_path(x+1,y,ex,ey))found=true; if(find_path(x,y+1,ex,ey))found=true; if(find_path(x-1,y,ex,ey))found=true; if(find_path(x,y-1,ex,ey))found=true; return found; } int main(){ int n,m; cin>>height>>width; n=height;m=width; for(int i=0;i<n;i++) { for(int j=0;j<m;j++){ cin>>adj[i][j]; if(adj[i][j]==0) blocked[i][j]=true; } } cout<<find_path(0,0,3,3)<<endl; return 0; }
true
680bbd491b28af1d870843b004f313c6e779163b
C++
Yittik13/Text-Game
/Battle.hpp
UTF-8
670
2.59375
3
[]
no_license
#ifndef BATTLE_H #define BATTLE_H #include "Gamestate.hpp" #include "Party.hpp" #include "Enemy.hpp" #include "PriorityQueue.hpp" class Battle: public Gamestate { public: Battle(const char* type, Party *playerParty, class enemyParty *enemyParty); void runBattle(); int endBattle(); void getInfo() { printf("\nBATTLE INFO\n"); playerParty -> getInfo(); enemyParty -> getEnemyPartyInfo(); } void displayBattleCommands(); void clearDisplay(); void updateTotalHealth(); void updateInfo(); private: Party *playerParty; enemyParty *enemyParty; int totalPlayerHealth; int totalEnemyHealth; //int curs_x; //int curs_y; }; #endif
true
3e592474d6c47c105ea7b99766f8390f0a55fd3c
C++
shunty-gh/AdventOfCode2015
/src/day13.cpp
UTF-8
3,827
2.953125
3
[]
no_license
#include <map> #include <queue> #include <regex> #include <stdexcept> #include <vector> #include "aocutil.h" // eg: Alice would lose 57 happiness units by sitting next to Bob. const std::string Pattern{R"((\w+) would (lose|gain) (\d+) happiness units by sitting next to (\w+)\.)"}; const std::regex re{Pattern}; struct DinerKey { std::string From, To; }; bool operator<(const DinerKey& a, const DinerKey& b) { return a.From == b.From ? a.To < b.To : a.From < b.From; } struct DinerToVisit { std::string DinerName; int HappinessPoints; std::vector<std::string> Seated; }; std::pair<std::vector<std::string>, std::map<DinerKey, int>> load_diners() { auto lines = get_input_lines(13, false); std::map<DinerKey, int> diners{}; std::vector<std::string> dinerNamesTmp{}; std::smatch sm; for (auto &&line : lines) { if (!std::regex_match(line, sm, re)) { throw std::invalid_argument("Error matching input line: " + line); } DinerKey key{sm[1], sm[4]}; int hp = (sm[2] == "lose" ? -1 * std::stoi(sm[3]) : std::stoi(sm[3])); diners[key] = hp; dinerNamesTmp.push_back(sm[1]); } std::vector<std::string> dinerNames; std::unique_copy(dinerNamesTmp.begin(), dinerNamesTmp.end(), std::back_inserter(dinerNames)); return std::make_pair(dinerNames, diners); } int get_optimal_happiness(std::vector<std::string> dinerNames, std::map<DinerKey, int> dinerHappiness) { // Start with diner 0. Seat everyone else next to them, add up points, seat everyone else next to them etc int dc = dinerNames.size(); auto firstDiner = dinerNames[0]; int happiest = 0; std::queue<DinerToVisit> tovisit{}; tovisit.push(DinerToVisit{firstDiner, 0, std::vector<std::string>{firstDiner}}); DinerToVisit current; while (!tovisit.empty()) { current = tovisit.front(); tovisit.pop(); for (int i = 0; i < dc; i++) { auto dn = dinerNames[i]; // Can't sit next to ourself if (current.DinerName == dn) { continue; } // Can't sit next to someone already seated if (std::find(current.Seated.begin(), current.Seated.end(), dn) != current.Seated.end()) { continue; } DinerKey k1{current.DinerName, dn}; DinerKey k2{dn, current.DinerName}; int hp = dinerHappiness[k1] + dinerHappiness[k2]; // Is this person the last person to be seated if ((current.Seated.size() + 1) == dc) { // Also add the points for seating them next to the first person DinerKey kk1{dn, firstDiner}; DinerKey kk2{firstDiner, dn}; hp += (dinerHappiness[kk1] + dinerHappiness[kk2]); // Is this our best yet? if ((current.HappinessPoints + hp) > happiest) { happiest = current.HappinessPoints + hp; } continue; } // ...otherwise, add to the seated list and add to the queue std::vector<std::string> seated{current.Seated}; seated.push_back(dn); tovisit.push(DinerToVisit{dn, current.HappinessPoints + hp, seated}); } } return happiest; } aoc_result_t day13() { auto dd = load_diners(); auto dinerNames = dd.first; auto dinerHappiness = dd.second; int p1 = get_optimal_happiness(dinerNames, dinerHappiness); for (size_t i = 0; i < dinerNames.size(); i++) { dinerHappiness[DinerKey{"Me", dinerNames[i]}] = 0; dinerHappiness[DinerKey{dinerNames[i], "Me"}] = 0; } dinerNames.push_back("Me"); int p2 = get_optimal_happiness(dinerNames, dinerHappiness); return {p1, p2}; }
true
4261179627245fe778dcf62f7fe1f4e0c4496a63
C++
jknight1985/photobot
/WebsocketServer/websocketserver.h
UTF-8
1,634
2.75
3
[]
no_license
#ifndef WEBSOCKETSERVER_H #define WEBSOCKETSERVER_H #include <QObject> #include <QtCore/QList> #include <QtCore/QByteArray> #include <QWebSocketServer> //hier wird QWebSocket bereits deklariert, //damit unten der Pointer verwendet werden kann QT_FORWARD_DECLARE_CLASS(QWebSocket) class WebSocketServer : public QObject { Q_OBJECT public: explicit WebSocketServer(quint16 port, QObject *parent = Q_NULLPTR); ~WebSocketServer(); signals: // Hier kann man eigene Signale anlegen und in Funktionen ueber emit aufrufen // Z.B. irgendeineFuncDieserKlasse() { emit(closed()); } oder emit closed(); // Mehr Infos zu signals und slots in websocketserver.cpp void closed(); private slots: // Hier werden die Slots angelegt, in diesem Fall als private slots. // Slots sind gleichzeitig ganz normale Funktionen void onNewConnection(); void processTextMessage(QString message); void processBinaryMessage(QByteArray message); void socketDisconnected(); public slots: // Hier die slots, die public sind. private: QWebSocketServer m_pWebSocketServer; // QList ist eine sortierte Liste // Sie enthält Objekte oder Pointer, die in den Klammern angegeben sind // Hier sind es QWebSocket-Pointer // // Objekten muessen bestimmte Methoden besitzen (copy-constructor, = operator,...) // Viele Objekte von Qt und einfache structs besitzen diese meistens schon. // Pointer koennen hingegen ohne Einschraenkungen in Listen gespeichert werden // Daher werden in diesem Fall Pointer verwendet QList<QWebSocket *> m_clients; }; #endif // WEBSOCKETSERVER_H
true
6578a5b14e0126952b044c1977da225a25bc3045
C++
ljdongysu/C-_demo
/book_5/waiting.cpp
UTF-8
423
3.171875
3
[]
no_license
#include<iostream> #include<ctime> int main() { using namespace std; float secs; cout<<"Enter the delay time, in seconds: "; cin>>secs; clock_t delay = secs*CLOCKS_PER_SEC; cout<<"starting\a\n"; clock_t start = clock(); while(clock() - start<delay); cout<<"done \a\n"; double price[5] = {4.99,10.99,6.87,7.99,8.49}; for (double x:price) cout<<x<<endl; return 0; }
true
649b39844cfaea37bd7d7ea9a5eec7e15b358bf1
C++
ros-industrial/keyence_experimental
/keyence_library/src/impl/messages/get_setting.cpp
UTF-8
1,389
2.578125
3
[]
permissive
#include <keyence/impl/messages/get_setting.h> #include <keyence/impl/keyence_utils.h> keyence::command::GetSetting::Request::Request(uint8_t level, uint8_t type, uint8_t category, uint8_t item, uint8_t target1, uint8_t target2, uint8_t target3, uint8_t target4) : level(level), type(type) , category(category), item(item) , target1(target1), target2(target2) , target3(target3), target4(target4) { using keyence::insert; } void keyence::command::GetSetting::Request::encodeInto(keyence::MutableBuffer buffer) { insert(buffer.data, static_cast<uint32_t>(0x00000000), 0); insert(buffer.data, level, 4); insert(buffer.data, static_cast<uint8_t>(0x0), 5); insert(buffer.data, static_cast<uint8_t>(0x0), 6); insert(buffer.data, static_cast<uint8_t>(0x0), 7); insert(buffer.data, type, 8); insert(buffer.data, category, 9); insert(buffer.data, item, 10); insert(buffer.data, static_cast<uint8_t>(0x0), 11); insert(buffer.data, target1, 12); insert(buffer.data, target2, 13); insert(buffer.data, target3, 14); insert(buffer.data, target4, 15); } void keyence::command::GetSetting::Response::decodeFrom(keyence::MutableBuffer resp) { data.resize(resp.size); memcpy(data.data(), resp.data, resp.size); }
true
4109cef45bbab1c0fa3fce6e489f0c220060e545
C++
NekoSilverFox/CPP
/001.5 - if else 三目运算符【作业】/Упорядочить три числа/Упорядочить три числа/源.cpp
GB18030
512
3.234375
3
[ "Apache-2.0" ]
permissive
#include <iostream> using namespace std; int main(void) { int a, b, c; cout << "a="; cin >> a; cout << "b="; cin >> b; cout << "c="; cin >> c; // Сֵ嵽 min int min = a < b ? a : b; min = min < c ? min : c; // ֵ嵽 max int max = a > b ? a : b; max = max > c ? max : c; // Ȼֵ֪maxСֵminôԵõ int mid = (a + b + c - min - max); cout << min << "<="<< mid << "<=" << max; cin.get(); return 0; }
true
7d8d4400dc6cf01915670e5c204eda1b4a4f43f8
C++
mukoedo1993/cpp_primer_solutions
/C++_chap12/exercise12_26/exercise12_26.cpp
UTF-8
817
3.078125
3
[]
no_license
#include<memory> using std::allocator; #include<iostream> #include<fstream> #include<string> using std::string; int main() { int n = 12; std::ifstream input("ex12_26i.txt"); //std::istream_iterator<string>it(input), eof; if (!input.is_open())exit(-1); std::ofstream output("ex12_26o.txt"); allocator<string>alloc; string* const p = alloc.allocate(n); string s; string* q = p; while (getline(input, s) && q != p + n) { alloc.construct(q++,s);//assign a new value to *q //We construct from the p to the (final q -1) } const size_t size = q - p;//remember how many strings we read auto q_clone = q - 1; while (q_clone != p-1) { output << *q_clone << " ";//To verify we have destroyed all: alloc.destroy(q_clone); q_clone--; } alloc.deallocate(p, n); }
true
862ec10afa55a2282de9fe17d95321a7a5294420
C++
jowie94/Zelda
/cEnemy.cpp
UTF-8
1,390
2.9375
3
[]
no_license
#include "cEnemy.h" #include "cScene.h" cEnemy::cEnemy(int texture, float life, float damage) : cBicho(life) { SetDamage(damage); this->texture = texture; fmod_system->createSound("sounds/enemy-kill.wav", FMOD_DEFAULT | FMOD_LOOP_OFF, 0, &kill_sound); fmod_system->createSound("sounds/enemy-hit.wav", FMOD_DEFAULT | FMOD_LOOP_OFF, 0, &hit_sound); } cEnemy::~cEnemy() { } int cEnemy::GetTexture() const { return texture; } void cEnemy::Collides(const cRect& position, const int orientation, cRect& collision, float& damage) { if(GetState() != STATE_DYING && cBicho::Collides(&position)) { GetArea(&collision); damage = GetDamage(); } } void cEnemy::SetAttacking(bool attacking) { this->attacking = attacking; } bool cEnemy::GetAttacking() const { return attacking; } FMOD::Sound* cEnemy::GetKillSound() { return kill_sound; } FMOD::Sound* cEnemy::GetHitSound() { return hit_sound; } void cEnemy::Logic(int* map, cPlayer& player) { cBicho::Logic(map); } bool cEnemy::CollidesMapWall(int *map, bool right) { int x, y; GetPosition(&x, &y); if (x < TILE_SIZE || x >= TILE_SIZE*(SCENE_WIDTH-1)) return true; else return cBicho::CollidesMapWall(map, right); } bool cEnemy::CollidesMapFloor(int *map, bool up) { int x, y; GetPosition(&x, &y); if (y < TILE_SIZE || y >= TILE_SIZE*(SCENE_HEIGHT - 1)) return true; else cBicho::CollidesMapFloor(map, up); }
true
adce94743114cd9a8277274da72385c181a16e65
C++
zooyer/cJSON
/JsonArray.cpp
UTF-8
1,062
3.046875
3
[]
no_license
#include "JsonArray.h" #include "JsonValue.h" JsonArray::JsonArray() { m_root = cJSON_CreateArray(); } JsonArray::JsonArray(const string & json) { m_root = cJSON_Parse(json.c_str()); } JsonArray::JsonArray(const JsonArray & arr) { m_root = cJSON_Parse(arr.toJson().c_str()); } JsonArray::~JsonArray() { if (m_root != NULL) { cJSON_Delete(m_root); m_root = NULL; } } JsonArray & JsonArray::operator=(const JsonArray & arr) { if (&arr == this) { return *this; } if (m_root != NULL) { cJSON_Delete(m_root); m_root = NULL; } m_root = cJSON_Parse(arr.toJson().c_str()); return *this; } void JsonArray::insert(int i, const JsonValue & val) { cJSON * v = cJSON_Parse(val.toJson().c_str()); cJSON_InsertItemInArray(m_root, i, v); } bool JsonArray::isEmpty() { if (m_root == NULL) { return false; } if (m_root->type == cJSON_NULL) { return true; } return false; } string JsonArray::toJson() const { if (m_root == NULL) { return ""; } char *ch = cJSON_Print(m_root); string json = ch; free(ch); return json; }
true
7dd44227da00c8c505fe5408f1a8ae06e43d9e9f
C++
42somoim/42somoim2
/johan/8주차/1517.cpp
UTF-8
759
2.8125
3
[]
no_license
#include <iostream> using namespace std; int arr[500001], arr2[500001]; long long recursive(int start, int end) { if (start == end) return (0); int mid = (start + end) / 2; long long result = recursive(start, mid) + recursive(mid + 1, end); int i = start; int j = mid + 1; int idx = 0; while (i <= mid || j <= end) { if (i <= mid && (j > end || arr[i] <= arr[j])) arr2[idx++] = arr[i++]; else { result += (mid - i + 1); arr2[idx++] = arr[j++]; } } for (int k = start; k <= end; k++) arr[k] = arr2[k - start]; return (result); } int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int N; cin >> N; for (int i = 0; i < N; i++) cin >> arr[i]; cout << recursive(0, N - 1) << "\n"; return (0); }
true
5123118fa7c17fceb06413d9e7571e38b0a87fac
C++
ghostrgk/mfs
/libs/fs++/src/block.cpp
UTF-8
1,241
2.8125
3
[]
no_license
#include "fs++/internal/block.h" #include <cassert> #include <utility> namespace fspp::internal { [[maybe_unused]] Blocks::Blocks(const uint64_t* block_num_ptr, uint64_t* free_block_num_ptr, uint8_t* bit_set_bytes, Block* block_bytes) : blocks_ptr_(block_bytes), free_block_num_ptr_(free_block_num_ptr), bit_set_(*block_num_ptr, bit_set_bytes) { } Blocks::Blocks(void* blocks_ptr_start, uint64_t* free_block_num_ptr, BitSet blocks_bitset) : blocks_ptr_(static_cast<Block*>(blocks_ptr_start)), free_block_num_ptr_(free_block_num_ptr), bit_set_(std::move(blocks_bitset)) { } int Blocks::createBlock(id_t* created_id) { if (*free_block_num_ptr_ == 0) { return -1; } --(*free_block_num_ptr_); id_t new_block_id = bit_set_.findCleanBit(); bit_set_.setBit(new_block_id); *created_id = new_block_id; return 0; } Block& Blocks::getBlockById(uint64_t block_id) { return blocks_ptr_[block_id]; } int Blocks::deleteBlock(id_t block_id) { if (!bit_set_.getBit(block_id)) { return -1; } bit_set_.clearBit(block_id); ++(*free_block_num_ptr_); return 0; } uint64_t Blocks::getFreeBlockNum() { return *free_block_num_ptr_; } } // namespace fspp::internal
true
d9e9752e2d393c71c16aba84f014d57fe455cdf9
C++
vgromov/esfwx
/escore/EsVariant.h
UTF-8
72,165
3.125
3
[]
no_license
#ifndef _es_variant_h_ #define _es_variant_h_ /// Variant data type, variable or constant which type is determined at runtime. /// class ESCORE_CLASS EsVariant { public: /// Possible types, sorted in the order of their promotional conversion /// enum Type { VAR_EMPTY, ///< No value in the variant VAR_BOOL, ///< Variant has Boolean value VAR_BYTE, ///< Variant has Byte value VAR_CHAR, ///< Variant has Character value VAR_UINT, ///< Variant has unsigned integer value. Its conversion rate is smaller than INT, not like in C VAR_INT, ///< Variant has integer value VAR_UINT64, ///< Variant has unsigned 64-bit integer value. Its conversion rate is smaller than INT, not like in C VAR_INT64, ///< Variant has 64-bit integer value VAR_DOUBLE, ///< Variant has double value VAR_BIN_BUFFER, ///< Variant has the binary buffer VAR_STRING, ///< Variant has string value VAR_STRING_COLLECTION, ///< Variant has string collection value VAR_POINTER, ///< Variant has generic pointer VAR_OBJECT, ///< Variant has an base interface of object VAR_VARIANT_COLLECTION, ///< Array of any type of elements, array of variants TypeInvalid = -1 ///< Specific 'Invalid' value, must be the last }; /// Tag that allows telling string constructor from the binary buffer constructor. /// enum AcceptStringType { ACCEPT_STRING }; /// Tag that allows telling EsString-char constructor from the something-something-int constructor. /// enum AcceptCharType { ACCEPT_CHAR }; /// Tag that allows telling pointer constructor from the integer-based|bool constructors /// enum AcceptPointerType { ACCEPT_POINTER }; /// Type for holding the array of variants /// typedef std::vector<EsVariant> Array; public: /// Default object constructor. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_EMPTY. /// EsVariant() ES_NOTHROW; /// Object constructor that creates an empty object of a given type. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_EMPTY. /// explicit EsVariant(Type type); /// Construct the value of type bool and with the value specified. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_BOOL. /// The value is set to one given. /// explicit EsVariant(bool n) ES_NOTHROW; /// Construct the value of type long and with the value specified. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_INT. /// The value is set to one given. /// EsVariant(long n) ES_NOTHROW; /// Construct the value of type llong and with the value specified. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_INT64. /// The value is set to one given. /// EsVariant(llong n) ES_NOTHROW; /// Construct the value of type ulong and with the value specified. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_UINT. /// The value is set to one given. /// EsVariant(ulong n) ES_NOTHROW; /// Construct the value of type ullong and with the value specified. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_UINT64. /// The value is set to one given. /// EsVariant(ullong n) ES_NOTHROW; /// Construct the value of type int and with the value specified. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_INT. /// The value is set to one given. /// EsVariant(int n) ES_NOTHROW; /// Construct the value of type unsigned int and with the value specified. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_UINT. /// The value is set to one given. /// EsVariant(unsigned n) ES_NOTHROW; /// Construct the value of type esU8 with the value specified. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_UINT. /// The value is set to one given. /// explicit EsVariant(esU8 b) ES_NOTHROW; /// Construct the value of type char and with the value specified. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_CHAR. /// The value is set to one given. /// EsVariant(EsString::value_type c, AcceptCharType) ES_NOTHROW; /// Construct the value of type double and with the value specified. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_DOUBLE. /// The value is set to one given. /// EsVariant(double f) ES_NOTHROW; /// Construct the value of type string and with the value specified /// as the constant character pointer. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_STRING. /// The value is set to one given. /// EsVariant(EsString::const_pointer p, AcceptStringType); EsVariant(EsString::const_pointer p, unsigned len, AcceptStringType); /// Construct the value of type bin buffer, /// and with the value specified as the constant pointer with length. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_BIN_BUFFER. /// The value is set to one given. /// EsVariant(EsBinBuffer::const_pointer, unsigned len); /// Construct the value of type binary buffer, /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_BIN_BUFFER. /// The value is set to one given. /// EsVariant(const EsBinBuffer& s); /// Construct the value of type string and with the value specified /// as EsString. Note that EsBinBuffer might have the same implementation /// as EsString, and it would be not obvious that the constructor from /// byte string creates the variant with type VAR_STRING. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_STRING. /// The value is set to one given. /// EsVariant(const EsString& s); /// Construct the value of type string collection and with the value specified /// as parameter. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_STRING_COLLECTION. /// The value is set to one given. /// EsVariant(const EsString::Array& v); /// Construct the value of type variant collection and with the value specified /// as parameter. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_VARIANT_COLLECTION. /// The value is set to one given. /// EsVariant(const EsVariant::Array& v); /// Construct the value of type interface pointer from some other interface pointer /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_OBJECT. /// The value is set to reference the object given. /// template < typename OtherIntfT > EsVariant(const EsIntfPtr< OtherIntfT >& intf) : m_type(VAR_OBJECT) { EsBaseIntf::Ptr p = intf; m_value.m_intf.m_ptr = p.get(); m_value.m_intf.m_own = p.own(); if(m_value.m_intf.m_ptr && m_value.m_intf.m_own) m_value.m_intf.m_ptr->incRef(); } /// Construct the value of type void pointer /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_POINTER. /// The value is set to reference the object given. /// explicit EsVariant(void* ptr, AcceptPointerType) ES_NOTHROW; /// Construct the value from the copy. Initialize the object /// with the attributes of the other object. /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. /// Has the same attributes as the other object given. /// EsVariant(const EsVariant& v); /// destroy the variant object, reclaim memory if the value was allocated dynamically /// /// PRECONDITION: None /// /// POSTCONDITION: The object is destroyed. /// ~EsVariant(); public: /// Services that work with type of the variant: /// Get the type of the variant object. /// /// PRECONDITION: None /// /// POSTCONDITION: The type of the variant is returned, see Type constants. /// inline Type typeGet() const ES_NOTHROW { return m_type; } /// Tells whether the variant is of type VAR_EMPTY, means not initialized /// with any value. /// /// PRECONDITION: None /// /// POSTCONDITION: True is returned if the variant is empty. /// bool isEmpty() const ES_NOTHROW; /// Check if variant is of boolean type. /// @return - true, if variant is of boolean type, /// - false otherwise. /// inline bool isBool() const ES_NOTHROW { return VAR_BOOL == m_type; } /// Whether the variant is of numeric type, so the arithmetic /// operations can be performed. /// The following types are arithmetic: VAR_BOOL, /// VAR_CHAR, VAR_INT, VAR_UINT, and VAR_DOUBLE. /// Empty and string types are not numeric. /// /// PRECONDITION: None /// /// POSTCONDITION: True if the variant is of string type. /// inline bool isNumeric() const ES_NOTHROW { return m_type > VAR_EMPTY && m_type <= VAR_DOUBLE; } /// Whether the variant can be indexed. /// /// PRECONDITION: None /// /// POSTCONDITION: VAR_STRING, VAR_BIN_BUFFER, VAR_STRING_COLLECTION, and VAR_VARIANT_COLLECTION /// will return true, The other types cannot be indexed. /// bool isIndexed() const; /// Whether the variant is a collection, array. /// /// PRECONDITION: None /// /// POSTCONDITION: VAR_STRING_COLLECTION, and VAR_VARIANT_COLLECTION /// will return true, The other types cannot be indexed. /// inline bool isCollection() const ES_NOTHROW { return m_type == VAR_STRING_COLLECTION || m_type == VAR_VARIANT_COLLECTION; } /// Whether the variant is an explicit variant collection type. /// /// PRECONDITION: None /// /// POSTCONDITION: VAR_VARIANT_COLLECTION /// will return true /// inline bool isVariantCollection() const ES_NOTHROW { return m_type == VAR_VARIANT_COLLECTION; } /// Whether the variant is an explicit string collection type. /// /// PRECONDITION: None /// /// POSTCONDITION: VAR_STRING_COLLECITON /// will return true /// inline bool isStringCollection() const ES_NOTHROW { return m_type == VAR_STRING_COLLECTION; } /// Check whether the variant is a string. /// /// PRECONDITION: None /// /// POSTCONDITION: VAR_STRING /// will return true /// inline bool isString() const ES_NOTHROW { return m_type == VAR_STRING; } /// Check whether the variant is a binary buffer /// /// PRECONDITION: None /// /// POSTCONDITION: VAR_BIN_BUFFER /// will return true /// inline bool isBinBuffer() const ES_NOTHROW { return m_type == VAR_BIN_BUFFER; } /// Get the count of the elements in the variant, if they can be indexed. /// /// PRECONDITION: isIndexed should be true, or the attempt to use this /// operation will lead to exception. /// /// POSTCONDITION: The count of the elements in the collection is returned. /// ulong countGet() const; /// Set the count of the elements in the variant, if they can be indexed. /// /// PRECONDITION: isIndexed should be true, or the attempt to use this /// operation will lead to exception. /// /// POSTCONDITION: The count of the elements in the collection is updated. /// void countSet(ulong newCount); /// Whether the variant has an interface reference. /// /// PRECONDITION: None /// /// POSTCONDITION: True if the variant is of type interface. /// bool isObject() const ES_NOTHROW; //// Return true if variant is of generic pointer type inline bool isPointer() const ES_NOTHROW { return m_type == VAR_POINTER; } public: /// Assignment operators: /// Assignment operator that takes variable of type bool. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value of type VAR_BOOL is assigned. /// EsVariant& operator=(bool b) { return doSetInt( b, VAR_BOOL ); } /// Assignment operator that takes variable of type byte. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value of type VAR_BYTE is assigned. /// EsVariant& operator=(esU8 b) { return doSetInt( b, VAR_BYTE ); } /// Assignment operator that takes variable of type char. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value of type VAR_CHAR is assigned. /// EsVariant& operator=(EsString::value_type c) { #if !defined(ES_USE_NARROW_ES_CHAR) # if 2 == ES_CHAR_SIZE return doSetInt( static_cast<llong>( static_cast<unsigned short>(c) ), VAR_CHAR ); # elif 4 == ES_CHAR_SIZE return doSetInt( static_cast<llong>( static_cast<ulong>(c) ), VAR_CHAR ); # else # error Unsupported|unknown ES_CHAR_SIZE! # endif #else return doSetInt( static_cast<llong>( static_cast<unsigned char>(c) ), VAR_CHAR ); #endif } /// Assignment operator that takes variable of type int. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value of type VAR_INT is assigned. /// EsVariant& operator=(int n) { return doSetInt( n, VAR_INT ); } /// Assignment operator that takes variable of type unsigned int. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value of type VAR_UINT is assigned. /// EsVariant& operator=(unsigned n) { return doSetInt( n, VAR_UINT ); } /// Assignment operator that takes variable of type long. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value of type VAR_INT is assigned. /// EsVariant& operator=(long n) { return doSetInt( n, VAR_INT ); } /// Assignment operator that takes variable of type ulong. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value of type VAR_UINT is assigned. /// EsVariant& operator=(ulong n) { return doSetInt( n, VAR_UINT ); } /// Assignment operator that takes variable of type llong. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value of type VAR_INT64 is assigned. /// EsVariant& operator=(llong n) { return doSetInt( n, VAR_INT64 ); } /// Assignment operator that takes variable of type ullong. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value of type VAR_UINT is assigned. /// EsVariant& operator=(ullong n) { return doSetInt( n, VAR_UINT64 ); } /// Assignment operator that takes variable of type double. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value of type VAR_DOUBLE is assigned. /// EsVariant& operator=(double f); /// Assignment operator that takes variable of type string. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value of type VAR_STRING is assigned. /// EsVariant& operator=(const EsString& s); /// Assignment operator that takes variable of type string collection. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value of type VAR_STRING_COLLECTION is assigned. /// EsVariant& operator=(const EsString::Array& s); /// Assignment operator that takes variable of type variant vector. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value of type VAR_VARIANT_COLLECTION is assigned. /// EsVariant& operator=(const EsVariant::Array& s); /// Assignment operator that takes variable of type EsVariant. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value has the same type and value as the one given. /// EsVariant& operator=(const EsVariant& v); /// Assignment operator that takes variable of type EsBinBuffer /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value has type VAR_BIN_BUFFER, and value specified. /// inline EsVariant& operator=(const EsBinBuffer& v) { assignBinBuffer(v); return *this; } /// Assign the Binary buffer to the variant type /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value has type VAR_BIN_BUFFER, and value specified. /// void assignBinBuffer(const EsBinBuffer& v); /// Assign the bin buffer to the variant type. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value has type VAR_BIN_BUFFER, and value specified /// with pointer and length. /// void assignBinBuffer(EsBinBuffer::const_pointer v, size_t len); /// Assign the string to the variant type. /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value has type VAR_STRING, and value specified /// with pointer and length. /// void assignString(EsString::const_pointer v, size_t len); /// Assignment operator that takes variable of type EsBaseIntf. /// Variant will take ref-counted ownership of the object /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value has the same type and value as the one given. /// EsVariant& operator=(const EsBaseIntf::Ptr& v); /// Assignment operator that takes variable of type OtherIntfT::Ptr. /// Variant will take ref-counted ownership of the object /// /// PRECONDITION: None /// /// POSTCONDITION: The previous value is discarded. /// The new value has the same type and value as the one given. /// template < typename OtherIntfT > EsVariant& operator=(const EsIntfPtr< OtherIntfT >& v) { return operator=( v.template request< EsBaseIntf >() ); } public: /// Conversion services: /// Interpret the variant value as type bool, if possible. /// The type of the value should allow conversion /// of it into boolean. It should either be boolean itself, /// or numeric. If the value is numeric, nonzero would mean TRUE. /// Also, string, byte string, and string collection, if empty, /// will yield to False. If they are not empty, their conversion to /// Long will be attempted as the result compared with zero. /// /// PRECONDITION: The conversion should be possible. /// If the current value is of incompatible type, /// bad conversion is thrown. /// /// POSTCONDITION: Boolean representation of the value is returned. /// bool asBool(const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as byte, if possible. /// The type of the value should fit within one byte. /// /// PRECONDITION: The conversion should be possible. /// Bad conversion can be thrown in cases the type is incompatible /// or the range is bad. /// /// POSTCONDITION: Byte representation of the value is returned. /// esU8 asByte(const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as type EsString::value_type, if possible. /// The type of the value should allow conversion /// of it into EsString::value_type. It should either be VAR_CHAR itself, /// or it should be numeric with the allowed range, /// or it should be a string with the size 1. /// /// PRECONDITION: The conversion should be possible. /// Bad conversion can be thrown in cases the type is incompatible /// or the range is bad. /// /// POSTCONDITION: Char representation of the value is returned. /// EsString::value_type asChar(const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as double word. /// This service is like asInt or asUInt, but it will ignore /// the sign and never throw an exception or overflow. /// /// PRECONDITION: The conversion should be possible. /// Bad conversion can be thrown in cases the type is incompatible /// or the range is bad. /// /// POSTCONDITION: Double word representation of the value is returned. /// esU32 asInternalDWord(const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as quad word. /// This service is like asLLong or asULLong, but it will ignore /// the sign and never throw an exception or overflow. /// /// PRECONDITION: The conversion should be possible. /// Bad conversion can be thrown in cases the type is incompatible /// or the range is bad. /// /// POSTCONDITION: Quad word representation of the value is returned. /// esU64 asInternalQWord(const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as integer type, if possible. /// The type of the value should allow conversion /// of it into integer. The numeric type has to fit within /// the range of integer, and the string has to be the valid /// string representation of integer. /// /// PRECONDITION: The conversion should be possible. /// Bad conversion can be thrown in cases the type is incompatible /// or the range is bad. /// /// POSTCONDITION: Integer representation of the value is returned. /// inline int asInt(const std::locale& loc = EsLocale::locale()) const { return static_cast<int>( asLong(loc) ); } /// Interpret the variant value as unsigned integer type, if possible. /// The type of the value should allow conversion /// of it into unsigned integer. The numeric type has to fit within /// the range of integer, and the string has to be the valid /// string representation of unsigned integer. /// /// PRECONDITION: The conversion should be possible. /// Bad conversion can be thrown in cases the type is incompatible /// or the range is bad. /// /// POSTCONDITION: Unsigned integer representation of the value is returned. /// inline unsigned asUInt(const std::locale& loc = EsLocale::locale()) const { return static_cast<unsigned>( asULong(loc) ); } /// Interpret the variant value as long integer type, if possible. /// The type of the value should allow conversion /// of it into long integer. The numeric type has to fit within /// the range of integer, and the string has to be the valid /// string representation of long integer. /// /// PRECONDITION: The conversion should be possible. /// Bad conversion can be thrown in cases the type is incompatible /// or the range is bad. /// /// POSTCONDITION: Long integer representation of the value is returned. /// long asLong(const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as ulong integer type, if possible. /// The type of the value should allow conversion /// of it into ulong integer. The numeric type has to fit within /// the range of integer, and the string has to be the valid /// string representation of ulong integer. /// /// PRECONDITION: The conversion should be possible. /// Bad conversion can be thrown in cases the type is incompatible /// or the range is bad. /// /// POSTCONDITION: Unsigned long integer representation of the value is returned. /// ulong asULong(const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as llong integer type, if possible. /// The type of the value should allow conversion /// of it into llong integer. The numeric type has to fit within /// the range of integer, and the string has to be the valid /// string representation of llong integer. /// /// PRECONDITION: The conversion should be possible. /// Bad conversion can be thrown in cases the type is incompatible /// or the range is bad. /// /// POSTCONDITION: Long long integer representation of the value is returned. /// llong asLLong(const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as ullong integer type, if possible. /// The type of the value should allow conversion /// of it into ullong integer. The numeric type has to fit within /// the range of integer, and the string has to be the valid /// string representation of ullong integer. /// /// PRECONDITION: The conversion should be possible. /// Bad conversion can be thrown in cases the type is incompatible /// or the range is bad. /// /// POSTCONDITION: Unsigned llong integer representation of the value is returned. /// ullong asULLong(const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as double precision floating point, if possible. /// The type of the value should allow conversion /// of it into double precision floating point.If this is the string, /// the string has to be the valid string representation of double precision number. /// /// PRECONDITION: The conversion should be possible. /// Bad conversion can be thrown in cases the type is incompatible /// or the range is bad. /// /// POSTCONDITION: The double precision number representation of the value is returned. /// double asDouble(const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as byte string, if possible. /// The only value that cannot be interpreted as byte string is an empty value. /// /// PRECONDITION: If the value of the variant is not initialized, /// the no value exception is thrown. /// /// POSTCONDITION: Byte string representation of the value is returned. /// EsBinBuffer asBinBuffer() const; /// Interpret the variant value as string, if possible. /// The only value that cannot be interpreted as string is an empty value. /// If the variant is an object, its AsString method is called. /// For Boolean value, its string representations are numeric: 1 or 0. /// /// PRECONDITION: If the value of the variant is not initialized, /// the no value exception is thrown. /// /// POSTCONDITION: String representation of the value is returned. /// EsString asString(const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as string, if possible, using mask that specifies the conversions to make. /// The mask is combination of EsUtilities::StrMasks. /// The only value that cannot be interpreted as string is an empty value. /// If the variant is an object, its AsString method is called. /// For Boolean value, its string representations are numeric: 1 or 0. /// /// PRECONDITION: If the value of the variant is not initialized, /// the no value exception is thrown. /// /// POSTCONDITION: String representation of the value is returned. /// EsString asString(unsigned mask, const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as a string with C escapes, if possible. /// The only value that cannot be interpreted as string is an empty value. /// If the variant is an object, its AsString method is called, then /// converted to escaped string. /// For Boolean value, its string representations are numeric: 1 or 0. /// /// PRECONDITION: If the value of the variant is not initialized, /// the no value exception is thrown. /// /// POSTCONDITION: Escaped string representation of the value is returned. /// EsString asEscapedString(const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as string collection, if possible. /// The string collection returns directly. /// The only value that cannot be interpreted as string is an empty value. /// For the rest, AsString is attempted and the resulting collection /// will have only one string in it. /// /// PRECONDITION: If the value of the variant is not initialized, /// the no value exception is thrown. /// /// POSTCONDITION: String collection representation of the value is returned. /// EsString::Array asStringCollection(const std::locale& loc = EsLocale::locale()) const; /// Interpret the variant value as variant collection, if possible. /// The variant collection returns directly. /// The only value that cannot be interpreted as variant is an empty value. /// For the rest, the resulting collection will have only one element. /// /// PRECONDITION: If the value of the variant is not initialized, /// the no value exception is thrown. /// /// POSTCONDITION: Variant collection representation of the value is returned. /// EsVariant::Array asVariantCollection() const; /// Interpret the variant value as object reference, if possible. /// The only value that can be interpreted as object is an object itself. /// /// PRECONDITION: An exception is thrown in case the value is not of type object. /// /// POSTCONDITION: Object reference is returned. /// EsBaseIntf::Ptr asObject(); /// Interpret the variant value as object reference, if possible. /// The only value that can be interpreted as object is an object itself. /// /// PRECONDITION: An exception is thrown in case the value is not of type object. /// /// POSTCONDITION: Object reference is returned. /// inline EsBaseIntf::Ptr asObject() const { return const_cast<EsVariant*>(this)->asObject(); } /// Interpret the variant value as an existing non-NULL object reference, if possible. /// The only value that can be interpreted as object is an object itself. /// /// PRECONDITION: An exception is thrown in case the value is not of type object. /// If the object is NULL, a no value exception is thrown. /// /// POSTCONDITION: Object reference is returned. /// EsBaseIntf::Ptr asExistingObject(); /// Interpret the variant value as an existing non-NULL constant object reference, if possible. /// The only value that can be interpreted as object is an object itself. /// /// PRECONDITION: An exception is thrown in case the value is not of type object. /// If the object is NULL, a no value exception is thrown. /// /// POSTCONDITION: Constant object reference is returned. /// EsBaseIntf::Ptr asExistingObject() const; /// Interpret the variant value as generic pointer, if possible. /// /// PRECONDITION: An exception is thrown in case the value is not of type object. /// /// POSTCONDITION: Object reference is returned. /// void* asPointer(); /// Interpret the variant value as generic pointer, if possible. /// /// PRECONDITION: An exception is thrown in case the value is not of type object. /// /// POSTCONDITION: Object reference is returned. /// inline void* asPointer() const { return const_cast<EsVariant*>(this)->asPointer(); } /// Discard the value of the variant type. /// /// PRECONDITION: None /// /// POSTCONDITION: Type of the variant becomes VAR_EMPTY. /// void setEmpty() ES_NOTHROW; /// Discard the value of the variant type, and set the null, /// empty or zero value of this given type. /// The null value will depend on the given type. /// For string it is an empty string, and for an integer it is zero. /// If no parameter is given, the type is preserved while its value becomes NULL. /// /// PRECONDITION: None /// /// POSTCONDITION: Type of the variant becomes one given, with null value. /// void setToNull(Type type = TypeInvalid) ES_NOTHROW; /// Efficiently swap the value with the given value. /// /// PRECONDITION: None. /// /// POSTCONDITION: The values are swapped. /// void swap(EsVariant& other) ES_NOTHROW; /// Fast method that moves the value to another variant, and sets the other variant type to Empty. /// This is possible only because variant values can always be moved. /// /// PRECONDITION: None. /// /// POSTCONDITION: The value is moved to this variant, other variant is set to empty. /// void move(EsVariant& other) ES_NOTHROW; /// Return this object with the power of the object given. /// The power type returned is always esD. /// /// PRECONDITION: The type should be compatible with the power operation. /// The compatible types are those that can be cast to esD. /// If not, the bad conversion is thrown. In case any of the values /// are not initialized, no value exception is thrown. /// /// POSTCONDITION: Powered esD value returned. /// EsVariant pow(const EsVariant& val, const std::locale& loc = EsLocale::locale()) const; /// Get element by index. /// One can check isIndexed property to know if the variant can be /// indexed. Also there is a countGet, which is callable only for /// isIndexed, and will return the number of items in the variant. /// /// PRECONDITION: The type should allow subscripting, /// such as VAR_STRING, VAR_BIN_BUFFER or VAR_STRING_COLLECTION. /// If an item is an object, it shall have a reflected service with the name Item. /// Otherwise the conversion exception is thrown. /// /// POSTCONDITION: The indexed item is returned. /// Its type depends on the type of the variant. /// EsVariant itemGet(const EsVariant& index) const; /// Access element by index. /// One can check isIndexed property to know if the variant can be /// indexed. Also there is a countGet, which is callable only for /// isIndexed, and will return the number of items in the variant. /// /// PRECONDITION: The only applicable type supported /// by this method is VAR_STRING_COLLECTION. /// Otherwise the conversion exception is thrown. /// /// POSTCONDITION: The indexed item reference is returned. /// EsVariant& itemAccess(const EsVariant& index); /// Set element by index. /// One can check isIndexed property to know if the variant can be /// indexed. Also there is a countGet, which is callable only for /// isIndexed, and will return the number of items in the variant. /// /// PRECONDITION: The type should allow subscripting, /// such as VAR_STRING, VAR_BIN_BUFFER or VAR_STRING_COLLECTION. /// If an item is an object, it shall have a reflected service with the name itemSet. /// Otherwise the conversion exception is thrown. /// /// POSTCONDITION: The indexed item is set to one given. /// void itemSet(const EsVariant& index, const EsVariant& value, const std::locale& loc = EsLocale::locale()); /// Remove an element by its index /// One can check isIndexed property to know if the variant can be /// indexed. Also there is a countGet, which is callable only for /// isIndexed, and will return the number of items in the variant. /// /// PRECONDITION: The type should allow subscripting, /// such as VAR_STRING, VAR_BIN_BUFFER or VAR_STRING_COLLECTION. /// If an item is an object, it shall have a reflected service with the name itemDelete. /// Otherwise the conversion exception is thrown. /// /// POSTCONDITION: The indexed item is set to one given. /// void itemDelete(const EsVariant& index); /// Returns true if a given item is in the variant. /// If the variant is a collection of any kind, /// true will mean the parameter is contained it in. /// If the variant is a simple variant, 'has' means equality. /// /// PRECONDITION: None /// /// POSTCONDITION: True will mean the value signified by a given variant /// is within this variant value. /// bool has(const EsVariant&) const; /// Add a given variant as a whole to the collection. /// This call is different from operator+=, as it does not /// unroll the collection items in case the given parameter is a collection. /// /// PRECONDITION: The type of the variant shall be VARIANT_COLLECTION, /// there is a debug check. /// /// POSTCONDITION: A variant is added to collection. Reference to variant itself is returned /// EsVariant& addToVariantCollection(const EsVariant& v, bool toFront = false); /// Adjust a given index to standards of indexing in script /// So the negative index will mean counting from the end of the array. /// /// PRECONDITION: The index shall be in range -count to count - 1, /// where count is a signed integer. Otherwise an exception is thrown. /// /// POSTCONDITION: An index is adjusted to denote the real array element. /// static void indexAdjust(long& index, ulong count); /// Adjust a given slice to standards of slicing in script. /// So the negative index will mean counting from the end of the array. /// A negative slice will mean no elements. /// /// PRECONDITION: Slice is always adjusted correctly. /// /// POSTCONDITION: A slice is adjusted, so it denotes the real array element range. /// static long sliceAdjust(long &from, long &to, ulong count); /// Return the slice of values for types that support subscrips. /// One can check isIndexed property to know if the variant can be /// indexed. Also there is a countGet, which is callable only for /// isIndexed, and will return the number of items in the variant. /// /// PRECONDITION: The type should allow subscripting, /// such as VAR_STRING, VAR_BIN_BUFFER or VAR_STRING_COLLECTION. /// If an item is an object, it shall have a reflected service with the name itemGet. /// Otherwise the conversion exception is thrown. /// /// POSTCONDITION: Result variant has the same type as this, /// but it has only a given subrange of elements. /// EsVariant sliceGet(long from, long to) const; /// Set the slice of values for types that support subscrips. /// Shrink or grow the number of items if necessary. /// One can check isIndexed property to know if the variant can be /// indexed. Also there is a GetCount, which is callable only for /// isIndexed, and will return the number of items in the variant. /// /// PRECONDITION: The type should allow subscripting, /// such as VAR_STRING, VAR_BIN_BUFFER or VAR_STRING_COLLECTION. /// If an item is an object, it shall have a reflected service with the name SetItem. /// Otherwise the conversion exception is thrown. /// /// POSTCONDITION: Result variant has a given slice of items set to new values. /// In case the number of values is lesser or bigger than the target slice, /// the number of items will change. /// //void sliceSet(int from, int to, const EsVariant& values); /// Generic algorithms /// /// Value|member look-up /// Return index of member if found, or null, if not found /// EsVariant find(const EsVariant& var) const; EsVariant findFirstOf(const EsVariant& var) const; EsVariant findLastOf(const EsVariant& var) const; /// Replace part of sequence, with another one, starting from specified offset. /// If count is not 0, replace cnt elements from the sequence with var. Otherwise, /// var length is used to find how many source elements to be replaced. /// void replace(const EsVariant& var, long offs, ulong cnt = 0); /// Sort elements collection void sortAscending(); void sortDescending(); /// Reverse order of elements in collection void reverse(); /// Operators /// inline EsVariant operator[](const EsVariant& idx) const { return itemGet(idx); } inline EsVariant& operator[](const EsVariant& idx) { return itemAccess(idx); } /// Equality operator. Standard conversions apply. /// /// PRECONDITION: In case any of the values are not initialized, /// no value exception is thrown. /// /// POSTCONDITION: True if the values of operands are logically equal. /// bool operator==(const EsVariant&) const; /// Inequality operator. Standard conversions apply. /// /// PRECONDITION: In case any of the values are not initialized, /// no value exception is thrown. /// /// POSTCONDITION: True if the values of operands are not logically equal. /// bool operator!=(const EsVariant& other) const { return !operator==(other); } /// Less-than operator. Standard conversions apply. /// /// PRECONDITION: In case any of the values are not initialized, /// no value exception is thrown. /// /// POSTCONDITION: True if the left value is smaller than the right value. /// bool operator<(const EsVariant&) const; /// Greater-than operator. Standard conversions apply. /// /// PRECONDITION: In case any of the values are not initialized, /// no value exception is thrown. /// /// POSTCONDITION: True if the left value is greater than the right value. /// bool operator>(const EsVariant&) const; /// Less-or-equal-than operator. Standard conversions apply. /// /// PRECONDITION: In case any of the values are not initialized, /// no value exception is thrown. /// /// POSTCONDITION: True if the left value is smaller or equal than the right value. /// bool operator<=(const EsVariant& v) const { return !operator>(v); } /// Greater-or-equal-than operator. Standard conversions apply. /// /// PRECONDITION: In case any of the values are not initialized, /// no value exception is thrown. /// /// POSTCONDITION: True if the left value is bigger or equal than the right value. /// bool operator>=(const EsVariant& v) const { return !operator<(v); } /// Operator OR. Standard conversions apply. /// /// Note that there is no difference between logical OR and bitwise OR. /// Logical or is applied for bool operands, and the resulting value is bool. /// For all the other numeric values the bitwise OR is performed. /// /// PRECONDITION: The operand types should be convertible to esBL or numeric. /// Otherwise bad conversion is raised. /// In case any of the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: In case of both Boolean operands, return true if either one is true. /// In case of the numeric values, do bitwise OR. /// EsVariant operator|(const EsVariant&) const; /// Operator AND. Standard conversions apply. /// Note that there is no difference between logical AND and bitwise AND. /// Logical and is applied for bool operands, the resulting value is bool. /// For all the other numeric values bitwise and is performed. /// /// PRECONDITION: The operand types should be convertible to esBL or numeric. /// Otherwise bad conversion is raised. /// In case any of the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: In case of both boolean operands, return true if both are true. /// In case of the numeric values, do bitwise AND. /// EsVariant operator&(const EsVariant&) const; /// Operator XOR. Standard conversions apply. /// Note that there is no difference between logical XOR and bitwise XOR. /// Logical XOR is applied for bool operands, the resulting value is bool. /// For all the other numeric values bitwise XOR is performed. /// /// PRECONDITION: The operand types should be convertible to esBL or numeric. /// Otherwise bad conversion is raised. /// In case any of the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: In case of both boolean operands, return true if both /// have the same value. In case of the numeric values, do bitwise XOR. /// EsVariant operator^(const EsVariant&) const; /// Unary bitwise negation operator. /// /// PRECONDITION: The type should be convertible to either bool /// or unsigned integer. Otherwise bad conversion is raised. /// In case any of the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: The result returned, NOT operator on this. /// EsVariant operator~() const; /// Unary logical negation operator. /// /// PRECONDITION: The type should be convertible to either bool /// or unsigned integer. Otherwise bad conversion is raised. /// In case any of the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: The result returned, NOT operator on this. /// EsVariant operator!() const; /// Unary operator minus. /// Please note that the unary operator plus is not defined for EsVariant. /// /// PRECONDITION: The type should be compatible with the operation. /// It should be arithmetic. Otherwise the conversion exception is reported. /// In case any of the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: The result returned, minus operator on this. /// EsVariant operator-() const; /// Binary operator plus. The interpretation depends on the context. /// /// First the conversion is applied according to the MDL rules. /// Preconditions apply for the conversion. If the converted values /// are of type TYPE_STRING, then the strings are concatenated. /// If the converted values are of the numeric type, the values are added. /// The result value is returned, and this object is not changed. /// /// PRECONDITION: The type should be compatible with the operation. /// Otherwise the conversion exception is thrown. In case any of /// the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: The result returned, a result of the operator plus. /// EsVariant operator+(const EsVariant&) const; /// Binary operator minus. Applicable for numerics or sets only. /// /// First the conversion is applied according to the MDL rules. /// Preconditions apply for the conversion. /// The converted values should be of numeric type. /// /// PRECONDITION: The type should be compatible with the operation. /// Otherwise the conversion exception is thrown. In case any of /// the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: The result returned, a result of the operator minus. /// EsVariant operator-(const EsVariant&) const; /// Binary multiplication operator. Applicable for numerics or sets only. /// /// First the conversion is applied according to the MDL rules. /// Preconditions apply for the conversion. /// The converted values should be of numeric type. /// /// PRECONDITION: The type should be compatible with the operation. /// Otherwise the conversion exception is thrown. In case any of /// the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: The result returned, a result of the multiplication operator. /// EsVariant operator*(const EsVariant&) const; /// Binary division operator. Applicable for numerics only. /// /// First the conversion is applied according to the MDL rules. /// Preconditions apply for the conversion. /// The converted values should be of numeric type. /// /// PRECONDITION: The type should be compatible with the operation, /// which means to be convertible to numeric type. /// Otherwise the conversion exception is thrown. In case any of /// the values are not initialized, no value exception is thrown. /// If the second argument is zero, division by zero is thrown. /// /// POSTCONDITION: The result returned, the result of the division operator. /// EsVariant operator/(const EsVariant&) const; /// Binary modulus operator. Applicable for numerics only. /// Modulus produces a reminder value from the division operator if both /// arguments are positive. /// /// First the conversion is applied according to the MDL rules. /// Preconditions apply for the conversion. /// The converted values should be of numeric type. /// /// PRECONDITION: The type should be compatible with the operation /// (be numeric). Otherwise the conversion exception is thrown. In case any of /// the values are not initialized, no value exception is thrown. /// If the second argument is zero, division by zero is thrown. /// /// POSTCONDITION: The result returned, a result of the modulus operator. /// EsVariant operator%(const EsVariant&) const; /// Bitwise left shift operator. Standard conversions apply. /// /// PRECONDITION: The type should be compatible with the operation, /// which means to be numeric. /// Otherwise the conversion exception is thrown. In case any of /// the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: Bitwise left shift is performed. /// EsVariant operator<<(const EsVariant&) const; /// Bitwise right shift operator. Standard conversions apply. /// /// PRECONDITION: The type should be compatible with the operation, /// which means to be numeric. /// Otherwise the conversion exception is thrown. In case any of /// the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: Bitwise right shift is performed. /// EsVariant operator>>(const EsVariant&) const; /// Prefix increment operator. /// It never attempts to change the type of this variant. /// /// PRECONDITION: The type should allow incrementation, /// which means it is numeric. Otherwise the exception is thrown. /// /// POSTCONDITION: The value is incremented, returned afterwards. /// EsVariant& operator++(); /// Prefix decrement operator. /// It never attempts to change the type of this variant. /// /// PRECONDITION: The type should allow incrementation, /// which means it is numeric. Otherwise the exception is thrown. /// /// POSTCONDITION: The value is incremented, returned afterwards. /// EsVariant& operator--(); /// Binary operator increment by value. /// /// PRECONDITION: The type should be compatible with the operation. /// Otherwise the conversion exception is thrown. In case any of /// the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: The value is incremented, this returned. /// EsVariant& operator+=(const EsVariant&); /// Binary operator decrement by value. /// /// PRECONDITION: The type should be compatible with the operation. /// Otherwise the conversion exception is thrown. In case any of /// the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: The value is decremented, this returned. /// EsVariant& operator-=(const EsVariant&); /// Binary operator multiply by value. /// /// PRECONDITION: The type should be compatible with the operation. /// Otherwise the conversion exception is thrown. In case any of /// the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: The value is multiplied, this returned. /// EsVariant& operator*=(const EsVariant&); /// Binary operator divide by value. /// /// PRECONDITION: The type should be compatible with the operation. /// Otherwise the conversion exception is thrown. In case any of /// the values are not initialized, no value exception is thrown. /// /// POSTCONDITION: The value is divided, this returned. /// EsVariant& operator/=(const EsVariant&); EsVariant& operator%=(const EsVariant&); EsVariant& operator>>=(const EsVariant&); EsVariant& operator<<=(const EsVariant&); EsVariant& operator|=(const EsVariant&); EsVariant& operator&=(const EsVariant&); EsVariant& operator^=(const EsVariant&); #ifdef ES_MODERN_CPP /// Constructor with move semantics EsVariant(EsVariant&& other) ES_NOTHROW; /// Move assignment EsVariant& operator=(EsVariant&& other) ES_NOTHROW; #endif /// Return contained type kind string. In case of non-null object, return object type /// Otherwise, return an empty string /// EsString kindGet() const; /// Object-specific proxy services /// /// Return true if variant is object of specified type bool isKindOf(const EsString& type) const; /// Return a type name of contained object EsString typeNameGet() const; /// Metaclass info proxies bool hasMethod(const EsString& mangledName) const; bool hasMethod(const EsString& name, ulong paramsCnt) const; bool hasProperty(const EsString& name) const; bool hasVariable(const EsString& name) const; bool hasField(const EsString& name) const; /// Try to cast contents implicitly to reflected object, and call its method EsVariant call(const EsString& method); EsVariant call(const EsString& method, const EsVariant& arg0); EsVariant call(const EsString& method, const EsVariant& arg0, const EsVariant& arg1); EsVariant call(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2); EsVariant call(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2, const EsVariant& arg3); EsVariant call(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2, const EsVariant& arg3, const EsVariant& arg4); EsVariant call(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2, const EsVariant& arg3, const EsVariant& arg4, const EsVariant& arg5); EsVariant classCall(const EsString& method); EsVariant classCall(const EsString& method, const EsVariant& arg0); EsVariant classCall(const EsString& method, const EsVariant& arg0, const EsVariant& arg1); EsVariant classCall(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2); EsVariant classCall(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2, const EsVariant& arg3); EsVariant classCall(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2, const EsVariant& arg3, const EsVariant& arg4); EsVariant classCall(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2, const EsVariant& arg3, const EsVariant& arg4, const EsVariant& arg5); /// Deal with variant container constness EsVariant call(const EsString& method) const; EsVariant call(const EsString& method, const EsVariant& arg0) const; EsVariant call(const EsString& method, const EsVariant& arg0, const EsVariant& arg1) const; EsVariant call(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2) const; EsVariant call(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2, const EsVariant& arg3) const; EsVariant call(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2, const EsVariant& arg3, const EsVariant& arg4) const; EsVariant call(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2, const EsVariant& arg3, const EsVariant& arg4, const EsVariant& arg5) const; EsVariant classCall(const EsString& method) const; EsVariant classCall(const EsString& method, const EsVariant& arg0) const; EsVariant classCall(const EsString& method, const EsVariant& arg0, const EsVariant& arg1) const; EsVariant classCall(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2) const; EsVariant classCall(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2, const EsVariant& arg3) const; EsVariant classCall(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2, const EsVariant& arg3, const EsVariant& arg4) const; EsVariant classCall(const EsString& method, const EsVariant& arg0, const EsVariant& arg1, const EsVariant& arg2, const EsVariant& arg3, const EsVariant& arg4, const EsVariant& arg5) const; /// Common service shot-cuts EsVariant clone(const EsVariant& factory = EsVariant::null()) const; /// Property access proxies EsVariant propertyGet(const EsString& property) const; void propertySet(const EsString& property, const EsVariant& val); /// Deal with constness void propertySet(const EsString& property, const EsVariant& val) const; /// Variable access proxy EsVariant variableGet(const EsString& variable) const; void variableSet(const EsString& variable, const EsVariant& val); /// Field access proxy EsVariant fieldGet(const EsString& field) const; /// Variant contents debug trace EsString trace() const ES_NOTHROW; public: ///< Semi-public services that has to be used carefully: /// Interpret the internals of the variant as bool. /// /// PRECONDITION: the type is VAR_BOOL, otherwise the behavior /// is undefined. The debugger version has the assert operator. /// /// POSTCONDITION: The value of bool is returned. /// inline bool doInterpretAsBool() const ES_NOTHROW { ES_ASSERT(m_type == VAR_BOOL); return m_value.m_llong != 0; } /// Interpret the internals of the variant as byte. /// /// PRECONDITION: the type is VAR_BOOL, otherwise the behavior /// is undefined. The debugger version has the assert operator. /// /// POSTCONDITION: The value of byte is returned. /// inline esU8 doInterpretAsByte() const ES_NOTHROW { ES_ASSERT(m_type == VAR_BYTE); return static_cast<esU8>(m_value.m_ullong); } /// Interpret the internals of the variant as UINT. /// /// PRECONDITION: the type is VAR_UINT, otherwise the behavior /// is undefined. The debugger version has the assert operator. /// /// POSTCONDITION: The value of UINT is returned. /// inline EsString::value_type doInterpretAsChar() const ES_NOTHROW { ES_ASSERT(m_type == VAR_CHAR); return static_cast<EsString::value_type>(m_value.m_ullong); } /// Interpret the internals of the variant as INT. /// /// PRECONDITION: the type is VAR_INT, otherwise the behavior /// is undefined. The debugger version has the assert operator. /// /// POSTCONDITION: The value of INT is returned. /// inline int doInterpretAsInt() const ES_NOTHROW { ES_ASSERT(m_type == VAR_INT); return static_cast<int>(m_value.m_llong); } /// Interpret the internals of the variant as UINT. /// /// PRECONDITION: the type is VAR_UINT, otherwise the behavior /// is undefined. The debugger version has the assert operator. /// /// POSTCONDITION: The value of UINT is returned. /// inline unsigned doInterpretAsUInt() const ES_NOTHROW { ES_ASSERT(m_type == VAR_UINT); return static_cast<unsigned>(m_value.m_ullong); } /// Interpret the internals of the variant as standard string. /// /// PRECONDITION: the type is VAR_STRING, otherwise the behavior /// is undefined. The non-UNICODE version has a flexibility that /// VAR_BIN_BUFFER is also allowed. The debugger version has the assert operator. /// /// POSTCONDITION: The reference to the variant buffer as it was a string /// is returned. /// inline EsString& doInterpretAsString() ES_NOTHROW { ES_ASSERT(m_type == VAR_STRING); ES_ASSERT(m_value.m_sptr); return *m_value.m_sptr; } /// Interpret the internals of the variant as constant standard string. /// /// PRECONDITION: the type is VAR_STRING, otherwise the behavior /// is undefined. The debugger version has the assert operator. /// /// POSTCONDITION: The reference to the variant buffer as it was a /// constant string is returned. /// inline const EsString& doInterpretAsString() const ES_NOTHROW { ES_ASSERT(m_type == VAR_STRING); ES_ASSERT(m_value.m_sptr); return *m_value.m_sptr; } /// Interpret the internals of the variant as byte string. /// /// PRECONDITION: the type is VAR_BIN_BUFFER, otherwise the behavior /// is undefined. The non-UNICODE version has a flexibility that /// VAR_STRING is also allowed. The debugger version has the assert operator. /// /// POSTCONDITION: The reference to the variant buffer as it was a string /// is returned. /// inline EsBinBuffer& doInterpretAsBinBuffer() ES_NOTHROW { ES_ASSERT(m_type == VAR_BIN_BUFFER); ES_ASSERT(m_value.m_bbptr); return *m_value.m_bbptr; } /// Interpret the internals of the variant as constant byte string. /// /// PRECONDITION: the type is VAR_BIN_BUFFER, otherwise the behavior /// is undefined. The non-UNICODE version has a flexibility that /// VAR_STRING is also allowed. The debugger version has the assert operator. /// /// POSTCONDITION: The reference to the variant buffer as it was a constant string /// is returned. /// inline const EsBinBuffer& doInterpretAsBinBuffer() const ES_NOTHROW { ES_ASSERT(m_type == VAR_BIN_BUFFER); ES_ASSERT(m_value.m_bbptr); return *m_value.m_bbptr; } /// Interpret the internals of the variant as string collection. /// /// PRECONDITION: the type is VAR_STRING_COLLECTION, otherwise the behavior /// is undefined. The debugger version has the assert operator. /// /// POSTCONDITION: The reference to the variant buffer as it was a string collection /// is returned. /// inline EsString::Array& doInterpretAsStringCollection() ES_NOTHROW { ES_ASSERT(m_type == VAR_STRING_COLLECTION); ES_ASSERT(m_value.m_saptr); return *m_value.m_saptr; } /// Interpret the internals of the variant as constant string collection. /// /// PRECONDITION: the type is VAR_STRING_COLLECTION, otherwise the behavior /// is undefined. The debugger version has the assert operator. /// /// POSTCONDITION: The reference to the variant buffer as it was a /// constant string collection is returned. /// inline const EsString::Array& doInterpretAsStringCollection() const ES_NOTHROW { ES_ASSERT(m_type == VAR_STRING_COLLECTION); ES_ASSERT(m_value.m_saptr); return *m_value.m_saptr; } /// Interpret the internals of the variant as variant collection. /// /// PRECONDITION: the type is VAR_VARIANT_COLLECTION, otherwise the behavior /// is undefined. The debugger version has the assert operator. /// /// POSTCONDITION: The reference to the variant buffer as it was a /// variant collection is returned. /// inline EsVariant::Array& doInterpretAsVariantCollection() ES_NOTHROW { ES_ASSERT(m_type == VAR_VARIANT_COLLECTION); ES_ASSERT(m_value.m_vaptr); return *m_value.m_vaptr; } /// Interpret the internals of the variant as constant variant collection. /// /// PRECONDITION: the type is VAR_VARIANT_COLLECTION, otherwise the behavior /// is undefined. The debugger version has the assert operator. /// /// POSTCONDITION: The reference to the variant buffer as it was a /// constant variant collection is returned. /// inline const EsVariant::Array& doInterpretAsVariantCollection() const ES_NOTHROW { ES_ASSERT(m_type == VAR_VARIANT_COLLECTION); ES_ASSERT(m_value.m_vaptr); return *m_value.m_vaptr; } /// Interpret the internals of the variant as an interface. /// /// PRECONDITION: the type is VAR_OBJECT, otherwise the behavior /// is undefined. The debugger version has the assert operator. /// /// POSTCONDITION: The incRef-ed interface smartptr is returned. /// only if variant owns the interface /// inline EsBaseIntf::Ptr doInterpretAsObject() ES_NOTHROW { ES_ASSERT(m_type == VAR_OBJECT); return EsBaseIntf::Ptr( m_value.m_intf.m_ptr, m_value.m_intf.m_own, m_value.m_intf.m_own ); } inline EsBaseIntf::Ptr doInterpretAsObject() const ES_NOTHROW { ES_ASSERT(m_type == VAR_OBJECT); return EsBaseIntf::Ptr( m_value.m_intf.m_ptr, m_value.m_intf.m_own, m_value.m_intf.m_own ); } inline void doAssignToEmpty(bool b) ES_NOTHROW { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_BOOL; m_value.m_llong = b; } inline void doAssignToEmpty(esU8 b) ES_NOTHROW { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_BYTE; m_value.m_ullong = b; } inline void doAssignToEmpty(EsString::value_type c) ES_NOTHROW { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_CHAR; #if !defined(ES_USE_NARROW_ES_CHAR) # if 2 == ES_CHAR_SIZE m_value.m_ullong = static_cast<ullong>( static_cast<unsigned short>(c) ); # elif 4 == ES_CHAR_SIZE m_value.m_ullong = static_cast<ullong>( static_cast<ulong>(c) ); # else # error Unsupported|unknown ES_CHAR_SIZE! # endif #else m_value.m_ullong = static_cast<ullong>( static_cast<unsigned char>(c) ); #endif } inline void doAssignToEmpty(int n) ES_NOTHROW { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_INT; m_value.m_llong = n; } inline void doAssignToInt(int n) ES_NOTHROW { ES_ASSERT(m_type == VAR_INT); m_value.m_llong = n; } inline void doAssignToEmpty(unsigned n) ES_NOTHROW { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_UINT; m_value.m_ullong = n; } inline void doAssignToUInt(unsigned n) ES_NOTHROW { ES_ASSERT(m_type == VAR_UINT); m_value.m_ullong = n; } inline void doAssignToEmpty(long n) ES_NOTHROW { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_INT; m_value.m_llong = n; } inline void doAssignToEmpty(ulong n) ES_NOTHROW { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_UINT; m_value.m_ullong = n; } inline void doAssignToEmpty(llong n) ES_NOTHROW { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_INT64; m_value.m_llong = n; } inline void doAssignToEmpty(ullong n) ES_NOTHROW { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_UINT64; m_value.m_ullong = n; } inline void doAssignToEmpty(double f) ES_NOTHROW { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_DOUBLE; m_value.m_double = f; } void doAssignToEmpty(EsString::const_pointer s); void doAssignToEmpty(const EsString& s); inline void doAssignToEmpty(const EsString::Array& s) { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_STRING_COLLECTION; m_value.m_saptr = new EsString::Array(s); ES_ASSERT(m_value.m_saptr); } inline void doAssignToEmpty(const EsVariant::Array& s) { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_VARIANT_COLLECTION; m_value.m_vaptr = new EsVariant::Array(s); ES_ASSERT(m_value.m_vaptr); } void doAssignToEmpty(const EsVariant& other); inline void doAssignEsBinBufferToEmpty(const EsBinBuffer& v) { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_BIN_BUFFER; m_value.m_bbptr = new EsBinBuffer(v); ES_ASSERT(m_value.m_bbptr); } inline void doAssignToEmpty(EsBaseIntf* i, bool own) ES_NOTHROW { ES_ASSERT(m_type == VAR_EMPTY); m_type = VAR_OBJECT; m_value.m_intf.m_ptr = i; m_value.m_intf.m_own = own; if( m_value.m_intf.m_ptr && m_value.m_intf.m_own ) m_value.m_intf.m_ptr->incRef(); } /// Assign the value of type interface pointer from some other interface pointer, /// without the use of smartptr interlock. Use with caution, for micro optimizations /// /// PRECONDITION: None /// /// POSTCONDITION: The object is built. The type is set to VAR_OBJECT. /// The value is set to reference the object given. /// template < typename OtherIntfT > inline void doAssignOtherIntfPtrToEmptyWithoutInterlock( const EsIntfPtr< OtherIntfT >& intf ) { ES_ASSERT( m_type == VAR_EMPTY ); m_type = VAR_OBJECT; EsBaseIntf::Ptr p; p.assignNonInterlocked( intf ); m_value.m_intf.m_ptr = p.get(); m_value.m_intf.m_own = p.own(); if( m_value.m_intf.m_ptr && m_value.m_intf.m_own ) m_value.m_intf.m_ptr->incRef(); } public: /// Empty variant, the same as NULL for pointers static const EsVariant& null() ES_NOTHROW; /// Empty collection variant static const EsVariant::Array& nullCollection() ES_NOTHROW; /// Empty object variant static const EsVariant& nullObject() ES_NOTHROW; /// Dump variant contents to a string static inline EsString dump(const EsVariant& v) ES_NOTHROW { return v.trace(); } private: /// Internal assignment service that constructs integer-based variant value /// with the particular type given. /// /// PRECONDITION: type has to be of generic integer type. Otherwise the /// behavior is undefined. /// /// POSTCONDITION: The variant is initialized with the value and type given. /// EsVariant& doSetInt(llong value, Type type) ES_NOTHROW; /// Set the type of the variant. /// If setting new type requires current value to be cleaned-up, do it, /// and return true. Otherwise, retain current contents, and return false. bool doSetType(Type type) ES_NOTHROW; /// Release object interface and nullify object interface pointer void releaseObject() ES_NOTHROW; /// Cleanup variant contents void doCleanup() ES_NOTHROW; /// Internal contents move services void internalMove(EsVariant& other) ES_NOTHROW; private: /// Variable to hold the variant value. /// It is the first data in the class for making sure it is aligned to the eight byte boundary. /// union Value { /// Used for storing of reflected object interface pointer /// struct { EsBaseIntf* m_ptr; bool m_own; } m_intf; /// used for storing void pointer void* m_pointer; /// Used for storing of all numerics /// llong m_llong; /// Used for storing of all unsigned numerics and characters /// ullong m_ullong; /// Used for storing of all floating point values /// double m_double; /// Used for storing of EsString data /// EsString* m_sptr; /// Used for storing EsBinBuffer data /// EsBinBuffer* m_bbptr; /// Used for storing of string data, mapped to EsString and EsBinBuffer /// EsString::Array* m_saptr; /// Used for storing the vector of variants /// EsVariant::Array* m_vaptr; } m_value; /// Type of the current value within variant. /// Type m_type; }; typedef EsVariant::Array EsVariantArray; #endif // _es_variant_h_
true
e23457bb290a838d14f3d92af6e9ffab359689a3
C++
Departuers/acwing-cpp
/dp/线性dp/最低通行费.cpp
UTF-8
1,278
3.046875
3
[ "MIT" ]
permissive
#include <iostream> #include <cstdio> #include <queue> #include <algorithm> #include <vector> #include <cstring> using namespace std; const int inf = 0x3f3f3f3f; int n, m; /** * f[i,j]定义为从(1,1)到(i,j)最小花费 * 属性min * 划分依据,上一步从上面过来,还是从左边过来 * 则f[i,j]=min(f[i-1][j],f[i][j-1])+w[i][j] * * 初始化问题 * 由于f数组默认初值是0, * 所以求第一行状态时只能从左边转移过来而不能从上边转移过来, * 否则求最小值会发生错误; * 同样求第一列状态时只能从上边的状态转移过来而不能从左边的状态转移过来。 * */ int f[110][110]; int a[110][110]; int main(int argc, char const *argv[]) { cin >> n; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) cin >> a[i][j]; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { if (i == 1 && j == 1){ f[i][j]=a[1][1]; continue; } f[i][j] = 1e9; if (i > 1) f[i][j] = min(f[i][j], f[i - 1][j] + a[i][j]); if (j > 1) f[i][j] = min(f[i][j], f[i][j - 1] + a[i][j]); } cout << f[n][n] << endl; return 0; }
true
764cae0258c0154ce423b2a345dcb1375bce74cb
C++
kaseyhan/geometric-primitives
/include/core/pixel.h
UTF-8
824
3
3
[]
no_license
#pragma once #include "cinder/gl/gl.h" namespace geometricprimitives { class Pixel { public: Pixel(); Pixel(float red, float green, float blue); Pixel(float red, float green, float blue, float alpha); float GetRed() const; float GetGreen() const; float GetBlue() const; float GetAlpha() const; glm::vec2 GetLocation() const; void SetRed(float new_red); void SetGreen(float new_green); void SetBlue(float new_blue); void SetAlpha(float new_alpha); void SetRGBA(float r, float g, float b, float a); void SetLocation(glm::vec2 new_loc); /* * Adds the given RGBA values to this Pixel's, taking alpha value into account */ void AddRGBA(float added_red, float added_green, float added_blue, float added_alpha); private: float red_; float green_; float blue_; float alpha_; }; }
true
a2211098f1aba5fa374cee64033ec7818bd973d1
C++
hdinh77/heat-text-editor
/test.cpp
UTF-8
238
2.671875
3
[]
no_license
// test.cpp for Heat text editor // Heather Dinh #include <iostream> #include <string> int main(int argc, char* argv[]) { if(argc != 2) { return 0; } for(int i = 0; i < 10; i++) { std::cout << "Hello world!" << endl; } return 8; }
true
3e098c7b921cd24bb5143ec501cf6ddc3b65dcc9
C++
gangsaur/grafika-layer
/shape.h
UTF-8
666
3.140625
3
[]
no_license
#ifndef shape_h #define shape_h #include "point.h" #include <list> class shape{ private: int corners; list<point*> points; public: shape(int n){ corners = n; } ~shape(){ points.clear(); } void add(point* p) { points.push_back(p); } void add(int x, int y){ points.push_back(new point(x,y)); } point* get(int n){ if (n < corners){ std::list<point*>::iterator it = points.begin(); int i = 0; while (i != n){ ++it; i++; } return *it; } else { return new point(); } } int count(){ return points.size(); } int getCorner(){ return corners; } }; #endif
true
b7d040cad021b9f3f12f57d9956244234cde81ed
C++
LuisEduardoR/SCC0250-CG
/src/Rendering/TextureObject.cpp
UTF-8
2,359
2.984375
3
[ "MIT" ]
permissive
#include "TextureObject.hpp" TextureObject::TextureObject(Type type) : type(type) { glGenTextures(1, &self); } TextureObject::~TextureObject() { glDeleteTextures(1, &self); } auto TextureObject::Bind() -> void { glBindTexture(static_cast<GLenum>(type), self); } auto TextureObject::Unbind() -> void { glBindTexture(static_cast<GLenum>(type), 0); } auto TextureObject::UploadTexture(GLint level, std::shared_ptr<Texture2D> textureAsset) -> void { Bind(); glTexImage2D( static_cast<GLenum>(type), level, GL_RGBA, static_cast<GLsizei>(textureAsset->Width()), static_cast<GLsizei>(textureAsset->Height()), 0, // Always zero. Legacy stuff. static_cast<GLenum>(textureAsset->Format()), static_cast<GLenum>(textureAsset->Type()), textureAsset->Pixels().data()); // Refactor this code into their own functions. glTexParameteri(static_cast<GLenum>(type), GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(static_cast<GLenum>(type), GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(static_cast<GLenum>(type), GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); glTexParameteri(static_cast<GLenum>(type), GL_TEXTURE_MAG_FILTER, GL_NEAREST); glGenerateMipmap(static_cast<GLenum>(type)); } auto TextureObject::UploadTexture(GLint level, const std::array<std::shared_ptr<Texture2D>, 6> &textureAssets) -> void { Bind(); GLenum i = 0; for (std::shared_ptr<Texture2D> textureAsset : textureAssets) { glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, level, GL_RGBA, static_cast<GLsizei>(textureAsset->Width()), static_cast<GLsizei>(textureAsset->Height()), 0, // Always zero. Legacy stuff. static_cast<GLenum>(textureAsset->Format()), static_cast<GLenum>(textureAsset->Type()), textureAsset->Pixels().data()); i++; } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); }
true
fbd970617fa57a3a7561db96e495c55f5689e87e
C++
bahlo-practices/pa
/semester2/practice4/exercise2/main.cpp
UTF-8
1,277
3.109375
3
[ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * File: main.cpp * * Created on 15. Mai 2013, 16:13 */ #include <iostream> #include "myVector.h" #include "myVec.h" int main(int argc, char** argv) { try { // myVector<double> h1( 5 ); myVector<int> i1; i1.push_back(5); i1.set(0, 1); std::cout << i1.get(0) << std::endl; myVec<double> d1; d1.push_back(2.3); d1.push_back(-2.3); // d1.push_back("asdasd"); geht nicht, falscher typ myVec<char> c1; c1.push_back('a'); // c1.push_back("asd"); //myVec<char> asd1(2, -5); std::cout << "asdasd" << std::endl; myVec<int> i3(0,5); i3.set(0,23); i3.set(1,21); i3.set(2,22); myVec<int> i2; i2 = i3; i2.set(2,55); std::cout << "asd" << std::endl; std::cout << i2.get(2)<< std::endl; std::cout << i3.get(2)<< std::endl; std::cout << "main" << std::endl; return 0; } catch (std::runtime_error) { return -3; } catch (std::exception& e) { std::cout << "Error: " << e.what() << std::endl; return -2; } catch (...) { std::cout << "Unknown Error\n"; return -1; } }
true
a89082a56b2cf30e0e1dfc1fa9789b2d0e9604ff
C++
lavandalia/work
/Codeforces/188 (Div. 1)/A/main.cpp
UTF-8
568
2.84375
3
[]
no_license
#include <iostream> using namespace std; int main() { int64_t X, Y, M; cin >> X >> Y >> M; if (X > Y) swap(X, Y); if (Y >= M) { cout << "0\n"; return 0; } if (X <= 0 and Y <= 0) { cout << "-1\n"; return 0; } int64_t operations = 0; if (X < 0) { int64_t k = (-X - 1) / Y + 1; operations += k; X += k * Y; } while (max(X, Y) < M) { ++operations; if (X > Y) swap(X, Y); X = X + Y; } cout << operations << "\n"; }
true
518dec6b30a848b21342db8da4dd1da46d1cc11f
C++
aliosmanulusoy/Probabilistic-Volumetric-3D-Reconstruction
/contrib/brl/bseg/boxm/util/boxm_raytrace_operations.cxx
UTF-8
8,662
2.703125
3
[]
no_license
#include "boxm_raytrace_operations.h" bool boxm_alpha_seg_len(double *xverts_2d, double* yverts_2d, float* vert_distances, boct_face_idx visible_faces, float alpha, vil_image_view<float> &alpha_distance) { // multiply each vertex distance by alpha float vert_alpha_distances[8]; float *vert_dist_ptr = vert_distances; float *vert_alpha_dist_ptr = vert_alpha_distances; for (unsigned int i=0; i<8; ++i) { *vert_alpha_dist_ptr++ = *vert_dist_ptr++ * alpha; } // for each face, create two triangle iterators and fill in pixel data // X_LOW // tri 0 boxm_triangle_interpolation_iterator<float> tri_it(xverts_2d, yverts_2d, vert_alpha_distances, 0, 4, 3); if (visible_faces & X_LOW) tri_interpolate_values(tri_it, alpha_distance, true); else tri_interpolate_values(tri_it, alpha_distance, false); // tri 1 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_alpha_distances, 4, 7, 3); if (visible_faces & X_LOW) tri_interpolate_values(tri_it, alpha_distance, true); else tri_interpolate_values(tri_it, alpha_distance, false); // X_HIGH // tri 0 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_alpha_distances, 1, 2, 5); if (visible_faces & X_HIGH) tri_interpolate_values(tri_it, alpha_distance, true); else tri_interpolate_values(tri_it, alpha_distance, false); // tri 1 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_alpha_distances, 2, 6, 5); if (visible_faces & X_HIGH) tri_interpolate_values(tri_it, alpha_distance, true); else tri_interpolate_values(tri_it, alpha_distance, false); // Y_LOW // tri 0 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_alpha_distances, 0, 1, 5); if (visible_faces & Y_LOW) tri_interpolate_values(tri_it, alpha_distance, true); else tri_interpolate_values(tri_it, alpha_distance, false); // tri 1 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_alpha_distances, 0, 5, 4); if (visible_faces & Y_LOW) tri_interpolate_values(tri_it, alpha_distance, true); else tri_interpolate_values(tri_it, alpha_distance, false); // Y_HIGH // tri 0 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_alpha_distances, 3, 2, 6); if (visible_faces & Y_HIGH) tri_interpolate_values(tri_it, alpha_distance, true); else tri_interpolate_values(tri_it, alpha_distance, false); // tri 1 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_alpha_distances, 3, 6, 7); if (visible_faces & Y_HIGH) tri_interpolate_values(tri_it, alpha_distance, true); else tri_interpolate_values(tri_it, alpha_distance, false); // Z_LOW // tri 0 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_alpha_distances, 0, 1, 2); if (visible_faces & Z_LOW) tri_interpolate_values(tri_it, alpha_distance, true); else tri_interpolate_values(tri_it, alpha_distance, false); // tri 1 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_alpha_distances, 0, 2, 3); if (visible_faces & Z_LOW) tri_interpolate_values(tri_it, alpha_distance, true); else tri_interpolate_values(tri_it, alpha_distance, false); // Z_HIGH // tri 0 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_alpha_distances, 4, 5, 6); if (visible_faces & Z_HIGH) tri_interpolate_values(tri_it, alpha_distance, true); else tri_interpolate_values(tri_it, alpha_distance, false); // tri 1 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_alpha_distances, 4, 7, 6); if (visible_faces & Z_HIGH) tri_interpolate_values(tri_it, alpha_distance, true); else tri_interpolate_values(tri_it, alpha_distance, false); return true; } bool boxm_depth_fill(double *xverts_2d, double* yverts_2d, float* vert_distances, boct_face_idx visible_faces, vil_image_view<float> &depth_image) { // for each face, create two triangle iterators and fill in pixel data // X_LOW // tri 0 boxm_triangle_interpolation_iterator<float> tri_it(xverts_2d, yverts_2d, vert_distances, 0, 4, 3); if (visible_faces & X_LOW) tri_interpolate_values(tri_it, depth_image, true); // tri 1 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_distances, 4, 7, 3); if (visible_faces & X_LOW) tri_interpolate_values(tri_it, depth_image, true); // X_HIGH // tri 0 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_distances, 1, 2, 5); if (visible_faces & X_HIGH) tri_interpolate_values(tri_it, depth_image, true); // tri 1 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_distances, 2, 6, 5); if (visible_faces & X_HIGH) tri_interpolate_values(tri_it, depth_image, true); // Y_LOW // tri 0 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_distances, 0, 1, 5); if (visible_faces & Y_LOW) tri_interpolate_values(tri_it, depth_image, true); // tri 1 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_distances, 0, 5, 4); if (visible_faces & Y_LOW) tri_interpolate_values(tri_it, depth_image, true); // Y_HIGH // tri 0 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_distances, 3, 2, 6); if (visible_faces & Y_HIGH) tri_interpolate_values(tri_it, depth_image, true); // tri 1 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_distances, 3, 6, 7); if (visible_faces & Y_HIGH) tri_interpolate_values(tri_it, depth_image, true); // Z_LOW // tri 0 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_distances, 0, 1, 2); if (visible_faces & Z_LOW) tri_interpolate_values(tri_it, depth_image, true); // tri 1 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_distances, 0, 2, 3); if (visible_faces & Z_LOW) tri_interpolate_values(tri_it, depth_image, true); // Z_HIGH // tri 0 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_distances, 4, 5, 6); if (visible_faces & Z_HIGH) tri_interpolate_values(tri_it, depth_image, true); // tri 1 tri_it = boxm_triangle_interpolation_iterator<float>(xverts_2d, yverts_2d, vert_distances, 4, 7, 6); if (visible_faces & Z_HIGH) tri_interpolate_values(tri_it, depth_image, true); return true; } bool cube_fill_value(double* xverts_2d, double* yverts_2d, boct_face_idx visible_faces, vil_image_view<float> &img, float const& val) { // for each face, create two triangle iterators and fill in pixel data boxm_triangle_scan_iterator tri_it(xverts_2d, yverts_2d, 0,4,3); if (visible_faces & X_LOW) { // tri 0 tri_it = boxm_triangle_scan_iterator(xverts_2d, yverts_2d, 0, 4, 3); tri_fill_value(tri_it, img, val); // tri 1 tri_it = boxm_triangle_scan_iterator(xverts_2d, yverts_2d, 4, 7, 3); tri_fill_value(tri_it, img, val); } if (visible_faces & X_HIGH) { // tri 0 tri_it = boxm_triangle_scan_iterator(xverts_2d, yverts_2d, 1, 2, 5); tri_fill_value(tri_it, img, val); // tri 1 tri_it = boxm_triangle_scan_iterator(xverts_2d, yverts_2d, 2, 6, 5); tri_fill_value(tri_it, img, val); } if (visible_faces & Y_LOW) { // tri 0 tri_it = boxm_triangle_scan_iterator(xverts_2d, yverts_2d, 0, 1, 5); tri_fill_value(tri_it, img, val); // tri 1 tri_it = boxm_triangle_scan_iterator(xverts_2d, yverts_2d, 0, 5, 4); tri_fill_value(tri_it, img, val); } if (visible_faces & Y_HIGH) { // tri 0 tri_it = boxm_triangle_scan_iterator(xverts_2d, yverts_2d, 3, 2, 6); tri_fill_value(tri_it, img, val); // tri 1 tri_it = boxm_triangle_scan_iterator(xverts_2d, yverts_2d, 3, 6, 7); tri_fill_value(tri_it, img, val); } if (visible_faces & Z_LOW) { // tri 0 tri_it = boxm_triangle_scan_iterator(xverts_2d, yverts_2d, 0, 1, 2); tri_fill_value(tri_it, img, val); // tri 1 tri_it = boxm_triangle_scan_iterator(xverts_2d, yverts_2d, 0, 2, 3); tri_fill_value(tri_it, img, val); } if (visible_faces & Z_HIGH) { // tri 0 tri_it = boxm_triangle_scan_iterator(xverts_2d, yverts_2d, 4, 5, 6); tri_fill_value(tri_it, img, val); // tri 1 tri_it = boxm_triangle_scan_iterator(xverts_2d, yverts_2d, 4, 7, 6); tri_fill_value(tri_it, img, val); } return true; }
true
5d4b8dd4efb5df9df926f1c221108763e2d35430
C++
Maulin-sjsu/DataStructuresPractise
/LeetCodeProblem/Graph/FloodFill.cpp
UTF-8
1,062
3.625
4
[]
no_license
#include <iostream> #include <vector> using namespace std; void printMatrix(vector<vector<int>> v1){ for(int i = 0; i < v1.size(); i++){ for(int j = 0; j < v1[i].size(); j++) { cout << v1[i][j] << " "; } } } void fill(vector<vector<int>> &image,int i, int j, int currColor,int newColor){ if(i < 0 || i >= image.size() || j < 0 || j >= image[i].size() || image[i][j] != currColor) { return; } image[i][j] = newColor; fill(image, i+1, j, currColor ,newColor); fill(image, i-1, j, currColor ,newColor); fill(image, i, j+1, currColor ,newColor); fill(image, i, j-1, currColor ,newColor); } vector<vector<int>> floodfill(vector<vector<int>> &image,int sr, int sc,int newColor){ if(image[sr][sc] == newColor) { return image; } //cout << image[sr][sc] << newColor << endl; fill(image, sr, sc, image[sr][sc], newColor); return image; } int main(){ vector<vector<int>> v1 = {{1,1,1},{1,1,0},{1,0,1}}; printMatrix(floodfill(v1,1,1,2)); }
true
353b57088185ffd76fc8ddd7666adaf594b50935
C++
psiden/BFAST3D
/eb/util/Qinv/Qinv.cpp
ISO-8859-1
8,689
2.828125
3
[ "BSD-2-Clause" ]
permissive
//#define TIMING //To compile on Linux: //mex Qinv.cpp CFLAGS="\$CFLAGS -fopenmp" LDFLAGS="\$LDFLAGS -fopenmp" #include "mex.h" #include "matrix.h" #include<cstdio> #include<list> #include<vector> #ifdef _OPENMP #include<omp.h> #endif #ifdef TIMING #include<ctime> #endif typedef std::pair<size_t,double> Qpairtype; typedef std::vector< Qpairtype > Qvectype; typedef std::vector< Qvectype > Qtype; /**Checks if a given array contains a square, full, real valued, double matrix. *@param tmp pointer to a matlab array.*/ bool mxIsRealSparseDouble(const mxArray* tmp){ return mxIsSparse(tmp) && !mxIsComplex(tmp) && mxIsDouble(tmp) && !mxIsEmpty(tmp); } /**Checks if a given array contains a real positive scalar. *@param tmp pointer to a matlab array.*/ bool mxIsRealPosScalar(const mxArray* tmp){ return mxGetNumberOfElements(tmp)==1 && !mxIsComplex(tmp) && mxIsDouble(tmp) && !mxIsEmpty(tmp); } /**Entry point for matlab interface (mex function). *A standard matlab entry point which generates a mex-file. */ //mexFunction entry point. extern "C" void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]){ #ifdef TIMING clock_t start = clock(); const double ticks_per_ms = static_cast<double>(CLOCKS_PER_SEC)/1000; #endif //inital data check if(nlhs>1) mexErrMsgTxt("Function returns ONE value."); if(nrhs!=1 && nrhs!=2) mexErrMsgTxt("Function requires 1-2 input(s)."); if(!mxIsRealSparseDouble(prhs[0])) mexErrMsgTxt("First argument should be a sparse, double matrix."); int Nthreads=8; if(nrhs==2){ if(!mxIsRealPosScalar(prhs[1])) mexErrMsgTxt("Second argument should be a real scalar."); double *ptrData = mxGetPr(prhs[1]); if(ptrData==NULL) mexErrMsgTxt("Unable to obtain pointers to second argument."); Nthreads = static_cast<int>( *ptrData ); if(Nthreads<1) Nthreads=1; } #ifdef _OPENMP //set nbr threads in openMP omp_set_dynamic(1); omp_set_num_threads(Nthreads); #endif //Optain pointer to the elements in the R-matrix mwIndex *Rir = mxGetIr(prhs[0]); mwIndex *Rjc = mxGetJc(prhs[0]); double *Rpr = mxGetPr(prhs[0]); if(Rir==NULL || Rjc==NULL || Rpr==NULL) mexErrMsgTxt("Unable to obtain pointers to data in R-matrix."); size_t n = mxGetN(prhs[0]); if(n != mxGetM(prhs[0]) ) mexErrMsgTxt("R-matrix should be square"); if(Rjc[n]==Rjc[n-1]) mexErrMsgTxt("R-matrix has an empty last row."); size_t i,j; Qtype R(n); std::vector<double> D(n); //Extract the elements and store the sparse R-matrix //in a more convinient format. if(Rjc[n]-Rjc[n-1] == 1){ //only one element in the last column, assume lower triangular matrix for(size_t c=0;c<n;++c){ if(Rir[Rjc[c]] != c) //not a diagonal element mexErrMsgTxt("R-matrix is not lower triangular."); D[c] = Rpr[Rjc[c]]; R[c].resize(Rjc[c+1]-Rjc[c]); for(j=Rjc[c],i=0;j<Rjc[c+1];++j,++i) R[c][i] = Qpairtype(Rir[j], Rpr[j]); } }else{ //assume upper triangular matrix - first find number of element in each row std::vector<size_t> nRow(n), iRow(n); for(size_t c=0;c<n;++c){ for(j=Rjc[c];j<Rjc[c+1];++j) ++nRow[Rir[j]]; if(Rir[Rjc[c+1]-1] != c) //not a diagonal element mexErrMsgTxt("R-matrix is not upper triangular."); D[c] = Rpr[Rjc[c+1]-1]; } for(size_t c=0;c<n;++c) R[c].resize( nRow[c] ); for(size_t c=0;c<n;++c){ for(j=Rjc[c];j<Rjc[c+1];++j) R[Rir[j]][iRow[Rir[j]]++] = Qpairtype(c, Rpr[j]); } }//if(Rjc[n]-Rjc[n-1] == 1){ }else{ } Qvectype::iterator pos; size_t Nmax=0; //divide all elemnts in R by the diagonal-elements for(i=0; i<n; ++i){ //find the maximal number of non-zero elements in any row of R if(Nmax < R[i].size()) Nmax = R[i].size(); //compute R[i,j]/D[i] for(pos=R[i].begin(); pos!=R[i].end(); ++pos) (pos->second) /=D[i]; //and compute 1/d^2 D[i] = 1/(D[i]*D[i]); } //count number of elements that is going to end up in iQ std::vector<size_t> nnz(n,1); for(i=0; i<n; ++i){ //first find the indices of the non-zero elements for(pos=++(R[i].begin()); pos!=R[i].end(); ++pos){ nnz[i]++; nnz[pos->first]++; } } //vectors containing the location and values within one column std::vector<size_t> ii(Nmax); std::vector<double> s(Nmax); std::vector< Qvectype::iterator > iQpos(Nmax); std::vector< Qvectype::iterator > iQstart(n); //create a structure holding the inverse matrix Qtype iQ(n); for(i=0; i<n; ++i){ iQ[i].resize(nnz[i]); iQstart[i] = iQ[i].end(); } #ifdef TIMING double compute_iQ_ind = 0; double compute_iQ_mult = 0; double compute_iQ_diag = 0; double compute_iQ_addEl = 0; double init_time = static_cast<double>(clock()-start) / ticks_per_ms; #endif //loop over the columns of the matrix i = n; while(i>0){ #ifdef TIMING start = clock(); #endif --i; //first find the indices of the non-zero elements for(pos=++(R[i].begin()), j=0; pos!=R[i].end(); ++pos, j++){ ii[j] = pos->first; //index of elements s[j] = 0; //set values to zero iQpos[j] = iQstart[ii[j]]; //start of each iQ row } #ifdef TIMING compute_iQ_ind += static_cast<double>(clock()-start) / ticks_per_ms; start = clock(); #endif //multiply the row of R with the rows of iQ #pragma omp parallel for private(pos) for(int j2=0; j2<(R[i].size()-1); ++j2){ Qvectype::iterator iQpos_tmp = iQpos[j2]; Qvectype::iterator iQend = iQ[ii[j2]].end(); for(pos=++(R[i].begin()); pos!=R[i].end(); ++pos){ for(;iQpos_tmp != iQend && iQpos_tmp->first < pos->first; ++iQpos_tmp){} if(iQpos_tmp != iQend && iQpos_tmp->first == pos->first) s[j2] += (iQpos_tmp->second) * (pos->second); } } #ifdef TIMING compute_iQ_mult += static_cast<double>(clock()-start) / ticks_per_ms; start = clock(); #endif //the diagonal elements double diag = D[i]; for(pos=++(R[i].begin()), j=0; pos!=R[i].end(); ++pos, ++j) diag += s[j] * (pos->second); #ifdef TIMING compute_iQ_diag += static_cast<double>(clock()-start) / ticks_per_ms; start = clock(); #endif //add the elements to iQ j = R[i].size()-1; while(j>0){ --j; *(--iQstart[i]) = Qpairtype(ii[j], -s[j]); *(--iQstart[ ii[j] ]) = Qpairtype(i, -s[j]); } *(--iQstart[i]) = Qpairtype(i, diag); #ifdef TIMING compute_iQ_addEl += static_cast<double>(clock()-start) / ticks_per_ms; #endif }//i = n; while(i>0){ #ifdef TIMING double compute_iQ = compute_iQ_ind + compute_iQ_mult + compute_iQ_diag + compute_iQ_addEl; start = clock(); #endif //count number of non-zero elements in iQ Nmax = 0; for(i=0; i<n; ++i) Nmax += iQ[i].size(); //construct sparse matrix. plhs[0] = mxCreateSparse(n,n,Nmax,mxREAL); double* pr = mxGetPr(plhs[0]); mwIndex* ir = mxGetIr(plhs[0]); mwIndex* jc = mxGetJc(plhs[0]); jc[0] = 0; for(i=0, j=0; i<n; ++i){ jc[i+1] = jc[i] + iQ[i].size(); for(pos=iQ[i].begin(); pos!=iQ[i].end(); ++pos, ++j){ ir[j] = pos->first; pr[j] = pos->second; } } #ifdef TIMING double create_iQ = static_cast<double>(clock()-start) / ticks_per_ms; mexPrintf("Timing info (in ms):\n"); mexPrintf(" init: %7.1f\n",init_time); mexPrintf(" comp. iQ ind : %7.1f\n", compute_iQ_ind); mexPrintf(" comp. iQ mult: %7.1f\n", compute_iQ_mult); mexPrintf(" comp. iQ diag: %7.1f\n", compute_iQ_diag); mexPrintf(" comp. iQ add : %7.1f\n", compute_iQ_addEl); mexPrintf(" comp. iQ: %7.1f\n",compute_iQ); mexPrintf("create iQ: %7.1f\n",create_iQ); mexPrintf(" total: %7.1f\n", init_time + compute_iQ + create_iQ); mexPrintf("\nNumber of threads: %i/%i\n",Nthreads,omp_get_max_threads()); #endif }//extern "C" void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) /**\interface writeSparse * function writeSparse(fname,A) * WRITESPARSE Writes sparse matrix to a text file. * * writeSparse(filname,A) * filenam: Filename to write to. * A: Sparse matrix to be written. fid = fopen(fname,'w'); [I,J,S] = find(A); I = I-1; J=J-1; fwrite(fid,[size(A,1) size(A,2)],'uint32'); for i=1:numel(I) fwrite(fid,[I(i) J(i)],'uint32'); fwrite(fid,S(i),'float64'); end fclose(fid); * Implemented in a MATLAB mex file using: * writeSparse.cpp * Copyright 2007 Johan Lindstrm */
true
004b985a49bcfabb2547ffcbe1a80399b9932b84
C++
thijshosman/learncpp-playground
/learncpp playground/constClass.h
UTF-8
279
2.734375
3
[]
no_license
#pragma once class constClass { private: int m_pr_value; public: int m_value; void print() const; // const after method name, before definition // since this class is going to be instantiated as const, all method also have to be const constClass(); ~constClass(); };
true
29a10c62039ad89590ef882f7b62254cd66d9330
C++
fwhxyer/PAT
/1058.cpp
UTF-8
310
2.53125
3
[]
no_license
#include<iostream> using namespace std; int main(){ int a,b,c,d,e,f,g,h,i; char t; while(cin>>a){ cin>>t>>b>>t>>c; cin>>d>>t>>e>>t>>f; i=c+f; h=b+e+i/29; i%=29; g=a+d+h/17; h%=17; cout<<g<<"."<<h<<"."<<i<<endl; } return 0; }
true
b3398ad13cfca675410700d84f78d14ea72ab633
C++
cvora23/CodingInterviewQ
/C-C++/Concepts/DeepVsShallowCopy.cpp
UTF-8
451
2.859375
3
[]
no_license
/* * DeepVsShallowCopy.cpp * * Created on: Sep 2, 2014 * Author: cvora */ // Cracking the Coding Interview - Sol 13.4 #include <string.h> #include <stddef.h> #include <cstdlib> using namespace std; struct Test{ char* ptr; }; void shallow_copy(Test& src,Test& dest){ dest.ptr = src.ptr; } void deep_copy(Test& src,Test& dest){ dest.ptr = (char*)malloc(strlen(src.ptr) + 1); strcpy(dest.ptr,src.ptr); } int main(){ return 0; }
true
b2c9995c4f6c2ef125c726a121bfff621873829d
C++
CarolineFs/AlgoesAnalysis
/lab_01/source/main.cc
UTF-8
1,156
2.9375
3
[]
no_license
#include <iostream> #include "EditDistanceTester.h" #include "CharWordHandler.h" using namespace std; int main(int argc, char **argv) { bool showTime = false; std::string s1; std::string s2; auto tester = new EditDistanceTester<string>; for (int idx = 1; idx < argc; idx++) { switch (argv[idx][0]) { case '0': tester->toLevenshteinRec(); break; case '1': tester->toWagnerFischer(); break; case '2': tester->toDamerauLevenshtein(); break; case '3': tester->toDamerauLevenshteinRec(); break; case 'o': tester->enableOptInfo(); break; case 'O': tester->disableOptInfo(); break; case 't': showTime = true; break; case 'T': showTime = false; } } while ((cin >> s1 >> s2).good()) { cout << tester->calculate(s1, s2) << " "; if (showTime) cout << tester->timeTestResult(); cout << '\n'; } delete tester; return 0; }
true
df0089177a5e9cc25d22bdf9a39ebbce47969509
C++
leek018/Algo
/baekjoon/baekjoon/baekjoon_14891.cpp
UTF-8
1,768
2.953125
3
[]
no_license
#include <iostream> #include <cstring> #include <string> using namespace std; string gear[4]; void rotate_cw(int target) { string copy = gear[target]; for (int i = 0; i < 7; i++) gear[target][i + 1] = copy[i]; gear[target][0] = copy[7]; } void rotate_ccw(int target) { string copy = gear[target]; for (int i = 0; i < 7; i++) gear[target][i] = copy[i + 1]; gear[target][7] = copy[0]; } int main() { ios::sync_with_stdio(0); cin.tie(0); int three = 2; int nine = 6; for (int i = 0; i < 4; i++) cin >> gear[i]; int cw_count = 0; int ccw_count = 0; int rotate_cw_target[2]; int rotate_ccw_target[2]; int k; cin >> k; for (int i = 0; i < k; i++) { cw_count = 0; ccw_count = 0; int number, direction; cin >> number >> direction; number -= 1; if (direction == 1) rotate_cw_target[cw_count++] = number; else rotate_ccw_target[ccw_count++] = number; int copy_direction = direction; for (int i = number; i > 0; i--) { copy_direction *= -1; if (gear[i][nine] != gear[i - 1][three]) { if (copy_direction == 1) rotate_cw_target[cw_count++] = i - 1; else rotate_ccw_target[ccw_count++] = i - 1; } else break; } copy_direction = direction; for (int i = number; i < 3; i++) { copy_direction *= -1; if (gear[i][three] != gear[i + 1][nine]) { if (copy_direction == 1) rotate_cw_target[cw_count++] = i + 1; else rotate_ccw_target[ccw_count++] = i + 1; } else break; } for (int i = 0; i < cw_count; i++) rotate_cw(rotate_cw_target[i]); for (int i = 0; i < ccw_count; i++) rotate_ccw(rotate_ccw_target[i]); } int answer = 0; for (int i = 0; i < 4; i++) { if (gear[i][0] == '1') answer += (1 << i); } cout << answer; }
true
b5e7ef54cd4b18e0274e5e93a9c810f47b96e866
C++
alexzhang13/rcj-code
/Software/navigate/navigateMap.cpp
UTF-8
2,647
2.71875
3
[]
no_license
#include "navigateMap.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> // external API functions void initMap(MapState *mapstate, const float cellsize, const unsigned int numcells_x, const unsigned int numcells_y) { unsigned int i, j; if(!mapstate) return; mapstate->mMapProp.CellSize = cellsize; mapstate->mMapProp.NumCellsX = numcells_x; mapstate->mMapProp.NumCellsY = numcells_y; mapstate->mMaptype = Fixed; mapstate->mOriginIndex = (unsigned int)(numcells_x*numcells_y/2); // allocate the map mapstate->mMap = (unsigned char **) malloc(numcells_y*sizeof(unsigned char*)); for(j = 0; j < numcells_y; j++) { mapstate->mMap[j] = (unsigned char *) malloc(numcells_x*sizeof(unsigned char)); } assert(mapstate->mMap != 0); for(j = 0; j < numcells_y; j++) { for(i = 0; i < numcells_x; i++) { mapstate->mMap[j][i] = mGray; } } return; } bool loadMapTxt(MapState *mapstate, char *filename) { int i, j; if(!mapstate || !filename) return false; FILE *hf = fopen(filename, "r"); if(!hf) return false; unsigned char **map = mapstate->mMap; /* map index: i: cnt%numCell_x j: cnt/numCell_y map[j][i] is assigned by the value from the file */ int cnt= 0; while(1) { // read in file // save to map if( feof(hf) ) { break ; } cnt++; } fclose(hf); return true; } bool loadMapColor(MapState *mapstate, char *imagename) { if(!mapstate || !imagename) return false; // not implemented return true; } void closeMap(MapState *mapstate) { unsigned int j; if(!mapstate) return; // free the map for(j = 0; j < mapstate->mMapProp.NumCellsY; j++) { free(mapstate->mMap[j]); } free(mapstate->mMap); mapstate->mMap = 0; } bool initVehiclePosition(MapState *mapstate, const Point3D Translation, const Point3D Rotation) { if(!mapstate) return false; return true; } bool updateParams(MapState *mapstate) { // not implemented yet return false; } // returns the total number of cells in the map const unsigned int getNumCells(MapState *mapstate) { if(!mapstate) return (unsigned int) (-1); unsigned int numCellsX = mapstate->mMapProp.NumCellsX; unsigned int numCellsY = mapstate->mMapProp.NumCellsY; return numCellsX * numCellsY; } // returns the length of the side of a map cell const float getCellSize(MapState *mapstate) { if(!mapstate) return -1.0f; return mapstate->mMapProp.CellSize; } unsigned char **get2dMap(MapState *mapstate) { if(!mapstate) return 0; return mapstate->mMap; } // print the map in color void printMap_color(MapState *mapstate) { } // print out the map in text format void printMap_txt(MapState *mapstate) { }
true
bbcf84854e03f1f04ca8b6ce768f1526bbbf0a16
C++
hohaidang/CPP_Basic2Advance
/Book_Source/Cpp-Primer-Plus-programming-exercises-master/Cpp-Primer-Plus-programming-exercises-master/code/Chapter18/18_3.cpp
UTF-8
539
3.359375
3
[]
no_license
// By luckycallor // Welcome to my site: www.luckycallor.com #include<iostream> using namespace std; template<typename Tval,typename... Targs> long double sum_value(Tval val,Targs... args) { long double sum; sum = (long double)val + sum_value(args...); return sum; } template<typename Tval> long double sum_value(Tval val) { return (long double)val; } int main() { long double sum; sum = sum_value(1,5,8.9); cout << sum << endl; sum = sum_value(1.8,89,9,'d'); cout << sum << endl; return 0; }
true
414f049d355b5910958ecd2fd6f97ca972923b39
C++
casa9eu/arduino-camp
/src/07/_15.ino
UTF-8
348
2.90625
3
[ "Apache-2.0" ]
permissive
#include <Servo.h> Servo servo_0; Servo servo_1; void setup(){ pinMode(A0, INPUT); servo_0.attach(0); pinMode(A1, INPUT); servo_1.attach(1); } void loop(){ servo_0.write(map(analogRead(A0), 0, 1023, 0, 180)); servo_1.write(map(analogRead(A1), 0, 1023, 0, 180)); delay(10); // Delay a little bit to improve simulation performance }
true
84ccc8a94d1f77d5013cf36aac21d67e83422b5b
C++
MukulMadaan/GeeksMustDo
/LinkList/DeleteNnodesAfterMnodes.cpp
UTF-8
437
3.21875
3
[]
no_license
void linkdelete(struct Node *head, int M, int N) { struct Node* current = head; struct Node* prev; int temp1,temp2; temp1 = M; temp2 = N; while(current){ while(M-- && current){ prev = current; current = current->next; } while(N-- && current){ prev->next = current->next; current = current->next; } M = temp1; N = temp2; } }
true
bd2be3f6040abaa48f91514f1b49163a409db475
C++
akshaymishra5395/GeeksforGeeks
/Kadane's Algorithm.cpp
UTF-8
599
3.34375
3
[]
no_license
class Solution{ public: // arr: input array // n: size of array //Function to find the sum of contiguous subarray with maximum sum. int maxSubarraySum(int arr[], int n){ int sum=INT_MIN; int s=0; for (int i=0;i<n;i++) { s+=arr[i]; if(s>sum) { sum=s; } if (s<0) { s=0; } } return sum; return sum; } };
true
1e307a4ab51be6d75c190ad37459900503da3cc6
C++
GZHU-JourneyWest/West-Codebase
/Raw/数据结构/树状数组(二维).cpp
UTF-8
351
2.984375
3
[]
no_license
// cell[x][y]增加v void add(int x, int y, int v) { for (int i = x; i<maxN; i+=lowbit(i)) for (int j = y; j<maxN; j+=lowbit(j)) cell[i][j] += v; } // (1, 1)至(x, y)中所有单元格的数值和 int get(int x, int y) { int rslt = 0; for (int i = x; i; i-=lowbit(i)) for (int j = y; j; j-=lowbit(j)) rslt += cell[i][j]; return rslt; }
true
34c9f7b7606f2e6be85f324272889fe490d8ecd0
C++
neilpradhan/Competitive_Programming
/Backtracking/rat_in_a_maze.cpp
UTF-8
1,131
2.8125
3
[]
no_license
#include<bits/stdc++.h> #include<iostream> using namespace std; void printfinal(int sol[20][20], int N){ for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ cout<<sol[i][j]<<" "; } } cout<<endl; } bool valid_index(int maze[20][20],int sol[20][20], int x, int y, int N){ if (x>=0 && x<N && y>=0 && y<N && maze[x][y] == 1 && sol[x][y]==0){ return true; } return false; } void find_path(int maze[20][20], int x, int y, int sol[20][20], int N){ //base case if (x == N-1 && y == N-1){ sol[x][y]=1; printfinal(sol,N); } if (valid_index(maze,sol, x, y,N)){ sol[x][y]=1; find_path(maze,x-1,y,sol, N); find_path(maze,x+1,y,sol, N); find_path(maze,x,y-1,sol, N); find_path(maze,x,y+1,sol, N); //backtrack sol[x][y]=0; } // the index goes out of bound } void ratInAMaze(int maze[20][20],int n){ int sol[20][20]; for(int i = 0; i < n ;i++){ for(int j = 0; j < n; j++){ sol[i][j]=0; } } find_path(maze,0,0,sol,n); //cout<<"path not found"; }
true
3baf99b242c0c743b6a9919844ec200e49a5946e
C++
gbrlas/AVSP
/CodeJamCrawler/dataset/12_24324_53.cpp
UTF-8
1,324
2.53125
3
[]
no_license
#include<algorithm> #include<iterator> #include<iostream> #include<sstream> #include<string> #include<vector> #include<queue> #include<map> #include<ctime> #include<cmath> #include<cstdlib> #include<cstdio> #include<cstring> using namespace std; const int maxn=2001; struct node { int x,y; }; node a[maxn]; int f[maxn]; int v,n,s,t,y; bool flag=false; void search() { int x=0; for (int i=1;i<=n;i++) if (s>=a[i].y&&f[i]!=2) { x=1; s+=2-f[i]; t++; f[i]=2; } if (x==1) search(); } void search0() { int x=0; for (int i=1;i<=n;i++) if (f[i]==0&&a[i].x<=s) { x=i; break; } for (int i=x+1;i<=n;i++) if (a[i].y>a[x].y&&a[i].x<=s&&f[i]==0) x=i; if (x==0) printf("!!!!!\n"); s++; t++; f[x]=1; } int main() { freopen("b.in","r",stdin); freopen("b.out","w",stdout); scanf("%d\n",&v); for (int u=1;u<=v;u++) { scanf("%d\n",&n); memset(f,0,sizeof(f)); for (int i=1;i<=n;i++) scanf("%d %d\n",&a[i].x,&a[i].y); s=0;t=0; y=s; while (s<2*n) { flag=true; y=s; for (int i=1;i<=n;i++) if ((f[i]==0&&s>=a[i].x)||(f[i]==1&&s>=a[i].y)) { flag=false; break; } if (flag) break; search(); if (s==y) search0(); } if (s>2*n) printf("!!!\n"); if (s==2*n) printf("Case #%d: %d\n",u,t); else printf("Case #%d: Too Bad\n",u); } return 0; }
true
194b4f04f305faaede0ce569aa8b8fc99eb67ace
C++
GaryPlaysGames/C-ProgammingLanguageTextBookPrograms
/Chapter 3 - Shaper Class Hierarchy/Chapter 3 - Shaper Class Hierarchy/Square.h
UTF-8
813
3.046875
3
[]
no_license
#ifndef SQUARE_H #define SQUARE_H #include <iostream> #include <initializer_list> #include "Shape.h" class Square : public Shape { public: Square(); Square(double a, double b, double c, double d); Square(std::initializer_list<double>& il); Square(const Square& a); Square& operator=(const Square& a); Square(Square&& a); Square& operator=(Square&& a); bool operator==(const Square& a) const; bool operator!=(const Square& a) const; Square& operator*(); friend std::ostream& operator<<(std::ostream& os, const Square& a); friend std::istream& operator>>(std::istream& is, const Square& a); bool operator()(const Square& a) const; double* begin() const; double* end() const; double area() const override; double parameter() const override; ~Square(); private: double* points; }; #endif
true
ce0b6aee2956db6153c1a454881f7c7362283153
C++
MiritHadar/Practice
/cpp/writer/writer.hpp
UTF-8
2,428
2.640625
3
[]
no_license
/******************************************************************************/ /* author: Ori Michaeli */ /* Reviewer: */ /* version: Draft */ /* Last update: 24-09-2019 */ /******************************************************************************/ #ifndef ILRD_RD6768_WRITER #define ILRD_RD6768_WRITER #if __cplusplus < 201103L #define nullptr NULL #define noexcept throw() #endif #include <iostream> // Streams #include <queue> // Queue funcs #include "uncopyable.hpp" #include "thread.hpp" #include "waitable_queue.hpp" namespace ilrd { template <typename MsgFunctor> class WriteMsgFunctor; template <typename MsgFunctor> class Writer : private Uncopyable { public: //Constructors explicit Writer(); ~Writer() noexcept; //Operators //Functions void WriteMsg(MsgFunctor msg_); private: //Member variables WaitableQueue<std::queue<MsgFunctor> > m_waitQ; WriteMsgFunctor<MsgFunctor> m_writeMsgFunctor; Thread m_thread; }; template <typename MsgFunctor> Writer<MsgFunctor>::Writer() : m_waitQ(), m_writeMsgFunctor(m_waitQ), m_thread(m_writeMsgFunctor) { ; } template <typename MsgFunctor> Writer<MsgFunctor>::~Writer() noexcept { m_writeMsgFunctor.SetStopFlag(); m_thread.Join(); } template <typename MsgFunctor> void Writer<MsgFunctor>::WriteMsg(MsgFunctor msg_) { m_waitQ.Push(msg_); } template <typename MsgFunctor> class WriteMsgFunctor : private Uncopyable { public: //Constructors explicit WriteMsgFunctor(WaitableQueue<std::queue<MsgFunctor> > &waitQ_); //~WriteMsgFunctor()noexcept = default; //Operators void operator()(); //Functions void SetStopFlag(); private: //Member variables WaitableQueue<std::queue<MsgFunctor> > &m_waitQ; bool m_stopFlag; }; template <typename MsgFunctor> WriteMsgFunctor<MsgFunctor>::WriteMsgFunctor (WaitableQueue<std::queue<MsgFunctor> > &waitQ_) : m_waitQ(waitQ_), m_stopFlag(false) { ; } template <typename MsgFunctor> void WriteMsgFunctor<MsgFunctor>::operator()() { while (!m_stopFlag) { MsgFunctor ret; if (m_waitQ.Pop(ret, static_cast<boost::chrono::milliseconds>(1000))) { ret(); } } } template <typename MsgFunctor> void WriteMsgFunctor<MsgFunctor>::SetStopFlag() { m_stopFlag = true; } }//namespace ilrd #endif //ILRD_RD6768_WRITER
true
d41f578530e4aaa61b6e0a91c87ba152952f573c
C++
dlswer23/cpp
/C++/접근제어지시자.cpp
UHC
560
3.484375
3
[]
no_license
#include<iostream> using namespace std; // : ü ϴ Լ(ڵ) // Ҹ : ü Ҹ ȣǴ Լ(ڵ) // Ŭ ̸ = Լ̸ // ȯ X , Ҹ ~ Լ̸ class CMyData { int m_nData; //private public: int GetData() {} void SetData(int nParam) { m_nData = nParam; } }; int main (){ CMyData a; // ü << νϽ << ȣ a.SetData(10); cout << a.GetData() << endl; return 0; } //
true
eeb943395a49624d96a730411d70af262f047bda
C++
letrend/yac-nc1
/software/src/cnc_gui/src/test_joystick.cpp
UTF-8
3,155
3.296875
3
[ "MIT" ]
permissive
/** * Author: Jason White * * Description: * Reads joystick/gamepad events and displays them. * * Compile: * gcc joystick.c -o joystick * * Run: * ./joystick [/dev/input/jsX] * * See also: * https://www.kernel.org/doc/Documentation/input/joystick-api.txt */ #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <linux/joystick.h> /** * Reads a joystick event from the joystick device. * * Returns 0 on success. Otherwise -1 is returned. */ int read_event(int fd, struct js_event *event) { ssize_t bytes; bytes = read(fd, event, sizeof(*event)); if (bytes == sizeof(*event)) return 0; /* Error, could not read full event. */ return -1; } /** * Returns the number of axes on the controller or 0 if an error occurs. */ size_t get_axis_count(int fd) { __u8 axes; if (ioctl(fd, JSIOCGAXES, &axes) == -1) return 0; return axes; } /** * Returns the number of buttons on the controller or 0 if an error occurs. */ size_t get_button_count(int fd) { __u8 buttons; if (ioctl(fd, JSIOCGBUTTONS, &buttons) == -1) return 0; return buttons; } /** * Current state of an axis. */ struct axis_state { short x, y; }; /** * Keeps track of the current axis state. * * NOTE: This function assumes that axes are numbered starting from 0, and that * the X axis is an even number, and the Y axis is an odd number. However, this * is usually a safe assumption. * * Returns the axis that the event indicated. */ size_t get_axis_state(struct js_event *event, struct axis_state axes[3]) { size_t axis = event->number / 2; if (axis < 3) { if (event->number % 2 == 0) axes[axis].x = event->value; else axes[axis].y = event->value; } return axis; } int main(int argc, char *argv[]) { const char *device; int js; struct js_event event; struct axis_state axes[3] = {0}; size_t axis; if (argc > 1) device = argv[1]; else device = "/dev/input/js0"; js = open(device, O_RDONLY); if (js == -1) perror("Could not open joystick"); /* This loop will exit if the controller is unplugged. */ while (read_event(js, &event) == 0) { switch (event.type) { case JS_EVENT_BUTTON: printf("Button %u %s\n", event.number, event.value ? "pressed" : "released"); break; case JS_EVENT_AXIS: axis = get_axis_state(&event, axes); if (axis < 3) printf("Axis %zu at (%6d, %6d)\n", axis, axes[axis].x, axes[axis].y); break; default: /* Ignore init events. */ break; } fflush(stdout); } close(js); return 0; }
true
7d50fa0ede5ec0ee4b3b53d116f3b38004db3903
C++
Nabz786/CIS-263project1
/include/AUDS.h
UTF-8
5,173
3.984375
4
[]
no_license
#include <iostream> #include <string> #include <cstdlib> #include <stdlib.h> /***************************************************************** * Almost Useless Data Structure (AUDS). This data structure will * hold any type of object, through the use of a class template. * * @author Runquan Ye, Nabeel Vali * @version Winter 2018 *****************************************************************/ template <typename T> class AUDS{ public: /*********************************************************************** *Generic Constructor used when program is started to intialize our *generic array *@Author Runquan Ye, Nabeel Vali ***********************************************************************/ AUDS(){ currentSize = 0; currentMax = 100; data = new T[currentMax]; } /************************************************************************ * This is the copy constructor. It will take as a parameter a reference * to another AUDS object and will perform a DEEP copy of the object. * @author: Nabeel * @return: Deep copy of the another data structure to this one ***********************************************************************/ AUDS(const AUDS &other){ currentSize = other.currentSize; currentMax = other.currentMax; data = new T[currentMax]; for(int j = 0; j<currentMax; j++){ data[j] = other.data[j]; } } /************************************************************************ * This is the copy operator=. It will perform the copy-and-swap we * learned about in class to set one object equal to another. It also * performs a DEEP copy. * @author: Runquan Ye * @return: the newly copyed data structure ***********************************************************************/ AUDS& operator = (AUDS other){ std::swap(currentMax, other.currentMax); std::swap(currentSize, other.currentSize); std::swap(data, other.data); return *this; } /************************************************************************ * This is the destructor. It will give back any memory we borrowed from * the OS to hold the data we stored. * @author: Runquan Ye ***********************************************************************/ ~AUDS(){ delete[] data; } /************************************************************************ * Returns the current number of objects we are holding. * @author: Nabeel Vali * @return: int the size/number of objects in the structure **********************************************************************/ int size(){ return currentSize; } /************************************************************************ * Adds the generic element to the data structure. If the array is full * we recreate the array making it 50% larger * @author: Nabeel Vali * @throws: Notification to the user that the array may have not been * created ***********************************************************************/ void push(T e){ if(currentSize == currentMax){ doubleArraySize(); data[currentSize] = e; currentSize++; } else{ data[currentSize] = e; currentSize++; } } /************************************************************************ * Removes a random item from the list. Moves the last item in the array * to the spot that was occupied by the element we removed. * @author: Runquan Ye & Nabeel * @return: T the popped object * @throws: Notification to the user that there's nothing left to pop ***********************************************************************/ T pop(){ //checks to see if user is popping from an empty structure and //notifys user if(currentSize == 0){ throw "No elements are left to pop"; } //if the "if" condition is not method remove a random element else{ T temp; int randomIndex = rand()%currentSize; temp = data[randomIndex]; data[randomIndex] = data[currentSize]; currentSize -= 1; return temp; } } private: /** Initial (starting) size of the array **/ int initialSize; /** Current size of our array **/ int currentSize; /** Current max size of the array **/ int currentMax; /** Generic pointer to our array **/ T* data; /************************************************************************* *created a new array 50% larger, and re-points the pointer *This method should be private as it should only be called on one *condition in the push() method *@Author Nabeel ************************************************************************/ void doubleArraySize(){ T* newData = new T[(int)(currentMax * 1.5)]; for(int i = 0; i < currentMax; i++){ newData[i] = data[i]; } delete[] data; data = newData; currentMax = (int)(currentMax * 1.5); } };
true
dee35ffd7809d20040661cb3ec48531236a5607f
C++
haran2001/DSA
/dp/test3.cpp
UTF-8
733
3.140625
3
[]
no_license
//template for dp #include<iostream> #include<stdio.h> #include<stdlib.h> #include<map> #include<iterator> #include<string.h> #include<unordered_set> using namespace std; unordered_set<string> st; void subsequence(string str){ for(int i=0; i<str.length(); i++){ for(int j=str.length(); j > i; j--){ string sub_str = str.substr(i, j); st.insert(sub_str); for(int k = 1; k < sub_str.length()-1; k++){ string sb = sub_str; sb.erase(sb.begin() + k); subsequence(sb); } } } } int main(){ string s = "aabc"; subsequence(s); for(auto i: st) cout << i << " "; cout << endl; return 0; }
true
b02d911e171f566c863868b74436cede2b0eb48d
C++
Tri125/GestionAbonnement
/Noeud.cpp
UTF-8
955
2.8125
3
[ "BSD-3-Clause" ]
permissive
#include "librairie.h" Noeud::Noeud() { pInfo = nullptr; pNext = nullptr; } Noeud::Noeud(Abonnement* ab) { pInfo = ab; pNext = nullptr; pBack = nullptr; } Noeud::Noeud(unsigned int i, string p, string n, string titre, string addr, DateEpoch date) { pInfo = new Abonnement(i, p, n, titre, addr, date); pNext = nullptr; pBack = nullptr; } Noeud::Noeud(unsigned int i, string p, string n, string titre, string addr, int a, int m, int j) { pInfo = new Abonnement(i, p, n, titre, addr, a, m ,j); pNext = nullptr; pBack = nullptr; } Noeud::~Noeud() { delete pInfo; } Noeud* dernierNoeud(Noeud* racine) { while (racine && racine->pNext) racine = racine->pNext; return racine; } string Noeud::ToString() { return pInfo->ToString(); } #pragma region Getter Abonnement* Noeud::getPInfo() { return pInfo; } #pragma endregion Getter #pragma region Setter void Noeud::setPInfo(Abonnement* info) { pInfo = info; } #pragma endregion Setter
true
50e6d6a68178f58de80c0976fefc6cc26e8f8d48
C++
IITK-SUMMER-QUAD-2015-TEAM/QuadIITK
/code/secondOrderFilter.ino
UTF-8
1,162
2.53125
3
[ "Unlicense" ]
permissive
#include<SPI.h> #include<Wire.h> #define CUTOFF 21// The cutoff frequency #define SAMPLE_RATE 100 #define NUM_FILTERS 6 enum {ACCEL_X , ACCEL_Y, ACCEL_Z, GYRO_X, GYRO_Y, GYRO_Z}; int16_t Tmp; class filter { public: static float coeff[5]; float filterInput(float input); private: float output[3]={0,0,0}; float input[3]={0,0,0}; }; float filter::coeff[5]; float filter::filterInput(float Input) { input[0]=Input; output[0]=coeff[0]*input[0]+coeff[1]*input[1]+coeff[2]*input[2]-coeff[3]*output[2]-coeff[4]*output[1]; output[2]=output[1]; output[1]=output[0]; input[2]=input[1]; input[1]=input[0]; return output[0]; } filter filters[NUM_FILTERS]; void getCoefficients(){ double sqrt2 = sqrt(2); double QcRaw = (2 * PI * CUTOFF) / SAMPLE_RATE; double QcWarp = tan(QcRaw); double gain = 1 / ( 1 + sqrt2 / QcWarp + 2 / ( QcWarp * QcWarp ) ); filter::coeff[4] = ( 1 - sqrt2 / QcWarp + 2 / ( QcWarp * QcWarp ) ) * gain; filter::coeff[3] = ( 2 - 2 * 2 / ( QcWarp * QcWarp ) ) * gain; filter::coeff[0] = 1 * gain; filter::coeff[1] = 2 * gain; filter::coeff[2] = 1 * gain; }
true
ea6ffa68427c116dede854bf52bbcfaef6d81050
C++
Sadanand14/FALCON_ENGINE
/Falcon/Falcon/Rendering/PipeLine/CanvasItems/Slider.h
UTF-8
1,873
2.765625
3
[]
no_license
#ifndef SLIDER_H #define SLIDER_H #include <string> #include "CanvasItem.h" #include "System/Types.h" namespace UI { /** * A basic Slider */ class Slider : public CanvasItem { protected: float m_minValue; float m_maxValue; float m_curValue; float m_step; nk_color m_sliderBarNormal; nk_color m_sliderBarHover; nk_color m_sliderBarActive; nk_color m_sliderBarFill; nk_color m_sliderCursorNormal; nk_color m_sliderCursorHover; nk_color m_sliderCursorActive; struct nk_vec2 m_cursorSize; float m_barHeight; public: Slider(); virtual ~Slider(); void Commands(nk_context* ctx) override; inline void SetMinValue(float minValue) { m_minValue = minValue; } inline void SetMaxValue(float maxValue) { m_maxValue = maxValue; } inline void SetStep(float step) { m_step = step; } inline float GetCurValue() { return m_curValue; } inline void SetBarNormalColor(glm::vec4 color) { m_sliderBarNormal = nk_rgba(color.r, color.g, color.b, color.a); } inline void SetBarHoverColor(glm::vec4 color) { m_sliderBarHover = nk_rgba(color.r, color.g, color.b, color.a); } inline void SetBarActiveColor(glm::vec4 color) { m_sliderBarActive = nk_rgba(color.r, color.g, color.b, color.a); } inline void SetBarFillColor(glm::vec4 color) { m_sliderBarFill = nk_rgba(color.r, color.g, color.b, color.a); } inline void SetCursorNormalColor(glm::vec4 color) { m_sliderCursorNormal = nk_rgba(color.r, color.g, color.b, color.a); } inline void SetCursorHoverColor(glm::vec4 color) { m_sliderCursorHover = nk_rgba(color.r, color.g, color.b, color.a); } inline void SetCursorActiveColor(glm::vec4 color) { m_sliderCursorActive = nk_rgba(color.r, color.g, color.b, color.a); } inline void SetCursorSize(glm::vec2 size) { m_cursorSize = nk_vec2(size.x, size.y); } inline void SetBarHeight(float height) { m_barHeight = height; } }; } #endif
true
a69ecc75f8888ed811ba7eef8f2215eb7f1e760c
C++
vrtex/tanks2
/main.cpp
UTF-8
556
2.59375
3
[]
no_license
#include "simulation.h" #include "Tank.h" int main() { sf::RenderWindow window; window.setFramerateLimit(60); Simulation test(&window, 2); Tank hurr(&window, {100, 200}, 20, 0); hurr.connect(&test); sf::Event e; while(window.isOpen()) { while(window.pollEvent(e)) { if(e.type == sf::Event::Closed) window.close(); if(test.getInput(e)) continue; if(hurr.getInput(e)) continue; } test.update(); hurr.update(); window.clear(); test.draw(); hurr.draw(); window.display(); } return 42; }
true
d5269d9a7eacb6695e8b1c6fc66334ec8643bfc3
C++
YiuWingTan/Algorithm
/LeetCode和一些杂题/Subsets II/源.cpp
WINDOWS-1252
1,040
3.359375
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; void getSubSets(vector<vector<int>> &result,vector<int> &arr,vector<int> &nums,int begin,int len) { if (arr.size() == len) { result.push_back(arr); return; } int size = nums.size() - (len - arr.size()) + 1; for (int i = begin; i <size; i++) { arr.push_back(nums[i]); getSubSets(result,arr,nums,i+1,len); arr.pop_back(); //Ծ while (i + 1 < size&&nums[i] == nums[i + 1]) i++; } return; } vector<vector<int>> subsetsWithDup(vector<int>& nums) { vector<vector<int>> result; vector<int> arr; result.push_back(vector<int>{}); sort(nums.begin(), nums.end()); for (int i = 1; i <= nums.size(); i++) { getSubSets(result, arr, nums, 0, i); } return result; } int main() { vector<int> nums = { 1,2,2 }; auto result = subsetsWithDup(nums); for (int i = 0; i < result.size(); i++) { for (int j = 0; j < result[i].size(); j++) { cout << result[i][j] << " "; } cout << endl; } getchar(); return 0; }
true
351410fe0b0186f8b22d1e6c5b066e253616508c
C++
Sumendra2906/DS-ALGO
/1-10/10 Searching and Sorting/string_sort.cpp
UTF-8
1,229
3.421875
3
[]
no_license
#include <iostream> using namespace std; bool subst(string a, string b) { int counter = 0; for (int i = 0; i < a.length(); i++) { if (counter == b.length()) { return true; } if (a[i] == b[counter]) { counter++; } else { counter = 0; } } return false; } bool compare(string a, string b) { if (subst(a, b) or subst(b, a)) { return a.length()>b.length(); } return (a < b); } void string_sort(int n, string *ar,bool (&compare)(string a,string b)) { for (int i = 0; i < n - 1; i++) { bool swapped = false; for (int j = 0; j < n - i - 1; j++) { if (compare(ar[j+1],ar[j])) { swap(ar[j], ar[j + 1]); swapped = true; } } if (swapped == false) { break; } } } int main() { int n; cin >> n; string *ar = new string[n]; for (int i = 0; i < n; i++) { cin >> ar[i]; } string_sort(n, ar,compare); for (int i = 0; i < n; i++) { cout << ar[i] << endl; } delete[] ar; return 0; }
true
a9401fa02342f2e80f20ffbfe98044e19ed12817
C++
hanchao/tangram-es
/core/src/scene/spotLight.cpp
UTF-8
2,413
2.703125
3
[ "MIT" ]
permissive
#include "spotLight.h" #include "glm/gtx/string_cast.hpp" std::string SpotLight::s_classBlock; SpotLight::SpotLight(const std::string& _name, bool _dynamic):PointLight(_name,_dynamic),m_direction(1.0,0.0,0.0),m_spotExponent(0.0),m_spotCutoff(0.0),m_spotCosCutoff(0.0) { m_typeName = "SpotLight"; m_type = LightType::SPOT; } SpotLight::~SpotLight() { } void SpotLight::setDirection(const glm::vec3 &_dir) { m_direction = _dir; } void SpotLight::setCutOff(float _cutoffAngle, float _exponent) { m_spotCutoff = _cutoffAngle; m_spotCosCutoff = cos(_cutoffAngle * 3.14159 / 180.0);//cos(_cutoff); m_spotExponent = _exponent; } void SpotLight::setupProgram( std::shared_ptr<ShaderProgram> _shader ) { if (m_dynamic) { PointLight::setupProgram(_shader); _shader->setUniformf(getUniformName()+".direction", m_direction); _shader->setUniformf(getUniformName()+".spotCosCutoff", m_spotCosCutoff); _shader->setUniformf(getUniformName()+".spotExponent", m_spotExponent); } } std::string SpotLight::getClassBlock() { if (s_classBlock.empty()) { s_classBlock = stringFromResource("spotLight.glsl")+"\n"; } return s_classBlock; } std::string SpotLight::getInstanceDefinesBlock() { std::string defines = ""; if (m_constantAttenuation!=0.0) { defines += "#define TANGRAM_SPOTLIGHT_CONSTANT_ATTENUATION\n"; } if (m_linearAttenuation!=0.0) { defines += "#define TANGRAM_SPOTLIGHT_LINEAR_ATTENUATION\n"; } if (m_quadraticAttenuation!=0.0) { defines += "#define TANGRAM_SPOTLIGHT_QUADRATIC_ATTENUATION\n"; } return defines; } std::string SpotLight::getInstanceAssignBlock() { std::string block = Light::getInstanceAssignBlock(); if (!m_dynamic) { block += ", " + glm::to_string(m_position); block += ", " + glm::to_string(m_direction); block += ", " + std::to_string(m_spotCosCutoff); block += ", " + std::to_string(m_spotExponent); if (m_constantAttenuation!=0.0) { block += ", " + std::to_string(m_constantAttenuation); } if (m_linearAttenuation!=0.0) { block += ", " + std::to_string(m_linearAttenuation); } if (m_quadraticAttenuation!=0.0) { block += ", " + std::to_string(m_quadraticAttenuation); } block += ")"; } return block; }
true
22eb936be80e9e04293f13715bb06a56bc7de229
C++
dominguezi10/p3Lab-6_IngridDominguez_Reposicion
/Normal.h
UTF-8
509
2.59375
3
[]
no_license
#include <string> #include <iostream> #include "Bombas.h" using namespace std; #ifndef NORMAL_H #define NORMAL_H //Inicio clase class Normal: public Bombas{ //Atributos private: int alcance; //metodos publicos public: //prototipos de metodos //constructor Normal(); Normal(int, int); //metodos accersores / mutadores int getAlcance(); void setAlcance(int); //Destructor ~Normal(); };//Fin de la clase #endif
true
8429c68b8eefb2767a549aac38783f289841e928
C++
ap-hynninen/cv_search
/src/Coord.cpp
UTF-8
5,530
2.5625
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <stdlib.h> #include "../include/Coord.hpp" // // Class constructor // Coord::Coord(const char *coord_filename, const int ncoord, const int nshoot, const float rnn) { this->ncoord = ncoord; this->nshoot = nshoot; coord = NULL; resid = NULL; mass = NULL; residue_start = NULL; nnlist_pos = NULL; nnlist = NULL; load_coord(coord_filename); build_nnlist(rnn); setup_residues(); } // // Class destructor // Coord::~Coord() { if (coord != NULL) { for (int i=0;i < nshoot;i++) delete [] coord[i]; delete [] coord; } if (resid != NULL) delete [] resid; if (mass != NULL) delete [] mass; if (residue_start != NULL) delete [] residue_start; if (nnlist_pos != NULL) delete [] nnlist_pos; if (nnlist != NULL) delete [] nnlist; } // // Builds neighborlist using the first shooting point // void Coord::build_nnlist(const float rnn) { // Estimate number of neighbors each atom has float xmin = 1.0e10; float ymin = 1.0e10; float zmin = 1.0e10; float xmax = -1.0e10; float ymax = -1.0e10; float zmax = -1.0e10; for (int i=0;i < ncoord;i++) { xmin = (xmin < coord[0][i].x) ? xmin : coord[0][i].x; ymin = (ymin < coord[0][i].y) ? ymin : coord[0][i].y; zmin = (zmin < coord[0][i].z) ? zmin : coord[0][i].z; xmax = (xmax > coord[0][i].x) ? xmax : coord[0][i].x; ymax = (ymax > coord[0][i].y) ? ymax : coord[0][i].y; zmax = (zmax > coord[0][i].z) ? zmax : coord[0][i].z; } double vol = (xmax-xmin)*(ymax-ymin)*(zmax-zmin); nnlist_len = (int)((4.0/3.0*3.14159265358979323846*rnn*rnn*rnn)*((double)ncoord)*1.2/vol) + 1; nnlist_len = (nnlist_len < ncoord*ncoord) ? nnlist_len : ncoord*ncoord; nnlist_pos = new int[ncoord+1]; nnlist = new int[nnlist_len]; // Build neighborlist int pos = 0; float rnn2 = rnn*rnn; for (int i=0;i < ncoord;i++) { float xi = coord[0][i].x; float yi = coord[0][i].y; float zi = coord[0][i].z; nnlist_pos[i] = pos; for (int j=0;j < ncoord;j++) { if (i != j) { float xj = coord[0][j].x; float yj = coord[0][j].y; float zj = coord[0][j].z; float dx = xi-xj; float dy = yi-yj; float dz = zi-zj; float r2 = dx*dx + dy*dy + dz*dz; if (r2 < rnn2) { // Reallocate if needed if (pos == nnlist_len) { int nnlist_len_new = (int)((double)nnlist_len*1.5); nnlist_len_new = (nnlist_len_new < ncoord*ncoord) ? nnlist_len_new : ncoord*ncoord; int *nnlist_new = new int[nnlist_len_new]; for (int t=0;t < nnlist_len;t++) { nnlist_new[t] = nnlist[t]; } delete [] nnlist; nnlist = nnlist_new; nnlist_len = nnlist_len_new; } // Add to list nnlist[pos++] = j; } } } } std::cout << "Coord::build_nnlist, pos/ncoord = " << pos/ncoord << std::endl; nnlist_pos[ncoord] = pos; } // // Setups residues // void Coord::setup_residues() { // Count the number of residues nresidue = 0; int prev_resid = -1; for (int i=0;i < ncoord;i++) { if (resid[i] != prev_resid) { prev_resid = resid[i]; nresidue++; } } residue_start = new int[nresidue+1]; // Mark residue starts prev_resid = -1; int j = 0; for (int i=0;i < ncoord;i++) { if (resid[i] != prev_resid) { prev_resid = resid[i]; residue_start[j] = i; j++; } } residue_start[nresidue] = ncoord; // Calculate the maximum residue size max_residue_size = 0; for (int i=0;i < nresidue;i++) { //std::cout << i << " " << get_residue_start(i) << " " << get_residue_stop(i) << std::endl; int residue_size = get_residue_stop(i) - get_residue_start(i) + 1; max_residue_size = (max_residue_size < residue_size) ? residue_size : max_residue_size; } std::cout << "Coord::setup_residues, nresidue = " << nresidue << " max_residue_size = " << max_residue_size << std::endl; } // // Load coordinates // void Coord::load_coord(const char *filename) { std::ifstream file; file.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { // Open file file.open(filename); std::cout << "Coord::load_coord, ncoord = " << ncoord << " nshoot = " << nshoot << std::endl; // Allocate coord coord = new float3*[nshoot]; for (int i=0;i < nshoot;i++) coord[i] = new float3[ncoord]; // Allocate resid resid = new int[ncoord]; // Allocate mass mass = new float[ncoord]; // Read coordinates for (int k=0;k < nshoot;k++) { for (int i=0;i < ncoord;i++) { char atomstr[6], atomname[6], resname[8]; int atomid, resid_tmp; double dummy1, dummy2; file >> atomstr >> atomid >> atomname >> resname >> resid_tmp >> coord[k][i].x >> coord[k][i].y >> coord[k][i].z >> dummy1 >> dummy2; if (k == 0) { // Set mass if (atomname[0] == 'H') { mass[i] = 1.008; } else if (atomname[0] == 'N') { mass[i] = 14.007; } else if (atomname[0] == 'C') { mass[i] = 12.011; } else if (atomname[0] == 'O') { mass[i] = 15.999; } else if (atomname[1] == 'H') { mass[i] = 1.008; } else { std::cerr << "Unidentified atom type at " << i+1 << " atomname="<< atomname << " atomid = "<< atomid << " assigned as H" << std::endl; //exit(1); mass[i] = 1.008; } // Set residue ID resid[i] = resid_tmp; } } } // Close file file.close(); } catch(std::ifstream::failure e) { std::cerr << "Error opening/reading/closing file " << filename << std::endl; exit(1); } }
true
0425925046475f9f0659b4718ed98e5fa89c62c1
C++
amecky/space
/src/queues/WorkQueue.h
UTF-8
1,754
2.734375
3
[ "Apache-2.0" ]
permissive
#pragma once #include <vector> #include "..\Common.h" #include "..\registries\PriceRegistry.h" class Serializer; // ------------------------------------------------------ // Work item // ------------------------------------------------------ struct WorkItem { int tile_x; int tile_y; WorkType work_type; int timer; int duration; int price_index; int building_id; int level; bool reschedule; bool done; }; // ------------------------------------------------------ // Event // ------------------------------------------------------ struct Event { WorkType work_type; int tile_x; int tile_y; int building_id; int level; }; // ------------------------------------------------------ // event buffer // ------------------------------------------------------ struct EventBuffer { Event events[256]; int size; void clear() { size = 0; } void add(const Event& e) { events[size++] = e; } const Event& get(int index) const { return events[index]; } }; // ------------------------------------------------------ // Work queue // ------------------------------------------------------ class WorkQueue { typedef std::vector<WorkItem> Queue; public: WorkQueue(PriceRegistry* price_registry); ~WorkQueue(void); void tick(int timeUnits); void createWork(WorkType work_type,int x,int y,int building_id, int level,int duration); bool hasEvents() { return _buffer.size > 0; } const Event& getEvent(int index) const { return _buffer.get(index); } const int event_size() const { return _buffer.size; } void remove(WorkType work_type, int x,int y); void show() const; void save(Serializer& writer); void load(Serializer& reader); private: PriceRegistry* _price_registry; Queue _queue; EventBuffer _buffer; };
true
e6fd22c1cadb157234a15a68f9d2c77b6685a986
C++
alexandre-janniaux/UGEngine
/UGEngine/include/UGEngine/Core/DestructionTrigger.ipp
UTF-8
510
2.59375
3
[]
no_license
#include <UGEngine/Core/DestructionTrigger.hpp> #include <UGEngine/Core/DestructionListener.hpp> namespace uge { template <typename T> DestructionTrigger<T>::DestructionTrigger(T& instance) : m_instance(instance) {} template <typename T> DestructionTrigger<T>::~DestructionTrigger() { for (auto listener : m_listeners) listener->onTriggerDestruction(&m_instance); } template <typename T> void DestructionTrigger<T>::subscribe(DestructionListener<T>& listener) { m_listeners.push_back(&listener); } }
true
23aedbea8ecacbd9050720c673bf0012f8965a57
C++
12330072/C-learning
/C++/Relax/Relax/counter1.h
UTF-8
269
2.53125
3
[]
no_license
#ifndef counter1_h #define counter1_h class counter1 { public: static int counter; counter1() { } static void count() { counter++; } void operator()() { counter++; } }; int counter1::counter = 0; #endif /* counter1_h */
true
75cbe73bee3a0f71113e9198f0db310768ccac5f
C++
ccpang96/SWORD
/SWORD/剑指offer/队列和栈/30.包含min函数的栈.cpp
GB18030
951
3.015625
3
[]
no_license
/************************************************************************/ /*@File Name : 30.minջ.cpp /*@Created Date : 2020/6/8 18:36 /*@Author : ccpang(ccpang96@163.com) /*@blog : www.cnblogs.com/ccpang /*@Description : /************************************************************************/ #include<iostream> #include<vector> #include<algorithm> #include<unordered_map> #include<string> #include<sstream> #include<queue> #include<stack> using namespace std; class Solution { public: void push(int value) { s1.push(value); if (value < minValue) { minValue = value; } s2.push(minValue); } void pop() { int min_value = s2.top(); s1.pop(); s2.pop(); if (min_value < s2.top()) minValue = s2.top(); } int top() { return s1.top(); } int min() { return s2.top(); } private: stack<int>s1; // stack<int>s2; //Сֵ int minValue = INT_MAX; };
true
52c9bfd709cc68036cc422132c54294fb2dbbfe7
C++
shubh720/Lauchpad-June
/Lecture-19/queuell.cpp
UTF-8
230
2.765625
3
[]
no_license
#include<iostream> using namespace std; template <typename T> struct node{ T data; node * next; node(T data){ this->data = data; next = NULL; } }; struct queue{ node * head; node * tail; };
true
c5f13eff0b7e4758a8cdbfeaf30c516d636d50ee
C++
acsearle/mania
/mania-test/delta_table-test.cpp
UTF-8
2,452
2.625
3
[]
no_license
// // delta_table-test.cpp // mania-test // // Created by Antony Searle on 27/11/19. // Copyright © 2019 Antony Searle. All rights reserved. // #include "delta_table.hpp" #include "debug.hpp" #include <catch2/catch.hpp> #include "tattler.hpp" namespace manic { TEST_CASE("delta_table") { SECTION("regression") { delta_table<u64, u64> x; REQUIRE_FALSE(x.contains(0)); } SECTION("default") { delta_table<u64, u64> t; REQUIRE(t.size() == 0); REQUIRE_FALSE(t.contains(0)); REQUIRE_FALSE(t.try_get(1)); SECTION("insert") { t.insert(1, 2); REQUIRE(t.size() == 1); REQUIRE(t.contains(1)); SECTION("get") { REQUIRE(t.get(1) == 2); } SECTION("erase") { t.erase(1); REQUIRE(t.size() == 0); REQUIRE_FALSE(t.contains(1)); } } } SECTION("stress") { const u64 N = 1'000'000; delta_table<u64, u64> t; for (u64 i = 0; i != N; ++i) { t.insert(i, hash(i)); } REQUIRE(t.size() == N); for (u64 i = 0; i != N / 2; ++i) { REQUIRE(t.contains(i)); REQUIRE_FALSE(t.contains(i + N)); } for (u64 i = 0; i != N; ++i) { u64 v = t.get(i); REQUIRE(v == hash(i)); } for (u64 i = 0; i != N; ++i) { t.erase(i); REQUIRE(t.size() == N - 1 - i); } REQUIRE(t.size() == 0); } SECTION("lifetimes") { const int N = 1'000'000; delta_table<int, tattler> t; for (int i = 0; i != N; ++i) { t.insert(i, tattler()); } REQUIRE(tattler::_live == N); for (int i = 0; i != N; ++i) { t.erase(i); } REQUIRE(tattler::_live == 0); } } }
true
af94aa4c56ba6a466473ceb8a1878431c36b408b
C++
Ranazh/Shakieva_ACM_Labs
/Lab1_ACM_2020/Strings/3.myAtoi/ConsoleApplication10/ConsoleApplication10.cpp
UTF-8
1,417
3.59375
4
[]
no_license
// ConsoleApplication10.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <iostream> #include <string> using namespace std; class Solution { public: bool isNumericChar(char c) //function to checking is char a digit { if (c >= '0' && c <= '9') return true; return false; } int myAtoi(string str) { int size = str.size(); long long res = 0; bool ch = true;//to checkin the first elemnts are only digit int sign = 1;//positive or negative if (size > 0) { int i = 0; while (i < size) { if (isNumericChar(str[i])) { //the char is digit ch = false; int temp = str[i] - '0';//convert to int res = 1LL * res * 10 + 1LL * temp;//input in result string //checking that the result is included in the range [−2^31, 2^31 − 1] if (res > 1LL * INT_MAX) { if (sign == -1) return INT_MIN; return INT_MAX; } } else if (str[i] == ' ') { if (ch == false) break; } else if ((str[i] == '-' || str[i] == '+') && ch == true) { if (str[i] == '-') sign = -1; ch = false; } else { return sign * res; } i++; } } return sign * res; } }; int main() { Solution *obj = new Solution(); string s; cin >> s; cout << obj->myAtoi(s); return 0; }
true
a673c5f34d8fbda2da90ff248ef1881f7ea7d004
C++
LaylaHirsh/Victor
/tools/ConfigTest.cc
UTF-8
1,633
2.96875
3
[]
no_license
#include <config.h> #include<stdio.h> int main() { double db=0.0; int it=0; unsigned int uit=0; string text; float ft=0.0; config tmp("../config/testconfig.cfg"); cout << "euro " << tmp.getParameter("euro",db) << endl; cout << "eindrittel " << tmp.getParameter("eindrittel",ft) << endl; cout << "pi " << tmp.getParameter("pi",ft) << endl; cout << "tausend " << tmp.getParameter("tausend",it) << endl; if(tmp.existParameter("text")) { cout << "Text " << tmp.getParameter("text",text) << endl; } cout << "Integernum " << tmp.getParameter("integernum",it) << endl; cout << "Unsigned int " << tmp.getParameter("integernum",uit) << endl; cout << "minuseins " << tmp.getParameter("minuseins",it) << endl; it=-3; if(tmp.setParameter("minuseins",it)){ cout << "minuseins was updated with setParameter" << endl;} cout << "minuseins " << tmp.getParameter("minuseins",it) << endl; uit=42; if(tmp.changeParameter("integernum",uit)){ cout << "integernum was changed !" << endl; } if(tmp.delParameter("text")) { cout << "text wurde geloescht" << endl;} if(tmp.delParameter("floatzahl")) { cout << "floatzahl wurde geloescht" << endl; } if(tmp.newParameter("testconfig1.cfg","testnew",ft)) { cout << "The parameter testnew was created" << endl; cout << "testnew " << tmp.getParameter("testnew",ft) << endl; } ft=0; string txt="neuer text :) 1.12.99"; if(tmp.newParameter("testconfig.cfg","neutext",txt)) { cout << "neutext lautet " << tmp.getParameter("neutext",txt) << endl; }; return 0; }
true
54864def67b3f4375dacceff59333bdbf78fb933
C++
edmilson-dk/academic-programming
/search-algorithms/binary-search/c++/recursive-binary-search.cpp
UTF-8
727
3.890625
4
[ "MIT" ]
permissive
// O(log n) #include <iostream> using namespace std; int recursiveBinarySearch(int vector[], int left, int right, int wanted) { if (left <= right) { int pivot = left + (right - left) / 2; if (vector[pivot] == wanted) return pivot; else if (vector[pivot] < wanted) { return recursiveBinarySearch(vector, pivot+1, right, wanted); } else { return recursiveBinarySearch(vector, left, pivot-1, wanted); } } else { return -1; } } int main() { int myVector[5] = { 10, 20, 40, 50, 30 }; int result = recursiveBinarySearch(myVector, 0, 4, 50 ); (result == -1) ? printf("Elemento não encontrado no vetor\n") : printf("Elemento encontrado no índice: %d\n", result); return 0; }
true
f5dd3a037389565e04013d2bb3241bfed2217abc
C++
hzqtc/zoj-solutions
/src/zoj1560.cpp
UTF-8
1,140
2.921875
3
[]
no_license
#include <iostream> #include <iomanip> #include <cmath> #define PI 3.14159265358979323846 #define RAD(x) ((double)((x) / 180.0 * PI)) using namespace std; int main() { int casecount; int cx1,cy1,cd1; int cx2,cy2,cd2; double ox,oy; cin >> casecount; while(casecount--) { cin >> cx1 >> cy1 >> cd1 >> cx2 >> cy2 >> cd2; if(cd1 == 180 || cd1 == 0)//l1 : x = cx1; l2 : y - cy2 = k2 * (x - cx2) { ox = (double)cx1; oy = cy2 + (-tan(RAD(cd2 - 90))) * (double)(cx1 - cx2); } else if(cd2 == 180 || cd2 == 0) { ox = cx2; oy = cy1 + (-tan(RAD(cd1 - 90))) * (double)(cx2 - cx1); } else { double k1 = -tan(RAD(cd1 - 90)),k2 = -tan(RAD(cd2 - 90)); ox = (cy2 - cy1 - k2 * cx2 + k1 * cx1) / (k1 - k2); oy = cy1 + k1 * (ox - cx1); } cout << setprecision(4) << setiosflags(ios::fixed); //if((int)(ox * 100000) % 10 >= 5) // ox += 0.0001; //if((int)(oy * 100000) % 10 >= 5) // oy += 0.0001; cout << ox << ' ' << oy << endl; } return 0; }
true
b0f628abfacce7552b132ed981a2e29dd4cef4ae
C++
yekesit/OA-or-Interview-Questions
/yelp/merge_intervals_resturant_2.cpp
UTF-8
1,254
3.21875
3
[ "MIT" ]
permissive
// // Created by Ke Ye on 2019-07-27. // #include <iostream> #include <vector> #include <unordered_map> using namespace std; pair<int, int> isSame(string& s1, string& s2){ int idx1 = s1.find_last_of(' '); int idx2 = s2.find_first_of(' '); return s1.substr(idx1 + 1) == s2.substr(0, idx2) ? make_pair(idx1, idx2) : make_pair(-1, -1); } vector<vector<string>> mergeTime(vector<vector<string>>& input){ vector<vector<string>> res{input[0]}; for(int i = 1; i < input.size(); i++){ if(res.back()[0] == input[i][0]){ auto cur = isSame(res.back()[1], input[i][1]); if(cur.first > 0){ res.back()[1] = res.back()[1].substr(0, cur.first) + input[i][1].substr(cur.second + 2); } else{ res.push_back(input[i]); } } else{ res.push_back(input[i]); } } return res; } int main() { vector<vector<string>> input{ {"Monday","10:00am - 2:00pm"}, {"Monday","2:00pm - 6:00pm"}, {"Tuesday","10:00am - 3:00pm"}, {"Tuesday","4:00pm - 6:00pm"} }; vector<vector<string>> res = mergeTime(input); for(auto& r : res) cout << r[0] << ' ' << r[1] << endl; }
true
579189e1ee6dbd2d940e0c4bab8fff7f3a67c990
C++
MindrescuAlbert/Tema_2_POO
/VinVarsat.h
UTF-8
785
2.65625
3
[]
no_license
#ifndef VINVARSAT_H #define VINVARSAT_H #include <iostream> #include <string> #include <vector> #include "produs.h" using namespace std; class VinVarsat: public produs { int volum; string tip; public: VinVarsat() : produs() { volum=0; tip.clear(); }; VinVarsat(int p,int vol,string tipp) :produs(p,"VinVarsat") { volum=vol; tip=tipp; } VinVarsat(const VinVarsat &v); VinVarsat& operator=(const VinVarsat &v); ~VinVarsat() { nume.clear(); tip.clear(); } int Getpret(); int Getvolum(); string Gettip(); void Setvolum(int vol); void citire(istream &in); void afisare(ostream &out) const; }; #endif // VINVARSAT_H
true
fefa2d014cbbc86746fd3bf582647bf83746d9fd
C++
MrBlueBird2/cpp-for-beginners
/linear-search/main.cpp
UTF-8
354
3.671875
4
[]
no_license
// Linear search is an algorithm to find an integer in an given array, It is slow, but, Fast when the length of the array is less. #include <iostream> using namespace std; int main() { int arr[] = { 10, 20, 30, 40, 50 }; int k = 30; for (int i = 0; i < arr.length(); i ++) { if (arr[i] == k) { cout << i << endl; break } } }
true
a449df300b6adc938f2d360db06e642a91f8a064
C++
kyulee2/Algorithm
/CourseScheduleIII/t1.cpp
UTF-8
2,160
3.875
4
[]
no_license
/* There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day. Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken. Example: Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]] Output: 3 Explanation: There're totally 4 courses, but you can take 3 courses at most: First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day. Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date. Note: The integer 1 <= d, t, n <= 10,000. You can't take two courses simultaneously. */ // Comment: Idea is to apply EDF (early deadline first) + max queue (scheduled course with max duration) // When schedule fails with EDF, replace the current task with one from max queue if the duration from queue is greater -- basically remove the old(longer) course from the queue and put the current one in the queue. // The queue contains the courses that are scheduled. class Solution { public: int scheduleCourse(vector<vector<int>>& courses) { sort(courses.begin(), courses.end(), [](const vector<int>&a, const vector<int>b) { return a[1] < b[1]; } ); priority_queue<int> q; int time = 0; int ans = 0; for(auto &c : courses) { int t = c[0]; int d = c[1]; if (d >= time + t) { q.push(t); time +=t ; } else if (q.size()>0 && q.top() > t) { time += t - q.top(); q.pop(); q.push(t); } } return q.size(); } };
true