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
fabd578a51c54cb21a6f2903916ac0207e412d50
C++
rybcom/circular_buffer
/tools/utilities/public/MemoryProfiler.h
UTF-8
680
3.078125
3
[ "BSD-3-Clause" ]
permissive
#pragma once #include <iostream> struct memory_profiler_t { std::size_t all_reservation_count; std::size_t all_releasing_count; std::size_t current_reservated_size; std::size_t current_reservated_count; }; inline memory_profiler_t memory_profiler; inline void * operator new(std::size_t size) { ++memory_profiler.current_reservated_count; memory_profiler.current_reservated_size += size; ++memory_profiler.all_reservation_count; return malloc(size); } inline void operator delete(void * obj, std::size_t size) { --memory_profiler.current_reservated_count; memory_profiler.current_reservated_size -= size; ++memory_profiler.all_releasing_count; free(obj); }
true
dfdb28a697781eda388cb5e3ff74d63ba24925cd
C++
SPontadit/LuxUmbra
/Luxumbra/source/rhi/RHI_ComputePipeline.cpp
UTF-8
2,457
2.546875
3
[ "Apache-2.0" ]
permissive
#include "rhi\RHI.h" namespace lux::rhi { ComputePipeline::ComputePipeline() noexcept : pipeline(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE), descriptorSetLayout(VK_NULL_HANDLE) { } void RHI::CreateComputePipeline(const ComputePipelineCreateInfo& luxComputePipelineCI, ComputePipeline& computePipeline) noexcept { VkShaderModule computeShaderModule = CreateShaderModule(luxComputePipelineCI.binaryComputeFilePath); VkPipelineShaderStageCreateInfo computeStageCI = {}; computeStageCI.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; computeStageCI.stage = VK_SHADER_STAGE_COMPUTE_BIT; computeStageCI.module = computeShaderModule; computeStageCI.pName = "main"; VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCI = {}; descriptorSetLayoutCI.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descriptorSetLayoutCI.bindingCount = TO_UINT32_T(luxComputePipelineCI.descriptorSetLayoutBindings.size()); descriptorSetLayoutCI.pBindings = luxComputePipelineCI.descriptorSetLayoutBindings.data(); CHECK_VK(vkCreateDescriptorSetLayout(device, &descriptorSetLayoutCI, nullptr, &computePipeline.descriptorSetLayout)); VkPipelineLayoutCreateInfo pipelineLayoutCI = {}; pipelineLayoutCI.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutCI.setLayoutCount = 1; pipelineLayoutCI.pSetLayouts = &computePipeline.descriptorSetLayout; pipelineLayoutCI.pushConstantRangeCount = TO_UINT32_T(luxComputePipelineCI.pushConstants.size()); pipelineLayoutCI.pPushConstantRanges = luxComputePipelineCI.pushConstants.data(); CHECK_VK(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &computePipeline.pipelineLayout)); VkComputePipelineCreateInfo computePipelineCI = {}; computePipelineCI.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; computePipelineCI.stage = computeStageCI; computePipelineCI.layout = computePipeline.pipelineLayout; CHECK_VK(vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &computePipelineCI, nullptr, &computePipeline.pipeline)); vkDestroyShaderModule(device, computeShaderModule, nullptr); } void RHI::DestroyComputePipeline(ComputePipeline& computePipeline) noexcept { vkDestroyPipeline(device, computePipeline.pipeline, nullptr); vkDestroyPipelineLayout(device, computePipeline.pipelineLayout, nullptr); vkDestroyDescriptorSetLayout(device, computePipeline.descriptorSetLayout, nullptr); } } // namespace lux::rhi
true
9f658a7b19a7d1990890235f69ccb2ee6ba5ed4d
C++
Anri-Lombard/cpp
/calebCurry/multifiles/math_utils.cpp
UTF-8
420
3.140625
3
[]
no_license
#include "math_utils.h" double area(int side) { return side * side; } double area(int length, int width) { return length * width; } double area(Rectangle rectangle) { return rectangle.length * rectangle.width; } double pow(double base, int pow) { int total = 1; for (int i = 0; i < pow; i++) { total *= base; } return total; } double pow(double base) { return base * base; }
true
1b49698b27b002318616aa7cd9eaa73f4ad31163
C++
AlexanderPVl/Labs-2curs1sem-
/lab1/Class.cpp
UTF-8
1,720
3.296875
3
[]
no_license
#include "Class.h" #include <math.h> //CUBE================================ int Cube::Deg3(int n) const{ return n*n*n; } Cube::Cube(int x, int y){ X = x; Y = y; } int Cube::GetX() const{ return X; } int Cube::GetY() const{ return Y; } void Cube::SetX(int x){ X = x; } void Cube::SetY(int y){ Y = y; } int Cube::MaxCube(){ int max = (X > Y) ? X : Y; return Deg3(max); } //VECTOR============================== void Vector2::FindNormal(){ if (!d('x') && !d('y')){ Coord[0] = Coord[1] = Coord[2] = Coord[3] = 0; return; } if (!d('x')){ Coord[0] = Coord[1] = Coord[3] = 0; Coord[2] = 1; return; } else if (!d('y')){ Coord[0] = Coord[1] = Coord[2] = 0; Coord[3] = 1; return; } else{ Coord[0] = Coord[1] = 0; Coord[2] = 1 / d('x'); Coord[3] = -1 / d('y'); return; } Coord[0] = 1; Coord[1] = 1; Coord[2] = 1; Coord[3] = 1; } Vector2::Vector2(double x1, double y1, double x2, double y2){ X1 = x1; Y1 = y1; X2 = x2; Y2 = y2; Coord = new double[4]; } Vector2::~Vector2(){ delete[] Coord; } double& Vector2::GetCoordRef(int i){ switch (i){ case 0: return X1; case 1: return Y1; case 2: return X2; case 3: return Y2; default: return X1; } } double Vector2::GetCoord(int i) const{ switch (i){ case 0: return X1; case 1: return Y1; case 2: return X2; case 3: return Y2; default: return 0; } } void Vector2::SetCoord(int i, double val){ GetCoordRef(i) = val; } double Vector2::d(const char var) const{ if (var == 'x')return (GetCoord(2) - GetCoord(0)); if (var == 'y')return (GetCoord(3) - GetCoord(1)); else return 0; } double Vector2::VectorLen() const{ return sqrt(pow(d('x'), 2) + pow(d('y'), 2)); } double Vector2::GetCoordArray(int i){ return Coord[i]; }
true
176887da4d186250c6fd593294bb2bd877e1ac0c
C++
Arindam8282/data-structure
/recursions/power.cpp
UTF-8
317
3.84375
4
[]
no_license
#include<iostream> using namespace std; int powerOf(int num,int power) { if(power>0) return num*powerOf(num,power-1); else return 1; } int main() { int num,power; cout<<"Enter a number : "; cin>>num; cout<<"Enter power : "; cin>>power; cout<<num<<" to the power "<<power<<" is "<<powerOf(num,power); }
true
d7138f93be50840c204c860e74ac176169c945dd
C++
lenomirei/C-C-
/使用类模板编写的双向链表/使用类模板编写的双向链表/标头.h
GB18030
1,486
3.390625
3
[]
no_license
#pragma once #include<iostream> using namespace std; template<class T> struct ListNode { T _data; ListNode *_next; ListNode *_prev; ListNode(T x) :_data(x) ,_next(NULL) ,_prev(NULL) { } }; template<class T> class SXList { public: SXList() :_head(NULL) ,_end(_head) { } SXList(SXList& l) :_head(NULL) ,_end(_head) { } void PushBack(T x)//Ϊ1.2.һ߶ { if (NULL==_head) { _head = new ListNode<T>(x); _end = _head; } else { ListNode<T>* tmp = new ListNode<T>(x); tmp->_prev = _end; _end->_next = tmp; _end = tmp; } } ~SXList() { } void PrintList() { ListNode<T>* cur = _head; while (cur) { cout << cur->_data << "<->"; cur = cur->_next; } cout << "NULL" << endl; } void swap(ListNode<T>* gai) { ListNode<T>* tmp; tmp = gai->_next; gai->_next = gai->_prev; gai->_prev = tmp; } void Reverse() { ListNode<T>* tmp; ListNode<T>* cur = _head; ListNode<T>* gai = _head; while (cur) { cur = cur->_next; swap(gai); gai = cur; } tmp = _head; _head = _end; _end = tmp; } void Destory() { ListNode<T> *cur = _head; ListNode<T> *del = _head; while (cur) { cur = cur->_next; delete del; del = cur; } } SXList& operator=(SXList &s) { Destory(); ListNode<T> *cur = s._head; while (cur) { PushBack(cur->_data); } } private: ListNode<T> *_head; ListNode<T> *_end; };
true
bd7a0c7f0bbec233a5469cfbc46749b323748698
C++
dyh1265/Assignment05
/rt/integrators/castingdist.cpp
UTF-8
1,040
2.609375
3
[]
no_license
#include "castingdist.h" #include <rt/world.h> #include <rt/intersection.h> #include <core/color.h> #include <core/vector.h> #include <cmath> namespace rt{ RayCastingDistIntegrator::RayCastingDistIntegrator(World* world, const RGBColor& nearColor, float nearDist, const RGBColor& farColor, float farDist): nearColor(nearColor),nearDist(nearDist),farColor(farColor),farDist(farDist) { this->world = world; } RGBColor RayCastingDistIntegrator::getRadiance(const Ray& ray) const { float col = 0; RGBColor rgb; Intersection rayIntersect = this->world->scene->intersect(ray); if (rayIntersect.distance > epsilon){ col = -dot(ray.d, rayIntersect.n); /* Linearly interpolate colours */ rgb = this->nearColor + (rayIntersect.distance - this->nearDist) * ((farColor - nearColor)/(farDist - nearDist)); } RGBColor resColor = RGBColor(col, col, col) * rgb; return resColor.clamp(); } }
true
ffd658b409ea260574b4bfa9ec71d1469eceb374
C++
pombredanne/ska_fft
/cpp/check_output.cc
UTF-8
1,087
2.78125
3
[ "MIT" ]
permissive
#include <cstdio> #include <cstdlib> #include <cstring> #include <complex> #include <vector> #include "helpers.h" using namespace std; typedef pair<int, int> location; int main(int argc, char** argv) { // read program options if (argc != 4) { printf("Wrong number of arguments.\n"); return 1; } const char* test_filename = argv[1]; const char* reference_filename = argv[2]; const int n = atoi(argv[3]); const int n2 = n * n; // read test and reference data vector<complexf> test_data(n2); if (!read_input(test_data.data(), test_filename, n)) { return 1; } vector<complexf> reference_data(n2); if (!read_input(reference_data.data(), reference_filename, n)) { return 1; } // compute l1 norm of difference double sum = 0.0; double sum2 = 0.0; for (int ii = 0; ii < n2; ++ii) { sum += abs(test_data[ii] - reference_data[ii]); sum2 += abs(reference_data[ii]); } printf("l1 norm of difference: %.6e\n", sum); printf("l1 norm of reference: %.6e\n", sum2); printf("relative error: %.6e\n", sum / sum2); return 0; }
true
b9d9ae47e275b69f42cd82d8070444299c57394b
C++
Mustafamemon/SEM_THREE
/DS LAB/Lab 3/task 1.cpp
UTF-8
369
3.578125
4
[]
no_license
#include <iostream> #include <new> #include <cstdlib> using namespace std; int fib1(int n) { return n; } int fib(int n, int a , int b,int sum) { if (n>2) { sum=a+b; cout<<fib1(sum)<<" "; a=b; b=sum; } else return 0; fib(--n,a,b,0); } int main() { int n; cout<<"Enter the number : "; cin>>n; cout<<"0 1 "; fib(n,0,1,0); }
true
ea578947dd921dd2cc926ed328c89571678c12f0
C++
Richard-coder-Nai/OJ
/acwing/1329.cpp
UTF-8
389
2.671875
3
[ "Apache-2.0" ]
permissive
#include <iostream> #include <string> using namespace std; string dirs[1005]; int father[1005]; int counter(int x) { if(father[x]==0) return dirs[x].size()+1; return dirs[x].size()+1+counter(father[x]); } int main(void) { int n; cin>>n; for(int i=1; i<=n; i++) { cin>>father[i]; cin>>dirs[i]; } int res = 0; for(int i=1; i<=n; i++) res += counter(i); cout<<res<<endl; }
true
e1dccca2f74041e2879ce202bca5aafe18026b7a
C++
penolove/MystupidC
/11063.cpp
UTF-8
825
3.0625
3
[]
no_license
#include <iostream> #include <algorithm> #include <string> #include <map> using namespace std; bool b2seq(int n, int arr[]){ int temp[20001]={0}; for(int i=0;i<n;i++){ for(int j=i;j<n;j++){ if(temp[arr[i]+arr[j]]==0){ temp[arr[i]+arr[j]]=1; }else{ return 0; } } } return 1; } //B2-sequence int main(void) { int times=0; int n; while(cin>>n){ times++; int arr[n]; int tempp=1; int increasing=1; for(int i=0;i<n;i++){ cin>>arr[i]; if(arr[i]<tempp){ increasing=0; } tempp=arr[i]; } if(increasing==1){ if(b2seq(n,arr)) cout<<"Case #"<<times<<": It is a B2-Sequence."<<"\n\n"; else{ cout<<"Case #"<<times<<": It is not a B2-Sequence."<<"\n\n"; } }else{ cout<<"Case #"<<times<<": It is not a B2-Sequence."<<"\n\n"; } } return 0; }
true
540d8df4a570f002f54f0178d189175940f50643
C++
hmehta095/MarkinItus
/markingItus.ino
UTF-8
2,238
2.609375
3
[]
no_license
// This #include statement was automatically added by the Particle IDE. #include <InternetButton.h> InternetButton button = InternetButton(); int DELAY = 200; void setup() { button.begin(); Particle.function("hppy0",Happy0); Particle.function("hppy",Happy); Particle.function("hppy1",Happy1); Particle.function("hppy2",Happy2); Particle.function("hppy3",Happy3); Particle.function("Angry",Angry); for(int i=0;i<3;i++){ button.allLedsOn(0,20,0); delay(500); button.allLedsOff(); delay(500); } } int Happy0(String cmd){ button.allLedsOff(); for(int i = 3; i <= 9; i++){ button.ledOn(i,0,255,0); button.ledOn(1,0,255,0); button.ledOn(11,0,255,0); } } int Happy(String cmd){ button.allLedsOff(); for(int i = 4; i <= 8; i++){ button.ledOn(i,0,255,0); button.ledOn(1,0,255,0); button.ledOn(11,0,255,0); } } int Happy1(String cmd){ button.allLedsOff(); for(int i = 5; i <= 7; i++){ button.ledOn(i,0,255,0); button.ledOn(1,0,255,0); button.ledOn(11,0,255,0); } } int Happy2(String cmd){ button.allLedsOff(); button.ledOn(6,0,255,0); button.ledOn(1,0,255,0); button.ledOn(11,0,255,0); } int Happy3(String cmd){ button.allLedsOff(); // button.ledOn(6,0,255,0); button.ledOn(1,0,255,0); button.ledOn(11,0,255,0); } int Angry(String cmd){ button.allLedsOff(); // button.ledOn(6,0,255,0); for(int i = 5; i <= 7; i++){ button.ledOn(i,255,0,0); button.ledOn(1,255,0,0); button.ledOn(11,255,0,0); } } void loop() { // if(button.buttonOn(4)){ // // choice A // Particle.publish("playerChoice","A",60,PRIVATE); // delay(DELAY); // } // if(button.buttonOn(2)){ // //choice B // Particle.publish("playerChoice","B",60,PRIVATE); // delay(DELAY); // } // if(button.buttonOn(3)){ // //Next question // Particle.publish("playerChoice","true",60,PRIVATE); // delay(DELAY); // } // if(button.buttonOn(1)){ // Particle.publish("playerChoice","C",60,PRIVATE); // delay(DELAY); // } }
true
d836573db696e4fa4206a4e5d592aa33c29a99b4
C++
neloe/cs401_graphfinal
/lorenz.cpp
UTF-8
2,967
3.09375
3
[]
no_license
// /// \file lorenz.cpp /// \author Nathan Eloe /// \brief Implementation of lorenz system threadiness // #include "lorenz.h" #include <iostream> using namespace std; const int SLEEP_TIME = 0; point operator* (const double & s, const point& p) { return {s * p.x, s * p.y, s * p.z}; } point operator+ (const point& p1, const point& p2) { return {p1.x + p2.x, p1.y + p2.y, p1.z + p2.z}; } point& point::operator+= (const point& p) { x += p.x; y += p.y; z += p.z; return *this; } std::ostream& operator << (std::ostream& o, const point& p) { o << "(" << p.x << ", " << p.y << ", " << p.z << ")"; return o; } double xdot (const point& p) { usleep(SLEEP_TIME); return P * (p.y - p.x); } double ydot(const point& p) { usleep(SLEEP_TIME); return R * p.x - p.y - p.x * p.z; } double zdot(const point& p) { usleep(SLEEP_TIME); return p.x * p.y - B * p.z; } void seq_step(point& p) { point k_1 = DT * point({xdot(p), ydot(p), zdot(p)}); point t1 = (0.5 * k_1) + p; point k_2 = DT * point({xdot(t1), ydot(t1), zdot(t1)}); point t2 = (0.5 * k_2) + p; point k_3 = DT * point({xdot(t2), ydot(t2), zdot(t2)}); point t3 = p + k_3; point k_4 = DT * point({xdot(t3), ydot(t3), zdot(t3)}); p += (RKAVG * (k_1 + (2 * k_2) + (2 * k_3) + k_4)); //cout << t1 << t2 << t3 << endl; //cout << k_1 << k_2 << k_3 << k_4 << p << endl; return; } double scaledot(dyn_var f, const point& p) { return DT * f(p); } void launch_xyz(future<double>& fx, future<double>& fy, future<double>& fz, const point& p) { fx = std::async(launch::async,scaledot, xdot, p); fy = std::async(launch::async,scaledot, ydot, p); fz = std::async(launch::async,scaledot, zdot, p); } void launch_xy(future<double>& fx, future<double>& fy, const point& p) { fx = std::async(launch::async,scaledot, xdot, p); fy = std::async(launch::async,scaledot, ydot, p); } void t1_step(point& p) { static future<double> fx, fy, fz; launch_xyz (fx, fy, fz, p); point k_1 = {fx.get(), fy.get(), fz.get()}; point t1 = (0.5 * k_1) + p; launch_xyz (fx, fy, fz, t1); point k_2 = {fx.get(), fy.get(), fz.get()}; point t2 = (0.5 * k_2) + p; launch_xyz (fx, fy, fz, t2); point k_3 = {fx.get(), fy.get(), fz.get()}; point t3 = p + k_3; launch_xyz (fx, fy, fz,t3); point k_4 = {fx.get(), fy.get(), fz.get()}; p += (RKAVG * (k_1 + (2 * k_2) + (2 * k_3) + k_4)); return; } void t2_step(point& p) { static future<double> fx, fy; launch_xy (fx, fy, p); double z = scaledot(zdot, p); point k_1 = {fx.get(), fy.get(), z}; point t1 = (0.5 * k_1) + p; launch_xy (fx, fy, p); z = scaledot(zdot, t1); point k_2 = {fx.get(), fy.get(), z}; point t2 = (0.5 * k_2) + p; launch_xy (fx, fy, t2); z = scaledot(zdot, t2); point k_3 = {fx.get(), fy.get(), z}; point t3 = p + k_3; launch_xy (fx, fy, t3); z = scaledot(zdot, t3); point k_4 = {fx.get(), fy.get(), z}; p += (RKAVG * (k_1 + (2 * k_2) + (2 * k_3) + k_4)); return; }
true
afc727eabb3f0f59ec43714054182729143c289d
C++
th3v0ice/Dwarf_Fortress_Clone
/Inventory.h
UTF-8
1,606
3.203125
3
[]
no_license
#include <vector> #include <memory> #include "Item.h" #include "Weapon.h" #include "Armor.h" #include "Consumable.h" #include "Map.h" #pragma once class Inventory { public: Inventory() : selected_item_idx(0), limit(3) { inventory.reserve(3); } Inventory(int l): selected_item_idx(0), limit(l) { inventory.reserve(limit); } void drawInventory(BUFFER &buffer); void dropFromInventory(); int addToInventory(std::shared_ptr<Item> item); void changeInventorySelection(int p, BUFFER &buffer); void setLimit(int lim) { limit = lim; } int getLimit() { return limit; } std::shared_ptr<Item> getSelectedItem(); void fillWithDummyData(){ std::shared_ptr<Weapon> w(new Weapon("Mighty sword", 100)); std::shared_ptr<Armor> a(new Armor("Shiny armor", 20)); std::shared_ptr<Consumable> c(new Consumable("Small potion", 10)); std::shared_ptr<Item> w_i = w; std::shared_ptr<Item> a_i = a; std::shared_ptr<Item> c_i = c; inventory.push_back(w_i); inventory.push_back(a_i); inventory.push_back(c_i); } std::size_t size() { return inventory.size(); } void clear() { inventory.clear(); } item_type getItemTypeAtIndex(int i) { return inventory[i]->getType(); }; private: std::vector<std::shared_ptr<Item>> inventory; int selected_item_idx; int limit; //Coordinates for a star which designates selected item. //It will be much faster to change the selection instead //of drawing everything again. int selected_item_idx_x; int selected_item_idx_y; };
true
77bbfc1c5849a93fb2f113c18d448136dad852cc
C++
vynaloze/FoP-assignment
/Person.cpp
UTF-8
660
3.390625
3
[]
no_license
#include "stdafx.h" #include "Person.h" Person::Person() { } Person::Person(string name1, string name2, string name3) { this->name1 = name1; this->name2 = name2; this->name3 = name3; } Person::~Person() { } void Person::setName(int whichOne, string value) throw (out_of_range) { switch (whichOne) { case 1: name1 = value; break; case 2: name2 = value; break; case 3: name3 = value; break; default: throw out_of_range(""); } } ostream& operator<<(ostream & s, Person p) { s << p.name1 << " " << p.name2 << " " << p.name3; return s; } istream& operator>> (istream& s, Person p) { s >> p.name1 >> p.name2 >> p.name3; return s; }
true
39b43838dfcdec5f51c970145ec6b1671de63312
C++
EricAOlson/Text_Adventure
/security.hpp
UTF-8
564
2.59375
3
[]
no_license
/******************** * Author: Eric Olson * Assignment: CS162 - Final Project: Train Riddle * Last Updated: 12/8/14 * Design: Header file for the security car class, derived from the car class. ********************/ #ifndef OLSON_SECURITY_HPP #define OLSON_SECURITY_HPP #include <iostream> #include <algorithm> #include <string> #include <vector> #include "car.hpp" #include "bag.hpp" class security : public car { public: /***CONSTRUCTORS***/ security(); /***MEMBER FUNCTIONS***/ bool action(bag &my_bag, short &clue); }; #endif
true
7a2f9482342c8aa742e6b66d451683f660df2ecf
C++
peaceminusones/ZYL-Leetcode
/剑指offer/JZ32_PrintMinNumber.cpp
UTF-8
842
3.578125
4
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: static bool cmp(int a, int b) { string s1 = "", s2 = ""; s1 += to_string(a) + to_string(b); s2 += to_string(b) + to_string(a); return s1 < s2; } string PrintMinNumber(vector<int> numbers) { string res = ""; sort(numbers.begin(), numbers.end(), cmp); for (int i = 0; i < numbers.size(); i++) { res += to_string(numbers[i]); } return res; } }; int main() { vector<int> numbers; int item; while (cin >> item) { numbers.push_back(item); if (cin.get() == '\n') break; } Solution s; string res = s.PrintMinNumber(numbers); cout << res << endl; return 0; }
true
9d79b9c1ff3aca1ad8307452883c1a413cc15c45
C++
Amrojano/UD3
/ecuacion2_modular.cpp
UTF-8
797
3.953125
4
[]
no_license
//Vamos a realizar un programa con modulos para calcular ecuaciones de segundo grado. #include <iostream> #include <cmath> using namespace std; // Declaramos la siguiente funcion antes del MAIN. void ecuacion(double &x1, double &x2) { double a, b, c; if (a != 0) { x1 = (-b + sqrt ( pow(b,2)-4*a*c) ) / (2*a); x2 = (-b - sqrt ( pow(b,2)-4*a*c) ) / (2*a); } else // Alternativa de la condicion if. //Salida. cout << "Solo una raiz: " << -c/b << endl; cout << "Las raices son: " << a << " y " << b << endl; } //Declaramos el programa con MAIN. int main() { double a, b, c; cout << "\nIntroduce coeficiente de 2º grado: "; cin >> a; cout << "\nIntroduce coeficiente del 1er grado: "; cin >> b; cout << "\nIntroduce coeficiente independiente: "; cin >> c; ecuacion(a, b); }
true
b5eabffdf3dcba65017b6f09a89e85a354872d8c
C++
CobaltSoixante/QTSlotMachine
/QTSlotMachine/EgmQTGui.cpp
UTF-8
8,726
2.671875
3
[]
no_license
#include "EgmQTGui.h" #include "EgmQTThreadWorkerObject.h" #include <boost/lexical_cast.hpp> // string s = boost::lexical_cast<string>( number ); #include <QHBoxLayout> #include <QGroupBox> #include <QMessageBox> // CREATE THE GUI: EgmQTGui::EgmQTGui(QWidget *parent, Egm& egm) : QWidget(parent), m_egm(egm), m_numOfReelsStillSpinning(0) { // Create the reels. QHBoxLayout* pReelsLayout = new QHBoxLayout(); // Horizontal-box layout - 1 [vertical] reel in each horizontal position. for (int reel_i=0; reel_i < m_egm.numOfReels(); reel_i++) { QVBoxLayout *pReel = new QVBoxLayout(); // Vertical-box layout - 1 position for each row of the reel. this->m_reels.push_back(vector<QLabel*>()); // store a new reel in the GUI class' internal reels collection. // Place initial [dummy] rows into the reel. const EgmReel& logicalReel = this->m_egm[reel_i]; for (int row_i=0; row_i < egm.numOfRows(); row_i++) { const EgmSymbol& egmSymbol = logicalReel[row_i]; QLabel* pLabel = new QLabel(); egmSymbol.putSymbol(pLabel); pReel->addWidget(pLabel, row_i); this->m_reels[reel_i].push_back(pLabel); // store the symbol in the current reel in the class' reels collection. // This symbol will be advanced continuously during a reel-spin/play session. } // for egm.numOfRows() // Put the reel into a group-box // (just as an effect, we don't need the group-box, but it puts a border around the entire reel, which looks noce). QGroupBox *pGroupBox = new QGroupBox(); pGroupBox->setLayout(pReel); // Aggregate the reel into our horizontal-collection of reels. //pReelsLayout->addLayout(pReel); // Add the reel pReelsLayout->addWidget(pGroupBox); // Add the reel's "dummy" group-box. (the group-box is only for effect - to get a border around the reel). } // for m_egm.numOfReels() // Create buttons that enable user to start/exit the test. QHBoxLayout* pButtonsLayout = new QHBoxLayout(); this->m_pPlayButton = new QPushButton("Play"); // keep an explicit record off the [Play] button] - so we can grey-it-out when the reels spi, and reactivate ot at the end of the spins. pButtonsLayout->addWidget(new QLabel(tr("Game Duration [seconds]:"))); this->m_pSecsPerGameText = new QLineEdit; m_pSecsPerGameText->setText(boost::lexical_cast<std::string>(m_egm.numOfSecsPerGame()).c_str()); pButtonsLayout->addWidget(m_pSecsPerGameText); pButtonsLayout->addWidget(new QLabel(" ")); // unused filler, so the main button horizontal-dimension doesn't use up all the row. pButtonsLayout->addWidget(new QLabel(" ")); // unused filler, so the main button horizontal-dimension doesn't use up all the row. pButtonsLayout->addWidget(this->m_pPlayButton); // THE MAIN BUTTON. pButtonsLayout->addWidget(new QLabel(" ")); // unused filler, so the main button horizontal-dimension doesn't use up all the row. pButtonsLayout->addWidget(new QLabel(" ")); // unused filler, so the main button horizontal-dimension doesn't use up all the row. // Connect the "Play" button to the "play()" method: connect(this->m_pPlayButton, SIGNAL(clicked()), this, SLOT(play())); // Create main-layout to contain the reels on top, and the buttons underneath. QVBoxLayout* pMainLayout = new QVBoxLayout(); // Add the reels to the main layout: QWidget* pReelsWidget = new QWidget(); pReelsWidget->setLayout(pReelsLayout); pMainLayout->addWidget(pReelsWidget); // Add the buttons to the main layout: QWidget* pButtonsWidget = new QWidget(); pButtonsWidget->setLayout(pButtonsLayout); pMainLayout->addWidget(pButtonsWidget); this->setLayout(pMainLayout); } EgmQTGui::~EgmQTGui(void) { } void EgmQTGui::advanceSymbolSlot( int reel_i, // Index of the reel for which the change is occuring (in this app: is identical for both GUI & EGM reel). int GUISymbol_i, int EGMSymbol_i ) { // replace the current symbol with the next one. const EgmReel& egmReel = this->m_egm[reel_i]; vector<QLabel*> guiReel = this->m_reels[reel_i]; egmReel[EGMSymbol_i].putSymbol(guiReel[GUISymbol_i]); // causes me to crash: reel[symbolIndex]->repaint(); // Force refresh of the label (otherwise: not always refreshed). // I don't think I need this: this->m_GUIReel[GUISymbol_i]->update(); // Better, but still unreliable. } // When the [Play] button of the GUI is clicked - this function that gets called. void EgmQTGui::play() { // Get the duration of the game. int duration = atoi(this->m_pSecsPerGameText->text().toStdString().c_str()); if (0 == duration) { // You'd think a message-box doesn't need all the above preliminary crap - but it does. QMessageBox msgBox; // Title of the box: msgBox.setText("BAD DURATION!"); // A bit of narrative in the box: msgBox.setInformativeText("Enter a valid duration in seconds for the game."); msgBox.exec(); return; } m_egm.setSecsPerGame(duration); // Grey-out the play-button [until all reels finish spinning]. this->m_pPlayButton->setEnabled(false); if (0 != this->m_numOfReelsStillSpinning) // sanity-check throw exception("EgmQTGui::play() - sanity check: reels still spinning when [Play] clicked."); this->m_numOfReelsStillSpinning = m_egm.numOfReels(); // Spin the reels on the "logical" egm (IE the actual game - not the displayed GUI stuff). this->m_egm.play(); // Create a thread for each reel [and start each]; // based much on a combination of QT formal doco (the suggestion to use worker-objects), but mainly: // http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/ for ( int reel_i=0; reel_i<this->m_egm.numOfReels(); ++reel_i) { QThread *thread = new QThread; const int milliSecsForThisReelToSpin = this->m_egm.numOfSecsPerGame()*1000/(this->m_egm.numOfReels() - reel_i); EgmQTThreadWorkerObject *worker = new EgmQTThreadWorkerObject( reel_i, // 20120807: I have to add this too, it's messy & can be neater, am just learning the "niceties" of QT and having to go through the GUI thread when updating the GUI from multiple threads. this->m_reels[reel_i], // The physical GUI reel that is displayed this->m_egm.reel(reel_i), // The logical EGM reel milliSecsForThisReelToSpin ); worker->moveToThread(thread); // This slot/signal is specific to my application: // I "grey-out" my [Play] button while the reels spin (otherwise all hell/access-violation cal occur if user clicks button in mid-spin); // When the reels have all finished spinning - I need the [Play] buttun to know, so it can re-activate itself. connect (thread, SIGNAL(finished()), this, SLOT(reelSpinCompleted())); // This is specific to my application: the thread emits a 'advanceSymbolSignal', // which causes a single 'advanceSymbolSlot' call to be executed in the context of the QT event-loop // (very important to update the QT display in the context of the QT event-loop: avoids nasty crashes). // NOTE: we need the worker-signal to connect to a slot from THIS THREAD: the main GUI thread! (won't work otherwise). connect( worker, SIGNAL(advanceSymbolSignal(int, int, int)), this, SLOT(advanceSymbolSlot(int, int, int)) ); // The rest of this is pretty much copied from the suggested recipe in: // http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/ connect(thread, SIGNAL(started()), worker, SLOT(doWork())); connect(worker, SIGNAL(finished()), thread, SLOT(quit())); connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); } } // When all reels have stopped spinning - enable the [Play] button again. // Note: because this slot is executed in the QT main event-loop context - // no multi-threaded synchronization mechanisms are required to protect member/instance variables used here. void EgmQTGui::reelSpinCompleted() { // Sanity check: if (0==this->m_numOfReelsStillSpinning) throw exception("EgmQTGui::reelSpinCompleted() - sanity check failed."); if (0 == --this->m_numOfReelsStillSpinning) this->m_pPlayButton->setEnabled(true); }
true
5c5de317ab3c1733cd8c6336b3a3405acebae67c
C++
Ivan19Aldana/Parcial-2-Programaci-n
/Serie 3 Inciso 1.cpp
ISO-8859-3
2,688
3.34375
3
[]
no_license
// Mynor Ivan Aldana Marin //0909-20-5400 // serie 3 Inciso 1 // Declaracin de Librerias #include <iostream> #include <conio.h> using namespace std; // Declaracin de Variables y Vectores int alfa[3][3]; // Filas y Columnas int total[3]; // Filas int e, h, op; // Variables y opcion // Estructura para Ingresar datos al curso void ingresoDatos(){ for ( e = 0; e <= 2; e++ ){ // Saltos en cada fila for ( h = 0; h <= 2; h++ ){ // Saltos en cada columna cout << "Ingreso dato en la fila " << e + 1 << " columna " << h + 1 << " = "; cin >> alfa[e][h]; // Ingreso de Datos } } } // Estructura para Sumar filas de la MAtriz ALFA void sumaTotal(){ total[0] = alfa[0][0] + alfa[1][1] + alfa[2][2]; total[1] = alfa[2][0] + alfa[2][1] + alfa[2][2]; total[2] = alfa[2][0] + alfa[1][1] + alfa[0][2]; } // Estructura para Mostrar Matriz ALFA y Vector TOTAL void mostrarMatrizVector(){ cout << " Matriz ALFA " << endl; for ( e = 0; e <= 2; e++ ){ // Saltos en cada fila cout << " " << alfa[e][0] << " " << alfa[e][1] << " " << alfa[e][2] << endl; } cout << endl << endl << endl << endl << endl; // 5 espacios cout << "Vector TOTAL" << endl; cout << " " << total[0] << " " << total[1] << " " << total[2] << endl; } // Estructura Principal C++ int main(){ do{ // Mostrar en Pantalla cout << "Bienvenidos al programa Vector Curso" << endl; cout << "1. Ingresar datos a la matriz ALFA" << endl; cout << "2. Calculo de sumas de filas de la matriz" << endl; cout << "3. Mostrar la matriz ALFA y el vector TOTAL" << endl; cout << "4. Finalizar" << endl; cout << "Elija Una Opcion --> "; cin >> op; // Ingreso de Opcion cout << endl << endl; switch ( op ){ //Segun la opcion elegida case 1: ingresoDatos(); // Llamado de la funcion de ingreso de datos system ("cls"); // Limpiamos pantalla break; // Salir Switch case 2: sumaTotal(); // Llamado de la funcion Sumar filas de la MAtriz ALFA cout << "Las operaciones se han realizado con exito" << endl; system ("pause"); // Detener Programa system ("cls"); // Limpiar Pantalla break; case 3: mostrarMatrizVector(); // Llamamos a la funcion Mostrar Matriz ALFA y Vector TOTAL getch(); // Detener Programa system ("cls"); // Limpiar Pantalla break; // Salir Switch case 4: break; // Salir Switch default: cout << "\nEsta Opcion no esta disponible" << endl; system ("pause"); // Detener Programa system ("cls"); // Limpiar Pantalla } } while ( op != 4 ); // Mientras op sea diferente a 4 seguir con el do While } // Mynor Ivan Aldana Marin //0909-20-5400
true
2dc18deca32175e2ab9a15d187fb5607790ecfaf
C++
McStasMcXtrace/NJOY21
/src/njoy21/input/HEATR/Card1/test/Card1.test.cpp
UTF-8
3,038
2.734375
3
[ "BSD-2-Clause" ]
permissive
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "njoy21.hpp" using namespace njoy::njoy21::input; SCENARIO( "Validating HEATR Card1 inputs", "[HEATR], [Card1]"){ GIVEN( "valid HEATR Card1 inputs" ){ WHEN( "all inputs are provided" ){ iRecordStream<char> iss1( std::istringstream("20 21 22 23\n") ); iRecordStream<char> iss2( std::istringstream("-20 21 22 -23\n") ); iRecordStream<char> iss3( std::istringstream("20 -21 -22 23\n") ); THEN( "the returned values are correct" ){ { HEATR::Card1 card1( iss1 ); REQUIRE( card1.nendf.value == 20 ); REQUIRE( card1.nin.value == 21 ); REQUIRE( card1.nout.value == 22 ); REQUIRE( card1.nplot.value == 23 ); } { HEATR::Card1 card1( iss2 ); REQUIRE( card1.nendf.value == -20 ); REQUIRE( card1.nin.value == 21 ); REQUIRE( card1.nout.value == 22 ); REQUIRE( card1.nplot.value == -23 ); } { HEATR::Card1 card1( iss3 ); REQUIRE( card1.nendf.value == 20 ); REQUIRE( card1.nin.value == -21 ); REQUIRE( card1.nout.value == -22 ); REQUIRE( card1.nplot.value == 23 ); } } // THEN } // WHEN WHEN( "optional input not provided" ){ iRecordStream<char> iss1( std::istringstream("20 21 22 /\n") ); iRecordStream<char> iss2( std::istringstream("-20 -21 -22 /\n") ); THEN( "the returned values are correct" ){ { HEATR::Card1 card1( iss1 ); REQUIRE( card1.nendf.value == 20 ); REQUIRE( card1.nin.value == 21 ); REQUIRE( card1.nout.value == 22 ); REQUIRE( card1.nplot.value == 0 ); } { HEATR::Card1 card1( iss2 ); REQUIRE( card1.nendf.value == -20 ); REQUIRE( card1.nin.value == -21 ); REQUIRE( card1.nout.value == -22 ); REQUIRE( card1.nplot.value == 0 ); } } // THEN } // WHEN } // GIVEN GIVEN( "invalid HEATR Card1 inputs" ){ WHEN( "all inputs are provided" ){ iRecordStream<char> iss1( std::istringstream("19 21 22 23\n") ); iRecordStream<char> iss2( std::istringstream("-20 -21 22 -23\n") ); iRecordStream<char> iss3( std::istringstream("20 -21 -22 21\n") ); THEN( "an exception is thrown" ){ REQUIRE_THROWS( HEATR::Card1( iss1 ) ); REQUIRE_THROWS( HEATR::Card1( iss2 ) ); REQUIRE_THROWS( HEATR::Card1( iss3 ) ); } // THEN } // WHEN WHEN( "optional input not provided" ){ iRecordStream<char> iss1( std::istringstream("19 21 22 /\n") ); iRecordStream<char> iss2( std::istringstream("-20 -21 22 /\n") ); iRecordStream<char> iss3( std::istringstream("20 -21 -21 /\n") ); THEN( "an exception is thrown" ){ REQUIRE_THROWS( HEATR::Card1( iss1 ) ); REQUIRE_THROWS( HEATR::Card1( iss2 ) ); REQUIRE_THROWS( HEATR::Card1( iss3 ) ); } // THEN } // WHEN } //GIVEN } // SCENARIO
true
06af68e36540b95533729d332ad19b1eec2ddf3b
C++
DaEunKim/111Coding
/조세퍼스문제/조세퍼스문제/main.cpp
UTF-8
753
2.734375
3
[]
no_license
// // main.cpp // 조세퍼스문제 // // Created by 김다은 on 2017. 2. 15.. // Copyright © 2017년 김다은. All rights reserved. // #include <iostream> #include <cstdio> #include <queue> using namespace std; int main(void){ int N; //사람 수 int M; //M번째 수 scanf("%d %d", &N, &M); //int arr[] ={0, }; queue<int> qu; for(int i = 1;i<=N;i++){ qu.push(i); } printf("<"); while (!qu.empty()) { for(int i = 1;i<M;i++){ qu.push(qu.front()); qu.pop(); } if(qu.size()!=1){ printf("%d, ", qu.front()); } else printf("%d", qu.front()); qu.pop(); } printf(">"); }
true
4231b2e509dc0ab9da81f4a0eed53163afc8fa88
C++
Paolo5150/397Project
/Engine/src/Components/Animator.h
UTF-8
2,729
2.84375
3
[]
no_license
#pragma once #include "..\Graphics\AnimatedModel.h" #include "..\Graphics\ModelAnimation.h" #include "..\GameObject\Component.h" #include <set> /** * @class Animator * @brief Specialized class for animator component * * Manages animations for an animated model * * @author Paolo Ferri * @version 01 * @date 1/05/2019 * @bug No known bugs. */ class Animator : public Component { public: friend class Model; friend class AnimatedModel; /** * @brief Constructor * @pre The animator does not exist * @post The animator is created * @param m The animated model */ Animator(AnimatedModel* m); /** * @brief Destructor * @pre The animator must exist * @post The animator is destroyed */ ~Animator(); /** * @brief Set the animation speed * @pre The animator must exist * @post The animation speed is updated * @param speed The new animation speed */ void SetAnimationSpeed(float speed) { animationSpeed = speed; } /** * @brief Set the animation index * @pre The animator must exist * @post The animation is updated * @param animation The new animation index * @param look Whether the animation should loop */ void SetCurrentAnimation(int animation, bool loop = true); /** * @brief Restart the animation * @pre The animator must exist * @post The animation is restarted */ void Reset(); /** * @brief Callback invoked before rendering * @pre The animator must exist * @param cam The camera used for rendering * @param currentShader The current active shader */ void OnPreRender(Camera& cam, Shader* currentShader = nullptr); double stopPercentage; private: /** * @brief The current animation speed */ float animationSpeed; /** * @brief Whether the animaition is playing */ bool isPlaying; /** * @brief Whether the animations has been reset */ bool isResetting; /** * @brief Animations list */ std::vector<ModelAnimation> animations; /** * @brief Overridden method for engine update */ void EngineUpdate() override; /** * @brief Overridden method for update */ void Update() override; /** * @brief The current animation */ ModelAnimation* currentAnimation; /** * @brief Current animation index */ int currentAnimationIndex; /** * @brief The model being animated */ AnimatedModel* model; /** * @brief The bones transformation matrices */ std::vector<glm::mat4> allBonesTransforms; /** * @brief Animation time track */ double time_in_ticks; /** * @brief The animation time legnth */ float animation_time; /** * @brief Previous animation time tick */ float previos_animation_Time; /** * @brief Whether the animation has been played at leasts one time */ bool playedOnce; };
true
2edc4707bb96aa63451a7398b4b27aea9911bf81
C++
Ayuyuyu/EasyWindowTool
/ColourPin/ColourBase.cpp
UTF-8
1,486
3.03125
3
[]
no_license
#include "StdAfx.h" #include "ColourBase.h" CColourBase::CColourBase(void) { memset(RGBList,0,sizeof(RGBList)); } CColourBase::~CColourBase(void) { } CString CColourBase::RGBto16(DWORD rgb[3]) { TCHAR szR[3]={0},szG[3]={0},szB[3]={0}; _itot(rgb[0],szR,16); _itot(rgb[1],szG,16); _itot(rgb[2],szB,16); CString strHEX; strHEX.Format(_T("0x%s%s%s"),szR,szG,szB); return strHEX; } void CColourBase::RGBTurnToList(DWORD rgb[3]) { memset(RGBList,0,sizeof(RGBList)); for (int i = 0;i <4;i++) { int R = rgb[0] - 5*(4-i); int G = rgb[1];// - 5*(4-i); int B = rgb[2] - 5*(4-i); if (R < 0 || B <0) { if (i == 0) { RGBList[i][0] =rgb[0]; RGBList[i][1] = rgb[1]; RGBList[i][2] = rgb[2]; } else { RGBList[i][0] = RGBList[i-1][0]; RGBList[i][1] = RGBList[i-1][1]; RGBList[i][2] = RGBList[i-1][2]; } } else { RGBList[i][0] = R; RGBList[i][1] = G; RGBList[i][2] = B; } } for (int i = 5;i <9;i++) { int R = rgb[0] + 5*(i-4); int G = rgb[1];// + 5*(i-4); int B = rgb[2] + 5*(i-4); if (R > 255 || B >255) { if (i ==5) { RGBList[i][0] =rgb[0]; RGBList[i][1] = rgb[1]; RGBList[i][2] = rgb[2]; } else{ RGBList[i][0] = RGBList[i-1][0]; RGBList[i][1] = RGBList[i-1][1]; RGBList[i][2] = RGBList[i-1][2]; } } else { RGBList[i][0] = R; RGBList[i][1] = G; RGBList[i][2] = B; } } RGBList[4][0]= rgb[0]; RGBList[4][1]= rgb[1]; RGBList[4][2]= rgb[2]; }
true
e623bb0c5313d7da4139988d9840cc1605e92d64
C++
VoIlAlex/nyann
/nyann-tests/test_drafts.cpp
UTF-8
5,705
2.765625
3
[ "MIT" ]
permissive
#include "pch.h" #include "../nyann/nyann/drafts.h" #include "..//nyann/nyann.h" namespace { using namespace nyann; TEST(DataSet_draft, Construction) { DataSet_draft<double> dataset_0({ 3, 3, 3 }); DataSet_draft<double> dataset_1 = { 1,2,3,4 }; DataSet_draft<double> dataset_2 = { {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4} }; DataSet_draft<double> dataset_3 = { { { {000}, {001} }, { {010}, {011} } }, { { {100}, {101} }, { {110}, {111} } } }; } TEST(DataSet_draft, Indexing) { DataSet_draft<double> dataset = { { {{000}, {001}}, {{010}, {011}} }, { {{100}, {101}}, {{110}, {111}} } }; ASSERT_EQ(dataset[0][0][0].value(), 000); ASSERT_EQ(dataset[1][1][1].value(), 111); try { dataset[1][1][1][1]; } catch (std::out_of_range& err) {} } TEST(DataSet_draft, Slicing_1) { DataSet_draft<double> dataset_3 = { { { {000}, {001} }, { {010}, {011} } }, { { {100}, {101} }, { {110}, {111} } } }; DataSet_draft<double> dataset_slice = dataset_3[{0, 2}][0][0]; DataSet_draft<double> expected_dataset_slice = { {000}, {100} }; EXPECT_EQ(expected_dataset_slice, dataset_slice); } TEST(DataSet_draft, Slicing_2) { DataSet_draft<double> dataset_3 = { { { {1010}, {001} }, { {010}, {011} } }, { { {100}, {101} }, { {110}, {111} } } }; DataSet_draft<double> dataset_slice = dataset_3[{0, -1}][{0, -1}][0]; DataSet_draft<double> expected_dataset_slice = { {1010, 010}, {100, 110} }; EXPECT_EQ(expected_dataset_slice, dataset_slice); } TEST(DataSet_draft, Slicing_3) { DataSet_draft<double> dataset_3 = { { { {1010}, {001} }, { {010}, {011} } }, { { {100}, {101} }, { {110}, {111} } } }; DataSet_draft<double> dataset_slice = dataset_3[{0, 2}][0][0]; DataSet_draft<double> expected_dataset_slice = { 1010, 100 }; EXPECT_EQ(expected_dataset_slice, dataset_slice); } TEST(DataSet_draft, SlicingInitialization_1) { DataSet_draft<double> dataset_3 = { { {1010, 001}, {010, 011} }, { {100, 101}, {110, 111} } }; dataset_3[{0, 2}][1][{0, 2}].set_value(DataSet_draft<double>{ { {0, 0} }, { {0, 0} } }); double first_zero = double(dataset_3[0][1][0]); double second_zero = double(dataset_3[0][1][1]); double third_zero = double(dataset_3[1][1][0]); double fourth_zero = double(dataset_3[1][1][1]); ASSERT_EQ(first_zero, 0); ASSERT_EQ(second_zero, 0); ASSERT_EQ(third_zero, 0); ASSERT_EQ(fourth_zero, 0); } TEST(DataSet_draft, SlicingInitialization_2) { DataSet_draft<double> dataset_3 = { { { {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1} }, { {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1} } }, { { {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1} }, { {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1} } } }; dataset_3[{0, 2}][1][0][{2, 4}].set_value(DataSet_draft<double>{ { {0, 0} }, { {0, 0} } }); double first_zero = double(dataset_3[0][1][0][2]); double second_zero = double(dataset_3[0][1][0][3]); double third_zero = double(dataset_3[1][1][0][2]); double fourth_zero = double(dataset_3[1][1][0][3]); ASSERT_EQ(first_zero, 0); ASSERT_EQ(second_zero, 0); ASSERT_EQ(third_zero, 0); ASSERT_EQ(fourth_zero, 0); } TEST(DataSet_draft, SplitInputOutput) { typedef nyann::DataSet_draft<double> dt; dt dataset = { {1.0, 1.0, 1.0, 3.0}, {2.0, 2.0, 2.0, 6.0}, {1.0, 2.0, 3.0, 6.0}, {0.0, 0.0, 0.0, 0.0} }; dt X = dataset[{0, -1}][{0, 3}]; dt y = dataset[{0, -1}][{3, 4}]; dt X_expected = { {1.0, 1.0, 1.0}, {2.0, 2.0, 2.0}, {1.0, 2.0, 3.0}, {0.0, 0.0, 0.0} }; dt y_expected = { dt{3.0}, dt{6.0}, dt{6.0}, dt{0.0} }; EXPECT_EQ(X, X_expected); EXPECT_EQ(y, y_expected); } TEST(DataSet_draft, SizeGetting_1) { DataSet_draft<double> dataset = { {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4} }; nyann::Size<> size = dataset.size(); nyann::Size<> expected_size = nyann::Size<>{ 4, 4 }; ASSERT_EQ(size, expected_size); } TEST(DataSet_draft, SizeGetting_2) { DataSet_draft<double> dataset = { {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4} }; nyann::Size<> size = dataset.get_size(); nyann::Size<> expected_size = nyann::Size<>{ 4, 4 }; ASSERT_EQ(size, expected_size); } TEST(DataSet_draft, AtIndex) { DataSet_draft<double> dataset_3 = { { { {000}, {001} }, { {010}, {011} } }, { { {100}, {101} }, { {110}, {111} } } }; double value = dataset_3.at_index({ 1, 1, 1 }); EXPECT_EQ(value, 111); } /*TEST(DataSet_draft, IO_formatting) { nyann::DataSet_draft<double> dataset = { {1.0, 2.0}, {3.0, 4.0} }; std::stringstream ss; ss << dataset << std::endl; EXPECT_EQ(ss.str(), "[[1, 2]\n[3, 4]]\n"); }*/ TEST(DataSet_draft, Iteration_default) { DataSet_draft<double> dataset = { {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4} }; DataSet_draft<double>::iterator it(&dataset, 0); ASSERT_EQ(*it, double(dataset[0][0])); ASSERT_EQ(*(it + 4), double(dataset[1][0])); } } // namespace
true
3d52bf4b2db6d3cec0d9ea03a0009171a444b70e
C++
philippds-learn/Programming-Principles-and-Practice-Using-Cpp_Bjarne-Stroustrup_Chapter-02-11
/p301_9_priceTimesWeight.cpp
UTF-8
1,437
3.546875
4
[]
no_license
// Philipp Siedler // Bjarne Stroustrup's PP // Chapter 8 Exercise 9 #include "std_lib_facilities.h" vector<double> price; vector<double> weight; class indexCalc { vector<double> p; vector<double> w; public: indexCalc(vector<double> _p, vector<double> _w) :p(_p), w(_w) { }; void readPrice(); void readWeight(); void calculate(); }; void indexCalc::readPrice() { while (cin) { char priceChar; double priceDouble; cin.get(priceChar); if (isspace(priceChar)) { if (priceChar == '\n') { break; } } cin.unget(); cin >> priceDouble; p.push_back(priceDouble); } } void indexCalc::readWeight() { while (p.size() != w.size()) { char weightChar; double weightDouble; cin.get(weightChar); if (isspace(weightChar)) { if (weightChar == '\n' && p.size() == w.size()) { break; } } cin.unget(); cin >> weightDouble; w.push_back(weightDouble); } } void indexCalc::calculate() { double index = 0; for (int i = 0; i < p.size(); i++) { index += p[i] * w[i]; } cout << index << "\n"; } int main() try { indexCalc ic(price, weight); cout << "Enter prices\n"; ic.readPrice(); cout << "Enter weights\n"; ic.readWeight(); ic.calculate(); keep_window_open(); } catch (runtime_error e) { cout << e.what() << "\n"; keep_window_open(); } catch (...) { cout << "Exiting\n"; keep_window_open(); } /* Enter prices 23 24 25 53 32 Enter weights 3 4 5 3 4 577 Please enter a character to exit */
true
248caefd9877edbf3ecb84c7c2ca2aeda63d57b0
C++
kalaharileeu/TestSDL2
/main.cpp
UTF-8
870
3.015625
3
[]
no_license
#include<SDL.h> SDL_Window* _gWindow = 0; SDL_Renderer* _gRenderer = 0; int main(int argc, char* args[]) { // initialize SDL if (SDL_Init(SDL_INIT_EVERYTHING) >= 0) { // if succeeded create our window _gWindow = SDL_CreateWindow("Hello SDL2", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN); // If window creation succeeded create renderer if (_gWindow != 0) { _gRenderer = SDL_CreateRenderer(_gWindow, -1, 0); } } else { return 1; // sdl could not initialize } // EVERYTHING GOOD draw blue window // Function expects Red, Green, Blue and Alpha as color values SDL_SetRenderDrawColor(_gRenderer, 0, 0, 255, 255); //clear the window SDL_RenderClear(_gRenderer); // show the window SDL_RenderPresent(_gRenderer); // set a delay before quitting SDL_Delay(5000); // clean up SDL SDL_Quit(); return 0; }
true
08e06cd5f54f3f0ebc1ebfa7370c72ff7dfc6b6a
C++
Trey0303/IntroToCpp
/IntroductionToCpp/Pointers/pointercpp.cpp
UTF-8
656
3.421875
3
[ "MIT" ]
permissive
#include <cstdlib> #include <iostream> #include "pointerh.h" void printFloats(float* arr, size_t size) { for (size_t i = 0; i < size; i++) { std::cout << arr[i]; } } int arraySum(int* arr, size_t size) { int total = 0; for (size_t i = 0; i < size; i++) { total += arr[i]; } std::cout << std::endl << total << std::endl; return total; } void initBools(bool* arr, size_t size, bool defaultValue) { for (size_t i = 0; i < size; i++) { arr[i] = defaultValue; std::cout << arr[i]; } } int* zeroArray(size_t size) { int* zeroarray = new int[size]; for (size_t i = 0; i < size; i++) { zeroarray[i] = 0; } return zeroarray; }
true
27f9d728a9b86dd9f8a1cd2eb4735b75401e2eb0
C++
parambedi1453/ADI
/dp/reduceNum.cpp
UTF-8
1,681
3.734375
4
[]
no_license
/* Given a number we need to reduce it to 1 in min number of stpes given number of operation as divide by 3,divide by 2,sub 1 eg 21 op 4 eg 10 op 3 */ #include<iostream> #include<cmath> using namespace std; const int inf = (int)1e9; // In this function we cannot compute 1000 because overlapping recursive calls int reduceNum(int n) { if(n==1) return 0; int a1 = INT8_MAX,a2=INT8_MAX,a3=INT8_MAX; if(n%3 == 0) a1= 1 + reduceNum(n/3); if(n%2 == 0) a2 = 1+reduceNum(n/2); a3= 1+reduceNum(n-1); return min(a1,min(a2,a3)); } // memoised solution to the above problem int memo[10000]; int reduceNumMemo(int n) { if(n==1) return 0; int a1 = INT8_MAX,a2=INT8_MAX,a3=INT8_MAX; if(memo[n]!=-1) return memo[n]; if(n%3 == 0) a1= 1 + reduceNumMemo(n/3); if(n%2 == 0) a2 = 1+reduceNumMemo(n/2); a3= 1+reduceNumMemo(n-1); memo[n] = min(a1,min(a2,a3)); return memo[n]; } int bottomUp(int n) { int dp[10000]; dp[0]=0; dp[1]=0; dp[2]=1; dp[3]=1; for(int currNum = 4;currNum<=n;++currNum) { int a1 = INT8_MAX; int a2 = INT8_MAX; int a3 = INT8_MAX; if(currNum%3 == 0) a1=1+dp[currNum/3]; if(currNum%2 == 0) a2=1+dp[currNum/2]; a3 = 1+dp[currNum-1]; dp[currNum] = min(a1,min(a2,a3)); } return dp[n]; } int main() { int n; cin>>n; // Simple recursive approch // int ans = reduceNum(n); // Memeoised approach for(int i=0;i<10000;i++) memo[i]=-1; int ans1 = reduceNumMemo(n); cout<<ans1<<endl; int ans = bottomUp(n); cout<<ans<<endl; }
true
e6b7c7e355bcf6fedc9a17b5ba4454839fc3b0d4
C++
guilhermelonde/projetos-pequenos
/C++ - Qt Creator/IdiomMaster/Projeto/registrodb.h
UTF-8
333
2.5625
3
[]
no_license
#ifndef REGISTRODB_H #define REGISTRODB_H #include <string> using namespace std; class RegistroDB { public: string A; // chave primária string B; int praticado; RegistroDB(string _A, string _B, int _praticado) { A = _A; B = _B; praticado = _praticado; } }; #endif // REGISTRODB_H
true
d89fcc7a7b95e7cb09b0438272600b7d591ecdf6
C++
DDreher/OpenCLSandbox
/src/HashTable/HashTable.cpp
UTF-8
12,347
3.015625
3
[ "BSL-1.0" ]
permissive
#include "HashTable/HashTable.h" #include <Base\OpenCLManager.h> #include "assert.h" #include "Base\Definitions.h" #include "Base\Utilities.h" HashTable::HashTable() { // Init random seed srand(random_seed_); } HashTable::~HashTable() { // Release buffers cl_int status = 0; if(table_buffer_ != 0) { status = clReleaseMemObject(table_buffer_); assert(status == mpp::ReturnCode::CODE_SUCCESS); } if (params_buffer_ != 0) { status = clReleaseMemObject(params_buffer_); assert(status == mpp::ReturnCode::CODE_SUCCESS); } } bool HashTable::Init(uint32_t table_size) { size_ = static_cast<uint32_t>(ceil(table_size * table_size_factor)); GenerateParams(); OpenCLManager* mgr = OpenCLManager::GetInstance(); assert(mgr != nullptr); cl_int status = 0; // 1. Allocate enough memory on GPU to fit hash table if(table_buffer_ == 0) { table_buffer_ = clCreateBuffer(mgr->context, CL_MEM_READ_WRITE, size_ * sizeof(uint64_t), NULL, NULL); } // 2. Initialize all the memory with empty elements std::vector<uint64_t> empty_elements(size_, mpp::constants::EMPTY); status = clEnqueueWriteBuffer(mgr->command_queue, table_buffer_, CL_TRUE, 0, size_ * sizeof(uint64_t), empty_elements.data(), 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); return status == mpp::ReturnCode::CODE_SUCCESS; } bool HashTable::Init(uint32_t table_size, const std::vector<uint32_t>& keys, const std::vector<uint32_t>& values) { bool success = true; for(current_iteration_ = 0; current_iteration_ < max_reconstructions; ++current_iteration_) { Init(table_size); if(keys.size() > 0) { success = Insert(keys, values); if(success) { break; } } } return success; } bool HashTable::Insert(const std::vector<uint32_t>& keys, const std::vector<uint32_t>& values) { assert(keys.size() == values.size()); OpenCLManager* mgr = OpenCLManager::GetInstance(); assert(mgr != nullptr); cl_int status = 0; // 1. Allocate GPU memory for key-val-pairs to insert, padded to size of wavefront cl_int next_multiple = static_cast<cl_int>( Utility::GetNextMultipleOf(static_cast<uint32_t>(keys.size()), static_cast<uint32_t>(mpp::constants::WAVEFRONT_SIZE))); cl_mem keys_buffer = clCreateBuffer(mgr->context, CL_MEM_READ_WRITE, next_multiple * sizeof(uint32_t), NULL, NULL); cl_mem values_buffer = clCreateBuffer(mgr->context, CL_MEM_READ_ONLY, next_multiple * sizeof(uint32_t), NULL, NULL); // 2. Fill buffers status = clEnqueueWriteBuffer(mgr->command_queue, keys_buffer, CL_TRUE, 0, keys.size() * sizeof(uint32_t), keys.data(), 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); status = clEnqueueWriteBuffer(mgr->command_queue, values_buffer, CL_TRUE, 0, values.size() * sizeof(uint32_t), values.data(), 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); // If necessary write padding if (keys.size() < next_multiple) { uint32_t num_padded_elements = next_multiple - static_cast<uint32_t>(keys.size()); std::vector<uint32_t> empty_elements(num_padded_elements, mpp::constants::EMPTY_32); size_t offset = keys.size() * sizeof(uint32_t); size_t num_bytes_written = num_padded_elements * sizeof(uint32_t); status = clEnqueueWriteBuffer(mgr->command_queue, keys_buffer, CL_TRUE, offset, num_bytes_written, empty_elements.data(), 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); status = clEnqueueWriteBuffer(mgr->command_queue, values_buffer, CL_TRUE, offset, num_bytes_written, empty_elements.data(), 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); } // 3. Construct status buffer cl_mem status_buffer = clCreateBuffer(mgr->context, CL_MEM_READ_WRITE, sizeof(uint32_t), NULL, NULL); int intital_status = 0; status = clEnqueueWriteBuffer(mgr->command_queue, status_buffer, CL_TRUE, 0, sizeof(uint32_t), &intital_status, 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); // 4. Run kernel const cl_kernel kernel_hashtable_insert = mgr->kernel_map[mpp::kernels::HASHTABLE_INSERT]; // args: __global uint32_t* keys, __global uint32_t* values, __global uint64_t* table, __constant uint32_t* params, __global uint32_t* out_status status = clSetKernelArg(kernel_hashtable_insert, 0, sizeof(cl_mem), (void*)&keys_buffer); assert(status == mpp::ReturnCode::CODE_SUCCESS); status = clSetKernelArg(kernel_hashtable_insert, 1, sizeof(cl_mem), (void*)&values_buffer); assert(status == mpp::ReturnCode::CODE_SUCCESS); status = clSetKernelArg(kernel_hashtable_insert, 2, sizeof(cl_mem), (void*)&table_buffer_); assert(status == mpp::ReturnCode::CODE_SUCCESS); status = clSetKernelArg(kernel_hashtable_insert, 3, sizeof(cl_mem), (void*)&params_buffer_); assert(status == mpp::ReturnCode::CODE_SUCCESS); status = clSetKernelArg(kernel_hashtable_insert, 4, sizeof(cl_mem), (void*)&status_buffer); assert(status == mpp::ReturnCode::CODE_SUCCESS); size_t global_work_size[1] = { static_cast<size_t>(next_multiple) }; size_t local_work_size[1] = { std::min(static_cast<size_t>(THREAD_BLOCK_SIZE), static_cast<size_t>(next_multiple)) }; status = clEnqueueNDRangeKernel(mgr->command_queue, kernel_hashtable_insert, 1, NULL, global_work_size, local_work_size, 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); // 5. Error checking - Check if max iterations have been exceeded // In theory we could check which elements failed to be inserted, then take the original state of the hashtable, generate new hash parameters and then reconstruct the hashtable // from scratch. There probably are elements left which could not be inserted due to collision though... // For now it's assumed that insert is only called once. uint32_t kernel_status = mpp::ReturnCode::CODE_SUCCESS; status = clEnqueueReadBuffer(mgr->command_queue, status_buffer, CL_TRUE, 0, sizeof(uint32_t), &kernel_status, 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); // DEBUG - Check which/how many elements failed to be inserted //if(kernel_status != mpp::ReturnCode::CODE_SUCCESS) //{ // std::vector<uint32_t> status_per_element(next_multiple); // status = clEnqueueReadBuffer(mgr->command_queue, keys_buffer, CL_TRUE, 0, next_multiple * sizeof(uint32_t), status_per_element.data(), 0, NULL, NULL); // assert(status == mpp::ReturnCode::CODE_SUCCESS); // // Assume that 0 and 1 are never used as keys for debug purposes // uint32_t num_unresolved_collisions = static_cast<uint32_t>(std::count(status_per_element.begin(), status_per_element.end(), mpp::ReturnCode::CODE_ERROR)); // std::cout << "Host Table construction iteration: " << current_iteration_ << " Num unresolved collisions: " << num_unresolved_collisions << std::endl; //} // 6. Cleanup -> Release buffers status = clReleaseMemObject(keys_buffer); assert(status == mpp::ReturnCode::CODE_SUCCESS); status = clReleaseMemObject(values_buffer); assert(status == mpp::ReturnCode::CODE_SUCCESS); status = clReleaseMemObject(status_buffer); assert(status == mpp::ReturnCode::CODE_SUCCESS); return kernel_status == mpp::ReturnCode::CODE_SUCCESS; } std::vector<uint32_t> HashTable::Retrieve(const std::vector<uint32_t>& keys) { OpenCLManager* mgr = OpenCLManager::GetInstance(); assert(mgr != nullptr); cl_int status = 0; // 1. Allocate GPU memory cl_int next_multiple = static_cast<cl_int>( Utility::GetNextMultipleOf(static_cast<uint32_t>(keys.size()), static_cast<uint32_t>(mpp::constants::WAVEFRONT_SIZE))); cl_mem keys_buffer = clCreateBuffer(mgr->context, CL_MEM_READ_ONLY, next_multiple * sizeof(uint32_t), NULL, NULL); cl_mem vals_buffer = clCreateBuffer(mgr->context, CL_MEM_READ_WRITE, next_multiple * sizeof(uint32_t), NULL, NULL); // 2. Fill buffer status = clEnqueueWriteBuffer(mgr->command_queue, keys_buffer, CL_TRUE, 0, keys.size() * sizeof(uint32_t), keys.data(), 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); // If necessary write padding if (keys.size() < next_multiple) { uint32_t num_padded_elements = next_multiple - static_cast<uint32_t>(keys.size()); std::vector<uint32_t> empty_elements(num_padded_elements, mpp::constants::EMPTY_32); size_t offset = keys.size() * sizeof(uint32_t); size_t num_bytes_written = num_padded_elements * sizeof(uint32_t); status = clEnqueueWriteBuffer(mgr->command_queue, keys_buffer, CL_TRUE, offset, num_bytes_written, empty_elements.data(), 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); } // 3. Construct parameters buffer cl_mem params_buffer = clCreateBuffer(mgr->context, CL_MEM_READ_WRITE, params_.size() * sizeof(uint32_t), NULL, NULL); status = clEnqueueWriteBuffer(mgr->command_queue, params_buffer, CL_TRUE, 0, params_.size() * sizeof(uint32_t), params_.data(), 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); // 4. invoke retrieve kernel const cl_kernel kernel_hashtable_retrieve = mgr->kernel_map[mpp::kernels::HASHTABLE_RETRIEVE]; // params: __global int32_t* keys, __global int64_t* table, __constant uint32_t* params status = clSetKernelArg(kernel_hashtable_retrieve, 0, sizeof(cl_mem), (void*)&keys_buffer); assert(status == mpp::ReturnCode::CODE_SUCCESS); status = clSetKernelArg(kernel_hashtable_retrieve, 1, sizeof(cl_mem), (void*)&vals_buffer); assert(status == mpp::ReturnCode::CODE_SUCCESS); status = clSetKernelArg(kernel_hashtable_retrieve, 2, sizeof(cl_mem), (void*)&table_buffer_); assert(status == mpp::ReturnCode::CODE_SUCCESS); status = clSetKernelArg(kernel_hashtable_retrieve, 3, sizeof(cl_mem), (void*)&params_buffer); assert(status == mpp::ReturnCode::CODE_SUCCESS); size_t global_work_size[1] = { static_cast<size_t>(next_multiple) }; size_t local_work_size[1] = { std::min(static_cast<size_t>(THREAD_BLOCK_SIZE), static_cast<size_t>(next_multiple)) }; status = clEnqueueNDRangeKernel(mgr->command_queue, kernel_hashtable_retrieve, 1, NULL, global_work_size, local_work_size, 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); // 5. Read back results std::vector<uint32_t> retrieved_entries(next_multiple); status = clEnqueueReadBuffer(mgr->command_queue, vals_buffer, CL_TRUE, 0, next_multiple * sizeof(uint32_t), retrieved_entries.data(), 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); // 6. Release buffers status = clReleaseMemObject(keys_buffer); assert(status == mpp::ReturnCode::CODE_SUCCESS); status = clReleaseMemObject(vals_buffer); assert(status == mpp::ReturnCode::CODE_SUCCESS); status = clReleaseMemObject(params_buffer); assert(status == mpp::ReturnCode::CODE_SUCCESS); retrieved_entries.resize(keys.size()); return retrieved_entries; } void HashTable::GenerateParams() { params_[PARAM_IDX_HASHFUNC_A_0] = rand(); params_[PARAM_IDX_HASHFUNC_B_0] = rand(); params_[PARAM_IDX_HASHFUNC_A_1] = rand(); params_[PARAM_IDX_HASHFUNC_B_1] = rand(); params_[PARAM_IDX_HASHFUNC_A_2] = rand(); params_[PARAM_IDX_HASHFUNC_B_2] = rand(); params_[PARAM_IDX_HASHFUNC_A_3] = rand(); params_[PARAM_IDX_HASHFUNC_B_3] = rand(); params_[PARAM_IDX_MAX_ITERATIONS] = max_iterations; params_[PARAM_IDX_TABLESIZE] = size_; OpenCLManager* mgr = OpenCLManager::GetInstance(); assert(mgr != nullptr); cl_int status = 0; if (params_buffer_ != 0) { status = clReleaseMemObject(params_buffer_); assert(status == mpp::ReturnCode::CODE_SUCCESS); } params_buffer_ = clCreateBuffer(mgr->context, CL_MEM_READ_ONLY, params_.size() * sizeof(uint32_t), NULL, NULL); status = clEnqueueWriteBuffer(mgr->command_queue, params_buffer_, CL_TRUE, 0, params_.size() * sizeof(uint32_t), params_.data(), 0, NULL, NULL); assert(status == mpp::ReturnCode::CODE_SUCCESS); }
true
f9fa57f964d0ef51be5c1b02f8a2d12f063d9782
C++
rotanov/way-station
/cpp-course/re-stl/src/dtl_Allocator.h
UTF-8
4,844
3.375
3
[]
no_license
#ifndef _ALLOCATOR_H_ #define _ALLOCATOR_H_ #include <cstdlib> #include <cassert> #include <malloc.h> /** * CSomeAllocator: * GetPointer(): returns pointer to allocated memory. * Resize(n): Stands for Allocate + Reallocate + Deallocate at the same time. * i.e. first time invokation Allocates memory, next calls used to reallocate memory and * if we want to ResizeTo(0) then it Deallocates memory. * Reserve() ensures given capacity */ template<typename DataType, unsigned int GrowthFactor = 2, unsigned int ReduceCriteria = 4> class CDynAllocator { private: size_t Capacity; DataType* Pointer; size_t Size; void Deallocate() { free(Pointer), Pointer = NULL, Capacity = 0, Size = 0; } void InvokeDestructors_(size_t from, size_t to) { if (Is<DataType>::concrete) return; for(size_t i = from; i < to; i++) (Pointer + i)->DataType::~DataType(); } void InvokeConstructors_(size_t from, size_t to) { if (Is<DataType>::concrete) return; // try // { for(size_t i = from; i < to; i++) new(Pointer + i)DataType(); // } // catch(...) // { // for(size_t i = 0; i < ElementsNumber; i++) // (Data + i)->DataType::~DataType(); // ORLY we have to call dtor if ctor raised exception? // Deallocate(); // throw; // } } public: typedef DataType value_type; typedef value_type* PointerType; typedef const value_type* ConstPointerType; typedef value_type& ReferenceType; typedef const value_type& ConstReferenceType; typedef std::size_t SizeType; //typedef std::ptrdiff_t DifferenceType; typedef ptrdiff_t DifferenceType; explicit CDynAllocator(size_t ASize = 0) : Capacity(0), Pointer(NULL), Size(0) { resize(ASize); } ~CDynAllocator() { Deallocate(); } size_t capacity() const { return Capacity; } size_t size() const { return Size; } DataType* pointer() { return Pointer; } void reserve(size_t ACapacity) { if (ACapacity <= Capacity) return; Capacity = ACapacity; DataType* NewPointer = static_cast<DataType*>(calloc(Capacity, sizeof(DataType))); #undef min std::swap(Pointer, NewPointer); InvokeConstructors_(0, Size); std::swap(Pointer, NewPointer); for(size_t i = 0; i < Size; i++) NewPointer[i] = Pointer[i]; InvokeDestructors_(0, Size); free(Pointer); Pointer = NewPointer; } void resize(size_t ASize) { if (ASize == 0) { InvokeDestructors_(0, Size); Deallocate(); return; } size_t OldCapacity = Capacity; if (ASize > Capacity) Capacity = ASize * GrowthFactor; else if (ASize * ReduceCriteria <= Capacity) Capacity /= ReduceCriteria; if (Capacity == OldCapacity) { InvokeConstructors_(Size, ASize); InvokeDestructors_(ASize, Size); Size = ASize; return; } DataType* NewPointer = static_cast<DataType*>(calloc(Capacity, sizeof(DataType))); #undef min size_t limit = std::min(Size, ASize); std::swap(Pointer, NewPointer); InvokeConstructors_(0, limit); std::swap(Pointer, NewPointer); for(size_t i = 0; i < limit; i++) NewPointer[i] = Pointer[i]; InvokeDestructors_(0, Size); free(Pointer); Pointer = NewPointer; InvokeConstructors_(Size, ASize); Size = ASize; return; } }; /** * CFixedAllocator: Tries to allocate memory in stack. Can't dynamically allocate more than it already has. */ template<typename DataType, size_t MaxElements> class CFixedAllocator { private: unsigned char Data[sizeof(DataType) * MaxElements]; size_t Size; public: CFixedAllocator() { memset(Data, 0, sizeof(DataType) * MaxElements); } explicit CFixedAllocator(size_t Size) { if (Size > MaxElements) throw std::bad_alloc(); memset(Data, 0, sizeof(DataType) * /*Size*/ MaxElements); } CFixedAllocator& operator =(const CFixedAllocator &rhs) { memcpy(Data, rhs.Data, sizeof(DataType) * MaxElements); return *this; } size_t GetCapacity() const { return MaxElements; } DataType* GetPointer() { return reinterpret_cast<DataType*>(Data); } void Resize(size_t Size) { if (Size > MaxElements) throw std::bad_alloc(); } }; /* Sample interface: template<typename DataType> class CDynAllocator { public: typedef DataType value_type; typedef value_type* PointerType; typedef const value_type* ConstPointerType; typedef value_type& ReferenceType; typedef const value_type& ConstReferenceType; typedef std::size_t SizeType; typedef std::ptrdiff_t DifferenceType; CDynAllocator() ~CDynAllocator(); CDynAllocator& operator =(const CDynAllocator &rhs) size_t GetCapacity() const; explicit CDynAllocator(size_t Size); DataType* GetPointer(); void Resize(size_t Size); }; */ #endif // _ALLOCATOR_H_
true
3eef578df803ec92b2e38b754ced01b82da9272d
C++
agriic/chess-vr
/src/Utils.cpp
UTF-8
1,400
3.015625
3
[ "Unlicense" ]
permissive
#include "Utils.hpp" #include <sys/stat.h> std::string aic::getAlphaNumeric(std::string input) { for (int i = 0; i < input.size(); i++) { auto c = input[i]; if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) { input[i] = '.'; } } input.erase(std::remove(input.begin(), input.end(), '.'), input.end()); return input; } bool aic::endsWith(const std::string& str, const std::string& needle) { if (str.length() >= needle.length()) { return (0 == str.compare (str.length() - needle.length(), needle.length(), needle)); } else { return false; } } bool aic::fileExists(const std::string& name) { struct stat buffer; return (stat (name.c_str(), &buffer) == 0); } float aic::euclideanDist(cv::Point2f& p, cv::Point2f& q) { cv::Point2f diff = p - q; return cv::sqrt(diff.x*diff.x + diff.y*diff.y); } std::string aic::replaceAll(const std::string& str, const std::string& from, const std::string& to) { std::string rez = str; size_t start_pos = 0; while((start_pos = rez.find(from, start_pos)) != std::string::npos) { size_t end_pos = start_pos + from.length(); rez.replace(start_pos, end_pos, to); start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx' } return rez; }
true
1776f35dac9500bde96fde7bb13b7bfc4227b9c3
C++
KleinFourGroup/cilk_tre_tests
/fib.cc
UTF-8
2,429
3.1875
3
[]
no_license
#include <cilk/cilk.h> #include <atomic> #include <iostream> #include <time.h> int fib(int n) { if (n < 2) return n; int x,y; x = fib(n - 1); y = fib(n - 2); return x + y; } int cfib(int n) { if (n < 2) return n; int x,y; x = cilk_spawn cfib(n - 1); y = cfib(n - 2); cilk_sync; return x + y; } int fibt(int n) { if (n < 2) return n; int x = 0; while (n >= 2) { int y = fibt(n - 1); x += y; n -= 2; } return x + n; } int fibt_at(int n) { if (n < 2) return n; std::atomic<int> x(0); while (n >= 2) { int y = fibt_at(n - 1); std::atomic_fetch_add(&x, y); n -= 2; } std::atomic_fetch_add(&x, n); int ret = x; return ret; } int cfibt_at(int n) { if (n < 2) return n; std::atomic<int> x(0); while (n >= 2) { int y = cilk_spawn cfibt_at(n - 1); std::atomic_fetch_add(&x, y); n -= 2; } cilk_sync; std::atomic_fetch_add(&x, n); int ret = x; return ret; } int fibt_arr(int n) { if (n < 2) return n; int x = 0; int MAX = n/2; int ind = 0; int y[MAX]; while (n >= 2) { y[ind] = fibt_arr(n - 1); ind ++; n -= 2; } for(ind = 0; ind < MAX; ind++) x += y[ind]; return x + n; } int cfibt_arr(int n) { if (n < 2) return n; int x = 0; int MAX = n/2; int ind = 0; int y[MAX]; while (n >= 2) { y[ind] = cilk_spawn cfibt_arr(n - 1); ind ++; n -= 2; } cilk_sync; for(ind = 0; ind < MAX; ind++) x += y[ind]; return x + n; } int main() { clock_t t; int in = 40; int n; t = clock(); n = fib(in); t = clock() - t; std::cout << n << " fib " << t * 1.0 / CLOCKS_PER_SEC << std::endl; t = clock(); n = cfib(in); t = clock() - t; std::cout << n << " cfib " << t * 1.0 / CLOCKS_PER_SEC << std::endl; t = clock(); n = fibt(in); t = clock() - t; std::cout << n << " fibt " << t * 1.0 / CLOCKS_PER_SEC << std::endl; t = clock(); n = fibt_at(in); t = clock() - t; std::cout << n << " fibt_at " << t * 1.0 / CLOCKS_PER_SEC << std::endl; t = clock(); n = cfibt_at(in); t = clock() - t; std::cout << n << " cfibt_at " << t * 1.0 / CLOCKS_PER_SEC << std::endl; t = clock(); n = fibt_arr(in); t = clock() - t; std::cout << n << " fibt_arr " << t * 1.0 / CLOCKS_PER_SEC << std::endl; t = clock(); n = cfibt_arr(in); t = clock() - t; std::cout << n << " cfibt_arr " << t * 1.0 / CLOCKS_PER_SEC << std::endl; return 0; }
true
072fa43e10f22434126df9a85392c76ae5a037b2
C++
zhushh/cplusplus
/play_code/huffman_code.cpp
UTF-8
2,449
3.578125
4
[]
no_license
#include <iostream> using namespace std; struct huffman_leaf { int weight; char ch; }; struct huffman_root { int sum_weight; struct huffman_leaf * data; struct huffman_root * left; struct huffman_root * right; huffman_root() : sum_weight(0), data(NULL), left(NULL), right(NULL) {} }; struct huffman_root * huffman[110]; void sort_huffman(int low, int hig) { if (low < hig) { int l = low, h = hig; struct huffman_root * ptr = huffman[low]; while (l < h) { while (l < h && huffman[h]->sum_weight > ptr->sum_weight) --h; if (l < h) huffman[l++] = huffman[h]; while (l < h && huffman[l]->sum_weight < ptr->sum_weight) ++l; if (l < h) huffman[h--] = huffman[l]; } huffman[l] = ptr; sort_huffman(low, l - 1); sort_huffman(l + 1, hig); } } struct huffman_root* create_huffman_tree(int n) { int i, j, k; for (i = n - 1, j = 0, k = 0; i > 0; i--, j++, k += 2) { huffman[n + j] = new struct huffman_root; huffman[n + j]->sum_weight = huffman[k]->sum_weight + huffman[k+1]->sum_weight; huffman[n + j]->left = huffman[k]; huffman[n + j]->right = huffman[k + 1]; sort_huffman(k + 2, n + j); } return huffman[n + j - 1]; } int count_length(struct huffman_root * root, int level) { if (NULL == root) return 0; int sum = 0; if (NULL != root->data) { sum += root->data->weight * level; } else { sum += count_length(root->left, level + 1); sum += count_length(root->right, level + 1); } return sum; } void clear_huffman_tree(struct huffman_root * root) { if (NULL == root) return; clear_huffman_tree(root->left); clear_huffman_tree(root->right); root->left = root->right = NULL; if (NULL != root->data) { delete root->data; root->data = NULL; } delete root; } int main() { int n; cin >> n; for (int i = 0; i < n; i++) { struct huffman_root * temp = new struct huffman_root; temp->data = new huffman_leaf; cin >> temp->data->ch >> temp->data->weight; temp->sum_weight = temp->data->weight; huffman[i] = temp; } sort_huffman(0, n - 1); struct huffman_root * root; root = create_huffman_tree(n); int sum = count_length(root, 0); cout << sum << endl; clear_huffman_tree(root); return 0; }
true
c4595ca22bd5b3c8f2f1a7130ac2103eaaebd96b
C++
hs-krispy/BOJ
/N&M(9).cpp
UTF-8
788
2.78125
3
[]
no_license
// // Created by 0864h on 2020-03-12. // #include<iostream> #include<cstdio> #include <algorithm> using namespace std; int arr[9], ans[9]; bool check[9]; int n, m; void seq(int count) { if(count == m) { for(int j = 0;j < count;j++) printf("%d ", ans[j]); printf("\n"); return; } bool num[10001] = {false, }; // 사용되는 수 자체를 체크 for(int i = 1;i <= n;i++) { if(!num[arr[i]] && !check[i]) { ans[count] = arr[i]; num[arr[i]] = true; check[i] = true; seq(count+1); check[i] = false; } } } int main() { int i; cin >> n >> m; for(i = 1;i <= n;i++) cin >> arr[i]; sort(&arr[1], &arr[n+1]); seq(0); }
true
0a91696b0f1885d3366171c747129a090441ff87
C++
thompsonsed/rfsim
/rfsim/lib/Fox.cpp
UTF-8
563
3.046875
3
[]
no_license
/** * @brief Contains the Fox class and behaviours. */ #include "Fox.h" void Fox::catchRabbit(vector<Rabbit> &rabbits, shared_ptr<RNGController> random) { if(!rabbits.empty()) { unsigned long index = random->i0(rabbits.size() - 1); energy += rabbits[index].getEnergy()*0.5; rabbits[index].kill(); } } bool Fox::canReproduce() { if(energy > 50) { energy -= 50; return true; } return false; } void Fox::exist() { energy -= 5; age += 1; } bool Fox::oldAge() { return age > 30; }
true
d724c8baac1f04fd4dd2cad00dc8b62f25415bac
C++
AnusreeK-2000/ADA_1BM18CS017
/ins_sort.cpp
UTF-8
956
3.75
4
[]
no_license
/* Sort a given set of N integer elements using Insertion Sort technique and compute its time taken. */ #include<iostream> #include<chrono> using namespace std::chrono; using namespace std; void insertion(int a[],int n) { for(int i=1;i<n;i++) { int item=a[i]; int j=i-1; while(j>=0 && a[j]>item) { a[j+1]=a[j]; j=j-1; } a[j+1]=item; } } int main() { int n; cout<<"Enter the size of the array"<<endl; cin>>n; int a[n]; for(int i=0;i<n;i++) a[i]=rand()%100; auto start = high_resolution_clock::now(); insertion(a,n); auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout<<"Sorted array is"<<endl; for(int i=0;i<n;i++) cout<<a[i]<<endl; cout<<"Time taken: "<<duration.count()<<" microseconds"<<endl; return 0; } /* output Enter the size of the array 20 Sorted array is 15 21 26 26 27 35 36 40 49 59 62 63 72 77 83 86 86 90 92 93 Time taken: 1 microseconds */
true
c1a7edf9567251f810eb20798a90ac4f0cb86f44
C++
jrthebish4/C867-class-roster-hw
/student.h
UTF-8
869
2.796875
3
[]
no_license
// // Created by Jakob Bishop on 2019-04-01. // #ifndef C867_STUDENT_H #define C867_STUDENT_H #include <string> #include "degree.h" using namespace std; class Student { public: Student(string, string, string, string, int, Degree, int[3]); ~Student(); string getStudentID(); string getFirstName(); string getLastName(); string getEmailAddress(); int getAge(); int *getDaysToComplete(); virtual Degree getDegreeProgram(); void setStudentID(string); void setFirstName(string); void setLastName(string); void setEmailAddress(string); void setAge(int); void setDegree(Degree); void setDaysToComplete(const int[]); virtual void print(); private: string studentID, firstName, lastName, emailAddress; int age; Degree degree; int daysToComplete[3]; }; #endif //C867_STUDENT_H
true
753b16626f24124141fa355eee9562ad44b91ffa
C++
xen/nwc-toolkit
/lib/token-trie-tracer.cc
UTF-8
2,009
2.65625
3
[ "BSD-3-Clause" ]
permissive
// Copyright 2010 Susumu Yata <syata@acm.org> #include <nwc-toolkit/token-trie-tracer.h> #include <algorithm> namespace nwc_toolkit { TokenTrieTracer::TokenTrieTracer() : token_trie_(NULL), table_(), current_node_id_(0), next_node_id_(0) {} void TokenTrieTracer::Clear() { token_trie_ = NULL; std::vector<unsigned int>().swap(table_); current_node_id_ = 0; next_node_id_ = 0; } void TokenTrieTracer::Trace(const TokenTrie &token_trie) { Clear(); token_trie_ = &token_trie; table_.resize((token_trie.table_size() + NUM_BITS_PER_INT - 1) / NUM_BITS_PER_INT, 0); current_node_id_ = TokenTrie::ROOT_NODE_ID; next_node_id_ = TokenTrie::ROOT_NODE_ID + 1; } bool TokenTrieTracer::Next(std::vector<int> *token_ids, int *freq) { if (RestoreFromCurrentNode(token_ids, freq)) { return true; } while (next_node_id_ < static_cast<int>(token_trie_->table_size())) { if (IsVisited(next_node_id_) || (token_trie_->node( next_node_id_).prev_node_id() == TokenTrie::INVALID_NODE_ID)) { ++next_node_id_; continue; } current_node_id_ = next_node_id_; ++next_node_id_; return RestoreFromCurrentNode(token_ids, freq); } return false; } bool TokenTrieTracer::RestoreFromCurrentNode( std::vector<int> *token_ids, int *freq) { if (current_node_id_ == TokenTrie::ROOT_NODE_ID) { return false; } int node_id = current_node_id_; table_[node_id / NUM_BITS_PER_INT] |= 1U << (node_id % NUM_BITS_PER_INT); current_node_id_ = token_trie_->node(node_id).prev_node_id(); if (IsVisited(current_node_id_)) { current_node_id_ = TokenTrie::ROOT_NODE_ID; } std::size_t count = 0; *freq = token_trie_->node(node_id).freq(); do { token_ids->push_back(token_trie_->node(node_id).token_id()); node_id = token_trie_->node(node_id).prev_node_id(); ++count; } while (node_id != TokenTrie::ROOT_NODE_ID); std::reverse(token_ids->end() - count, token_ids->end()); return true; } } // namespace nwc_toolkit
true
fa86f43f9a81ec7b5289e9b20358e98d3f4b2910
C++
longneicool/jian_zhi_offer
/chap2/6_recreateBinaryTree/testcase/testcase.cpp
UTF-8
361
2.734375
3
[]
no_license
#include "gtest/gtest.h" #include "tree.h" #include "testfixture.h" TEST_F(BinaryTreeCreaterTest, test_normal_case) { int preOrderArray[] = {1, 2, 4, 7, 3, 5, 6, 8}; int inOrderArray[] = {4, 7, 2, 1, 5, 3, 8, 6}; BinaryTreeNodePtr head = construct(preOrderArray, inOrderArray, sizeof(inOrderArray)/sizeof(int)); int i = 0; EXPECT_EQ(1, head->val); }
true
a7a75b13d05fe8288345b2fa6a632941dfc4364d
C++
tterrag1098/COSC482
/Homework03/Bubbles/GraphicsEngine.h
UTF-8
1,200
2.6875
3
[]
no_license
#ifndef GRAPHICSENGINE_H_INCLUDED #define GRAPHICSENGINE_H_INCLUDED #include <GL/glew.h> #include <SFML/Graphics.hpp> #include <SFML/OpenGL.hpp> #include <SFML/System.hpp> #include <iostream> #include <string> #include <stdio.h> #include "LoadShaders.h" #include "Bubble.h" #include "ProgramDefines.h" /** \file GraphicsEngine.h \brief Header file for GraphicsEngine.cpp \author Don Spickler \version 1.1 \date Written: 1/9/2016 <BR> Revised: 1/9/2016 */ /** \class GraphicsEngine \brief The GraphicsEngine class is an extension of sf::RenderWindow which handles all of the graphics rendering in the program. */ class GraphicsEngine : public sf::RenderWindow { private: GLenum mode; ///< Mode, either point, line or fill. int sscount; ///< Screenshot count to be appended to the screenshot filename. std::vector<Bubble*> stars; ///< All stars to draw. public: GraphicsEngine(std::string, GLint, GLint); ~GraphicsEngine(); void refresh(); void display(); void changeMode(); void screenshot(); void resize(); void setSize(unsigned int, unsigned int); std::vector<Bubble*> getStars(); }; #endif // GRAPHICSENGINE_H_INCLUDED
true
b277f27fbe30a2ef611483615d860f90c45b9c54
C++
andreyvro/SMT-GA
/GA_ST_CORE/Individuo.h
UTF-8
2,247
2.796875
3
[]
no_license
#ifndef INDIVIDUO_H #define INDIVIDUO_H #include <vector> #include <algorithm> #include <omp.h> #include "Grafo.h" #include "Aux.h" using namespace std; class Individuo { private: Grafo *grafo; unsigned int qtdPontosSteiner = 0; // Quantidade de Pontos steiner vector<Vertice> pontoSteiner; // Armazena vértices (grafo e steiner) vector< vector<bool> > matrizAdj; // Matriz de adjacencia double fitness; // Fitness do indivíduo public: Individuo(); // Inicia cromossomo zerado const unsigned int getQtdPtFixo(); // Retorna a quantidade de vertices do grafo const unsigned int getQtdPtSteiner(); // Retorna quantidade de pontos steiner const unsigned int getQtdPtTotal(); // Retorna tamanho do cromossomo const unsigned int getQtdMaxSteiner(); // Retorna a quantidade máxima de pontos steiner void addPontoSteiner(Vertice pontoSteiner); // Adiciona um ponto Steiner void remPontoSteiner(unsigned int indice); // Remove um ponto Steiner (indice do ponto steiner) Vertice &getVertice(unsigned int indice); // Retorna Vértice (grafo e steiner) double getDistancia(unsigned int indice1, unsigned int indice2); // Retorna distancia entre dois vértices double getAngulo(unsigned int indice1, unsigned int indice2, unsigned int indice3); void setGene(unsigned int x, unsigned int y, bool valor); // Altera gene const bool getGene(unsigned int x, unsigned int y); // Retorna gene // Retorna lista de vertices que são adjacêntes, Se (ordenado == true), retorna vértices ordenados por menor distância void getPtsAdjacentes(unsigned int vertice, vector<unsigned int> &adj, bool ordenar = false); void calcularFitness(); // Calcula e seta valor de fitness void setFitness(double fitness); // Seta valor de Fitness const double getFitness(); // Retorna fitness do indivíduo }; #endif // INDIVIDUO_H
true
28fbb4a66510e3a97c0bb34f350b5de9b532ad1c
C++
WhyteNoise/rWhyteMultiplayerSystemsMidterm
/rWhyteMSMidterm/rWhyteMSMidterm/Player.cpp
UTF-8
1,818
3.140625
3
[]
no_license
#include "Player.h" PlayerChar::PlayerChar() { userName = "Peasant"; thisType = Peasant; } PlayerChar::PlayerChar(std::string name, ClassType classType, int uid) { userName = name; thisType = classType; userID = uid; if (classType == BattleMaster) { health = 10; attack = 3; healVal = 2; } else if (classType == Monk) { health = 10; attack = 2; healVal = 5; } else if (classType == Rogue) { health = 5; attack = 5; healVal = 1; } else if (classType == Peasant) { health = 1; attack = 1; healVal = 0; } } std::string ConvertClassType(PlayerChar::ClassType value) { if (value == PlayerChar::BattleMaster) { return "BattleMaster"; } else if (value == PlayerChar::Monk) { return "Monk"; } else if (value == PlayerChar::Rogue) { return "Rogue"; } else if (value == PlayerChar::Peasant) { return "Peasant"; } else { return "Invalid Class"; } } void PlayerChar::Damage(int value) { health = health - value; } std::string PlayerChar::GetName() const { return userName; } void PlayerChar::SetName(std::string value) { userName = value; } void PlayerChar::SetAddress(RakNet::SystemAddress value) { address = value; } RakNet::SystemAddress PlayerChar::GetAddress() { return address; } PlayerChar::ClassType PlayerChar::GetClassType() { return thisType; } void PlayerChar::SetClassType(PlayerChar::ClassType value) { thisType = value; } int PlayerChar::GetPower() { return attack; } int PlayerChar::GetHealth() { return health; } void PlayerChar::HealSelf() { health = health + healVal; } std::string PlayerChar::GetStats() { return "User Name:" + userName + "\nClass: " + ConvertClassType(thisType) + "\nAttack: " + std::to_string(attack) + "\nCurrent Health: " + std::to_string(health) + "\nUser ID: " + std::to_string(userID) + "\n"; }
true
acdcba177ce6312beaaa3a226f846dbed91b9e2a
C++
pes-magic/procon
/GCJ/2020-Round3/A.cpp
UTF-8
1,578
2.625
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include <cstdio> using namespace std; string solve(const string& S, const string& T){ int n = S.size(); int m = T.size(); vector<vector<int>> dp(n+1, vector<int>(m+1, 100000000)); vector<vector<pair<int, int>>> prev(n+1, vector<pair<int, int>>(m+1)); dp[0][0] = 0; for(int i=0;i<=S.size();i++){ for(int j=0;j<=T.size();j++){ if(i < S.size()){ if(dp[i+1][j] > dp[i][j] + 1){ dp[i+1][j] = dp[i][j] + 1; prev[i+1][j] = make_pair(i, j); } } if(j < T.size()){ if(dp[i][j+1] > dp[i][j] + 1){ dp[i][j+1] = dp[i][j] + 1; prev[i][j+1] = make_pair(i, j); } } if(i < S.size() && j < T.size()){ if(dp[i+1][j+1] > dp[i][j] + (S[i] == T[j] ? 0 : 1)){ dp[i+1][j+1] = dp[i][j] + (S[i] == T[j] ? 0 : 1); prev[i+1][j+1] = make_pair(i, j); } } } } string res = ""; int pi = S.size(), pj = T.size(); while(dp[pi][pj] > dp.back().back()/2){ auto p = prev[pi][pj]; if(p.second != pj){ res = T[p.second] + res; } pi = p.first; pj = p.second; } return S.substr(0, pi) + res; } int main(){ int T; cin >> T; for(int t=1;t<=T;t++){ string a, b; cin >> a >> b; printf("Case #%d: %s\n", t, solve(a, b).c_str()); } }
true
d635b6e92fa7e284b46ffd6b847eed1fdd510fa8
C++
esharp054/Networks
/des.cpp
UTF-8
4,860
3.171875
3
[]
no_license
// // eventsim.cpp // // // Created by Yeem Diallo on 9/30/16. // // int min_w = 15; #include <stdio.h> #include <algorithm> // for random_shuffle() #include <iostream> // for cout #include <list> // for queue #include <vector> // for vector #include <time.h> // Execution event in a descrete event driven simulation. class event { public: // Construct sets time of event. event (unsigned int t) : time(t) { } // Execute event by invoking this method. //pure virtual function virtual void processEvent () = 0; //const unsigned int numberOfNodes; const unsigned int time; }; // returns a random integer between 0 and n with n <= 32767 <= INT_MAX int irand (int n) { static int seq[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf }; std::random_shuffle (seq, seq + sizeof seq / sizeof *seq); const int rnd = ((seq [0] << 11) | (seq [1] << 8) | (seq [2] << 4)) + seq [3]; return rnd % n; } class Node{ //private: public: int totNumFrames = 0; //int counterToSend; //int flowTime; //Number of frames left to send //Number of frames sent int framesLeft = 0; int timeTaken = 0; int startTime = 0; int backOff = 0; int mulitiplier = 1; void setNumFrames(int maxNum){ //srand(time(NULL)); totNumFrames = rand() % maxNum + 1; framesLeft = totNumFrames; } void setBackOff(){ backOff = rand() % (min_w * mulitiplier) + 1; } int getNumFrames(){ return totNumFrames; } int getFramesLeft(){ return framesLeft; } }; struct nodeComparator { bool operator() (const Node * left, const Node * right) const { return left->totNumFrames > right->totNumFrames; } }; // Framework for discrete event-driven simulations. class simulation { public: simulation () : numberOfNodes(0), time(0), eventQueue (){} void run (); void scheduleEvent(event * newEvent) { eventQueue.push_back(newEvent); } unsigned int numberOfNodes; unsigned int time; protected: std::list<event*> eventQueue; std::list<Node> activeNodes; }; void simulation::run () { while (! eventQueue.empty ()) { event * nextEvent = eventQueue.front(); eventQueue.pop_front(); time = nextEvent->time; nextEvent->processEvent(); delete nextEvent; } } class fillNodeEvent : public event { public: fillNodeEvent (Node * s, unsigned int t): event(t), n(s), time(t){ } virtual void processEvent (); protected: Node * n; int time; }; class counterEvent : public event { public: counterEvent (Node * s, unsigned int t): event(t), n(s), curTime(t){ } virtual void processEvent (); protected: Node * n; int curTime; }; // Simulation class mySimulation : public simulation { public: mySimulation () : simulation (), numberOfNodes(2) { } void canSend (unsigned int numberOfFrames); // Data fields. unsigned int numberOfNodes; } mySim; void fillNodeEvent::processEvent () { n->setNumFrames(10); n->startTime = time; n->setBackOff(); std::cout << "Number of frames for node: " << n->totNumFrames << "\n"; std::cout << "Start time for node: " << n->startTime << "\n"; mySim.scheduleEvent(new counterEvent(n, time)); } void counterEvent::processEvent () { std::cout << "Time: " << curTime << " "; //Send Frame if(n->backOff == 0){ n->framesLeft--; n->timeTaken += 1; curTime += 1; n->mulitiplier = 1; n->setBackOff(); std::cout << "Sent a Frame" << "\n"; if(n->getFramesLeft() != 0){ mySim.scheduleEvent(new counterEvent(n, curTime)); } } //Decrement backoff counter and increase time taken else{ std::cout << "Backoff" << "\n"; n->backOff--; n->timeTaken += 1; curTime += 1; mySim.scheduleEvent(new counterEvent(n, curTime)); } } int main () { srand(time(NULL)); std::cout << "Wifi Discrete Event Simulator\n"; Node * n1 = new Node(); //n1.setNumFrames(10); /*std::cout << "Number of frames for node 1: " << n1.totNumFrames << "\n"; Node n2; n2.setNumFrames(10); std::cout << "Number of frames for node 2: " << n2.totNumFrames << "\n";*/ mySim.scheduleEvent (new fillNodeEvent(n1, 5)); int time = 0; //event newEvent(time); //simulation mySim; mySim.run(); std::cout << "Total Time: " << n1->timeTaken<< "\n"; delete n1; //mySim.scheduleEvent(newEvent); // theSimulation.scheduleEvent (new arriveEvent (t, 1 + irand (4))); // Run the simulation. //theSimulation.run (); return 0; }
true
b0379c7ae377cec6b092b2bb19d8488dde90de24
C++
karoldabek/gitrepo
/cpp/funkcje.cpp
UTF-8
287
3.171875
3
[]
no_license
/* * funkcje.cpp */ #include <iostream> using namespace std; void sumuj(int a, int b) { cout << "Suma: " << a+b << endl; } int main(int argc, char **argv) { int a, b; cout << "Podaj liczby: " << endl; cin >> a >> b; sumuj(a, b); sumuj(b, a); return 0; }
true
97227cbf68361aad2f6b516b27e70a34e47f8502
C++
prettyboyucas/Leetcode
/Leetcode/106ConstructBinaryTreefrominorderandPostorderTraversal.cpp
GB18030
779
3.3125
3
[ "MIT" ]
permissive
//ǰһֻȡһͬǰһ class Solution { public: typedef vector<int>::iterator Iter; TreeNode *buildTreeRecur(Iter istart, Iter iend, Iter pstart, Iter pend) { if (istart == iend)return NULL; int rootval = *(pend - 1); Iter iterroot = find(istart, iend, rootval); TreeNode *res = new TreeNode(rootval); res->left = buildTreeRecur(istart, iterroot, pstart, pstart + (iterroot - istart)); res->right = buildTreeRecur(iterroot + 1, iend, pstart + (iterroot - istart), pend - 1); return res; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // write your code here return buildTreeRecur(inorder.begin(), inorder.end(), postorder.begin(), postorder.end()); } };
true
07cc9e3a0e2c979419dec80c6f77f2c223c6bc2f
C++
Mariam819/my-project
/Pir.ino
UTF-8
364
2.671875
3
[]
no_license
void Pir() { LightSensorVal = analogRead(A0); PIRSensorVal = digitalRead(2); RelayOutputVal = 8; if (LightSensorVal < 600) { if (PIRSensorVal == HIGH) { digitalWrite(8, HIGH); delay(5000); // Wait for 5000 millisecond(s) } else { digitalWrite(8, LOW); delay(1000); // Wait for 1000 millisecond(s) } } }
true
56341d645fa971260777fdc2ade3f69b1d8c9038
C++
ahnaf22/algoCode
/dijkstra.cpp
UTF-8
1,405
2.90625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; vector<int> edge[100], cost[100]; const int infinity =999999; struct data { int city, dist; bool operator < (const data &p) const { return dist > p.dist; } }; int dijkstra(int source, int destination) { int d[100]; for(int i=0; i<100; i++) d[i] = infinity; priority_queue<data> q; data u, v; u.city = source, u.dist = 0; q.push( u ); d[ source ] = 0; while( !q.empty() ) { u = q.top(); q.pop(); int ucost = d[ u.city ]; for(int i=0; i<edge[u.city].size(); i++) { v.city = edge[u.city][i], v.dist = cost[u.city][i] + ucost; if( d[v.city] > v.dist ) { d[v.city] = v.dist; q.push( v ); } } } return d[ destination ]; } int main() { int e,n,p,q,c,s,en; cin>>n>>e; for(int i=0;i<e;i++) { cin>>p>>q; edge[p].push_back(q); edge[q].push_back(p); cost[p].push_back(1); cost[q].push_back(1); } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { int a=dijkstra(i,j); if(a==infinity) cout<<"-"<<" "; else cout<<a<<" "; } cout<<endl; } }
true
94f9f0008187d864245378f89f80db9f725109fa
C++
clwyatt/CTC
/Code/SlicerModules/VirtualColon/CSVReader.cpp
UTF-8
4,074
2.671875
3
[ "BSD-3-Clause" ]
permissive
/* * CSVReader.cpp * * Created on: Oct 11, 2008 * Author: haxu */ #include "CSVReader.hpp" #include <fstream> #include <iostream> #include "boost/spirit/core.hpp" #include "boost/spirit/utility/loops.hpp" #include "boost/spirit/dynamic/stored_rule.hpp" using namespace boost::spirit; // constructor CSVReader::CSVReader(string fname_, string colFormat_) : _fname(fname_), _colFormat(colFormat_), _parseSuccess(false), _rowNum(0), _colNum(0) { } // destructor CSVReader::~CSVReader() { /* for (vector<any>::iterator it = _bag.begin(); it != _bag.end(); it++) { if (any_cast<vector<string> * >(&*it)) { delete *(any_cast<vector<string> * >(&*it)); cout << "delete vector<string> *" << endl; } else if (any_cast<vector<double> * > (&*it)) { delete *(any_cast<vector<double> * >(&*it)); cout << "delete vector<double> *" << endl; } else if (any_cast<vector<int> * >(&*it)) { delete *(any_cast<vector<int> * >(&*it)); cout << "delete vector<int> *" << endl; } } */ } // int CSVReader::parseFile() { // construct boost::spirit parse rule stored_rule<> ruleLine; shared_ptr< vector<string> > vecString; shared_ptr< vector<int> > vecInt; shared_ptr< vector<double> > vecDouble; // build rule for the first column string::const_iterator strit = _colFormat.begin(); if (strit != _colFormat.end()) { if (*strit == 's') { vecString.reset(new vector<string>()); _bag.push_back(vecString); ruleLine = repeat_p(1, more)[~ch_p(',')][push_back_a(*vecString)]; } else if (*strit == 'f') { vecDouble.reset(new vector<double>()); _bag.push_back(vecDouble); ruleLine = real_p[push_back_a(*vecDouble)]; } else if (*strit == 'd') { vecInt.reset(new vector<int>()); _bag.push_back(vecInt); ruleLine = int_p[push_back_a(*vecInt)]; } else if (*strit == ',') ruleLine = ch_p(','); else return -1; // err: invalid format string if (*strit != ',') { _colNum++; } } // build rule for the rest of line while (++strit != _colFormat.end()) { if (*strit == 's') { vecString.reset(new vector<string>()); _bag.push_back(vecString); ruleLine = ruleLine.copy() >> repeat_p(1, more)[~ch_p(',')][push_back_a(*vecString)]; } else if (*strit == 'f') { vecDouble.reset(new vector<double>()); _bag.push_back(vecDouble); ruleLine = ruleLine.copy() >> real_p[push_back_a(*vecDouble)]; } else if (*strit == 'd') { vecInt.reset(new vector<int>()); _bag.push_back(vecInt); ruleLine = ruleLine.copy() >> int_p[push_back_a(*vecInt)]; } else if (*strit == ',') ruleLine = ruleLine.copy() >> ch_p(','); else return -1; // err: invalid format string if (*strit != ',') { _colNum++; } } // parse file ifstream ifs(_fname.c_str()); if (ifs.fail()) return -1; // err: open file failed string line; while (ifs.good()) { getline(ifs, line); if (ifs.eof() && line.length() == 0) // read nothing before hit EOF break; parse_info<> info = parse(line.c_str(), ruleLine); if (!info.full) { return -1; // err: parse error } else { /* cout << _rowNum + 1 << ":\t"; for (unsigned int i = 0; i < _colNum; i++) { if (_colFmt.at(i) == 's') { vecString = any_cast< shared_ptr< vector<string> > >(_bag.at(i)); cout << vecString->at(_rowNum) << ","; } else if (_colFmt.at(i) == 'f') { vecDouble = any_cast< shared_ptr< vector<double> > >(_bag.at(i)); cout << vecDouble->at(_rowNum) << ","; } else if (_colFmt.at(i) == 'd') { vecInt = any_cast< shared_ptr < vector<int> > >(_bag.at(i)); cout << vecInt->at(_rowNum) << ","; } else return -1; // err: unknown col format } cout << endl; */ _rowNum++; } } _parseSuccess = true; return 0; }
true
ffc278979f2b8b7962ac9d4152fedaa33924fbe0
C++
duyquan071299/CastlevaniaUit
/CastlevaniaUit/AnimationDatabase.cpp
UTF-8
1,279
2.640625
3
[]
no_license
#include"AnimationDatabase.h" CAnimationDatabase * CAnimationDatabase::instance = NULL; CAnimationDatabase * CAnimationDatabase::GetInstance() { if (instance == NULL) instance = new CAnimationDatabase(); return instance; } void CAnimationDatabase::Add(AniType type,unordered_map<State, LPANIMATION> temp) { animations[type] = temp; } LPANIMATION CAnimationDatabase::Get(AniType type, State ObjectState) { return (animations[type])[ObjectState]; } void CAnimationDatabase::LoadAnimation() { CSpriteDatabase* sprites = CSpriteDatabase::GetInstance(); string object; int AnType,Amount,Defaulttime, NumberOfFrame,GraphType,Index,Time,state; LPANIMATION ani; ifstream ifs("Resources\\Texts\\Animation.txt"); if (ifs.is_open()) { while (ifs.good()) { ifs >> AnType >> Amount; unordered_map<State, LPANIMATION> temp; for (int i = 0; i < Amount; i++) { ifs >> Defaulttime >> NumberOfFrame >> state; ani = new CAnimation(Defaulttime); for (int j = 0; j < NumberOfFrame; j++) { ifs >> GraphType >> Index >> Time; ani->Add(static_cast<GraphicType>(GraphType), Index, Time); temp[static_cast<State>(state)] = ani; Add(static_cast<AniType>(AnType),temp); } } } } }
true
90533540b10c3d0e08573cfbc20f2eaca262534b
C++
BJas/InterviewBit
/hashing/anagrams.cpp
UTF-8
671
2.796875
3
[]
no_license
#include<iostream> #include<vector> #include<unordered_map> using namespace std; int main() { int n; cin>>n; string x; vector<string> str; for(int i=0; i<n; i++) { cin>>x; str.push_back(x); } unordered_map<string, vector<int> > m; for(int i=0; i<n; i++) { x = str[i]; sort(x.begin(), x.end()); m[x].push_back(i+1); } vector<vector<int> > result; unordered_map<string, vector<int> >::iterator it; for(it=m.begin(); it!=m.end(); it++) { result.push_back(it->second); } for(int i=0; i<result.size(); i++) { for(int j=0; j<result[i].size(); j++) { cout<<result[i][j]<<" "; } cout<<endl; } return 0; }
true
b3678112e5dc0131f284dba72757bb853a35e471
C++
iiSky101/rmsk2
/object_registry.h
UTF-8
18,236
2.53125
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
/*************************************************************************** * Copyright 2017 Martin Grap * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ #ifndef __object_registry__ #define __object_registry__ /*! \file object_registry.h * \brief Header file for the service_provider, registry_manager and object_registry classes. */ #include<string> #include<unordered_map> #include<utility> #include<map> #include<sigc++/functors/slot.h> #include<tlv_stream.h> const unsigned int ERR_METHOD_NOT_FOUND = 100; const unsigned int ERR_CLASS_NOT_FOUND = 101; const unsigned int ERR_NOT_IMPLEMENTED = 102; const unsigned int ERR_SYNTAX_INPUT = 103; const unsigned int ERR_OBJECT_CREATE = 104; const unsigned int ERR_SEMANTICS_INPUT = 105; const unsigned int ERR_RANDOMIZATION_FAILED = 106; const unsigned int ERR_CALL_FAILED = 107; const unsigned int ERR_ROTOR_SET_UNKNOWN = 108; using namespace std; class object_registry; /*! \brief All callbacks that implement TLV functionality have to be of this type. */ typedef sigc::slot<unsigned int, tlv_entry&, tlv_stream *> tlv_callback; /*! \brief An abstract TLV class. A service provider is a thing that knows how to create and manage objects * which provide TLV functionality. * * Each type of object made available over the TLV interface has to have an associated service provider. * It can be used to create new objects, delete existing objects and return tlv_callback objects which * allow to call a specific object's methods. */ class service_provider { public: /*! \brief Constructor. Any service provider has to know an object registry in order register objects * it has created. The parameter obj_registry has to point to an appropriate object of type * object_registry. */ service_provider(object_registry *obj_registry) { registry = obj_registry; counter = 0; } /*! \brief Implementations of this method are intended to return a tlv_callback object that can be used to * create new TLV objects of type managed by this service provider. */ virtual tlv_callback *make_new_handler() = 0; /*! \brief Implementations of this method have to create new objects of the type managed by the servide provider * and register them with the object registry. Implementations have to return ERR_OK if a new object was * successfully created. * * Functors for implementations of this method are returned by make_new_handler(). The parameter params has to * contain the parameters which are needed to create a new TLV object of the desired type. The parameter * out_stream has to point to a tlv_stream that can be used to talk to the connected client. */ virtual unsigned int new_object(tlv_entry& params, tlv_stream *out_stream) = 0; /*! \brief Implementations of this method have to create and return a functor which allows to call the * method which is named by the parameter method_name on the object specified by the parameter * object. * * In case of an error NULL is to be returned by implementations of this method. */ virtual tlv_callback *make_functor(string& method_name, void *object) = 0; /*! \brief Implementations of this method have to delete the object specified in parameter object. */ virtual void delete_object(void *obj_to_delete) = 0; /*! \brief Has to return a human readable description of the type of TLV objects which are managed by this * service provider. */ virtual string get_name() = 0; /*! \brief Destructor. */ virtual ~service_provider() { ; } protected: /*! \brief Each object regsitered with the object regsitry is given a handle. This method generates a new handle * and stores it in the string referenced by parameter new_handle. * * The algorithm used by this method to create a new handle is extremely simple. Append a ':' and the current value * of service_provider::counter to the string returned by get_name(). No checking for uniqeness of the handle * is performed against the object regsitry. As the counter is a 64 bit unsiged int we should nerver see any repitition * of a handle during the typical life time of a service_provider instance. */ virtual void make_handle(string& new_handle); /*! \brief Points to the object registry used by this service_provider instance. */ object_registry *registry; /*! \brief A pointer which is incremented each time a new object is created by this service_provider instance. * The value of this counter becomes part of the created handle. */ unsigned long int counter; }; /*! \brief A TLV class that serves as the base class for all TLV pseudo objects. A pseudo object can be used to implement * methods that can be called without an underlying object. In that sense subclasses of this class can be used to * implement static methods. */ class pseudo_object { public: /*! \brief Constructor. The parameter obj_name has to contain the name of the pseudo object. */ pseudo_object(const char *obj_name) { name = string(obj_name); } /*! \brief This method is used to determine the callback that is capable of handling a call of the static method given in parameter * method. * * NULL is returned in case of an error. */ virtual tlv_callback *get_handler(string& method) = 0; /*! \brief Returns the name of the pseudo object. */ virtual string get_name() { return name; } /*! \brief Destructor. */ virtual ~pseudo_object() { ; } protected: /*! \brief Holds the name of the pseudo object. */ string name; }; class registry_manager; typedef unsigned int (registry_manager::*manager_fun)(tlv_entry& params, tlv_stream *out_stream); /*! \brief A TLV class that implements generic TLV methods which are provided by all object registries and are * therefore independent of any service_provider. * * TLV methods provided by the registry_manager of an object_registry appear as methods of a special object * with the handle "root". */ class registry_manager : public pseudo_object { public: /*! \brief Constructor. The parameter obj_registry has to point to the object_registry that is serviced * by this registry_manager instance. */ registry_manager(object_registry *rgstry); /*! \brief This method creates and returns tlv_callbacks for the root.listobjects(), root.clear() and * root.listproviders() methods. The desired method name has to be specified through the method_name * parameter. * * In case of an error NULL is returned. */ tlv_callback *get_handler(string& method_name); /*! \brief This method deletes all objects currently managed by the object_registry. The parameter * params is not evaluated and can therfore reference any valid tlv_entry object. The parameter * out_stream is used to talk to the client. * * In case of success ERR_OK is returned. */ virtual unsigned int clear_processor(tlv_entry& params, tlv_stream *out_stream); /*! \brief This method returns the handles of all objects objects currently managed by the object_registry to * the client. The parameter params is not evaluated and can therfore reference any valid tlv_entry object. * The parameter out_stream is used to talk to the client. * * In case of success ERR_OK is returned. */ virtual unsigned int list_objects_processor(tlv_entry& params, tlv_stream *out_stream); /*! \brief This method returns the names of all service_providers currently known to the object_registry to * the client. The parameter params is not evaluated and can therfore reference any valid tlv_entry object. * The parameter out_stream is used to talk to the client. * * In case of success ERR_OK is returned. */ virtual unsigned int list_providers_processor(tlv_entry& params, tlv_stream *out_stream); /*! \brief This method returns the names of all pseudo objects currently known to the object_registry to * the client. The parameter params is not evaluated and can therfore reference any valid tlv_entry object. * The parameter out_stream is used to talk to the client. * * In case of success ERR_OK is returned. */ virtual unsigned int list_pseudo_objects_processor(tlv_entry& params, tlv_stream *out_stream); /*! \brief This method returns the number of calls handled by the object registry managed by this registry_manager * object to the client. * * In case of success ERR_OK is returned. */ virtual unsigned int get_num_calls(tlv_entry& params, tlv_stream *out_stream); /*! \brief Destructor. */ virtual ~registry_manager() { ; } protected: /*! \brief Holds a pointer to the object_registry which is serviced by this registry_manager instance. */ object_registry *registry; /*! \brief Holds a map which maps the name of the method the user wants to call to a pointer to the * member function which implements that method. */ map<string, manager_fun> method_pointers; }; class rmsk_pseudo_object; /*! \brief typedef for a pointer to a member function of class rotor_machine_proxy which is suitable as a tlv_callback. */ typedef unsigned int (rmsk_pseudo_object::*rmsk_pseudo_object_fun)(tlv_entry& params, tlv_stream *out_stream); /*! \brief A TLV class that implements static methods which can be called through the "rmsk2" pseudo object. */ class rmsk_pseudo_object : public pseudo_object { public: /*! \brief Constructor. */ rmsk_pseudo_object(); /*! \brief This method is used to determine the callback that is capable of handling a call of the static method given in parameter * method. * * NULL is returned in case of an error. */ virtual tlv_callback *get_handler(string& method); /*! \brief This method returns default state data for a spcified machine to the caller. The parameter params represents * a string that has to contain the name of the machine for which the default state is to be returned. * The parameter out_stream is used to talk to the client. * * In case of success ERR_OK is returned. */ virtual unsigned int get_default_state_processor(tlv_entry& params, tlv_stream *out_stream); /*! \brief This method creates state data for a requested machine type an configuration and returns it to the client. The parameter * params has to be a vector of length three. The first element has to be a string that specifies the machine name, the second * has to be a string to string dirctionary that specifies a suitable machine configuration and the third has to specify a * rotor position in the form of a string. If you do not want change the rotor position an empty string has to be provided as * the rotor position. The parameter out_stream is used to talk to the client. * * In case of success ERR_OK is returned. */ virtual unsigned int get_state_processor(tlv_entry& params, tlv_stream *out_stream); /*! \brief This method transforms an UKW D plug specification in Bletchley Park format to the format used by the German Air Force in WWII. * * In case of success ERR_OK is returned. */ virtual unsigned int ukwd_bp_to_gaf_processor(tlv_entry& params, tlv_stream *out_stream); /*! \brief This method transforms an UKW D plug specification in German Air Force format to the format used by Bletchley Park in WWII. * * In case of success ERR_OK is returned. */ virtual unsigned int ukwd_gaf_to_bp_processor(tlv_entry& params, tlv_stream *out_stream); /*! \brief Destructor. */ virtual ~rmsk_pseudo_object() { ; } protected: /*! \brief Maps each allowed method name to a pointer of type rmsk_pseudo_object_fun, where that pointer points to a method of * rmsk_pseudo_object that knows how to perform the requested method call. */ unordered_map<string, rmsk_pseudo_object_fun> rmsk_pseudo_object_proc; }; /*! \brief A TLV class that manages all TLV objects known to a TLV server. It delegates the creation of new objects and * the construction of tlv_callback objects to the appropriate service_provider instance. */ class object_registry { public: /*! \brief Constructor. */ object_registry(); /*! \brief This is the main method of an object_registry instance. It is called by the processor callback of the tlv_server. * It is used to determine a callback that is capable to handle a call of the method (given in parameter * method) on the object specified by the handle object_name. * * NULL is returned in case of an error. The caller is responsible for deleting objects returned by this method. This * method knows about the pseudo objects "root" and "new". Calls to the "root" object are delegated to object_registry::manager. * Calls to the "new" object are forwarded to the service provider responsible for creating new objects of the type requested * in the parameter method. */ virtual tlv_callback *get_processor(string& object_name, string& method); /*! \brief This method can be used to register a newly created object with the object registry. The parameter name has * to specify the handle of the newly created object. The parameter new_object specifies a pointer to the new * object and a pointer to the service provider which can be used to manage it. */ virtual void add_object(string& name, pair<void *, service_provider *>& new_object); /*! \brief This method deletes the object with the handle object_name and removes the handle from the object registry. */ virtual void delete_object(string& object_name); /*! \brief This method deletes all objects currently knwon to this object_regsitry instance. */ virtual void clear(); /*! \brief This method adds a new pseudo object to this object_regsitry instance. */ virtual void add_pseudo_object(pseudo_object *pseudo_obj); /*! \brief This method returns a reference to all the pseudo objects known by this object_registry instance. */ virtual map<string, pseudo_object *>& get_pseudo_objects() { return pseudo_objects; } /*! \brief This method deletes an existing pseudo object from this object_regsitry instance. */ virtual void delete_pseudo_object(string& pseudo_name); /*! \brief Returns a reference to the internal data structure which maps each of the object handles currently known to this * object_regsitry instance to a std::pair containing a pointer to the actual object and a pointer to the associated * service_provider instance. */ virtual map<string, pair<void *, service_provider *> >& get_objects() { return objects; } /*! \brief Returns a reference to the internal data structure which maps the name of each service_provider known to this * object registry instance to a pointer to the appropriate service_provider object. */ virtual map<string, service_provider *>& get_providers() { return func_factory; } /*! \brief Adds the service_provider object referenced through parameter provider under the name given in parameter class_name to * the object registry. * * Important: The object_registry instance takes ownership of the object referenced through the parameter provider and deletes * it when this becomes necessary. */ virtual void add_service_provider(service_provider *provider); /*! \brief Returns the number of calls recorded by this object registry. */ unsigned long int get_num_calls() { return num_calls; } /*! \brief Records call for statistic purposes. */ void record_call() { num_calls++; } /*! \brief This method deletes the service_provider with name class_name from the object regsitry. It also deletes all objects * that are managed by the service_provider which is to be deleted. */ virtual void delete_service_provider(string& class_name); /*! \brief Destructor. Deletes all objects and service providers. */ virtual ~object_registry(); protected: /*! Maps object handles to a std::pair containing a pointer to the actual object and the associated service_provider. */ map<string, pair<void *, service_provider *> > objects; /*! Maps service provider names to the actual service_provider objects. */ map<string, service_provider *> func_factory; /*! Holds the registry manager associated with this object_regsitry instance. */ registry_manager manager; /*! Maps pseudo object names to pseudo objects. */ map<string, pseudo_object *> pseudo_objects; /*! Holds the number of calls recorded by this object registry. */ unsigned long int num_calls; }; #endif /* __object_registry__ */
true
3f81329f64257e55a795ff2287130ea48e2127f5
C++
log-m/post-office-thread-sim
/LinkedList.h
UTF-8
390
2.921875
3
[]
no_license
#ifndef LINKEDLIST_H #define LINKEDLIST_H #include <iostream> using namespace std; struct node { int val; //Customer number, worker number, or job node * next; }; class LinkedList { public: LinkedList(); virtual ~LinkedList(); bool enqueue(int item); int dequeue(); protected: private: node * head; }; #endif // LINKEDLIST_H
true
e6ec005f9ba5e13a8b9e30c5319743cddaaa8fb2
C++
de-passage/parsers.cpp
/include/parsers/description/construct.hpp
UTF-8
1,824
2.703125
3
[ "MIT" ]
permissive
#ifndef GUARD_PARSERS_DESCRIPTION_CONSTRUCT_HPP #define GUARD_PARSERS_DESCRIPTION_CONSTRUCT_HPP #include "./modifiers.hpp" #include "./sequence.hpp" #include "../interpreters/make_parser.hpp" #include "../interpreters/object_parser.hpp" namespace parsers::description { template <class T, class... Ps> struct construct : modifier<sequence<Ps...>, interpreters::make_parser_t<interpreters::object_parser>> { using base = modifier<sequence<Ps...>, interpreters::make_parser_t<interpreters::object_parser>>; constexpr construct() noexcept = default; template <class... Us> constexpr explicit construct([[maybe_unused]] type_t<T>, Us&&... u) noexcept : base{sequence{std::forward<Us>(u)}...} {} template <class It> using result_t = T; template <class U, std::enable_if_t< dpsg::is_template_instance_v<std::decay_t<U>, std::tuple>, int> = 0> constexpr T operator()(U&& tpl) const noexcept { return instanciate( std::forward<U>(tpl), dpsg::feed_t<std::decay_t<U>, std::index_sequence_for>{}); } template <class U, std::enable_if_t< !dpsg::is_template_instance_v<std::decay_t<U>, std::tuple> && std::is_constructible_v<T, U>, int> = 0> constexpr T operator()(U&& tpl) const noexcept { return T{std::forward<U>(tpl)}; } private: template <class U, std::size_t... S> constexpr T instanciate(U&& tpl, [[maybe_unused]] std::index_sequence<S...>) const noexcept { return T{std::get<S>(std::forward<U>(tpl))...}; } }; template <class D, class T> construct(type_t<D>, T&&) -> construct<D, detail::remove_cvref_t<T>>; } // namespace parsers::description #endif // GUARD_PARSERS_DESCRIPTION_AS_STRING_VIEW_HPP
true
dae231c81761d377ecfb141bda6d1d3b17baa20a
C++
jhormanpa/Udea-informatica2
/Ejercicio16/main.cpp
UTF-8
988
3.484375
3
[]
no_license
#include <iostream> using namespace std; /* Este programa realiza el promedio de las veces que se ingresa un número hasta que se * ingresa el número cero y esta no entra en el promedio*/ int main(){ float numero, suma=0, cont=0, prom=0; /* declaramos las variables como float en caso que el promedio no sea entero*/ cout << "Ingrese un numero "; /* pedimos el número y le damos una variable... */ cin >> numero; /*... que la reciba */ while(numero !=0) /* usamos el ciclo while con la condición que sea diferente de cero e ingresar al ciclo*/ { suma= suma+numero; /* realizamos las operaciones para hallar el promedio*/ cont=cont+1; prom=suma/cont; cout<<"ingrese un numero "; /* volvemos a preguntar para continuar hasta que este sea cero*/ cin>>numero; } cout <<prom<<endl; /* mostramos el promedio de los numeros ingresados*/ }
true
723f0be01f64eb85c4be9ef9b097b170d89c079f
C++
KmMnJn/awewa
/algo_hw2_bfs.cpp
UTF-8
1,933
3.265625
3
[]
no_license
#include <iostream> #include <queue> using namespace std; int p[] = {20,30,35,12,3}; int w[] = {2, 5, 7, 3, 1}; int W = 13; int n = 4; int maxprofit = 0; int pcount; int ncount; struct node{ int level; int profit; int weight; }; void knapsack(); float bound(node u); int main(){ cout <<endl; cout << "0/1 knapsack problem - breath-first-search"<<endl;; cout << endl; for(int i = 0; i<n; i++){ cout << "(" << p[i] << ", " <<w[i] << "), "; } cout << "(" << p[n] << ", " <<w[n] << ") " << endl; cout << "W = " << W << endl << endl; knapsack(); cout << "nodes visited : " << pcount + ncount << endl; cout << "max profit : " <<maxprofit << endl <<endl; } void knapsack(){ queue <node> q; node u, v; v.level = -1; v.profit = 0; v.weight = 0; pcount++; q.push(v); while(!q.empty()){ v = q.front(); q.pop(); u.level = v.level + 1; u.profit = v.profit + p[u.level]; u.weight = v.weight + w[u.level]; if (u.weight <= W && u.profit > maxprofit) maxprofit = u.profit; if (bound(u) > maxprofit){ q.push(u); pcount++; }else ncount++; u.weight=v.weight; u.profit=v.profit; if(bound(u) > maxprofit){ q.push(u); pcount++; // 유망한 노드 } else ncount++; // 유망하지 않은 노드 } } float bound(node u){ int j, k, totweight; int result; if (u.weight >= W) return 0; else{ result = u.profit; j = u.level + 1; totweight = u.weight; while ((j <= n) && (totweight + w[j] <= W)){ totweight = totweight + w[j]; result = result + p[j]; j++; } k = j; if (k <= n) result = result + (W - totweight) * p[k]/w[k]; return result; } }
true
a24bd52e2d9d992aaad0584602cb207f0c3e15d0
C++
SnowDawn933/algorithm-learning-notes
/ACM/basic algorithm/merge+sort.cpp
UTF-8
1,693
3.96875
4
[]
no_license
//归并排序的实现方法:递归实现 在合并子列(merge函数)时使用了 two pointer 的思想 #include <cstdio> void merge(int a[], int l1, int r1, int l2, int r2); void mergesort(int a[], int left, int right); int main(void) { int a[110]; int n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } mergesort(a, 0, n - 1); for (int i = 0; i < n; i++) { printf("%d ", a[i]); } return 0; } void mergesort(int a[], int left, int right) { if (left < right) //只要left<right { int mid = (left + right) / 2; //取中点 mergesort(a, left, mid); //递归,将左右区间分别进行归并排序 mergesort(a, mid + 1, right); merge(a, left, mid, mid + 1, right); //将左右区间合并 } } void merge(int a[], int l1, int r1, int l2, int r2) // 使用了 two pointer 的思想,将两个有序的数列合并到一个数列中 { int i = l1, j = l2; //i指向左边序列的开始,j指向右边序列的开始 int temp[110], index = 0; //将两个序列的数先暂时存入temp中 while (i <= r1 && j <= r2) //将两个数列中的每一个元素进行比较,比较小的就放入temp,对应序列向后指一位 { if (a[i] < a[j]) { temp[index++] = a[i++]; } else { temp[index++] = a[j++]; } } while (i <= r1) //最后将剩余的存入temp temp[index++] = a[i++]; while (j <= r2) temp[index++] = a[j++]; for (int i = 0; i < index; i++) //将合并后的序列赋值回数组a { a[l1 + i] = temp[i]; } }
true
3ff685c0166f4103917aa5ea05ca9f08a2f9bf4e
C++
Iqra350/krock2_traversability
/core/simulation/env/webots/krock/krock2_ros/controllers/Tem_controller/source/controller_misc.cpp
UTF-8
2,229
2.609375
3
[]
no_license
#include "controller.hpp" using namespace std; using namespace Eigen; MatrixXd Controller :: transformation_Ikin_Webots(MatrixXd joint_angles_in, int direction, int shifts) { shifts=shifts==0?0:1; if(direction<0){ //WEBOTS 2 ROBOT for(int i=0;i<NUM_MOTORS;i++){ joint_angles_in(i)=(joint_angles_in(i)-angShiftsCorrIkin2Webots[i]*shifts*my_pi/180.)*angSignsCorrIkin2Webots[i]; } } else if(direction>0){ //ROBOT 2 WEBOTS for(int i=0;i<NUM_MOTORS;i++){ joint_angles_in(i)=joint_angles_in(i)*angSignsCorrIkin2Webots[i] + angShiftsCorrIkin2Webots[i]*shifts*my_pi/180.; } } return joint_angles_in; } MatrixXd Controller :: transformation_Ikin_Robot(MatrixXd joint_angles_in, int direction, int shifts) { shifts=shifts==0?0:1; if(direction<0){ //ROBOT 2 IKIN for(int i=0;i<NUM_MOTORS;i++){ joint_angles_in(i)=(joint_angles_in(i)-angShiftsCorrIkin2Robot[i]*shifts*my_pi/180.)*angSignsCorrIkin2Robot[i]; } } else if(direction>0){ //IKIN 2 ROBOT for(int i=0;i<NUM_MOTORS;i++){ joint_angles_in(i)=joint_angles_in(i)*angSignsCorrIkin2Robot[i] + angShiftsCorrIkin2Robot[i]*shifts*my_pi/180.; } } return joint_angles_in; } MatrixXd Controller :: flipKinematics(MatrixXd joint_angles_in) { MatrixXd flipped_angles=joint_angles_in; // flip left-right flipped_angles.block<4,1>(0,0)=joint_angles_in.block<4,1>(4,0); flipped_angles.block<4,1>(4,0)=joint_angles_in.block<4,1>(0,0); flipped_angles.block<4,1>(8,0)=joint_angles_in.block<4,1>(12,0); flipped_angles.block<4,1>(12,0)=joint_angles_in.block<4,1>(8,0); // correct axes for(int i=0; i<4; i++){ // pitch //flipped_angles(i*4,0)*=-1; // yaw flipped_angles(i*4+1,0)*=-1; // roll flipped_angles(i*4+2,0)*=-1; // knee flipped_angles(i*4+3,0)*=-1; } // flip spine flipped_angles.block(16,0,NUM_MOTORS-16,1)*=-1; // flip roll /* flipped_angles(2,0)*=-1; flipped_angles(2,1)*=-1; flipped_angles(2,2)*=-1; flipped_angles(2,3)*=-1;*/ return flipped_angles; }
true
d940d7b71117b0cd2aa4d7c5e5a61d7d1e239282
C++
CarlosDeg/EjerciciosC
/c+++++/num imparesfor.cpp
UTF-8
606
3.046875
3
[]
no_license
//capturar numero impar y sumar numero par FOR #include <iostream> #include <stdio.h> using namespace std; int main () { /*int resultado,cantidad; int y, Suma=0,Num; cout<<"Capturar Total de cantidad "; cin>>resultado; for(y=1;y<=resultado;y++) { cout<<"Captrurar cantidad "; cout<<y; cout<<"\n"; cin>>cantidad; Num=cantidad%2; if(Num==0) { Suma=Suma+cantidad; } else{ cout<<"cantidad Impar "; cout<<cantidad; } }*/ int n=1+1; int c=1; while(c<n){ cout<<c<<"kgk"; } cout<<"La Suma de la cantidad Par es "; cout<<n; return 0; }
true
6a08cb00e3066cdcf3c529ce3ba2d18f3555f59f
C++
hackerlank/XEffect2D
/engine/XEffeEngine/XControl/XCalendar.h
GB18030
4,496
2.609375
3
[]
no_license
#ifndef _JIA_XCALENDAR_ #define _JIA_XCALENDAR_ //++++++++++++++++++++++++++++++++ //Author: ʤ(JiaShengHua) //Version: 1.0.0 //Date: 2014.6.30 //-------------------------------- #include "XButton.h" #include "XTimer.h" #include "../XXml.h" namespace XE{ //һѡ //עĿǰĴ׸ҪŻ //Ŀǰռûƶ class XCalendar:public XControlBasic { private: XBool m_isInited; bool m_haveChoose; bool m_needShowToday; //ǷҪʾ bool m_needShowChoose; //ǷҪʾѡ XVector2 m_todayPos; //λ XVector2 m_choosePos; //ѡڵλ XRect m_rect; //Χ XSystemTime m_todayDate; //ڵ XSystemTime m_curSetDate; //ǰõʱ XSystemTime m_curShowData; //ǰʾʼʱ XButton m_yearAddBtn; //ӵbutton XButton m_yearDecBtn; XFontUnicode m_yearTxt; XButton m_monthAddBtn; //ӵbutton XButton m_monthDecBtn; XFontUnicode m_monthTxt; //XFontUnicode m_titleTxt; XFontUnicode m_titleFont[7]; XFontUnicode m_dateFont[42]; static void ctrlProc(void*,int,int); public: XBool initWithoutSkin(const XFontUnicode &font); XBool initWithoutSkin(){return initWithoutSkin(getDefaultFont());} using XObjectBasic::setPosition; //⸲ǵ void setPosition(float x,float y); using XObjectBasic::setScale; //⸲ǵ void setScale(float x,float y); using XObjectBasic::setColor; //⸲ǵ void setColor(float r,float g,float b,float a); void setAlpha(float a); //һЩýӿ XSystemTime getTodayDate() const {return m_todayDate;} void setTodayDate(const XSystemTime &t) {m_todayDate = t;} bool getHaveChoose() const{return m_haveChoose;} XSystemTime getCurChooseDate() const {return m_curSetDate;} void setCurChooseDate(const XSystemTime &t) {m_curSetDate = t;} XSystemTime getCurShowDate() const {return m_curShowData;} void setCurShowDate(const XSystemTime &t) {m_curShowData = t;} protected: void updateCurDate(); void draw(); //水ť void drawUp(); void update(float stepTime); XBool mouseProc(float x,float y,XMouseState mouseState); //궯Ӧ XBool keyboardProc(int,XKeyState){return XFalse;} //Ƿ񴥷 void insertChar(const char *,int){;} XBool canGetFocus(float x,float y); //жϵǰǷԻý XBool canLostFocus(float,float){return XTrue;} //Ӧǿʱʧȥ void setLostFocus(); //ʧȥ public: XCalendar() :m_isInited(XFalse) ,m_haveChoose(false) ,m_needShowToday(false) ,m_needShowChoose(false) { m_ctrlType = CTRL_OBJ_CALENDAR; } ~XCalendar(){release();} void release(); //Ϊ֧ؼṩӿڵ֧ XBool isInRect(float x,float y); //xyǷϣxyĻľ XVector2 getBox(int order); //ȡĸ꣬ĿǰȲת ////virtual void justForTest() {;} private://Ϊ˷ֹظֵƹ캯 XCalendar(const XButton &temp); XCalendar& operator = (const XButton& temp); //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //ʵֽؼ״̬ı() public: virtual XBool saveState(TiXmlNode &e) { if(!m_needSaveAndLoad) return XTrue; //Ҫֱӷ XSystemTime tmp = getCurChooseDate(); if(!XXml::addLeafNode(e,(m_ctrlName + "Year").c_str(),XString::toString(tmp.year))) return XFalse; if(!XXml::addLeafNode(e,(m_ctrlName + "Month").c_str(),XString::toString(tmp.month))) return XFalse; if(!XXml::addLeafNode(e,(m_ctrlName + "Day").c_str(),XString::toString(tmp.day))) return XFalse; return XTrue; } virtual XBool loadState(TiXmlNode *e) { if(!m_needSaveAndLoad) return XTrue; //Ҫֱӷ XSystemTime tmp; if(XXml::getXmlAsInt(e,(m_ctrlName + "Year").c_str(),tmp.year) == NULL) return XFalse; if(XXml::getXmlAsInt(e,(m_ctrlName + "Month").c_str(),tmp.month) == NULL) return XFalse; if(XXml::getXmlAsInt(e,(m_ctrlName + "Day").c_str(),tmp.day) == NULL) return XFalse; setCurChooseDate(tmp); return XTrue; } //--------------------------------------------------------- }; #if WITH_INLINE_FILE #include "XCalendar.inl" #endif } #endif
true
ee0f6503949ff25cf8a47138d6ffd60c40206ae0
C++
Freddie-Cooke/Random
/storage.cpp
UTF-8
203
2.96875
3
[]
no_license
// storage.cpp // learning about different storage types #include <iostream> using namespace std; int main() { register int x = 2147483647; auto y = 1; cout << x << endl; cout << y; return 0; }
true
0493d94c16f8ff047b4a17fefbe14ea68b65fe72
C++
shidenggui/cplusplusprimer-answer
/5.21.cpp
UTF-8
380
2.90625
3
[]
no_license
#include <iostream> using namespace std; int main(){ string s1; string s2; unsigned cnt = 1; cin>>s1; while(cin>>s2){ if(s1 == s2){ if(isupper(s1[0])){ ++cnt; cout<<s1; break; } }else{ if(1 < cnt){ cout<<"string: "<<s1<<" count: "<<cnt<<endl; cnt = 1; } s1 = s2; } } if(1 == cnt){ cout<<"no!!!"; } cout<<"end!!!"; return 0; }
true
1a2b3b31b89d28898768bf8011a2c082df83a6cd
C++
sachinsinha26/arduino-based-smartphone-controlled-vehicle
/arduino_code_for_smartphone_controlled_vehicle.ino
UTF-8
4,784
3.109375
3
[]
no_license
/* * Arduino based Smartphone controlled vehicle using Bluetooth Module HC-06, Arduino Board, L293D motor controller integrated circuit Written by: Sachin Kumar Sinha, Indian Institute of Information Technology Senapati, Manipur Date: 29th November 2017 • The Bluetooth module (HC-06) is having four pins (+5V, GND, Rx, Tx) which connected to the Arduino board at (+5V, GND, Rx, Tx) respectively. • In the Arduino board the pin (12, 11, 10, 9) are the output pins which are connected to the motor driver circuits input pins (2, 7, 10, 15). The Arduino board works in 5v voltage supply. • In the motor driver circuits the input pins are (2, 7, 10, 15) and the output pins are (3,6,11,14) which is connected to the two DC geared motor through a 100 microfarad capacitor on each side. • The pins(1,9) are the enable pins which is connected to the pin (16) Vcc 5V . • The pin (16) is getting 5V constant voltage supply through voltage regulator (IC7805). • The pin (8) Vss is getting 14v voltage supply to drive the motor. • The pins (4,5,12,13) are the GND pins .  The working principle of this robot is that there is a Bluetooth module which is having four pins (+5V, GND, Rx, Tx) which connected to the Arduino board at (+5V, GND, Rx, Tx) respectively .  The Bluetooth module at first connects with the android phone. When the phone gives a command, the RX (Receiver) of the Bluetooth module receives the command and transmit it to the Arduino board at the TX (transceiver) pin.  The motor driver circuit is connected to the Arduino board with four inputs and the output from the motor driver circuit is connected to the two motors.  The Received command from the Bluetooth module is processed by the Arduino board according to the code uploaded in the Arduino board  which then sends accordingly the output command to the motor driver circuit input pins (2, 7, 10, 15) and then accordingly the output pins (3,6,11,14) of the motor driver circuit connected to the motors rotates the motor in clockwise or anticlockwise direction. */ /*Initializing the recieved data from user via HC-06 Arduino compatible bluetooth module*/ char data = 0; //Variable for storing received data /*Setting pinmodes and baud rate*/ void setup() { Serial.begin(9600); //Sets the data rate in bits per second (baud) for serial data transmission pinMode(13, OUTPUT); pinMode(12, OUTPUT); pinMode(11, OUTPUT); pinMode(10, OUTPUT); pinMode(9, OUTPUT); pinMode(2,OUTPUT); pinMode(3,OUTPUT); } /*Defining funciton for making both the LEDs connected with pin 13 and 12 to glow on command from user's mobile application*/ void ledon() { digitalWrite(13,HIGH); digitalWrite(2,HIGH); digitalWrite(3,LOW); } /*Defining funciton for making both the LEDs connected with pin 13 and 12 to off on command from user's mobile application*/ void ledoff() { digitalWrite(13,LOW); digitalWrite(2,LOW); digitalWrite(3,LOW); } /*Function setting motors to move forward*/ void forward(){ digitalWrite(12, HIGH); digitalWrite(11,LOW); digitalWrite(10, LOW); digitalWrite(9, HIGH); delay(10); } /*Function setting motors to move reverse*/ void reverse(){ digitalWrite(12, LOW); digitalWrite(11, HIGH); digitalWrite(10, HIGH); digitalWrite(9, LOW); delay(10); } /*Function setting motors to turn left with left wheels moving reverse and right wheel moving forward*/ void left(){ digitalWrite(12, LOW); digitalWrite(11, HIGH); digitalWrite(10, LOW); digitalWrite(9, HIGH); delay(10); } /*Function setting motors to turn right with right wheels moving reverse and left wheel moving forward*/ void right(){ digitalWrite(12, HIGH); digitalWrite(11, LOW); digitalWrite(10, HIGH); digitalWrite(9, LOW); delay(10); } /*Function defining all pins to set low to stop the vehicle*/ void stopp(){ digitalWrite(12, LOW); digitalWrite(11, LOW); digitalWrite(10, LOW); digitalWrite(9, LOW); delay(10); } void loop() { if(Serial.available() > 0) // Send data only when you receive data: { /*Getting data given by user through application on Serial Monitor*/ data = Serial.read(); Serial.print(data); Serial.print("\n"); /*Decision making statements to excute instructions provided by user.*/ if(data=='a') forward(); if(data=='e') reverse(); if(data=='b') left(); if(data=='d') right(); if(data=='c') stopp(); if(data=='f') ledon(); if(data=='g') ledoff(); } }
true
b66990538c7bbbd06bd4197124899fe687a793f7
C++
ha-yujin/algorithm
/baekjoon/C++/q2751.cpp
UHC
1,278
4.0625
4
[]
no_license
// ϱ 2 /* պ ؼ */ #include <iostream> // 迭 ij ϴ Լ void merge(int *arr, int *arr2, int left, int right) { int low = left; int mid = (left + right) / 2; int high = mid + 1; int x = left; while (low <= mid && high <= right) { if (arr[low] <= arr[high]) { arr2[x] = arr[low]; low++; } else { arr2[x] = arr[high]; high++; } x++; } if (low > mid) { for (int i = high; i <= right; i++) { arr2[x++] = arr[i]; } } else { for (int i = low; i <= mid; i++) { arr2[x++] = arr[i]; } } for (int i = left; i <= right; i++) { arr[i] = arr2[i]; } } // 迭 2 迭 , 2迭 ģ void mergeSort(int *arr, int *arr2, int left, int right) { if (left < right) { int mid = (left + right) / 2; mergeSort(arr, arr2, left, mid); mergeSort(arr, arr2, mid + 1, right); merge(arr, arr2, left, right); } } int main() { int N; scanf_s("%d", &N); int *data = new int[N]; int *sorted = new int[N]; for (int i = 0; i < N; i++) scanf_s("%d", &data[i]); mergeSort(data, sorted, 0, N - 1); for (int i = 0; i < N; i++) printf("%d\n", data[i]); return 0; }
true
9236b2eab3c1b8b375b02867f562794098aafb58
C++
kakanikatija/amx
/Arduino/amx/gps.ino
UTF-8
6,165
2.53125
3
[]
no_license
#define maxChar 256 char gpsStream[maxChar]; int streamPos; void gps(byte incomingByte){ char temp2[2]; char temp3[3]; char temp5[5]; char temp7[7]; char temp12[12]; // check for start of new message // if a $, start it at Pos 0, and continue until next G if(incomingByte=='$') { // Serial.print("String position:"); // Serial.println(streamPos); // Serial.println(gpsStream); //process last message if(streamPos > 10){ // $GNGGA,003549.000,2716.6206,N,08227.4920,W,2,12,0.93,33.0,M,-28.8,M,,*7E // for some reason using strcmp misses some codes; so we will just do 1 char at a time // memcpy(&temp5[0], &gpsStream[1], 5); // char testStr[5]; // strcpy(testStr, "GNGGA"); //if(strcmp(temp5, testStr) == 0){ /* if(gpsStream[1]=='G' & gpsStream[2]=='N' & gpsStream[3]=='G' & gpsStream[4]=='G' & gpsStream[5]=='A'){ // Serial.println("got one"); // check response status int curPos = 7; memcpy(&temp2[0], &gpsStream[curPos], 2); sscanf(temp2, "%d", &gpsHour); curPos += 2; memcpy(&temp2[0], &gpsStream[curPos], 2); sscanf(temp2, "%d", &gpsMinute); curPos += 2; memcpy(&temp2[0], &gpsStream[curPos], 2); sscanf(temp2, "%d", &gpsSecond); gpsTime.sec = gpsSecond; gpsTime.minute = gpsMinute; gpsTime.hour = gpsHour; curPos = 18; memcpy(&temp2[0], &gpsStream[curPos], 2); curPos += 2; int latDeg; float latMin; float tempVal; sscanf(temp2, "%d", &latDeg); memcpy(&temp7[0], &gpsStream[curPos], 7); sscanf(temp7, "%f", &latMin); tempVal = (double) latDeg + (latMin / 60.0); if (tempVal>0.0 & tempVal<=90.0){ latitude = tempVal; curPos = 28; memcpy(&latHem, &gpsStream[curPos], 1); } curPos = 30; memcpy(&temp3[0], &gpsStream[curPos], 3); curPos += 3; int lonDeg; float lonMin; sscanf(temp3, "%d", &lonDeg); memcpy(&temp7[0], &gpsStream[curPos], 7); sscanf(temp7, "%f", &lonMin); tempVal = (double) lonDeg + (lonMin / 60.0); if (tempVal>0.0 & tempVal<=180.0){ longitude = tempVal; curPos = 41; memcpy(&lonHem, &gpsStream[curPos], 1); } } */ // OriginGPS // $GNRMC,134211.000,A,2715.5428,N,08228.7924,W,1.91,167.64,020816,,,A*62 // Adafruit GPS // $GPRMC,222250.000,A,2716.6201,N,08227.4996,W,1.01,301.49,250117,,,A*7C char rmcCode[6 + 1]; float rmcTime; // 225446 Time of fix 22:54:46 UTC char rmcValid[2]; // A Navigation receiver warning A = OK, V = warning float rmcLat; // 4916.45,N Latitude 49 deg. 16.45 min North char rmcLatHem[2]; float rmcLon; // 12311.12,W Longitude 123 deg. 11.12 min West char rmcLonHem[2]; float rmcSpeed; // 000.5 Speed over ground, Knots float rmcCourse;// 054.7 Course Made Good, True char rmcDate[6 + 1];// 191194 Date of fix 19 November 1994 float rmcMag;// 020.3,E Magnetic variation 20.3 deg East char rmcMagHem[2]; char rmcChecksum[4 + 1]; // *68 mandatory checksum if(gpsStream[1]=='G' & gpsStream[2]=='P' & gpsStream[3]=='R' & gpsStream[4]=='M' & gpsStream[5]=='C'){ char temp[streamPos + 1]; //char temp[100]; const char s[2] = ","; char *token; gpsTimeout += 1; memcpy(&temp, &gpsStream, streamPos); //Serial.println(temp);s //testing with a known string 72 chars //strcpy(temp, "$GNRMC,134211.000,A,2715.5428,N,08228.7924,W,1.91,167.64,020816,43,W,A*62"); //Serial.println(temp); token = strtok(temp, s); sprintf(rmcCode, "%s", token); //Serial.println(rmcCode); token = strtok(NULL, s); sscanf(token, "%f", &rmcTime); sscanf(token, "%2d%2d%2d", &gpsHour, &gpsMinute, &gpsSecond); //Serial.println(rmcTime); token = strtok(NULL, s); sprintf(rmcValid, "%s", token); //Serial.println(rmcValid); token = strtok(NULL, s); sscanf(token, "%f", &rmcLat); //Serial.println(rmcLat, 6); token = strtok(NULL, s); sprintf(rmcLatHem, "%s", token); //Serial.println(rmcLatHem); token = strtok(NULL, s); sscanf(token, "%f", &rmcLon); //Serial.println(rmcLon, 6); token = strtok(NULL, s); sprintf(rmcLonHem, "%s", token); //Serial.println(rmcLonHem); token = strtok(NULL, s); sscanf(token, "%f", &rmcSpeed); //Serial.println(rmcSpeed); token = strtok(NULL, s); sscanf(token, "%f", &rmcCourse); //Serial.println(rmcCourse); token = strtok(NULL, s); sprintf(rmcDate, "%s", token); sscanf(token, "%2d%2d%2d", &gpsDay, &gpsMonth, &gpsYear); //gpsYear += 2000; // Serial.println(rmcDate); // Serial.print("Day-Month-Year:"); // Serial.print(gpsDay); Serial.print("-"); // Serial.print(gpsMonth); Serial.print("-"); // Serial.println(gpsYear); token = strtok(NULL, s); sscanf(token, "%f", &rmcMag); //Serial.println(rmcMag); token = strtok(NULL, s); sprintf(rmcMagHem, "%s", token); //Serial.println(rmcMagHem); token = strtok(NULL, s); sprintf(rmcChecksum, "%s", token); //Serial.println(rmcChecksum); if(rmcValid[0]=='A'){ latitude = rmcLat; longitude = rmcLon; latHem = rmcLatHem[0]; lonHem = rmcLonHem[0]; goodGPS = 1; } } } // start new message here streamPos = 0; } gpsStream[streamPos] = incomingByte; streamPos++; if(streamPos >= maxChar) streamPos = 0; }
true
56f14f1431356118e8e101f9988ba7ae5817cfff
C++
BiEchi/Algorithms
/CommonDS/LinkedList(DList)/dlist.h
UTF-8
3,102
2.671875
3
[]
no_license
/* tab:8 * * dlist.cpp - source file for CS225 Linked List. * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without written agreement is * hereby granted, provided that the above copyright notice and the following * two paragraphs appear in all copies of this software. * * IN NO EVENT SHALL THE AUTHOR OR THE UNIVERSITY OF ILLINOIS BE LIABLE TO * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, * EVEN IF THE AUTHOR AND/OR THE UNIVERSITY OF ILLINOIS HAS BEEN ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * THE AUTHOR AND THE UNIVERSITY OF ILLINOIS SPECIFICALLY DISCLAIM ANY * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND NEITHER THE AUTHOR NOR * THE UNIVERSITY OF ILLINOIS HAS ANY OBLIGATION TO PROVIDE MAINTENANCE, * SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." * * Author: Klaus-Dieter Schewe * Version: 2 * Creation Date: ? * Filename: main.cpp * History: * Klaus-Dieter Schewe 1 16 January 2021 * First written. * Hao BAI 2 19 January 2021 * Annotations added. * */ #ifndef dlist_h #define dlist_h template<class T> class DList; template<class T> class node { // private: friend class DList<T>; public: node(T item = 0, node<T> *pt_n = 0, node<T> *pt_p = 0); // virtual ~node(void); T getdata(void); node<T> *getnext(void); node<T> *getprevious(void); void setdata(T item); void setnext(node<T> *pt); void setprevious(node<T> *pt); private: // these are the member data inside the class node. T dataitem; node<T> *pt_next; node<T> *pt_previous; }; template<class T> class DList { public: DList(void); // virtual ~DList(); T operator[](int index); int getlength(void); void setitem(int index, T value); T getitem(int index); void append(T value); void insert(int index, T value); void remove(int index); void concat(DList<T> *dlist); bool member(T value); bool equal(DList<T> *dlist); bool sublist(DList<T> *dlist); private: // notice. DList can get access to class node to use this class type. // this is because DList is a FRIEND of class node. // refer C++ primer plus, friend class. (Chapter 15.1) // you need to design a class TV and a class remote. is it better to define their // relationships to be is-a, has-a, or connected-with? of course it's the last one. // thus, it's better to define this relationship using a friend class. // notice. a friend class (DList) can access to the origin class (node), even the private // members in the DList can be accessed as well. node<T> *dummy; int numitems; node<T> *locate(int index); node<T> *first(void); node<T> *last(void); }; #endif /* dlist_h */
true
2091ce530c98cce025070a044159db990c981215
C++
wingyiu/ndelvor
/DelaunayVoronoi/DataParser.cpp
UTF-8
1,002
2.6875
3
[ "BSD-3-Clause" ]
permissive
#include "DataParser.h" bool DataParser::hasNext() { if(feof(m_file) == 0) { return true; } else { return false; } } Point* DataParser::getNext() { double *coord = new double[m_dimension]; for(int i=0; i<m_dimension; i++) { fscanf(m_file, "%lf", coord+i); fscanf(m_file, "%*[ ,\n]"); } Point* p = new Point(m_dimension, coord); return p; } unsigned DataParser::getDimension() { return m_dimension; } bool DataParser::isFileValid() { return false; } DataParser::~DataParser() { if(m_file != NULL) { fclose(m_file); } } DataParser::DataParser(const char *filename):m_file(NULL), m_filename(filename), m_dimension(0) { m_file = fopen(m_filename, "r"); fscanf(m_file, " @dimension:%d", &m_dimension); } DataParser::DataParser(FILE *file):m_file(file), m_filename(NULL), m_dimension(0) { } DataParser::DataParser():m_file(NULL), m_filename(NULL), m_dimension(0) { }
true
2579ee6b597e4d7518a18fcabe1107cc99fea237
C++
HJPyo/C
/boj19845.cpp
UTF-8
519
2.796875
3
[]
no_license
#include<iostream> using namespace std; int n, m, ar[2555555] = {}; int f(int x, int y) { if(ar[x] < y) return 0; int L = 1, R = n, Ans; while(L <= R){ int M = (L+R)/2; if(L >= R){ Ans = (ar[M] < y) ? L-1 : L; break; } if(ar[M] >= y) L = M+1; else R = M; } return Ans-x + ar[x]-y+1; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> m; for(int i = 1; i <= n; i++) cin >> ar[i]; while(m--){ int X, Y; cin >> X >> Y; cout << f(X,Y) << '\n'; } }
true
d78ccd7414582813c2500a07120466a0b2464a61
C++
SRAM/RacerMateDLL
/glib/mru.h
UTF-8
2,163
2.8125
3
[ "MIT" ]
permissive
#ifndef _MRU_H_ #define _MRU_H_ #ifdef WIN32 #pragma warning(disable:4101 4786) // "str" unreferenced #include <windows.h> #else #include <string.h> #endif #include <assert.h> #ifdef USE_LIST #error "USE_LIST is already defined" #endif #define USE_LIST #ifdef USE_LIST #include <list> #include <algorithm> #include <ini.h> #else #include <vector> #endif #include <string> /********************************************************************* stack: LIFO FIFO (=queue) 0 item0 1 item1 .... n itemn items added by increasing index 0 1 ... N *********************************************************************/ class MRU { private: MRU(const MRU&); MRU &operator = (const MRU&); // unimplemented #ifdef USE_LIST std::list<std::string> data; std::list<std::string>::iterator p; int maxsize; // starts off as -1 #else std::vector<std::string> data; #endif int bp; public: MRU(void); virtual ~MRU(); inline void push_back(const char *_str) { data.push_back(_str); return; } inline void push_front(const char *_str) { data.push_front(_str); return; } inline int size(void) { return (int)data.size(); } inline const char *getItem(int i) { #ifdef USE_LIST p = data.begin(); for(int j=0; j<i; j++) { p++; } //p = p + i; return (*p).c_str(); #else return data[i].c_str(); #endif } void setItem(int i, const char *_str); inline int getIndex(const char *_str) { //p = std::find(data.begin(), data.end(), _str); int i = 0; for(p = data.begin(); p!=data.end(); p++) { if (strcmp((*p).c_str(),_str)==0) { return i; } i++; } return -1; // not found } void move(int from, int to); // moves the item in the 'from' position to the 'to' position void dump(void); void ini_write(Ini *ini, char *section); void clear_data(void); int ini_read(Ini *ini, char *_section); void sync(const char *_str); }; #endif // #ifndef _MRU_H_
true
8a11ab7614a7fb0f35966a4dd3057daec6e8502e
C++
Shani-Rabi/Server-and-client---online-movie-rental-service
/Client/src/task.cpp
UTF-8
801
2.640625
3
[]
no_license
// // Created by shani on 1/9/18. // #include <stdlib.h> #include "../include/ConnectionHandler.h" #include "../include/task.h" task::task(ConnectionHandler & connectionHandler):_connectionHandler(connectionHandler){ } // this task will be taken by the second thread. //his job is to read from the user and forward the message to the server. //he will stop when the flag should terminate is true. // the first thread will change the flag to true . void task::run() { while (!_connectionHandler.shouldTerminate() && (!std::cin.eof()) ) { const short bufsize = 1024; char buf[bufsize]; std::cin.getline(buf, bufsize); std::string line(buf); if(!_connectionHandler.shouldTerminate() && !_connectionHandler.sendLine(line)) break; } }
true
8da046331c149650e73b3b3eb3bea541759bc832
C++
naordahan/Task-7
/TicTacToe.cpp
UTF-8
6,845
2.65625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/mman.h> #include <assert.h> #include <iostream> #include "TicTacToe.h" using namespace std; // Player& TicTacToe::winner()const // { // uint xCount=0; // uint oCount=0; // // \> // for (int i = 0; i < game_board.length; i++){ // if(this->game_board[{i,i}].c=='.'){ // break; // } // else if(this->game_board[{i,i}].c=='X'){ // xCount++; // } // else if(this->game_board[{i,i}].c=='O'){ // oCount++; // } // } // //CHECK // if(oCount==game_board.length){win->setChar('O'); // return *(this->win); // } // else if(xCount==game_board.length) // {win->setChar('X'); // return *(this->win); // } // // </ // oCount=0,xCount=0; // for (int i = 0; i < game_board.length; i++){ // if(this->game_board[{i,(int)game_board.length-1-i}].c=='.'){ // break; // } // else if(this->game_board[{i,(int)game_board.length-1-i}].c=='X'){ // xCount++; // } // else if(this->game_board[{i,(int)game_board.length-1-i}].c=='O'){ // oCount++; // } // } // //CHECK // if(oCount==game_board.length){ // win->setChar('O'); // return *(this->win); // } // else if(xCount==game_board.length) // {win->setChar('X'); // return *(this->win); // } // //row // oCount=0,xCount=0; // for (int i = 0; i < game_board.length; i++){ // for (int j = 0; j < game_board.length; j++){ // if(this->game_board[{i,j}].c=='X'){ // xCount++; // } // else if(this->game_board[{i,j}].c=='O'){ // oCount++; // } // } // //CHECK // if(oCount==game_board.length){ // win->setChar('O'); // return *(this->win); // } // else if(xCount==game_board.length) // {win->setChar('X'); // return *(this->win); // } // oCount=0,xCount=0; // } // //column // for (int i = 0; i < game_board.length; i++){ // for (int j = 0; j < game_board.length; j++){ // if(this->game_board[{j,i}].c=='X'){ // xCount++; // } // else if(this->game_board[{j,i}].c=='O'){ // oCount++; // } // } // //CHECK // if(oCount==game_board.length){ // win->setChar('O'); // return *(this->win); // } // else if(xCount==game_board.length) // {win->setChar('X'); // return *(this->win); // } // oCount=0,xCount=0; // } // //end - winner // } //______________________________________________________________________________________________________________________ Player& TicTacToe::winner()const { return *win; } //____________________________________________ TicTacToe::TicTacToe(){ } TicTacToe::~TicTacToe(){ // for (int i = 0; i < game_board.length; i++){ // delete[] game_board.b[i]; // } // //delete[] game_board.b; // // delete[] win; } bool TicTacToe::FullBoard(Board& ptr){ for(int i=0;i<ptr.length;i++){ for(int j=0;j<ptr.length;j++){ if(ptr.b[i][j]=='.'){return false;} } } return true; } TicTacToe::TicTacToe(uint length):game_board{length}{ } //________________________________________________________________________ void TicTacToe::play(Player& xPlayer, Player& oPlayer) {game_board='.'; bool flag=true; xPlayer.myChar='X'; oPlayer.myChar='O'; while (flag&&(!FullBoard(game_board))&&(!check_win(game_board))) { try {if(game_board[{xPlayer.play(game_board)}].c=='O') { win=&oPlayer; flag=false; } } catch(const string& ex) { game_board='.'; win=&oPlayer; flag=false; } if(flag) { if(check_win(game_board)){return;} try {game_board[{xPlayer.play(game_board)}].c='X';} catch(const string& ex) { game_board='.'; game_board[{xPlayer.play(game_board)}].c='X'; win=&oPlayer; flag=false; } if(check_win(game_board)){win=&xPlayer; return;} } try {if(game_board[{oPlayer.play(game_board)}].c=='X') { win=&xPlayer; flag=false; } } catch(const string& ex) { game_board='.'; game_board[{xPlayer.play(game_board)}].c='X'; win=&xPlayer; flag=false; } if(flag) { try {game_board[{oPlayer.play(game_board)}].c='O';} catch(const string& ex) { game_board='.'; game_board[{xPlayer.play(game_board)}].c='X'; win=&xPlayer; flag=false; } if(check_win(game_board)){win=&oPlayer;} } } } //____________________________________________________ Board TicTacToe::board() const { return this->game_board; } // // Fullgame_board //________________check wining__________________ bool TicTacToe::check_win(Board& t_board){ uint n=t_board.length; uint count_o=0,count_x=0; while(1){ for(int i=0;i<n;i++) {count_o=0; count_x=0; for(int j=0;j<n;j++) {if(t_board[{i,j}].c=='X') { count_x++; if(count_x==n){return true; } } if(t_board[{i,j}].c=='O') { count_o++; if(count_o==n){return true; } } } } for(int i=0;i<n;i++) {count_o=0; count_x=0; for(int j=0;j<n;j++) {if(t_board[{j,i}].c=='X') { count_x++; if(count_x==n){return true;} } if(t_board[{j,i}].c=='O') { count_o++; if(count_o==n){return true;} } } } count_o=0; count_x=0; for(int i=0;i<n;i++) { if(t_board[{(int)(n-1-i),i}].c=='X') { count_x++; if(count_x==n){return true;} } if(t_board[{i,(int)(n-1-i)}].c=='O') { count_o++; if(count_o==n){return true;} } } count_o=0; count_x=0; for(int i=n-1;i>=0;i--) { if(t_board[{i,i}].c=='X') { count_x++; if(count_x==n){return true;} } if(t_board[{i,i}].c=='O') { count_o++; if(count_o==n){return true;} } } return false; } return false; }
true
1e62efb7cefb5187d3b6c6c81c247b78c8a01d8d
C++
EduFill/hbrs-ros-pkg
/hbrs_common/hbrs_algorithms/statistics/means.hpp
UTF-8
697
2.640625
3
[]
no_license
/* * means.hpp * * Created on: 14.04.2011 * Author: Frederik Hegger */ #ifndef MEANS_HPP_ #define MEANS_HPP_ #include <ros/ros.h> #include <pcl/point_types.h> #include <pcl/filters/passthrough.h> class Means { public: template <typename PointT> static void determineArithmeticMean3D(const pcl::PointCloud<PointT> &pcl_cloud_input, double &mean_x, double &mean_y, double &mean_z) { mean_x = mean_y = mean_z = 0.0; unsigned int i; for(i=0; i < pcl_cloud_input.size(); ++i) { mean_x += pcl_cloud_input.points[i].x; mean_y += pcl_cloud_input.points[i].y; mean_z += pcl_cloud_input.points[i].z; } mean_x /= i; mean_y /= i; mean_z /= i; } }; #endif /* MEANS_HPP_ */
true
f650f1013503ea9c73ba9d3ac51a3c59b0f8331a
C++
negibokken/sandbox
/code-interview/chapter3/question4/main.cc
UTF-8
1,135
3.65625
4
[]
no_license
#include <iostream> #include <vector> using namespace std; template <typename T> class MyQueue { private: vector<T> s1, s2; public: void add(T x) { s1.push_back(x); } void remove() { if (s1.size() == 0) { throw "QUEUE_EMPTY_ERROR"; } while (!s1.empty()) { // Remove Last one if (s1.size() != 1) { s2.push_back(s1.back()); } s1.pop_back(); } while (!s2.empty()) { s1.push_back(s2.back()); s2.pop_back(); } } T peek() { if (s1.size() == 0) { throw "QUEUE_EMPTY_ERROR"; } while (!s1.empty()) { s2.push_back(s1.back()); s1.pop_back(); } T result = s2.back(); while (!s2.empty()) { s1.push_back(s2.back()); s2.pop_back(); } return result; } bool isEmpty() { return s1.size() == 0; } }; int main(void) try { MyQueue<int> q; for (int i = 0; i < 10; ++i) { q.add(i); } for (int i = 0; i < 10; ++i) { cout << q.peek() << endl; q.remove(); } cout << "Empty: " << (q.isEmpty() ? "true" : "false") << endl; return 0; } catch (char *s) { cerr << s << endl; }
true
ffd32944bd3feb14929bf74e059f958fab742028
C++
MuhammadFadhilArkan/vending-machine
/Coding/I2C_LCD_TUTORIAL/I2C_LCD_TUTORIAL/I2C_LCD_TUTORIAL.ino
UTF-8
785
2.953125
3
[]
no_license
#include <LiquidCrystal_I2C.h> /* www.electronicsprojectshub.com */ /*Import following Libraries*/ //I2C pins declaration LiquidCrystal_I2C lcd(0x27, 16, 2); void setup() { lcd.begin();//Defining 16 columns and 2 rows of lcd display lcd.backlight();//To Power ON the back light //lcd.backlight();// To Power OFF the back light } void loop() { //Write your code lcd.setCursor(0,0); //Defining positon to write from first row,first column . lcd.print("HELLOW"); //You can write 16 Characters per line . lcd.setCursor(0,1); //Defining positon to write from second row,first column . lcd.print("FRIENDS!"); delay(8000); lcd.clear();//Clean the screen lcd.setCursor(0,0); lcd.print("INSERT"); lcd.setCursor(0,1); lcd.print("COIN!"); delay(8000); }
true
f2a68a96df4f7e2d7257ff4afb5a30e9a5c8cf7d
C++
jameskumar/Online-Judge-Solutions
/SPOJ/CLASSICAL/HERDING.cpp
UTF-8
810
2.78125
3
[]
no_license
#include <iostream> #include <cstdio> #include <queue> #include <cstring> using namespace std; int n,m,ans; char grid[1009][1009]; int visited[1009][1009]; bool dfs(int i, int j, int pid) { while(1) { if(visited[i][j]) { if(visited[i][j]==pid) return true; else return false; } visited[i][j]=pid; switch(grid[i][j]) { case 'W': j--; break; case 'E': j++; break; case 'N': i--; break; case 'S': i++; break; default: break; } } } void solve() { int i,j,pid; memset(visited,0,sizeof(visited)); pid=0; ans=0; for(i=0;i<n;i++) for(j=0;j<m;j++) if(!visited[i][j]) { pid++; if(dfs(i,j,pid)) ans++; } } main() { int i; scanf("%d %d",&n,&m); for(i=0;i<n;i++) scanf(" %s",grid[i]); solve(); printf("%d\n",ans); return 0; }
true
95c8222df71476b224acec21497aae81f197f6b7
C++
AuditoryBiophysicsLab/EarLab
/tags/release-2.0/Modules/Fanout/Fanout.cpp
UTF-8
3,638
2.53125
3
[ "MIT" ]
permissive
#include <iostream> #include "Fanout.h" #include "CParameterFile.h" #include "ParameterStatus.h" #include "Earlab.h" #include <stdio.h> #include <memory.h> #include <string.h> #include "EarlabException.h" using namespace std; Fanout::Fanout() { memset(this, 0, sizeof(Fanout)); mLogger = new Logger(); SetModuleName("Fanout"); } Fanout::~Fanout() { if (mModuleName != NULL) delete [] mModuleName; } int Fanout::ReadParameters(char *ParameterFileName) { if (mModuleName == NULL) return ReadParameters(ParameterFileName, "Fanout"); else return ReadParameters(ParameterFileName, mModuleName); } int Fanout::ReadParameters(char *ParameterFileName, char *SectionName) { CParameterFile theParamFile(ParameterFileName); //ParameterStatus Status; mLogger->Log(" ReadParameters: %s \"%s\"", mModuleName, ParameterFileName); return 1; } int Fanout::Start(int NumInputs, EarlabDataStreamType InputTypes[EarlabMaxIOStreamCount], int InputSize[EarlabMaxIOStreamCount][EarlabMaxIOStreamDimensions], int NumOutputs, EarlabDataStreamType OutputTypes[EarlabMaxIOStreamCount], int OutputSize[EarlabMaxIOStreamCount][EarlabMaxIOStreamDimensions], unsigned long OutputElementCounts[EarlabMaxIOStreamCount]) { int i, j; mLogger->Log(" Start: %s", mModuleName); // Perform some validation on my parameters to make sure I can handle the requested input and output streams... if (NumInputs != 1) throw EarlabException("%s: Currently this module can only handle one input stream. Sorry!", mModuleName); if (NumOutputs == 0) throw EarlabException("%s: This module must have at least one output stream. Sorry!", mModuleName); if (InputTypes[0] != WaveformData) throw EarlabException("%s: Currently this module can only handle waveform input data streams. Sorry!", mModuleName); for (i = 0; i < NumOutputs; i++) if (OutputTypes[i] != WaveformData) throw EarlabException("%s: Currently this module can only handle waveform output data streams. Sorry!", mModuleName); mNumOutputs = NumOutputs; for (i = 0; i < NumOutputs; i++) { OutputElementCounts[i] = 1; for (j = 0; j < EarlabMaxIOStreamDimensions; j++) { if (InputSize[0][j] != OutputSize[i][j]) throw EarlabException("%s: Input size mismatch. Dimension %d of input does not match output stream %d", mModuleName, j, i + 1); if (InputSize[0][j] == 0) { mNumberOfDimensions = j; break; } OutputElementCounts[i] *= OutputSize[i][j]; } } return 1; } int Fanout::Advance(EarlabDataStream *InputStream[EarlabMaxIOStreamCount], EarlabDataStream *OutputStream[EarlabMaxIOStreamCount]) { int i; unsigned long BufLen; FloatMatrixN *Input, *Output[EarlabMaxIOStreamCount]; mLogger->Log(" Advance: %s", mModuleName); Input = ((EarlabWaveformStream *)InputStream[0])->GetData(); for (i = 0; i < mNumOutputs; i++) Output[i] = ((EarlabWaveformStream *)OutputStream[i])->GetData(); for (i = 0; i < mNumOutputs; i++) { *(Output[i]) = *(Input); } Output[0]->GetData(&BufLen); return (int)BufLen; } int Fanout::Stop(void) { mLogger->Log(" Stop: %s", mModuleName); return 1; } int Fanout::Unload(void) { mLogger->Log(" Unload: %s", mModuleName); return 1; } void Fanout::SetModuleName(char *ModuleName) { if (mModuleName != NULL) delete [] mModuleName; mModuleName = new char[strlen(ModuleName) + 1]; strcpy(mModuleName, ModuleName); } void Fanout::SetLogger(Logger *TheLogger) { if (mLogger != NULL) delete mLogger; mLogger = TheLogger; }
true
39aaec26077227bf125c83ef92783b30282749d0
C++
parkjungeun/Algorithm-Problem-Code
/BOJ/[BOJ]1157_단어 공부.cpp
UTF-8
594
3.046875
3
[]
no_license
#include<iostream> #include<algorithm> #include<string> using namespace std; pair<char, int> alpha[26]; bool cmp(pair<char, int> &a, pair<char, int> &b) { return a.second > b.second ? true : false; } int main() { ios::sync_with_stdio(0); cin.tie(0); for (char c = 'A'; c <= 'Z'; c++) alpha[c - 'A'].first = c; string str; cin >> str; for (int i = 0; i < str.length(); ++i) str[i] < 'a' ? alpha[str[i]-'A'].second++ : alpha[str[i] - 'a'].second++; sort(alpha, alpha + 26, cmp); if (alpha[0].second == alpha[1].second) cout << '?'; else cout << alpha[0].first; return 0; }
true
96d8d239ad8542c19620fcf63079a4569c7b55ee
C++
sicongzhao/cht_Duke_courses
/ECE551-cpp/自主练习课/test_signed.cpp
UTF-8
263
3
3
[ "MIT" ]
permissive
#include <stdio.h> #include <stdlib.h> int main(void) { int a = -1; unsigned int b = 0; if(a + b > 0) { //did we get -1 or 4billion? printf("Unsigned %d\n", a + b); } else { printf("Signed %d\n", a + b); } return EXIT_SUCCESS; }
true
bb7978fd162e7aa4228fbd3c58e8f876f898bbfc
C++
goodpaperman/template
/11.chapter/BartonNackman/BartonNackman.cpp
GB18030
453
2.609375
3
[]
no_license
// BartonNackman.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include <typeinfo.h> class S { }; template <typename T> class Wrapper { public: Wrapper(T obj) : object(obj) { } friend void f(Wrapper<T> const& a) { printf("void f(Wrapper<%s> const& a)\n", typeid(T).name()); } private: T object; }; int _tmain(int argc, _TCHAR* argv[]) { S s; Wrapper<S> w(s); f(w); f(s); return 0; }
true
2fe88d8948218bc1a6654f80791bd97714f7d0d2
C++
himanshu-code/C-Cpp
/elabstack.cpp
UTF-8
626
3.03125
3
[]
no_license
#include<stdio.h> #define capacity 10 int queue[capacity]; int front=0; int rear=0; void push(int x) { queue[rear]=x; rear++; } void dequeue() { if(front==rear) { printf("Underflow"); } else front++; } void display() { int i; if(rear==0) { printf("Underflow"); } else{ for(i=front;i<rear;i++) { printf("%d->",queue[i]); } i=front; printf("%d->\n",queue[i]); } } int main() { int n,x; scanf("%d",&n); while(n!=0) { switch(n) { case 1: scanf("%d",&x); push(x); break; case 2: dequeue(); break; case 3:display(); break; } scanf("%d",&n); } return 0; }
true
a60a83cb1d8f2de99e4a64b6ae0d18c445c7fa04
C++
aranoy15/embedded-software
/app/lib/stream/actions.cpp
UTF-8
7,873
3.046875
3
[]
no_license
#include <lib/stream/actions.hpp> #include <cstring> namespace { char digital_char_by_index(int index) { static const char* digits = "0123456789ABCDEF"; //O_ASSERT(index < 16); return digits[index]; } } using namespace lib::stream; IntegerFormatAction::IntegerFormatAction(uint64_t data) : _data(data), _is_signed(false) { } IntegerFormatAction::IntegerFormatAction(int64_t data) : _data(data), _is_signed(true) { } IntegerFormatAction::IntegerFormatAction(uint32_t data) : _data(data), _is_signed(false) { } IntegerFormatAction::IntegerFormatAction(int32_t data) : _data(data), _is_signed(true) { } IntegerFormatAction::IntegerFormatAction(uint16_t data) : _data(data), _is_signed(false) { } IntegerFormatAction::IntegerFormatAction(int16_t data) : _data(data), _is_signed(true) { } IntegerFormatAction::IntegerFormatAction(uint8_t data) : _data(data), _is_signed(false) { } IntegerFormatAction::IntegerFormatAction(int8_t data) : _data(data), _is_signed(true) { } /* IntegerFormatAction::IntegerFormatAction(int data) : _data(data), _is_signed(true) { } IntegerFormatAction::IntegerFormatAction(unsigned data) : _data(data), _is_signed(false) { } IntegerFormatAction::IntegerFormatAction(std::size_t data) : _data(data), _is_signed(false) { } */ void IntegerFormatAction::action(Stream& stream) const { auto& format_settings = stream.format_settings(); //O_ASSERT(format_settings.radix <= 16); const int max_digits = 32; char digits[max_digits] = {0}; bool is_negative = _is_signed and (static_cast<int32_t>(_data) < 0); uint64_t number = _is_signed ? abs(static_cast<int64_t>(_data)) : _data; uint64_t devider = format_settings.radix; int digital_count = 0; do { //O_ASSERT(digital_count < max_digits); int digit = number % devider; digits[max_digits - digital_count - 1] = digital_char_by_index(digit); number /= devider; ++digital_count; } while (number != 0); if (is_negative) { //O_ASSERT(digital_count < max_digits); digits[max_digits - digital_count - 1] = '-'; ++digital_count; } int left_padding = 0; int right_padding = 0; calculate_paddings(format_settings, digital_count, left_padding, right_padding); const uint8_t* write_data = reinterpret_cast<const uint8_t*>(digits + max_digits - digital_count); stream.repeat(format_settings.padding_char, left_padding); stream.write(write_data, digital_count); stream.repeat(format_settings.padding_char, right_padding); } void IntegerFormatAction::calculate_paddings( const Stream::FormatSettings& settings, int digital_count, int& left_padding, int& right_padding) const { if (settings.int_width == 0) { left_padding = 0; right_padding = 0; return; } switch (settings.justify) { case Stream::Justify::Left: left_padding = 0; right_padding = settings.int_width - digital_count; break; case Stream::Justify::Center: left_padding = (settings.int_width - digital_count) / 2; right_padding = settings.int_width - left_padding; break; case Stream::Justify::Right: left_padding = settings.int_width - digital_count; right_padding = 0; break; } //O_ASSERT(left_padding >= 0); //O_ASSERT(right_padding >= 0); } DoubleFormatAction::DoubleFormatAction(const double& data) : _data(data), _digits_after_dot_amount(2) { } void DoubleFormatAction::action(Stream& stream) const { double data = _data; const uint32_t max_digits_after_dot = 12; char digits_after_dot[max_digits_after_dot] = {0}; if (data < 0) data *= -1; data -= static_cast<int32_t>(data); for (uint32_t i = 0; i < _digits_after_dot_amount; i++) { data = data * 10; int32_t digit = static_cast<int32_t>(data); //O_ASSERT(digit <= 9); data -= digit; digits_after_dot[i] = '0' + digit; } int32_t integer_part = static_cast<int32_t>(_data); uint32_t number = (integer_part < 0) ? abs(integer_part) : integer_part; const uint32_t devider = 10; uint32_t digit_count = 0; const uint32_t max_digits_before_dot = 24; char digits_before_dot[max_digits_before_dot] = {0}; do { //O_ASSERT(digit_count < max_digits_before_dot); int digit = number % devider; digits_before_dot[max_digits_before_dot - digit_count - 1] = '0' + digit; number /= devider; ++digit_count; } while (number != 0); if (_data < 0) { //O_ASSERT(digit_count < max_digits_before_dot); digits_before_dot[max_digits_before_dot - digit_count - 1] = '-'; ++digit_count; } const uint32_t max_digits = max_digits_after_dot + max_digits_before_dot; char digits[max_digits] = {0}; memcpy(digits, digits_before_dot + (max_digits_before_dot - digit_count), digit_count); memcpy(digits + digit_count, ".", 1); digit_count++; memcpy(digits + digit_count, digits_after_dot, _digits_after_dot_amount); const uint8_t* write_data = reinterpret_cast<const uint8_t*>(digits); stream.write(write_data, _digits_after_dot_amount + digit_count); } StringFormatAction::StringFormatAction(const char* data) : _data(data) {} void StringFormatAction::action(Stream& stream) const { auto& format_settings = stream.format_settings(); int32_t size = strlen(_data); uint16_t left_padding = 0; uint16_t right_padding = 0; if (format_settings.width > size) { switch (format_settings.justify) { case Stream::Justify::Left: left_padding = 0; right_padding = format_settings.width - size; break; case Stream::Justify::Center: left_padding = (format_settings.width - size) / 2; right_padding = (format_settings.width - size) - left_padding; break; case Stream::Justify::Right: left_padding = format_settings.width - size; right_padding = 0; break; } } const uint8_t* write_data = reinterpret_cast<const uint8_t*>(_data); stream.repeat(format_settings.padding_char, left_padding); stream.write(write_data, size); stream.repeat(format_settings.padding_char, right_padding); } void RadixAction::action(Stream& stream) const { auto& format_settings = const_cast<Stream::FormatSettings&>(stream.format_settings()); format_settings.radix = _radix; stream.set_format_settings(format_settings); } void WidthAction::action(Stream& stream) const { auto& format_settings = const_cast<Stream::FormatSettings&>(stream.format_settings()); format_settings.width = _width; stream.set_format_settings(format_settings); } void PaddingCharAction::action(Stream& stream) const { auto& format_settings = const_cast<Stream::FormatSettings&>(stream.format_settings()); format_settings.padding_char = _pedding_char; stream.set_format_settings(format_settings); } void JustifyAction::action(Stream& stream) const { auto& format_settings = const_cast<Stream::FormatSettings&>(stream.format_settings()); format_settings.justify = _justify; stream.set_format_settings(format_settings); } void IntWidthAction::action(Stream& stream) const { auto& format_settings = const_cast<Stream::FormatSettings&>(stream.format_settings()); format_settings.int_width = _width; format_settings.padding_char = _pad; stream.set_format_settings(format_settings); } void ReadSizeAction::action(Stream& stream) const { Stream::ReadSize& read_size = const_cast<Stream::ReadSize&>(stream.read_size()); read_size.data_size = _read_size; stream.set_read_size(read_size); }
true
e7b3364972c9807aab53cfc35534f3c694fb8396
C++
kjgonzalez/codefiles
/cpp_sandbox/vector_array/check.cpp
UTF-8
620
3.78125
4
[ "MIT" ]
permissive
/* objective: understand how a silly array of vector of ints works. */ #include <iostream> #include <vector> using namespace std; int main(){ vector<int> sample[3]; sample[0].push_back(0); sample[0].push_back(1); sample[0].push_back(2); sample[1].push_back(3); sample[1].push_back(4); sample[1].push_back(5); sample[2].push_back(6); sample[2].push_back(7); sample[2].push_back(8); /* | 0 1 2 | | 3 4 5 | | 6 7 8 | */ cout << "Hello world\n"; int arr = 2; int vec = 1; cout << "item: " << sample[arr][vec] << "\n"; return 0; }//main
true
dbd101de694b271cb65036aa6b3b66dad6c79a12
C++
hedinasr/Interpol
/view/src/Animation.cpp
UTF-8
2,413
3.015625
3
[ "MIT" ]
permissive
#include "opengl.h" #include "Vec3f.h" #include <time.h> #include "Animation.h" #include <cassert> const int NBPB=10; // NomBre de Points de Bezier (entre 2 points de Contr il y aura NPB points) float temps() { return float(clock())/CLOCKS_PER_SEC; } /** Fonction de calcul pc[0..3] sont les 4 points de controles t le parametre p le point resultat de la courbe */ Vec3f Bezier(const Vec3f& p0, const Vec3f& p1, const Vec3f& p2, const Vec3f& p3, const float t) { float t1,t13,t3; Vec3f p, r0, r1, r2, r3; t1 = 1 - t; t13 = t1 * t1 * t1; t3 = t * t * t; //p = t13*p0 + 3*t*t1*t1*p1 + 3*t*t*t1*p2 + t3*p3; vecMul( r0, t13, p0); vecMul( r1, 3*t*t1*t1, p1); vecMul( r2, 3*t*t*t1, p2); vecMul( r3, t3, p3); vecAdd( p, r0, r1); vecAdd( p, p, r2); vecAdd( p, p, r3); return p; } void animInit(Animation& a, const char* nom_fichier) { const int taille=512; char txt[taille]; FILE* f; f = fopen( nom_fichier, "r"); assert( f ); // donnée temporaire (=point de controle PC) servant pour calculer les points finaux (P) int NBPC; Vec3f* PC; do { fgets( txt,taille,f); } while( txt[0]=='#' ); assert( sscanf( txt, "%d\n", &NBPC)==1 ); a.nbp = (NBPC/4)*NBPB; // Nombre de points en tout PC = new Vec3f[NBPC]; a.P = new Vec3f[a.nbp]; int i; for(i=0;i<NBPC;++i) { do { fgets( txt,taille,f); } while( txt[0]=='#' ); assert( sscanf( txt, "%f %f %f\n", &PC[i].x, &PC[i].y, &PC[i].z)==3 ); } printf("Animation: %d PdC et %d P en tout\n", NBPC, a.nbp); //for(i=0;i<NBPC;++i) vecPrint( a.P[i] ); // Courbe de Bezier int c=0, j; for (i=0;i<NBPC;i+=4) // Pour calculer une courbe de Bezier, on regroupe les points de controle par 4 { for (j=0;j<NBPB;j++) { a.P[c] = Bezier( PC[i], PC[(i+1)%NBPC], PC[(i+2)%NBPC], PC[(i+3)%NBPC], float(j)/(NBPB) ); c++; } } delete[] PC; } void animDraw(const Animation& a) { int i; glPushAttrib( GL_ENABLE_BIT ); glLineWidth(5); glDisable(GL_LIGHTING ); glDisable(GL_TEXTURE_2D); glColor4f(1,0,0,1); glBegin(GL_LINE_LOOP); for (i=0;i<a.nbp;i++) { //printf("%f %f %f\n", P[i].x, P[i].y, P[i].z ); glVertex3f( a.P[i].x, a.P[i].y, a.P[i].z ); } glEnd(); glPopAttrib(); }
true
b7df90bc16689567371ffb85de9797963a08cec8
C++
gzgreg/ACM
/2017-12-29/D.cpp
UTF-8
1,621
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef vector<int> vi; struct rational_t { ll nu, de; rational_t(const ll &n = 0, const ll &d = 1) { ll g = __gcd(abs(n), abs(d)); nu = n / g; de = d / g; if (de < 0) { nu = -nu; de = -de; } } rational_t operator+(const rational_t& b) const { return rational_t( nu*b.de+de*b.nu, de*b.de ); } rational_t operator-(const rational_t& b) const { return rational_t( nu*b.de-de*b.nu, de*b.de ); } rational_t operator-() { return rational_t(-nu, de); } rational_t operator*(const rational_t& b) const { return rational_t( nu*b.nu, de*b.de ); } rational_t operator/(const rational_t& b) const { return rational_t( nu*b.de, de*b.nu ); } bool operator== (const rational_t & b) const {return nu * b.de == b.nu * de;} bool operator== (const int &k) const { return nu == k * de; } bool operator< (const rational_t& b) const { return nu * b.de < b.nu * de; }}; int numAs = 0; ld ans; ld totProb; ld prob; int k, pa, pb; void dfs(int depth, ld curProb, int curVal) { if(curProb < 1e-10 || depth > 1000) return; numAs++; dfs(depth+1, curProb * prob, curVal); numAs--; curVal += numAs; if(curVal >= k) { ans = ans + curProb * curVal; totProb = totProb + curProb; return; } dfs(depth+1, curProb * (1-prob), curVal); } int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> k >> pa >> pb; prob = (ld) pa / (pb + pa); dfs(0, 1, 0); ans = ans / totProb; cout << fixed << setprecision(15) << ans << endl; cout << totProb << endl; return 0; }
true
c40eb0f00fe4400fccfea487802478113a89cffc
C++
zackluckyf/codechefeasy
/divisors-product.cpp
UTF-8
1,472
3.890625
4
[]
no_license
// // main.cpp // divisors-product // // Created by Zack Fanning on 9/23/15. // Copyright © 2015 Zackluckyf. All rights reserved. // /* Being in love with number theory, Johnny decided to take a number theory course. On the first day, he was challenged by his teacher with the following problem: given a number N, compute the product of its positive divisors. Johnny is desperate to impress his new teacher so he asks you for help. In this problem, the divisors of N do not include the number N itself. For example, if N=12, the divisors of N (excluding N) are 1, 2, 3, 4, and 6. Thus, the product of divisors is 1x2x3x4x6=144. Since the result may be very large, if the result has more than 4 decimal digits, Johnny only needs to compute the last 4 digits of it. */ #include <iostream> #include <vector> #include <iomanip> int main(int argc, const char * argv[]) { int userInput; std::vector<int> divisors; std::cout << "Enter the number whose divisors you would like to see multiplied, for numbers greater than 4 digits only the last 4 numbers will be shown: "; std::cin >> userInput; for (int i = 1; i <= userInput/2; i++) { if(userInput % i == 0) { divisors.push_back(i); } } int total = 1; for (int i = 1; i < divisors.size(); i++) { total = total * (divisors[i]); } std::cout << "\n" << std::setw(4) << std::setfill('0') << total%10000 << "\n"; return 0; }
true
6b98e9e3a43ccb596498fa820967a2051a6c31a5
C++
hushpe/leetcode
/Num_092.cpp
UTF-8
1,474
3.65625
4
[]
no_license
#include<iostream> using namespace std; // https://leetcode-cn.com/problems/reverse-linked-list-ii struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Solution { public: ListNode* reverseBetween(ListNode* head, int left, int right) { if(left > right || head == nullptr) return head; if(1 == left) return reverse(head, right-left+1); int idx = 2; ListNode *preHead = head; ListNode *curHead = head->next; while(preHead && idx < left) { preHead = preHead->next; curHead = curHead->next; idx++; } if(idx != left) return head; preHead->next = reverse(curHead, right-left+1); return head; } ListNode* reverse(ListNode* head, int len) { if(1 == len || head == nullptr) return head; ListNode *lastHead = head; ListNode *preHead = head; ListNode *curHead = head->next; int idx = 1; while(curHead && idx < len) { ListNode *tmp = curHead->next; curHead->next = preHead; preHead = curHead; curHead = tmp; idx++; } if(idx != len) { lastHead->next = nullptr; } else { lastHead->next = curHead; } return preHead; } };
true
729dd39af57bc604abfdb10a59aa9ab16a9f757d
C++
jgonfroy42/CPP_piscine
/module00/ex01/ClassContact.cpp
UTF-8
2,081
3.03125
3
[]
no_license
#include "phonebook.hpp" contact::contact(void) {} void contact::get_all(void) const { std::cout << this->_f_name << std::endl; std::cout << this->_l_name << std::endl; std::cout << this->_nickname << std::endl; std::cout << this->_login << std::endl; std::cout << this->_address << std::endl; std::cout << this->_email << std::endl; std::cout << this->_phone << std::endl; std::cout << this->_birthday << std::endl; std::cout << this->_meal << std::endl; std::cout << this->_underwear << std::endl; std::cout << this->_secret << std::endl; } void contact::print_info(std::string str) const { if (str.size() <= 10) std::cout << std::setw(10) << str; else std::cout << str.substr(0, 9) << "."; } void contact::get_info(int index) const { std::cout << std::setw(10) << index; std::cout << "|"; print_info(this->_f_name); std::cout << "|"; print_info(this->_l_name); std::cout << "|"; print_info(this->_login); std::cout << std::endl; } void contact::init(void) { std::string var; std::cout << "First Name :" << std::endl; std::getline(std::cin, var); this->_f_name = var; std::cout << "Last Name :" << std::endl; std::getline(std::cin, var); this->_l_name = var; std::cout << "Nickname :" << std::endl; std::getline(std::cin, var); this->_nickname = var; std::cout << "Login :" << std::endl; std::getline(std::cin, var); this->_login = var; std::cout << "Postal Address :" << std::endl; std::getline(std::cin, var); this->_address = var; std::cout << "Email Address :" << std::endl; std::getline(std::cin, var); this->_email = var; std::cout << "Phone Number :" << std::endl; std::getline(std::cin, var); this->_phone = var; std::cout << "Birthday Date :" << std::endl; std::getline(std::cin, var); this->_birthday = var; std::cout << "Favorite Meal :" << std::endl; std::getline(std::cin, var); this->_meal = var; std::cout << "Underwear Color :" << std::endl; std::getline(std::cin, var); this->_underwear = var; std::cout << "Darkest Secret :" << std::endl; std::getline(std::cin, var); this->_secret = var; }
true
14ff3e93b709c6bb7150317a3deb8cb1e8815fc0
C++
HK-FLYE/Annotated_STL_Sources
/test/lconfig_null_template_arguments.cpp
UTF-8
1,487
3.359375
3
[]
no_license
#include <iostream> #include <cstddef> // 类模板的某个具体实现与其友元函数模板的某个实现有一一对应的关系 using namespace std; class alloc { }; template <class T, class Alloc = alloc, size_t BufSiz = 0> class deque { public: deque() { cout << "deque" << ' '; } }; template <class T, class Sequence = deque<T> > class stack { template <class U, class Y> friend bool operator==(const stack<U, Y>&, const stack<U, Y>& ) ; template <class U, class Y> friend bool operator<(const stack<U, Y>&, const stack<U, Y>& ) ; // friend bool operator== <> (const stack&, const stack&); // friend bool operator< <> (const stack&, const stack&); public: stack() { cout << "Stack" << endl; } private: Sequence c; }; template <class T, class Sequence> bool operator==(const stack<T, Sequence>& x, const stack<T, Sequence>& y) { return cout << "operator==" << '\t'; } template <class T, class Sequence> bool operator<(const stack<T, Sequence>& x, const stack<T, Sequence>& y) { return cout << "operator<" << '\t'; } int main(int argc, char const *argv[]) { stack<int> x; stack<int> y; cout << (x == y) << endl; cout << (x < y) << endl; // operator== 1 输出 // operator< 1 stack<char> y1; // cout << (x == y1) << endl; //会报错 // cout << (x < y1) << endl; return 0; }
true
91e17f918b2e35b9008c42e1303eadf8def602a6
C++
aerdo/tg_mpei_course
/Range Sum of BST.cpp
UTF-8
343
3.3125
3
[]
no_license
//https://leetcode.com/problems/range-sum-of-bst/ class Solution { public: int rangeSumBST(TreeNode* root, int L, int R) { if (!root) return 0; int res=0; if (root->val>=L&&root->val<=R)res+=root->val; res+=rangeSumBST(root->right,L,R); res+=rangeSumBST(root->left,L,R); return res; } };
true
d6ec6bd85b5910bdfae5466920781c33eca9ebf6
C++
goltango/parallel-programming
/MatrixMult1.cpp
UTF-8
975
2.84375
3
[]
no_license
#include <stdio.h> #include <ctime> #define BUFFSIZE 800 int main(int argc, char *argv[]) { int i, j, k; int M = BUFFSIZE; int K = BUFFSIZE; int N = BUFFSIZE; float matA[BUFFSIZE][BUFFSIZE]; float matB[BUFFSIZE][BUFFSIZE]; float matC[BUFFSIZE][BUFFSIZE]; for(i=0;i<M;i++){ for(j=0;j<K;j++){ matA[i][j]=1.0; matB[i][j]=1.0; } } printf("Multiplying %d x %d matrix.\n", M, M); clock_t begin = clock(); for(i=0;i<M;i++){ for(j=0;j<K;j++){ matC[i][j]=0.0; for(k=0;k<N;k++){ matC[i][j]=matC[i][j]+matA[i][k]*matB[k][j]; } } } clock_t end = clock(); for(i=0;i<3;i++){ printf("\n"); for(j=0;j<3;j++){ printf(" %.1f, ", matC[i][j]); } } double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; printf("\n\nExecutionTime: %fs \n", elapsed_secs); }
true
f7a245d37c41a19d4101fa3cfb35dc91b332606f
C++
aman-aman/Leetcode
/34. Search for a Range.cpp
UTF-8
646
2.9375
3
[]
no_license
//aman kumar jha class Solution { public: vector<int> searchRange(vector<int>& a, int target) { int n=a.size(); vector<int> r(2,-1); if(n==0) return r; int i=0,j=n-1; while(i<j) { int m=(i+j)/2; if(a[m]<target) i=m+1; else j=m; } if (a[i]!=target) return r; else r[0]=i; j=n-1; while (i < j) { int m=(i+j)/2+1; if (a[m]>target)j=m-1; else i = m; } r[1] = j; return r; } };
true
e4dd1a3d9949ad0490634fd03d42b534f3dc6747
C++
aryankh1409/Misc-Programs
/Competitive/expression.cpp
UTF-8
197
2.515625
3
[ "MIT" ]
permissive
#include<stdio.h> #include<math.h> int main() { int x,y; scanf("%d%d",&y,&x); int negative = 5 * pow(x,3) - 4 * pow(x,2) + 3 * x + 2; int ans = y - negative; printf("%d",ans); }
true
e1b63173c37efd5b36b976ae83464be6e8536732
C++
MajickTek/hesperus2
/source/engine/core/hesp/io/files/OnionTreeFile.tpp
UTF-8
1,619
2.75
3
[]
no_license
/*** * hesperus: OnionTreeFile.tpp * Copyright Stuart Golodetz, 2009. All rights reserved. ***/ #include <fstream> #include <hesp/exceptions/Exception.h> #include <hesp/io/sections/OnionTreeSection.h> #include <hesp/io/sections/PolygonsSection.h> namespace hesp { //#################### LOADING METHODS #################### /** Loads the polygons and onion tree from the specified onion tree file. @param filename The name of the onion tree file @param polygons Used to return the polygons to the caller @param tree Used to return the onion tree to the caller */ template <typename Poly> void OnionTreeFile::load(const std::string& filename, std::vector<shared_ptr<Poly> >& polygons, OnionTree_Ptr& tree) { std::ifstream is(filename.c_str(), std::ios_base::binary); if(is.fail()) throw Exception("Could not open " + filename + " for reading"); PolygonsSection::load(is, "Polygons", polygons); tree = OnionTreeSection::load(is); } //#################### SAVING METHODS #################### /** Saves the polygons and onion tree to the specified onion tree file. @param filename The name of the onion tree file @param polygons The polygons @param tree The onion tree */ template <typename Poly> void OnionTreeFile::save(const std::string& filename, const std::vector<shared_ptr<Poly> >& polygons, const OnionTree_CPtr& tree) { std::ofstream os(filename.c_str(), std::ios_base::binary); if(os.fail()) throw Exception("Could not open " + filename + " for writing"); PolygonsSection::save(os, "Polygons", polygons); OnionTreeSection::save(os, tree); } }
true
d9f2a0fce5f0df0e8e3b78b534de4df821d612d7
C++
sanchi191/Plagiarism
/plag-project/plagproject/media1/emma/27_mEcUQyQ.cpp
UTF-8
5,139
2.765625
3
[]
no_license
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; int min(int a, int b){ return (a<b)?a:b; } int mergeSort(int a[], int s, int e); int merge(int a[], int s, int e); bool cmp(int ri, int rj); bool mergeSortCheck(int a[], int s, int e); bool mergeCheck(int a[], int s, int e); class Judge{ public: int n; int *p, *q, *s, *r, *pInv, *qInv;; int rInvCount, pInvCount, qInvCount, sInvCount; //they have values means their corresponding arrays are useless int WRONGI, WRONGJ, WRONGK; bool isConsistent; Judge(); void takeInput(); void constructInv(); void constructS(); void getR(); bool verifyR1(); bool verifyR2(); bool verifyR(); void printR(); void constructInvCount(); void findK(); void godKnows(); }; void Judge::takeInput(){ scanf("%d", &n); p = new int[n+1]; q = new int[n+1]; for(int i=1; i<=n; i++) scanf("%d", &p[i]); for(int i=1; i<=n; i++) scanf("%d", &q[i]); } void Judge::godKnows(){ int *pcopy = new int[n+1]; for(int i=1; i<=n; i++) pcopy[i] = p[i]; for(int i=1; i<=n; i++){ r[i] = pInv[r[i]]; q[i] = pInv[q[i]]; p[i] = pInv[i]; } constructInv(); verifyR1(); findK(); WRONGI = pcopy[WRONGI]; WRONGJ = pcopy[WRONGJ]; WRONGK = pcopy[WRONGK]; } void Judge::findK(){ int I, J; for(int i=1; i<=n; i++){ if(WRONGI == r[i]){ I=i; break;} } for(int j=1; j<=n; j++){ if(WRONGJ == r[j]){ J=j; break;} } for(; J<=I-2;){ if(cmp(r[J+1], r[I])){ WRONGJ = r[J]; WRONGK = r[J+1]; break; } else{ J++; } } } void Judge::constructInv(){ pInv = new int[n+1]; qInv = new int[n+1]; for (int i = 1; i<=n; i++) { pInv[p[i]] = i; qInv[q[i]] = i; } } void Judge::constructS(){ s = new int[n+1]; for(int i=1; i<=n; i++){ s[i] = pInv[q[i]]; } } void Judge::getR(){ r = new int[n+1]; for(int i=0; i<=n; i++) r[i] = i; sort(r+1, r+n+1, cmp); } Judge::Judge(){ takeInput(); constructInv(); getR(); isConsistent = verifyR(); if(isConsistent){ printf("consistent\n"); printR(); } else{ printf("inconsistent\n"); printf("%d %d %d\n", WRONGI, WRONGJ, WRONGK); } } void Judge::printR(){ for(int i=1; i<=n; i++) printf("%d ", r[i]); printf("\n"); } bool Judge::verifyR1(){ int *rcopy = new int[n+1]; for(int i=1; i<=n; i++) rcopy[i] = r[i]; bool ans = mergeSortCheck(rcopy, 1, n+1); delete[] rcopy; return ans; } bool Judge::verifyR2(){ constructS(); constructInvCount(); if(rInvCount == (pInvCount + qInvCount - sInvCount)/2) return true; else return false; } bool Judge::verifyR(){ bool pass1 = verifyR1(); // if pass1==true => rInvCount stores the correct inversion count // if pass1==false =>rInvCount stores the wrong inversion count if(!pass1){ findK(); return false; } bool pass2 = verifyR2(); if(!pass2){ godKnows(); return false; } return true; } void Judge::constructInvCount(){ // if program reaches this => rInvCOunt is already initialised! int *copy = new int[n+1]; for(int i=1; i<=n; i++) copy[i] = p[i]; pInvCount = mergeSort(copy, 1, n+1); for(int i=1; i<=n; i++) copy[i] = q[i]; qInvCount = mergeSort(copy, 1, n+1); for(int i=1; i<=n; i++) copy[i] = s[i]; sInvCount = mergeSort(copy, 1, n+1); delete[] copy; } Judge govind; int main(){ return 0; } int mergeSort(int a[], int s, int e){ if(s+1==e) return 0; int m = (s+e)/2; int x = mergeSort(a, s, m); int y = mergeSort(a, m, e); int z = merge(a, s, e); return x+y+z; } int merge(int a[], int s, int e){ int m = (s+e)/2; int *t = new int[e-s]; int z = 0; int i=s, j=m, k=0; while(i<m && j<e){ if(a[i]<=a[j]){ t[k++] = a[i++]; } else{ t[k++]=a[j++]; z+=(m-i); } } while(i<m) t[k++] = a[i++]; while(j<e) t[k++] = a[j++]; for(k=0, i=s; i<e; i++, k++) a[i]=t[k]; delete[] t; return z; } bool cmp(int ri, int rj){ if( (ri<rj) + (govind.pInv[ri]<govind.pInv[rj]) + (govind.qInv[ri]<govind.qInv[rj]) >= 2) return true; else return false; } bool mergeSortCheck(int a[], int s, int e){ if(s+1==e) {return true;} int m = (s+e)/2; bool x = mergeSortCheck(a, s, m); if(!x) return x; bool y = mergeSortCheck(a, m, e); if(!y) return y; bool z = mergeCheck(a, s, e); return (x && y && z); } bool mergeCheck(int a[], int s, int e){ int m = (s+e)/2; int i, j, k; int pMin = govind.n + 1; int qMin = govind.n + 1; int *t = new int[e-s]; int z = 0; i=s, j=m, k=0; while(i<m && j<e){ if(a[i]<a[j]){ if(govind.pInv[a[i]] > pMin) { govind.WRONGI = govind.p[pMin]; govind.WRONGJ = a[i]; return false;} if(govind.qInv[a[i]] > qMin) { govind.WRONGI = govind.q[qMin]; govind.WRONGJ = a[i]; return false;} t[k++] = a[i++]; } else{ pMin = min(pMin, govind.pInv[a[j]]); qMin = min(qMin, govind.qInv[a[j]]); t[k++]=a[j++]; govind.rInvCount += (m-i); } } while(i<m){ if(govind.pInv[a[i]] > pMin) { govind.WRONGI = govind.p[pMin]; govind.WRONGJ = a[i]; return false;} if(govind.qInv[a[i]] > qMin) { govind.WRONGI = govind.q[qMin]; govind.WRONGJ = a[i]; return false;} t[k++] = a[i++]; } while(j<e) t[k++] = a[j++]; // no need to update pMin and qMin for(k=0, i=s; i<e; i++, k++) a[i]=t[k]; delete[] t; return true; }
true
33b8ef88f3e6fab33ab4ef89249ab98ea16b639b
C++
msrLi/portingSources
/ACE/ACE_wrappers/apps/drwho/server.cpp
UTF-8
2,486
2.578125
3
[ "Apache-2.0" ]
permissive
//============================================================================= /** * @file server.cpp * * Driver program for the server. Note that it is easy to reuse the * server for other distributed programs. Pretty much all that must * change are the functions registered with the communciations * manager. * * @author Douglas C. Schmidt */ //============================================================================= #include "Options.h" #include "SMR_Server.h" #include "ace/ACE.h" #include "ace/Log_Msg.h" #include "ace/OS_NS_signal.h" #include "ace/OS_NS_time.h" #include "ace/OS_NS_stdlib.h" #include "ace/OS_NS_sys_socket.h" static char * time_stamp (void) { time_t time_now; char *temp; time_now = ACE_OS::time (0); temp = ACE_OS::asctime (ACE_OS::localtime (&time_now)); temp[12] = 0; return temp; } // Catch the obvious signals and die with dignity... static void exit_server (int sig) { ACE_DEBUG ((LM_DEBUG, "%s exiting on signal %S\n", time_stamp (), sig)); ACE_OS::exit (0); } // Returns TRUE if the program was started by INETD. static int started_by_inetd (void) { sockaddr_in sin; int size = sizeof sin; return ACE_OS::getsockname (0, reinterpret_cast<sockaddr *> (&sin), &size) == 0; } // Does the drwho service. static void do_drwho (SMR_Server &smr_server) { if (smr_server.receive () == -1) ACE_ERROR ((LM_ERROR, "%p\n", Options::program_name)); if (smr_server.send () == -1) ACE_ERROR ((LM_ERROR, "%p\n", Options::program_name)); } // If the server is started with any argument at all then it doesn't // fork off a child process to do the work. This is useful when // debugging! int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { ACE_OS::signal (SIGTERM, (ACE_SignalHandler)exit_server); ACE_OS::signal (SIGINT, (ACE_SignalHandler)exit_server); ACE_OS::signal (SIGQUIT, (ACE_SignalHandler)exit_server); Options::set_options (argc, argv); Options::set_opt (Options::STAND_ALONE_SERVER); int inetd_controlled = started_by_inetd (); if (!inetd_controlled && Options::get_opt (Options::BE_A_DAEMON)) ACE::daemonize (); SMR_Server smr_server (Options::port_number); if (inetd_controlled) do_drwho (smr_server); else { for (;;) do_drwho (smr_server); /* NOTREACHED */ } return 0; }
true
59a06ff586eaae44b41c9c3b9bba28431f1c62d7
C++
sailzeng/zcelib
/src/commlib/zcelib/zce/string/format.cpp
UTF-8
22,213
2.578125
3
[ "Apache-2.0" ]
permissive
#include "zce/predefine.h" #include "zce/os_adapt/stdlib.h" #include "zce/string/format.h" #ifndef FMT_MIN #define FMT_MIN(a,b) (((a)<(b))?(a):(b)) #endif #ifndef FMT_MAX #define FMT_MAX(a,b) (((a)>(b))?(a):(b)) #endif //我为了追求速度,dopr_outch,将函数dopr_outch 改写成了宏, #ifndef FMT_DOPR_OUTCH #define FMT_DOPR_OUTCH(a,b,c,d) if (((b)) < (c)) \ (a)[((b))++] = d; #endif //static void dopr_outch(char *buffer, size_t &use_len, size_t max_len, char c) //{ // if (use_len < max_len) // { // buffer[(use_len)++] = c; // } //} //格式化double void zce::fmt_double(char* buffer, size_t max_len, size_t& use_len, double fvalue, size_t width, size_t precision, int flags) { //ZCE_ASSERT(buffer); buffer[0] = '\0'; use_len = 0; //对于参数进行检查, if (max_len == 0) { return; } //如果你不关注精度,将精度调整成6, if (precision == 0 || precision > 64) { precision = DEFAULT_DOUBLE_PRECISION; } //double的最大长度E308 const size_t LEN_OF_TMP_OUT_BUF = 512; char tmp_out_buf[LEN_OF_TMP_OUT_BUF + 1]; tmp_out_buf[LEN_OF_TMP_OUT_BUF] = '\0'; //输出要用的字符串 int decimal = 0, sign = 0; if (flags & FMT_EXPONENT) { //指数ecvt的精度是输出数字的长度,不是小数点的长度,所以会有precision + 1 zce::ecvt_r(fvalue, static_cast<int>(precision + 1), &decimal, &sign, tmp_out_buf, LEN_OF_TMP_OUT_BUF); } else { zce::fcvt_r(fvalue, static_cast<int>(precision), &decimal, &sign, tmp_out_buf, LEN_OF_TMP_OUT_BUF); } int cvt_str_len = static_cast<int>(strlen(tmp_out_buf)); if (cvt_str_len <= 0) { return; } //计算各种方式下的字符串空间,看对齐方式下还要增加多少个空格 //下面的部分数字应该用常量,但是我都解释了,不啰嗦了 int sign_len = 0; if (sign || flags & FMT_PLUS || flags & FMT_SPACE) { sign_len = 1; } int out_str_len = 0; if (flags & FMT_EXPONENT) { //7的来历是1.E+001,sign_len为符号位置占用的空间 out_str_len = static_cast<int>(7 + precision + sign_len); } else { //tmp_out_buf if (decimal > 0) { //1为小数点. out_str_len = 1 + cvt_str_len + sign_len; } else { //2为"0.", out_str_len = static_cast<int>(2 + precision + sign_len); } } //要填补的空格长度 int space_pad_len = static_cast<int>(width - out_str_len); //如果要右对齐, if (!(flags & FMT_LEFT_ALIGN) && space_pad_len > 0) { for (int i = 0; i < space_pad_len; i++) { FMT_DOPR_OUTCH(buffer, use_len, max_len, ' '); } } //取出符号,进行判断,//如果浮点小于0,填写负数标示 if (sign) { FMT_DOPR_OUTCH(buffer, use_len, max_len, '-'); } else if (flags & FMT_PLUS) { FMT_DOPR_OUTCH(buffer, use_len, max_len, '+'); } else if (flags & FMT_SPACE) { FMT_DOPR_OUTCH(buffer, use_len, max_len, ' '); } //用指数的方式输出 if (flags & FMT_EXPONENT) { //输出第一个数字和. FMT_DOPR_OUTCH(buffer, use_len, max_len, tmp_out_buf[0]); FMT_DOPR_OUTCH(buffer, use_len, max_len, '.'); //将小数部分输出 for (size_t i = 0; i < precision; ++i) { FMT_DOPR_OUTCH(buffer, use_len, max_len, tmp_out_buf[i + 1]); } //输出指数部分,根据大小写输出指数E if (flags & FMT_UP) { FMT_DOPR_OUTCH(buffer, use_len, max_len, 'E'); } else { FMT_DOPR_OUTCH(buffer, use_len, max_len, 'e'); } //下面这段代码即使snprintf(bufbuffer+use_len,max_len-use_len,"%+0.3d",decimal); //是我有点走火入魔,我这样写无非是希望加快一点点速度, //将指数输出,使用"%+0.3d"的格式 int i_exponent = decimal - 1; if (i_exponent >= 0) { FMT_DOPR_OUTCH(buffer, use_len, max_len, '+'); } else { FMT_DOPR_OUTCH(buffer, use_len, max_len, '-'); } //绝对值,因为我 int u_exponent = i_exponent >= 0 ? i_exponent : -i_exponent; int out_dec = 0; //输出百位 if (u_exponent >= 100) { out_dec = u_exponent / 100; u_exponent = u_exponent - out_dec * 100; FMT_DOPR_OUTCH(buffer, use_len, max_len, '0' + static_cast<char>(out_dec)); } //输出10位和个位 out_dec = 0; if (u_exponent >= 10) { out_dec = u_exponent / 10; u_exponent = u_exponent - out_dec * 10; FMT_DOPR_OUTCH(buffer, use_len, max_len, '0' + static_cast<char>(out_dec)); } FMT_DOPR_OUTCH(buffer, use_len, max_len, '0' + static_cast<char>(u_exponent)); } else { //整数和小数混合输出 if (decimal > 0) { //将整数部分输出 for (size_t i = 0; i < cvt_str_len - precision; ++i) { FMT_DOPR_OUTCH(buffer, use_len, max_len, tmp_out_buf[i]); } FMT_DOPR_OUTCH(buffer, use_len, max_len, '.'); //将小数部分输出 for (size_t i = 0; i < precision; ++i) { FMT_DOPR_OUTCH(buffer, use_len, max_len, tmp_out_buf[i + cvt_str_len - precision]); } } //纯小数输出 else { FMT_DOPR_OUTCH(buffer, use_len, max_len, '0'); FMT_DOPR_OUTCH(buffer, use_len, max_len, '.'); //补充好0 for (size_t i = 0; i < precision - cvt_str_len; ++i) { FMT_DOPR_OUTCH(buffer, use_len, max_len, '0'); } //将小数部分输出 for (int i = 0; i < cvt_str_len; ++i) { FMT_DOPR_OUTCH(buffer, use_len, max_len, tmp_out_buf[i]); } } } //如果要左对齐,在尾巴上补气空格 if ((flags & FMT_LEFT_ALIGN) && space_pad_len > 0) { for (int i = 0; i < space_pad_len; i++) { FMT_DOPR_OUTCH(buffer, use_len, max_len, ' '); } } } void zce::fmt_double(std::string& stdstr, double fvalue, size_t width, size_t precision, int flags) { //如果你不关注精度,将精度调整成6, if (precision == 0 || precision > 64) { precision = DEFAULT_DOUBLE_PRECISION; } //double的最大长度E308 const size_t LEN_OF_TMP_OUT_BUF = 512; char tmp_out_buf[LEN_OF_TMP_OUT_BUF + 1]; tmp_out_buf[LEN_OF_TMP_OUT_BUF] = '\0'; //输出要用的字符串 int decimal = 0, sign = 0; if (flags & FMT_EXPONENT) { //指数ecvt的精度是输出数字的长度,不是小数点的长度,所以会有precision + 1 zce::ecvt_r(fvalue, static_cast<int>(precision + 1), &decimal, &sign, tmp_out_buf, LEN_OF_TMP_OUT_BUF); } else { zce::fcvt_r(fvalue, static_cast<int>(precision), &decimal, &sign, tmp_out_buf, LEN_OF_TMP_OUT_BUF); } int cvt_str_len = static_cast<int>(strlen(tmp_out_buf)); if (cvt_str_len <= 0) { return; } //计算各种方式下的字符串空间,看对齐方式下还要增加多少个空格 //下面的部分数字应该用常量,但是我都解释了,不啰嗦了 int sign_len = 0; if (sign || flags & FMT_PLUS || flags & FMT_SPACE) { sign_len = 1; } int out_str_len = 0; if (flags & FMT_EXPONENT) { //7的来历是1.E+001,sign_len为符号位置占用的空间 out_str_len = static_cast<int>(7 + precision + sign_len); } else { //tmp_out_buf if (decimal > 0) { //1为小数点. out_str_len = 1 + cvt_str_len + sign_len; } else { //2为"0.", out_str_len = static_cast<int>(2 + precision + sign_len); } } //要填补的空格长度 int space_pad_len = static_cast<int>(width - out_str_len); //如果要右对齐, if (!(flags & FMT_LEFT_ALIGN) && space_pad_len > 0) { stdstr.append(space_pad_len, ' '); } //取出符号,进行判断,//如果浮点小于0,填写负数标示 if (sign) { stdstr.append(1, '-'); } else if (flags & FMT_PLUS) { stdstr.append(1, '+'); } else if (flags & FMT_SPACE) { stdstr.append(1, ' '); } //用指数的方式输出 if (flags & FMT_EXPONENT) { //输出第一个数字和. stdstr.append(1, tmp_out_buf[0]); stdstr.append(1, '.'); //将小数部分输出 for (size_t i = 0; i < precision; ++i) { stdstr.append(1, tmp_out_buf[i + 1]); } //输出指数部分,根据大小写输出指数E if (flags & FMT_UP) { stdstr.append(1, 'E'); } else { stdstr.append(1, 'e'); } //下面这段代码即使snprintf(bufbuffer+use_len,max_len-use_len,"%+0.3d",decimal); //是我有点走火入魔,我这样写无非是希望加快一点点速度, //将指数输出,使用"%+0.3d"的格式 int i_exponent = decimal - 1; if (i_exponent >= 0) { stdstr.append(1, '+'); } else { stdstr.append(1, '-'); } //绝对值,因为我 int u_exponent = i_exponent >= 0 ? i_exponent : -i_exponent; int out_dec = 0; //输出百位 if (u_exponent >= 100) { out_dec = u_exponent / 100; u_exponent = u_exponent - out_dec * 100; stdstr.append(1, '0' + static_cast<char>(out_dec)); } //输出10位和个位 out_dec = 0; if (u_exponent >= 10) { out_dec = u_exponent / 10; u_exponent = u_exponent - out_dec * 10; stdstr.append(1, '0' + static_cast<char>(out_dec)); } stdstr.append(1, '0' + static_cast<char>(u_exponent)); } else { //整数和小数混合输出 if (decimal > 0) { //将整数部分输出 for (size_t i = 0; i < cvt_str_len - precision; ++i) { stdstr.append(1, tmp_out_buf[i]); } stdstr.append(1, '.'); //将小数部分输出 for (size_t i = 0; i < precision; ++i) { stdstr.append(1, tmp_out_buf[i + cvt_str_len - precision]); } } //纯小数输出 else { stdstr.append(1, '0'); stdstr.append(1, '.'); //补充好0 for (size_t i = 0; i < precision - cvt_str_len; ++i) { stdstr.append(1, '0'); } //将小数部分输出 for (int i = 0; i < cvt_str_len; ++i) { stdstr.append(1, tmp_out_buf[i]); } } } //如果要左对齐,在尾巴上补气空格 if ((flags & FMT_LEFT_ALIGN) && space_pad_len > 0) { stdstr.append(space_pad_len, ' '); } } //-------------------------------------------------------------------------------------------------------------------- //用于int64的格式化输出,注意这个函数在BUFFER末尾不添加\0,从BSD的openssh snprintf代码移植 void zce::fmt_int64(char* buffer, size_t max_len, size_t& use_len, int64_t value, BASE_NUMBER base, size_t width, size_t precision, int flags) { use_len = 0; if (0 == max_len) { return; } uint64_t uvalue = value; const size_t MAX_OUT_LEN = 64; char convert[MAX_OUT_LEN + 1]; convert[MAX_OUT_LEN] = '\0'; int signvalue = 0; size_t place = 0; // amount to space pad int space_pad_len = 0; // amount to zero pad int zero_pad_len = 0; //0x,或者0前缀的长度,#标识时使用 int prefix_len = 0; //对符号位置进行处理 if (!(flags & FMT_UNSIGNED)) { if (value < 0) { signvalue = '-'; uvalue = -value; } // Do a sign (+/i) else if (flags & FMT_PLUS) { signvalue = '+'; } else if (flags & FMT_SPACE) { signvalue = ' '; } } //如果要添加0x之类的前缀 if (flags & FMT_PREFIX) { if (BASE_NUMBER::HEXADECIMAL == base) { prefix_len = 2; } if (BASE_NUMBER::OCTAL == base) { prefix_len = 1; } } const char BASE_UPPERCASE_OUTCHAR[] = { "0123456789ABCDEF" }; const char BASE_LOWERCASE_OUTCHAR[] = { "0123456789abcdef" }; //如果是大写,16进制的转换全部用大写 const char* use_char_ary = BASE_LOWERCASE_OUTCHAR; if (flags & FMT_UP) { use_char_ary = BASE_UPPERCASE_OUTCHAR; } do { convert[place++] = use_char_ary[uvalue % static_cast<int>(base)]; uvalue = (uvalue / static_cast<int>(base)); } while (uvalue && (place < MAX_OUT_LEN)); //计算要填补多少0或者空格 zero_pad_len = static_cast<int>(precision - place); space_pad_len = static_cast<int>(width - FMT_MAX(precision, place) - (signvalue ? 1 : 0) - prefix_len); //如果精度空间有多的,但是没有要求填写0,那么仍然填写' ' if (flags & FMT_ZERO) { if (zero_pad_len < 0) { zero_pad_len = 0; } zero_pad_len += space_pad_len; space_pad_len = 0; } //右对齐填补空格 if (!(flags & FMT_LEFT_ALIGN) && space_pad_len > 0) { for (int i = 0; i < space_pad_len; i++) { FMT_DOPR_OUTCH(buffer, use_len, max_len, ' '); } } //填补符号 if (signvalue) { FMT_DOPR_OUTCH(buffer, use_len, max_len, static_cast<char>(signvalue)); } if (flags & FMT_PREFIX) { //十六进制添加0x if (BASE_NUMBER::HEXADECIMAL == base) { FMT_DOPR_OUTCH(buffer, use_len, max_len, '0'); if (flags & FMT_UP) { FMT_DOPR_OUTCH(buffer, use_len, max_len, 'X'); } else { FMT_DOPR_OUTCH(buffer, use_len, max_len, 'x'); } } //8进制添加0 if (BASE_NUMBER::OCTAL == base) { FMT_DOPR_OUTCH(buffer, use_len, max_len, '0'); } } //在精度范围输出0,如果没有0标识符号,填写' ' if (zero_pad_len > 0) { for (int i = 0; i < zero_pad_len; i++) { FMT_DOPR_OUTCH(buffer, use_len, max_len, '0'); } } //输出数字 while (place > 0) { --place; FMT_DOPR_OUTCH(buffer, use_len, max_len, convert[place]); } //左对齐,在末尾添加空格 if ((flags & FMT_LEFT_ALIGN) && space_pad_len > 0) { for (int i = 0; i < space_pad_len; i++) { FMT_DOPR_OUTCH(buffer, use_len, max_len, ' '); } } } void zce::fmt_int64(std::string& stdstr, int64_t value, BASE_NUMBER base, size_t width, size_t precision, int flags) { uint64_t uvalue = value; const size_t MAX_OUT_LEN = 64; char convert[MAX_OUT_LEN + 1]; convert[MAX_OUT_LEN] = '\0'; char signvalue = 0; size_t place = 0; // amount to space pad int space_pad_len = 0; // amount to zero pad int zero_pad_len = 0; //0x,或者0前缀的长度,#标识时使用 int prefix_len = 0; //对符号位置进行处理 if (!(flags & FMT_UNSIGNED)) { if (value < 0) { signvalue = '-'; uvalue = -value; } // Do a sign (+/i) else if (flags & FMT_PLUS) { signvalue = '+'; } else if (flags & FMT_SPACE) { signvalue = ' '; } } //如果要添加0x之类的前缀 if (flags & FMT_PREFIX) { if (BASE_NUMBER::HEXADECIMAL == base) { prefix_len = 2; } if (BASE_NUMBER::OCTAL == base) { prefix_len = 1; } } const char BASE_UPPERCASE_OUTCHAR[] = { "0123456789ABCDEF" }; const char BASE_LOWERCASE_OUTCHAR[] = { "0123456789abcdef" }; //如果是大写,16进制的转换全部用大写 const char* use_char_ary = BASE_LOWERCASE_OUTCHAR; if (flags & FMT_UP) { use_char_ary = BASE_UPPERCASE_OUTCHAR; } //注意得到的字符串是反转的 do { convert[place++] = use_char_ary[uvalue % static_cast<int>(base)]; uvalue = (uvalue / static_cast<int>(base)); } while (uvalue && (place < MAX_OUT_LEN)); //计算要填补多少0或者空格 zero_pad_len = static_cast<int>(precision - place); space_pad_len = static_cast<int>(width - FMT_MAX(precision, place) - (signvalue ? 1 : 0) - prefix_len); //如果精度空间有多的,但是没有要求填写0,那么仍然填写' ' if (flags & FMT_ZERO) { if (zero_pad_len < 0) { zero_pad_len = 0; } zero_pad_len += space_pad_len; space_pad_len = 0; } //右对齐填补空格 if (!(flags & FMT_LEFT_ALIGN) && space_pad_len > 0) { stdstr.append(space_pad_len, ' '); } //填补符号 if (signvalue) { stdstr.append(1, signvalue); } if (flags & FMT_PREFIX) { //十六进制添加0x if (BASE_NUMBER::HEXADECIMAL == base) { stdstr.append(1, '0'); if (flags & FMT_UP) { stdstr.append(1, 'X'); } else { stdstr.append(1, 'x'); } } //8进制添加0 if (BASE_NUMBER::OCTAL == base) { stdstr.append(1, '0'); } } //在精度范围输出0,如果没有0标识符号,填写' ' if (zero_pad_len > 0) { stdstr.append(zero_pad_len, '0'); } //输出数字 while (place > 0) { --place; stdstr.append(1, convert[place]); } //左对齐,在末尾添加空格 if ((flags & FMT_LEFT_ALIGN) && space_pad_len > 0) { stdstr.append(space_pad_len, ' '); } } //-------------------------------------------------------------------------------------------------------------------- //用于字符串的格式化输出,注意这个函数末尾不添加\0 void zce::fmt_str(char* buffer, size_t max_len, size_t& use_len, const char* value, size_t str_len, size_t width, size_t precision, int flags) { use_len = 0; //不用处理的参数的情况 if (0 == max_len || (0 == width && 0 == precision)) { return; } //对参数进行整理 if (value == nullptr) { value = "<nullptr>"; str_len = 6; } size_t out_len = FMT_MIN(str_len, precision); //输出的空格数量 int space_pad_len = static_cast<int>(width - out_len); //右对齐填补空格(非左对齐) if (!(flags & FMT_LEFT_ALIGN) && space_pad_len > 0) { for (int i = 0; i < space_pad_len; i++) { FMT_DOPR_OUTCH(buffer, use_len, max_len, ' '); } } size_t copy_len = FMT_MIN(out_len, max_len); memcpy(buffer + use_len, value, copy_len); use_len += copy_len; max_len -= copy_len; /*while (out_cnt < out_len) { FMT_DOPR_OUTCH(buffer, use_len, max_len, *value++); ++out_cnt; }*/ //左对齐,在末尾添加空格 if ((flags & FMT_LEFT_ALIGN) && space_pad_len > 0) { for (int i = 0; i < space_pad_len; i++) { FMT_DOPR_OUTCH(buffer, use_len, max_len, ' '); } } } void zce::fmt_str(std::string& stdstr, const char* value, size_t str_len, size_t width, size_t precision, int flags) { //不用处理的参数的情况 if (0 == width && 0 == precision) { return; } //对参数进行整理 if (value == 0) { value = "<nullptr>"; str_len = 6; } size_t out_len = FMT_MIN(str_len, precision); //输出的空格数量 int space_pad_len = static_cast<int>(width - out_len); //右对齐填补空格(非左对齐) if (!(flags & FMT_LEFT_ALIGN) && space_pad_len > 0) { stdstr.append(space_pad_len, ' '); } stdstr.append(value, out_len); //左对齐,在末尾添加空格 if ((flags & FMT_LEFT_ALIGN) && space_pad_len > 0) { stdstr.append(space_pad_len, ' '); } }
true
7404e8fd586f523872c057887abb5ec44ef2adca
C++
sofian/UM7-Arduino
/UM7.cpp
UTF-8
3,423
2.734375
3
[]
no_license
#include "UM7.h" #define DREG_QUAT_AB 0x6D // Packet address sent from the UM7 that contains quaternion values. #define DREG_EULER_PHI_THETA 0x70 // Packet address sent from the UM7 that contains roll,pitch,yaw and rates. #define DD 91.02222 // divider for degrees #define DR 16.0 // divider for rate #define DQ 29789.09091 // divider for quaternion element UM7::UM7() : state(STATE_ZERO){} // Default constructor bool UM7::encode(byte c){ switch(state){ case STATE_ZERO: if (c == 's'){ state = STATE_S; // Entering state S from state Zero } else { state = STATE_ZERO; } return false; case STATE_S: if (c == 'n'){ state = STATE_SN; // Entering state SN from state S } else { state = STATE_ZERO; } return false; case STATE_SN: if (c == 'p'){ state = STATE_SNP; // Entering state SNP from state SN. Packet header detected. } else { state = STATE_ZERO; } return false; case STATE_SNP: state = STATE_PT; // Entering state PT from state SNP. Decode packet type. packet_type = c; packet_has_data = (packet_type >> 7) & 0x01; packet_is_batch = (packet_type >> 6) & 0x01; batch_length = (packet_type >> 2) & 0x0F; if (packet_has_data){ if (packet_is_batch){ data_length = 4 * batch_length; // Each data packet is 4 bytes long } else { data_length = 4; } } else { data_length = 0; } return false; case STATE_PT: state = STATE_DATA; // Next state will be READ_DATA. Save address to memory. (eg 0x70 for a DREG_EULER_PHI_THETA packet) address = c; data_index = 0; return false; case STATE_DATA: // Entering state READ_DATA. Stay in state until all data is read. data[data_index] = c; data_index++; if (data_index >= data_length){ state = STATE_CHK1; // Data read completed. Next state will be CHK1 } return false; case STATE_CHK1: // Entering state CHK1. Next state will be CHK0 state = STATE_CHK0; checksum1 = c; return false; case STATE_CHK0: state = STATE_ZERO; // Entering state CHK0. Next state will be state Zero. checksum0 = c; return checksum(); } } bool UM7::checksum(){ checksum10 = checksum1 << 8; // Combine checksum1 and checksum0 checksum10 |= checksum0; computed_checksum = 's' + 'n' + 'p' + packet_type + address; for (int i = 0; i < data_length; i++){ computed_checksum += data[i]; } if (checksum10 == computed_checksum){ save(); return true; } else { return false; } } void UM7::save(){ init_read(); switch(address){ case DREG_QUAT_AB : if(packet_is_batch){ next_short(&_qa); next_short(&_qb); next_short(&_qc); next_short(&_qd); }else{ next_short(&_qa); next_short(&_qb); } break; case DREG_EULER_PHI_THETA : // data[6] and data[7] are unused. if(packet_is_batch){ next_short(&_roll); next_short(&_pitch); next_short(&_yaw); short unused; next_short(&unused); next_short(&_roll_rate); next_short(&_pitch_rate); next_short(&_yaw_rate); }else{ next_short(&_roll); next_short(&_pitch); } break; } } void UM7::init_read() { read_index = 0; } void UM7::next_short(short* dst) { *dst = (data[read_index++] << 8) | data[read_index++]; } float UM7::convert_degree(short deg) { return deg / DD; } float UM7::convert_rate(short rate) { return rate / DR; } float UM7::convert_quat(short quat) { return quat / DQ; }
true
cd213641ab06617ed3202f224f08a5aad7028273
C++
jackyhkust/OpenCV31-DemoVideoPlayer
/Frame.cpp
UTF-8
10,439
2.796875
3
[]
no_license
#include "Frame.h" #include "matMsgBox.h" #include <array> #include <cstdlib> using namespace std; Frame::Frame(){ } Frame::Frame(const cv::Mat& src) { src.copyTo(*this); } Frame::~Frame() { } //get Histogram data in vector form vector<Mat> Frame::getHistVec(int iOutputChannel = RGB) { Mat channelPlanes[3]; bool uniform = true; bool accumulate = false; vector<Mat> outHist; //spliting part //RGB channel1:B, Channel2:G,Channel3:R if (iOutputChannel == RGB) { int histSize = 256; float range[] = { 0, 256 }; const float* histRange = { range }; split(*this, channelPlanes); Mat b_hist, g_hist, r_hist; calcHist(&channelPlanes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate); calcHist(&channelPlanes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate); calcHist(&channelPlanes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate); outHist = vector<Mat>{ b_hist, g_hist, r_hist }; } else if (iOutputChannel == HSV) { cv::Mat hsvImage; cv::cvtColor(*this, hsvImage, COLOR_BGR2HSV); split(hsvImage, channelPlanes); Mat h_hist, s_hist, v_hist; int histSizeH = 180; int histSizeS = 100; int histSizeV = 100; float rangeH[] = { 0, histSizeH }; float rangeS[] = { 0, histSizeS }; float rangeV[] = { 0, histSizeV }; const float* histRangeH = { rangeH }; const float* histRangeS = { rangeS }; const float* histRangeV = { rangeV }; calcHist(&channelPlanes[0], 1, 0, Mat(), h_hist, 1, &histSizeH, &histRangeH, uniform, accumulate); calcHist(&channelPlanes[1], 1, 0, Mat(), s_hist, 1, &histSizeS, &histRangeS, uniform, accumulate); calcHist(&channelPlanes[2], 1, 0, Mat(), v_hist, 1, &histSizeV, &histRangeV, uniform, accumulate); outHist = vector<Mat>{ h_hist, s_hist, v_hist }; } else { cout << "Wrong iOutputChannel" << endl; } return outHist; } //get the image of info box cv::Mat Frame::getInfoMat(MatMsgBox& infoTemp) { int oriRow = this->rows; int oriCol = this->cols; Mat histRGB = this->getHistMat(RGB, oriCol / 2, oriRow / 3); Mat outputFrame = Mat::zeros(oriRow + 10, oriCol + histRGB.cols + 10, this->type()); Mat histHSV = this->getHistMat(HSV, oriCol / 2, oriRow / 3); this->copyTo(outputFrame(Range(0, oriRow), Range(0, oriCol))); histRGB.copyTo(outputFrame(Range(0, histRGB.rows), Range(oriCol, oriCol + histRGB.cols))); histHSV.copyTo(outputFrame(Range(histRGB.rows, histRGB.rows + histHSV.rows), Range(oriCol, oriCol + histHSV.cols))); infoTemp.copyTo(outputFrame(Range(histRGB.rows + histHSV.rows, histRGB.rows + histHSV.rows + infoTemp.rows), Range(oriCol, oriCol + infoTemp.cols))); return outputFrame; return cv::Mat(); } //get image of histograms Mat Frame::getHistMat(int iOutputChannel = RGB,int hist_w = 512, int hist_h = 400){ Mat ch0, ch1, ch2; vector<cv::Mat>histTest = getHistVec(iOutputChannel); ch0 = histTest[0]; ch1 = histTest[1]; ch2 = histTest[2]; Mat histImage(hist_h, hist_w, CV_8UC3, Scalar(0, 0, 0)); ///// Normalize the result to [ 0, histImage.rows ] normalize(ch0, ch0, 0, histImage.rows, NORM_MINMAX, -1, Mat()); normalize(ch1, ch1, 0, histImage.rows, NORM_MINMAX, -1, Mat()); normalize(ch2, ch2, 0, histImage.rows, NORM_MINMAX, -1, Mat()); if (iOutputChannel == RGB){ /// Establish the number of bins int histSize = 256; // Draw the histograms for B, G and R int binRGB_w = cvRound((double)hist_w / histSize); ///// Draw for each channel for (int i = 1; i < histSize; i++) { line(histImage, Point(binRGB_w*(i - 1), hist_h - cvRound(ch0.at<float>(i - 1))), Point(binRGB_w*(i), hist_h - cvRound(ch0.at<float>(i))), Scalar(255, 0, 0), 2, 8, 0); line(histImage, Point(binRGB_w*(i - 1), hist_h - cvRound(ch1.at<float>(i - 1))), Point(binRGB_w*(i), hist_h - cvRound(ch1.at<float>(i))), Scalar(0, 255, 0), 2, 8, 0); line(histImage, Point(binRGB_w*(i - 1), hist_h - cvRound(ch2.at<float>(i - 1))), Point(binRGB_w*(i), hist_h - cvRound(ch2.at<float>(i))), Scalar(0, 0, 255), 2, 8, 0); } } else if (iOutputChannel == HSV){ int histSizeH = 180; int histSizeS = 100; int histSizeV = 100; // Draw the histograms for B, G and R int binH_w = cvRound((double)hist_w / histSizeH); int binS_w = cvRound((double)hist_w / histSizeS); int binV_w = cvRound((double)hist_w / histSizeV); for (int i = 1; i < histSizeH; i++) { line(histImage, Point(binH_w*(i - 1), hist_h - cvRound(ch0.at<float>(i - 1))), Point(binH_w*(i), hist_h - cvRound(ch0.at<float>(i))), Scalar(255, 0, 0), 2, 8, 0); } for (int i = 1; i < histSizeS; i++) { line(histImage, Point(binS_w*(i - 1), hist_h - cvRound(ch1.at<float>(i - 1))), Point(binS_w*(i), hist_h - cvRound(ch1.at<float>(i))), Scalar(0, 255, 0), 2, 8, 0); } for (int i = 1; i < histSizeV; i++) { line(histImage, Point(binV_w*(i - 1), hist_h - cvRound(ch2.at<float>(i - 1))), Point(binV_w*(i), hist_h - cvRound(ch2.at<float>(i))), Scalar(0, 0, 255), 2, 8, 0); } } return histImage; } void Frame::showHist(int iOutputChannel = RGB,int hist_w = 512, int hist_h = 400) { //get the image of hist Mat histImage(hist_h, hist_w, CV_8UC3, Scalar(0, 0, 0)); histImage=getHistMat(iOutputChannel,hist_w,hist_h); //put them on windows if (iOutputChannel == RGB){ namedWindow("HistRGB", WINDOW_AUTOSIZE); imshow("HistRGB", histImage); } else if (iOutputChannel == HSV){ namedWindow("HistHSV", WINDOW_AUTOSIZE); imshow("HistHSV", histImage); } } float Frame::chMean(int channelNo,int iOutputChannel=RGB){ //calculate the mean of a channel Vec4d meanArr,stddevArr; if(iOutputChannel==RGB){ cv::meanStdDev(*this,meanArr,stddevArr); }else if(iOutputChannel==HSV){ Mat tempHSV; cv::cvtColor(*this,tempHSV,COLOR_BGR2HSV); cv::meanStdDev(tempHSV,meanArr,stddevArr); } return meanArr[channelNo]; } float Frame::chSD(int channelNo,int iOutputChannel=RGB){ //calculate the SD of a channel Vec4d meanArr,stddevArr; if(iOutputChannel==RGB){ cv::meanStdDev(*this,meanArr,stddevArr); }else if(iOutputChannel==HSV){ Mat tempHSV; cv::cvtColor(*this,tempHSV,COLOR_BGR2HSV); cv::meanStdDev(tempHSV,meanArr,stddevArr); } return stddevArr[channelNo]; } //a handy transfromation from hue to RGB color, satuation and value are preseted Scalar Frame::hueConvert(float hue) { Mat hsvColor(1, 1, CV_8UC3, Scalar(hue, 255, 255)); Mat rgbColor(1, 1, CV_8UC3, Scalar(0, 0, 255)); cvtColor(hsvColor, rgbColor, COLOR_HSV2BGR); Scalar finalColor = Scalar(rgbColor.data[0, 0, 0], rgbColor.data[0, 0, 1], rgbColor.data[0, 0, 2], 255); return finalColor; } vector<float> Frame::dominantColorHue(){ cv::Mat hsvImage; Size small(this->rows/64,this->cols/64); Mat smallImg; //we scale the image to a smaller one to reduce processing time cv::pyrDown(*this, smallImg); cv::pyrDown(smallImg, smallImg); cv::pyrDown(smallImg, smallImg); cv::pyrDown(smallImg, smallImg); cv::pyrDown(smallImg, smallImg); cv::cvtColor(smallImg, hsvImage, COLOR_BGR2HSV); Mat channelPlanes[3]; split(hsvImage, channelPlanes); Mat hueImage=channelPlanes[0]; Mat p=Mat::zeros(hueImage.rows*hueImage.cols, 1, CV_32F); hueImage.convertTo(p,CV_32F); Mat labels; Mat centers; kmeans(p, 3, labels,TermCriteria( TermCriteria::EPS+TermCriteria::COUNT, 5, 2.0),3, KMEANS_PP_CENTERS, centers); //output the cluster centers to vector vector<float> output{ centers.at<float>(0), centers.at<float>(1),centers.at<float>(2) }; return output; } //using the MatMsgBox to build a image for infobox MatMsgBox Frame::getInfoBoxMat(int h, int w, int rh, double font){ Scalar blackBackground = Scalar::all(0); MatMsgBox infoBox(h, w, blackBackground); infoBox.setRowHeight(rh); infoBox.setFontSize(font); infoBox.addString("R Mean: " + std::to_string(chMean(2)) + " SD: " + std::to_string(chSD(2)), Scalar::all(255)); infoBox.addString("G Mean: " + std::to_string(chMean(1)) + " SD: " + std::to_string(chSD(1)), Scalar::all(255)); infoBox.addString("B Mean: " + std::to_string(chMean(0)) + " SD: " + std::to_string(chSD(0)), Scalar::all(255)); infoBox.addString("H Mean: " + std::to_string(chMean(0, HSV)) + " SD: " + std::to_string(chSD(0, HSV)), Scalar::all(255)); infoBox.addString("S Mean: " + std::to_string(chMean(1, HSV)) + " SD: " + std::to_string(chSD(1, HSV)), Scalar::all(255)); infoBox.addString("V Mean: " + std::to_string(chMean(2, HSV)) + " SD: " + std::to_string(chSD(2, HSV)), Scalar::all(255)); vector<float>domHue = dominantColorHue(); float domHue1 = domHue[0]; float domHue2 = domHue[1]; float domHue3 = domHue[2]; string strhueCluster1 = "Hue Cluster 1:" + std::to_string(domHue1); string strhueCluster2 = "Hue Cluster 2:" + std::to_string(domHue2); string strhueCluster3 = "Hue Cluster 3:" + std::to_string(domHue3); Scalar finalColor1 = hueConvert(domHue1); Scalar finalColor2 = hueConvert(domHue2); Scalar finalColor3 = hueConvert(domHue3); infoBox.addString(strhueCluster1, finalColor1); infoBox.addString(strhueCluster2, finalColor2); infoBox.addString(strhueCluster3, finalColor3); return infoBox; } void Frame::updateInfoMat() { //update the infobox MatMsgBox infoBox = getInfoBoxMat(300, 400, 20, 0.5); infoBox.setWindowName("InfoBox1"); infoBox.update(); } //update the info box with windowanme input void Frame::updateInfoMat(string input) { MatMsgBox infoBox = getInfoBoxMat(300, 400, 20, 0.5); infoBox.setWindowName(input); infoBox.update(); } //get an image with the frame and all relavent information and histogram cv::Mat Frame::getInfoMat(){ int oriRow=this->rows; int oriCol=this->cols; Mat histRGB=this->getHistMat(RGB,oriCol/2,oriRow/3); MatMsgBox infoBoxMat = getInfoBoxMat(oriRow/3,histRGB.cols, 20, 0.5); Mat outputFrame= Mat::zeros(oriRow+10,oriCol+histRGB.cols+10,this->type()); Mat histHSV=this->getHistMat(HSV,oriCol/2,oriRow/3); this->copyTo(outputFrame(Range(0,oriRow),Range(0,oriCol))); histRGB.copyTo(outputFrame(Range(0,histRGB.rows),Range(oriCol,oriCol+histRGB.cols))); histHSV.copyTo(outputFrame(Range(histRGB.rows,histRGB.rows+histHSV.rows),Range(oriCol,oriCol+histHSV.cols))); infoBoxMat.copyTo(outputFrame(Range(histRGB.rows + histHSV.rows, histRGB.rows + histHSV.rows+infoBoxMat.rows), Range(oriCol, oriCol + infoBoxMat.cols))); return outputFrame; }
true