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
a2afd2d20d5b7569f2da46df0055086f79b62ce3
C++
takumus/trump
/src/display/display.h
UTF-8
669
2.53125
3
[]
no_license
#ifndef _JP_TACM_DISPLAY #define _JP_TACM_DISPLAY #include "sprite.h" #include <string> using namespace std; class Display{ public: void setup(int width, int height, char background); void clear(); void render(); void draw(Sprite* s); void mask(Sprite* s); void repeatBackground(Sprite* s); int getWidth(); int getHeight(); private: string _data; string _maskData; int _width, _height; char _background; bool _maskMode = false; bool _masked = false; void _draw(Sprite* s, double px, double py); void _mask(); void setDot(int x, int y, char c); void setDots(double x, double y, string data, int w, int h, bool transparent, double scale); }; #endif
true
6e3245ccb82a94412d69014b9ce5139f9dc8e002
C++
stdstring/leetcode
/Algorithms/Tasks.0501.1000/0525.ContiguousArray/solution.cpp
UTF-8
1,742
3.21875
3
[ "MIT" ]
permissive
#include <algorithm> #include <unordered_map> #include <vector> #include "gtest/gtest.h" namespace { class Solution { public: [[nodiscard]] int findMaxLength(std::vector<int> const &nums) const { size_t maxSubarrayLength = 0; std::unordered_map<int, size_t> prefixBalanceMap; int balance = 0; for (size_t index = 0; index < nums.size(); ++index) { balance += (nums[index] == 0 ? -1 : 1); auto iterator = prefixBalanceMap.find(balance); if (iterator == prefixBalanceMap.end()) prefixBalanceMap.emplace(balance, index); else maxSubarrayLength = std::max(maxSubarrayLength, index - iterator->second); if (balance == 0) maxSubarrayLength = index + 1; } return static_cast<int>(maxSubarrayLength); } }; } namespace ContiguousArrayTask { TEST(ContiguousArrayTaskTests, Examples) { const Solution solution; ASSERT_EQ(2, solution.findMaxLength({0, 1})); ASSERT_EQ(2, solution.findMaxLength({0, 1, 0})); } TEST(ContiguousArrayTaskTests, FromWrongAnswers) { const Solution solution; ASSERT_EQ(2, solution.findMaxLength({0, 1, 1})); ASSERT_EQ(68, solution.findMaxLength({0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1})); } }
true
85d376083d2cfef06fba7e326ec0811e2a721c66
C++
ArpitSingla/Advance-Data-Structures
/AVL.cpp
UTF-8
4,116
3.53125
4
[]
no_license
#include<iostream> #define ll long long using namespace std; struct node{ ll info; node *left,*right; ll height; }; ll height(node *n){ if(n==NULL){ return 0; } else{ ll ldepth=height(n->left); ll rdepth=height(n->right); return max(ldepth,rdepth)+1; } } ll balanceFactor(node *n){ if(n==NULL){ return 0; } return height(n->left)-height(n->right); } node *newNode(ll info){ node *temp=new node(); temp->info=info; temp->left=NULL; temp->right=NULL; temp->height=1; return temp; } node *leftRotate(node *root){ node *temp; temp=root->right; root->right=temp->left; temp->left=root; temp->height=1+max(height(temp->left),height(temp->right)); root->height=1+max(height(root->left),height(root->right)); return temp; } node *rightRotate(node *root){ node *temp; temp=root->left; root->left=temp->right; temp->right=root; temp->height=1+max(height(temp->left),height(temp->right)); root->height=1+max(height(root->left),height(root->right)); return temp; } node *insertNode(node *root,ll info){ if(root==NULL){ return newNode(info); } if(info<root->info){ root->left=insertNode(root->left,info); } else if(info>root->info){ root->right=insertNode(root->right,info); } else{ return root; } root->height=1+max(height(root->right),height(root->left)); ll balance=balanceFactor(root); if(balance>1 && info<root->left->info){ cout<<root->info<<endl; return rightRotate(root); } else if(balance<-1 && info>root->right->info){ cout<<root->info<<endl; return leftRotate(root); } else if(balance>1 && info>root->left->info){ cout<<root->info<<endl; root->left=leftRotate(root->left); return rightRotate(root); } else if(balance<-1 && info<root->right->info){ cout<<root->info<<endl; root->right=rightRotate(root->right); return leftRotate(root); } return root; } node* inOrderSuccessor(node* root) { node* current = root; while(current->left != NULL) { current = current->left; } return current; } node *deleteNode(node *root,ll info){ node *temp; if(root==NULL){ return 0; } if(info<root->info){ root->left=deleteNode(root->left,info); } else if(info>root->info){ root->right=deleteNode(root->right,info); } else{ if(root->left==NULL || root->right==NULL){ temp=root; if(root->left==NULL){ root=root->right; } else if(root->right==NULL){ root=root->left; } delete(temp); } else{ node *temp=inOrderSuccessor(root->right); root->info=temp->info; root->right=deleteNode(root->right,temp->info); } } if(root==NULL){ return root; } root->height=1+max(height(root->left),height(root->right)); ll balance=balanceFactor(root); if(balance > 1 && balanceFactor(root->left) < 0) { cout<<root->info<<'\n'; root->left = leftRotate(root->left); return rightRotate(root); } else if(balance > 1 && balanceFactor(root->left) >= 0) { cout<<root->info<<'\n'; return rightRotate(root); } else if(balance < -1 && balanceFactor(root->right) > 0) { cout<<root->info<<'\n'; root->right = rightRotate(root->right); return leftRotate(root); } else if(balance < -1 && balanceFactor(root->right) <= 0) { cout<<root->info<<'\n'; return leftRotate(root); } return root; } void inOrder(node *n){ if(n!=NULL){ inOrder(n->left); cout<<n->info<<" "; inOrder(n->right); } } void preOrder(node *n){ if(n!=NULL){ cout<<n->info<<" "; preOrder(n->left); preOrder(n->right); } } void postOrder(node *n){ if(n!=NULL){ postOrder(n->left); postOrder(n->right); cout<<n->info<<" "; } } int main(){ long long n; cin>>n; node* root = NULL; while(n--){ char c; long long a; cin>>c>>a; if (c == 'i'){ root = insertNode(root,a); } else if (c == 'd'){ root = deleteNode(root,a); } } preOrder(root); cout<<endl; inOrder(root); cout<<endl; postOrder(root); }
true
ec6e22e1e9a40da6119a8457b7aff03dd16482f9
C++
zeos/signalflow
/source/src/node/processors/delays/comb.cpp
UTF-8
1,380
2.609375
3
[ "MIT" ]
permissive
#include "signalflow/node/oscillators/constant.h" #include "signalflow/node/processors/delays/comb.h" #include <stdlib.h> namespace signalflow { CombDelay::CombDelay(NodeRef input, NodeRef delay_time, NodeRef feedback, float max_delay_time) : UnaryOpNode(input), delay_time(delay_time), feedback(feedback) { this->name = "comb-delay"; this->create_input("delay_time", this->delay_time); this->create_input("feedback", this->feedback); SIGNALFLOW_CHECK_GRAPH(); for (int i = 0; i < SIGNALFLOW_MAX_CHANNELS; i++) { buffers.push_back(new SampleRingBuffer(max_delay_time * this->graph->get_sample_rate())); } } CombDelay::~CombDelay() { for (auto buffer : buffers) { delete buffer; } } void CombDelay::process(Buffer &out, int num_frames) { SIGNALFLOW_CHECK_GRAPH(); for (int channel = 0; channel < this->num_input_channels; channel++) { for (int frame = 0; frame < num_frames; frame++) { sample delay = this->delay_time->out[channel][frame]; sample feedback = this->feedback->out[channel][frame]; float offset = delay * this->graph->get_sample_rate(); sample rv = input->out[channel][frame] + (feedback * buffers[channel]->get(-offset)); out[channel][frame] = rv; buffers[channel]->append(rv); } } } }
true
bb00e723024d11a3b63a5df414c4641e01ebd930
C++
idtoto2001/Kinect-finger-tracking-library
/candescentport/candescentport/HandTracking/FingerPointDetector.cpp
UTF-8
3,581
2.9375
3
[]
no_license
#include "FingerPointDetector.h" #include "LineThinner.h" #include "../pointfnc.h" #include <limits> FingerPointDetector::FingerPointDetector(HandDataSourceSettings* settings1){ settings=settings1; } std::vector<FingerPoint*>* FingerPointDetector::FindFingerPoints(Contour* contour, ConvexHull* convexHull){ contourPoints = contour->points; LineThinner *LT = new LineThinner(settings->MinimumDistanceBetweenFingerPoints,true); std::vector<Point*>* thinnedHullPoints = LT->Filter(convexHull->Points); std::vector<Point*>* verifiedHullPoints = VerifyPointsByContour(thinnedHullPoints); //iterate through and create FingerPoints from Points, return this std::vector<FingerPoint*>* fingerpoints = new std::vector<FingerPoint*>; std::vector<Point*>::iterator iter; Point* p; for (iter = verifiedHullPoints->begin();iter<verifiedHullPoints->end();iter++) { p = (Point*)*iter; fingerpoints->push_back(new FingerPoint(p)); } return fingerpoints; } std::vector<Point*>* FingerPointDetector::VerifyPointsByContour(std::vector<Point*>* candidatePoints){ std::vector<Point*>* out = new std::vector<Point*>; std::vector<Point*>::iterator iter; Point* p; for (iter=candidatePoints->begin();iter<candidatePoints->end();iter++) { p = (Point*)*iter; if (VerifyIsFingerPointByContour(p)){ out->push_back(p); } } return out; } bool FingerPointDetector::VerifyIsFingerPointByContour(Point* candidatePoint){ int index = FindIndexOfClosestPointOnContour(candidatePoint); Point* pointOnContour = contourPoints->at(index); Point* point1 = FindPointInDistanceForward(pointOnContour, index); Point* point2 = FindPointInDistanceBackward(pointOnContour, index); pointfunctions pntfnc; double distance = pntfnc.distance(point1, point2); if (distance > settings->MaximumDistanceBetweenIntersectionPoints) { return false; } Point *center = &pntfnc.Center(point1, point2); return pntfnc.distance(center, pointOnContour) >= settings->MinimumDistanceFingerPointToIntersectionLine; } int FingerPointDetector::FindIndexOfClosestPointOnContour(Point* fingerPoint){ int index = 0; int resultIndex = -1; double minDist = std::numeric_limits<double>::max(); std::vector<Point*>::iterator iter; Point *p; pointfunctions pntfnc; double distance; for (iter=contourPoints->begin();iter<contourPoints->end();iter++) { p = (Point*)*iter; distance = pntfnc.distance(p->x, p->y, fingerPoint->x, fingerPoint->y); if (distance < minDist) { resultIndex = index; minDist = distance; } index++; } return resultIndex; } Point* FingerPointDetector::FindPointInDistanceForward(Point* candidatePoint, int startIndex){ return FindPointInDistance(candidatePoint, startIndex, 1); } Point* FingerPointDetector::FindPointInDistanceBackward(Point* candidatePoint, int startIndex){ return FindPointInDistance(candidatePoint, startIndex, 0); } Point* FingerPointDetector::FindPointInDistance(Point* candidatePoint, int startIndex, int dir){ int resultIndex = startIndex; pointfunctions pntfnc; do { if (dir) { resultIndex = resultIndex++; } else { resultIndex = resultIndex--; } std::vector<Point*>::iterator iter; int Count = 0; for (iter=contourPoints->begin();iter<contourPoints->end();iter++) { Count++; } if (resultIndex < 0) { resultIndex = Count - 1; } if (resultIndex >= Count) { resultIndex = 0; } } while (pntfnc.distance(candidatePoint, contourPoints->at(resultIndex)) < settings->MinimumDistanceIntersectionPoints && resultIndex != startIndex); return contourPoints->at(resultIndex); }
true
2df2ed364d27be834b5cb19b210d1224621fc828
C++
0000duck/noether
/noether_tpp/test/tool_path_modifier_utest.cpp
UTF-8
8,882
2.875
3
[]
no_license
#include <boost/core/demangle.hpp> #include <gtest/gtest.h> #include <random> #include <regex> #include <noether_tpp/core/tool_path_modifier.h> // Implementations #include <noether_tpp/tool_path_modifiers/no_op_modifier.h> #include <noether_tpp/tool_path_modifiers/waypoint_orientation_modifiers.h> #include <noether_tpp/tool_path_modifiers/organization_modifiers.h> using namespace noether; /** @brief Creates an identity waypoint */ Eigen::Isometry3d createIdentityWaypoint() { return Eigen::Isometry3d::Identity(); } /** @brief Creates a waypoint with random position and orientation */ Eigen::Isometry3d createRandomWaypoint() { Eigen::Vector3d t = Eigen::Vector3d::Random(); Eigen::Vector3d r = Eigen::Vector3d::Random() * EIGEN_PI; Eigen::Isometry3d pose = Eigen::AngleAxisd(r.x(), Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(r.y(), Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(r.z(), Eigen::Vector3d::UnitZ()) * Eigen::Translation3d(t); return pose; } ToolPaths createArbitraryToolPath(const unsigned p, const unsigned s, const unsigned w, std::function<Eigen::Isometry3d()> waypoint_generator) { ToolPaths paths(p); for (ToolPath& path : paths) { path.resize(s); for (ToolPathSegment& segment : path) { segment.resize(w); std::fill(segment.begin(), segment.end(), waypoint_generator()); } } return paths; } ToolPaths createRasterGridToolPath(const unsigned p, const unsigned s, const unsigned w) { ToolPaths paths; paths.reserve(p); for (unsigned p_idx = 0; p_idx < p; ++p_idx) { ToolPath path; path.reserve(s); for (unsigned s_idx = 0; s_idx < s; ++s_idx) { ToolPathSegment segment; segment.reserve(w); for (unsigned w_idx = 0; w_idx < w; ++w_idx) { Eigen::Isometry3d waypoint(Eigen::Isometry3d::Identity()); waypoint.translation().x() = static_cast<double>(s_idx * w + w_idx); waypoint.translation().y() = static_cast<double>(p_idx); waypoint.translation().z() = 0.0; segment.push_back(waypoint); } path.push_back(segment); } paths.push_back(path); } return paths; } ToolPaths shuffle(ToolPaths tool_paths, std::size_t seed = 0) { // Seeded random number generator std::mt19937 rand(seed); for (ToolPath& tool_path : tool_paths) { for (ToolPathSegment& segment : tool_path) { // Shuffle the order of waypoints in tool path segments std::shuffle(segment.begin(), segment.end(), rand); } // Shuffle the order of tool path segments in the tool path std::shuffle(tool_path.begin(), tool_path.end(), rand); } // Shuffle the order of tool paths within the container std::shuffle(tool_paths.begin(), tool_paths.end(), rand); return tool_paths; } /** * @brief Compares two tool paths for approximate equality * @details Eigen::Transform<...> doesn't provide an equality operator, so we need to write a custom function to compare * two tool paths for approximate equality */ void compare(const ToolPaths& a, const ToolPaths& b) { ASSERT_EQ(a.size(), b.size()); for (std::size_t i = 0; i < a.size(); ++i) { ASSERT_EQ(a[i].size(), b[i].size()); for (std::size_t j = 0; j < a[i].size(); ++j) { ASSERT_EQ(a[i][j].size(), b[i][j].size()); for (std::size_t k = 0; k < a[i][j].size(); ++k) { ASSERT_TRUE(a[i][j][k].isApprox(b[i][j][k])); } } } } /** * @brief Test fixture for all tool path modifiers */ class ToolPathModifierTestFixture : public testing::TestWithParam<std::shared_ptr<const ToolPathModifier>> { }; TEST_P(ToolPathModifierTestFixture, TestOperation) { auto modifier = GetParam(); ASSERT_NO_THROW(modifier->modify(createArbitraryToolPath(4, 1, 10, createIdentityWaypoint))); ASSERT_NO_THROW(modifier->modify(createArbitraryToolPath(4, 1, 10, createRandomWaypoint))); } /** * @brief Test fixture specifically for one-time tool path modifiers */ class OneTimeToolPathModifierTestFixture : public testing::TestWithParam<std::shared_ptr<const OneTimeToolPathModifier>> { }; TEST_P(OneTimeToolPathModifierTestFixture, TestOperation) { auto modifier = GetParam(); // Create several arbitrary tool paths std::vector<ToolPaths> inputs = { createArbitraryToolPath(4, 1, 10, createIdentityWaypoint), createArbitraryToolPath(4, 1, 10, createRandomWaypoint) }; for (const ToolPaths& input : inputs) { // Apply the modifier ToolPaths output_1; ASSERT_NO_THROW(output_1 = modifier->modify(input)); // Apply the modifier again to the previous output and check that it does not change ToolPaths output_2 = modifier->modify(output_1); compare(output_1, output_2); } } /** @brief Extracts the demangled class name behind the namespace for printing in unit test */ std::string getClassName(const ToolPathModifier& modifier) { std::regex re(".*::(.*)"); std::smatch match; std::string class_name = boost::core::demangle(typeid(modifier).name()); if (std::regex_match(class_name, match, re)) return match[1]; throw std::runtime_error("Failed to get class name from demangled name"); } /** @brief Prints name of class for unit test output */ template <typename T> std::string print(testing::TestParamInfo<std::shared_ptr<const T>> info) { return getClassName(*info.param) + "_" + std::to_string(info.index); } // Create a vector of implementations for the modifiers std::vector<std::shared_ptr<const ToolPathModifier>> createModifiers() { return { std::make_shared<NoOpToolPathModifier>(), std::make_shared<FixedOrientationModifier>(Eigen::Vector3d(1, 0, 0)), std::make_shared<UniformOrientationModifier>(), std::make_shared<DirectionOfTravelOrientationModifier>(), std::make_shared<RasterOrganizationModifier>(), std::make_shared<SnakeOrganizationModifier>() }; } std::vector<std::shared_ptr<const OneTimeToolPathModifier>> createOneTimeModifiers() { std::vector<std::shared_ptr<const ToolPathModifier>> modifiers = createModifiers(); std::vector<std::shared_ptr<const OneTimeToolPathModifier>> one_time_modifiers; one_time_modifiers.reserve(modifiers.size()); for (auto modifier : modifiers) { auto m = std::dynamic_pointer_cast<const OneTimeToolPathModifier>(modifier); if (m != nullptr) one_time_modifiers.push_back(m); } return one_time_modifiers; } INSTANTIATE_TEST_SUITE_P(ToolPathModifierTests, ToolPathModifierTestFixture, testing::ValuesIn(createModifiers()), print<ToolPathModifier>); INSTANTIATE_TEST_SUITE_P(OneTimeToolPathModifierTests, OneTimeToolPathModifierTestFixture, testing::ValuesIn(createOneTimeModifiers()), print<OneTimeToolPathModifier>); /////////////////////////////////// // Implementation-specific tests // /////////////////////////////////// TEST(ToolPathModifierTests, OrganizationModifiersTest) { // Create a raster grid tool path pattern const unsigned n_paths = 4; const unsigned n_segments = 2; const unsigned n_waypoints = 10; const ToolPaths tool_paths = createRasterGridToolPath(n_paths, n_segments, n_waypoints); const ToolPaths shuffled_tool_paths = shuffle(tool_paths); // Create a raster pattern from the original tool paths RasterOrganizationModifier raster; ToolPaths raster_tool_paths = raster.modify(tool_paths); // The original tool path is already a raster, so a raster modifier shouldn't change the structure compare(tool_paths, raster_tool_paths); // Modify the shuffled tool path to produce a raster pattern raster_tool_paths = raster.modify(shuffled_tool_paths); compare(tool_paths, raster_tool_paths); // Create a snake pattern from the shuffled tool paths SnakeOrganizationModifier snake; const ToolPaths snake_tool_paths = snake.modify(shuffled_tool_paths); // Check the snake pattern for (unsigned i = 0; i < n_paths - 1; ++i) { const ToolPath& first = snake_tool_paths.at(i); const ToolPath& second = snake_tool_paths.at(i + 1); // The last waypoint in the last segment of the first path should have the same x-axis value as the first waypoint // in the first segment of the second path ASSERT_DOUBLE_EQ(first.back().back().translation().x(), second.front().front().translation().x()); } // Convert the snake tool paths into raster tool paths and compare to the original raster_tool_paths = raster.modify(snake_tool_paths); compare(tool_paths, raster_tool_paths); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
true
440a45dfc8743eb046d3a98696980cd8a17ee025
C++
bingyingL/spoc_lite
/sand_classifier/include/sand_classifier/classifier.h
UTF-8
3,281
2.53125
3
[]
no_license
/*! * @file classifier.h * @brief Base classifier class implementation * @author Kyon Otsu <otsu@jpl.nasa.gov> * @date 2017-02-24 */ #ifndef _CLASSIFIER_H_ #define _CLASSIFIER_H_ #include <ros/ros.h> #include <image_transport/image_transport.h> #include <image_transport/subscriber_filter.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/exact_time.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/image_encodings.h> #include <vector> #include <opencv2/core/core.hpp> namespace spoc { /*! * Base classifier class. * * This class handles ROS message communication. The algorithms * must be implemented in classify() function in child classes. */ class Classifier { public: /*! Constructor with ROS NodeHandle */ Classifier(ros::NodeHandle nh, ros::NodeHandle pnh); /*! Destructor */ ~Classifier(); protected: /*! Subscribe color image, and publish results */ virtual void image_cb(const sensor_msgs::ImageConstPtr &msg); /*! Subscribe color/disparity images. Results are filtered by distance */ virtual void image_disparity_cb(const sensor_msgs::ImageConstPtr &img_msg, const sensor_msgs::ImageConstPtr &dst_msg); /*! * Main classification implementation. Implement this in chid class. * @param src_bgr input color image * @param dst_labl output label image * @param dst_prob output probability image */ virtual bool classify(const cv::Mat &src_bgr, cv::Mat &dst_labl, cv::Mat &dst_prob) = 0; /*! * Superimpose color on input image based on value. * @param value value in [0.0, 1.0] * @param dst output image * @param base base color image * @param mask mask region to be superimposed * @param colormap colormap specifier. See OpenCV's COLOR_* params */ virtual void image_overlay(const cv::Mat &value, cv::Mat &dst, const cv::Mat &base, const cv::Mat &mask, int colormap=2); /*! @{ ROS node handles */ ros::NodeHandle nh; ros::NodeHandle pnh; image_transport::ImageTransport it; /*! @} */ /*! @{ ROS publishers/subscribers */ image_transport::Subscriber img_sub; image_transport::SubscriberFilter img_sub_filter; image_transport::SubscriberFilter dsp_sub_filter; image_transport::Publisher ovly_pub; image_transport::Publisher labl_pub; image_transport::Publisher prob_pub; /*! @} */ /*! @{ Message synchronizers */ typedef message_filters::sync_policies::ExactTime< sensor_msgs::Image, sensor_msgs::Image > SyncPolicy; message_filters::Synchronizer<SyncPolicy> sync; /*! @} */ /*! Label ID of sand class */ int id_sand_class; /*! Probability threshold */ double threshold; /*! Disparity threshold for filtering */ double min_disparity; }; } // namespace spoc #endif // _CLASSIFIER_H_
true
b05d5bc930122572f915fc65e1e6afcdab34eff9
C++
dorev/dryad
/runtime/src/scale.h
UTF-8
4,479
2.921875
3
[]
no_license
#pragma once #include "types.h" #include "chord.h" #include "constants.h" namespace Dryad { struct ScaleOffsets { ScaleOffsets ( NoteValue tonic = 0, NoteValue supertonic = MajorSecond, NoteValue mediant = MajorThird, NoteValue subdominant = PerfectFourth, NoteValue dominant = PerfectFifth, NoteValue submediant = MajorSixth, NoteValue leadindTone = MajorSeventh ) : offsets { tonic, supertonic, mediant, subdominant, dominant, submediant, leadindTone } { } NoteValue offsets[7]; }; const ScaleOffsets MajorScaleOffsets = ScaleOffsets(); const ScaleOffsets MinorNaturalOffsets = ScaleOffsets(0, 2, 3, 5, 7, 8, 10); const ScaleOffsets MinorHarmonicOffsets = ScaleOffsets(0, 2, 3, 5, 7, 8, 11); const ScaleOffsets MinorMelodicOffsets = ScaleOffsets(0, 2, 3, 5, 7, 9, 11); struct ScaleDegrees { ScaleDegrees ( Chord first = Chord(C, Degree::Tonic, ChordQualities::Major | ChordQualities::MajorSeventh), Chord second = Chord(D, Degree::Supertonic, ChordQualities::Minor | ChordQualities::Seventh), Chord third = Chord(E, Degree::Mediant, ChordQualities::Minor | ChordQualities::Seventh), Chord fourth = Chord(F, Degree::Subdominant, ChordQualities::Major | ChordQualities::MajorSeventh), Chord fifth = Chord(G, Degree::Dominant, ChordQualities::Major | ChordQualities::MajorSeventh), Chord sixth = Chord(A, Degree::Submediant, ChordQualities::Major | ChordQualities::Seventh), Chord seventh = Chord(B, Degree::LeadingTone, ChordQualities::HalfDiminished) ) : chords { first, second, third, fourth, fifth, sixth, seventh } { } Chord chords[7]; }; class Scale { public: Scale ( ScaleOffsets offsets = ScaleOffsets(), ScaleOffsets descendingOffsets = ScaleOffsets(), ScaleDegrees degrees = ScaleDegrees(), NoteValue root = C ) : offsets(offsets) , descendingOffsets(descendingOffsets) , degrees(degrees) , root(root) { UpdateChordRoots(); } void UpdateChordRoots() { for (int i = 0; i < 7; ++i) { degrees.chords[i].root = (root + offsets.offsets[i]) % Octave; } } static UInt32 DegreeToScaleIndex(Degree degree) { switch(degree) { case Degree::Tonic: return 0; case Degree::Supertonic: return 1; case Degree::Mediant: return 2; case Degree::Subdominant: return 3; case Degree::Dominant: return 4; case Degree::Submediant: return 5; case Degree::LeadingTone: return 6; default: return 7; } } NoteValue GetDegreeRoot(Degree degree) const { UInt32 degreeIndex = DegreeToScaleIndex(degree); if (degreeIndex < 7) { return degrees.chords[degreeIndex].root; } return Octave; } ScaleOffsets offsets; ScaleOffsets descendingOffsets; ScaleDegrees degrees; NoteValue root; const Chord& TonicChord() const { return degrees.chords[0]; } const Chord& SupertonicChord() const { return degrees.chords[1]; } const Chord& MediantChord() const { return degrees.chords[2]; } const Chord& SubdominantChord() const { return degrees.chords[3]; } const Chord& DominantChord() const { return degrees.chords[4]; } const Chord& SubmediantChord() const { return degrees.chords[5]; } const Chord& LeadingToneChord() const { return degrees.chords[6]; } const Chord SecondaryDominantChord() const { return Chord(DominantChord().root + PerfectFifth, Degree::Dominant, ChordQualities::Major | ChordQualities::MajorSeventh); } }; const Scale MajorScale = Scale(); }
true
c7a6a80979b223ead0d8a46337e879f4c7b88502
C++
jaidurn/Design-Tests-take-2
/Design Tests/FontCache.h
UTF-8
700
2.609375
3
[]
no_license
#pragma once //========================================================================================== // File Name: FontCache.h // Author: Brian Blackmon // Date Created: 8/19/2019 // Purpose: // Loads and stores fonts that have been created. //========================================================================================== #include <map> #include <string> #include "Font.h" #include "Texture.h" class Renderer; typedef std::string string; class FontCache { public: FontCache(Renderer *renderer); ~FontCache(); Font* getFont(string fontPath, int pointSize, Font::FontFlags flag, bool italics); private: std::map<string, Font*> m_fonts; Renderer *m_renderer; void cleanUp(); };
true
5660a4551be9d236043d371e6bdc1830db9e069b
C++
PollockCR/Practice-Problems
/HackerRank/cut-the-sticks.cpp
UTF-8
825
3.28125
3
[]
no_license
// https://www.hackerrank.com/challenges/cut-the-sticks #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; void cutSticks( vector<int> ); int main() { int numSticks, i, temp; vector<int> sticks; cin >> numSticks; for( i = 0; i < numSticks; i++ ){ cin >> temp; sticks.push_back( temp ); } cutSticks( sticks ); return 0; } void cutSticks( vector<int> sticks ){ if( !sticks.empty() ){ cout << sticks.size() << endl; vector<int> newSticks; int sticksMin, i, temp; sticksMin = *(min_element(sticks.begin(), sticks.end())); for( i = 0; i < sticks.size(); i++ ){ temp = sticks[i]; if( temp - sticksMin > 0 ){ newSticks.push_back( temp - sticksMin ); } } cutSticks( newSticks ); } }
true
9f6ed6a8816a7c88d9d0cfa26ed39cba92d51d47
C++
gokulmuvvala/My-C-codes
/If_else.cpp
UTF-8
263
3.28125
3
[]
no_license
#include<stdio.h> //if else program to find largest among two numbers main() { int n1,n2; printf(" Enter the valuea of n1 & n2"); scanf("%d%d",&n1,&n2); if(n1>n2) { printf("n1 is greater than n2 "); } else { printf("n2 is grater than n1"); } }
true
a9de69314734dee8571917829a2f8a4f44515153
C++
tgalg/KnightsTour
/KnightsTour/KnightsTour.cpp
UTF-8
1,724
3.40625
3
[]
no_license
/** * @file KnightsTour.cpp * @author Tom Gallagher * @date 03/22/16 * @KnightsTour implementation */ #include "KnightsTour.h" const int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; const int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; KnightsTour::KnightsTour(int m, int n, int r, int c) { rsize = m; csize = n; board = new int*[m]; for(int i = 0; i < m; i++) { board[i] = new int[n]; } visited = new bool*[m]; for(int i = 0; i < m; i++) { visited[i] = new bool[n]; } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { visited[i][j] = false; } } board[r][c] = 0; visited[r][c] = true; } KnightsTour::~KnightsTour() { } bool KnightsTour::isSafe(int x, int y) { if((x < 0) || (x >= rsize) || (y < 0) || (y >= csize)) { return false; } else if(visited[x][y]) { return false; } else { return true; } } bool KnightsTour::Move(int m, int n, int x, int y, int cur) { if(cur == m*n) { return true; } else { for(int i = 0; i < 8; i++) { if(isSafe(x+xMove[i], y+yMove[i])) { x = x+xMove[i]; y = y+yMove[i]; board[x][y] = cur; visited[x][y] = true; if(Move(m, n, x, y, cur+1)) { return true; } else { visited[x][y] = false; x = x-xMove[i]; y = y-yMove[i]; } } } } return false; } void KnightsTour::printBoard() { for(int i = 0; i < rsize; i++) { for(int j = 0; j < csize; j++) { cout<< "["; if(board[i][j] < 10) { cout<< " "; } cout << board[i][j] << "] "; } cout<< "\n"; } }
true
7e37d8c3c4fc8c64bc595b815d13b6ee404af60d
C++
reetpriye/cplusplus-programs
/38aSingleInheritanceDeepDive.cpp
UTF-8
1,364
4.09375
4
[]
no_license
// Single Inheritance(Publicly Derived) // Author: REET #include <iostream> using namespace std; class Base { int data1; public: int data2; void setData(); int getData1(); int getData2(); }; void Base ::setData() { data1 = 10; data2 = 20; } int Base ::getData1() { return data1; } int Base ::getData2() { return data2; } class Derived : public Base { int data3; public: void process(); void display(); }; void Derived ::process() { data3 = data2 * getData1(); } void Derived ::display() { cout << "Value of data1 is " << getData1() << endl; cout << "Value of data2 is " << data2 << endl; cout << "Value of data3 is " << data3 << endl; } /* Private member can not be inherited, but we have the getData1() function which helps to get access to private variable of the base class. For data1, we have to invoke function getData1() as data1 is private member of Base Class. data2 can be obtained directly as it is inherited publicly from base class. data3 can be directly printed as it is initialized in derived class. */ int main() { Derived der; der.setData(); der.process(); der.display(); return 0; } /* WARNING: Output may vary according to architecture type or input. Output of the program : Value of data1 is 10 Value of data2 is 20 Value of data3 is 200 */
true
c4d034b9b9d3a9455544d88de0ee042c21f75af3
C++
poborskii/CAADoc_SelectAgent
/CAAVisualization.edu/CAAVisBasics.m/src/CAAVisBaseDocument.cpp
UTF-8
3,432
2.71875
3
[]
no_license
// COPYRIGHT DASSAULT SYSTEMES 2000 //Local Framework #include "CAAVisBaseDocument.h" #include "CAAVisBaseView.h" //Visualization Framework #include "CAT3DBagRep.h" #include "CATReadWriteCgr.h" //For the InsertModel method #include "CATViewer.h" int CAAVisBaseDocument::_ViewName = 0; //------------------------------------------------------------------------------- CAAVisBaseDocument::CAAVisBaseDocument(CATDialog *iDialogParent, const char * iDocumentName) { _pRootContainer = NULL; //Creation of the document's view: // - Creates a dialog object (window) // - Creates a viewer in this window, where // our 3D graphical data will be visualized. CreateDocView(iDialogParent, iDocumentName); } //------------------------------------------------------------------------------- CAAVisBaseDocument::~CAAVisBaseDocument() { //We must deallocate the memory used for the model. DeleteModel(); _pView = NULL; } //------------------------------------------------------------------------------- void CAAVisBaseDocument::CreateDocView(CATDialog * iDialogParent, const char *iDocViewName) { char viewName[20]; sprintf(viewName, "View%d", _ViewName); _ViewName++; _pView = new CAAVisBaseView(iDialogParent, this, viewName); _pView->Build(); //Set the document view window title. //We want our window to have the name of the //file we load, with its path. //So, we're passing through a SetTitle //and not through a NLS file. CATUnicodeString viewTitle(iDocViewName); _pView->SetTitle(viewTitle); _pView->SetVisibility(CATDlgShow); } //------------------------------------------------------------------------------- CAAVisBaseView * CAAVisBaseDocument::GetView() { return _pView; } //------------------------------------------------------------------------------- void CAAVisBaseDocument::CreateModel() { //The implementation is let to the inherited classes. } //------------------------------------------------------------------------------- void CAAVisBaseDocument::DeleteModel() { if( NULL != _pRootContainer) { // An object inherited from CATRep must never be // deallocated by "delete". One must called the // "Destroy" method on it. _pRootContainer->Destroy(); _pRootContainer = NULL; } } //------------------------------------------------------------------------------- CAT3DBagRep * CAAVisBaseDocument::GetModel() { return _pRootContainer; } //------------------------------------------------------------------------------- void CAAVisBaseDocument::InsertModel(const char *iCGRFileName) { if(NULL == _pRootContainer) { //If no container exists, one must create it: _pRootContainer = new CAT3DBagRep; } //Reading of the CGR file. We get a pointer to CAT3DRep. CAT3DRep *pBagToInsert = CATReadCgr((char *)iCGRFileName, USE_LODS_TEXTURE_EDGE); if(NULL != pBagToInsert) { _pRootContainer->AddChild(*pBagToInsert); } CATViewer *pViewer = _pView->GetViewer(); if(NULL != pViewer) { pViewer->Draw(); } } //------------------------------------------------------------------------------- void CAAVisBaseDocument::AddRepToViewer() { _pView->Add3DRep(_pRootContainer); } //-------------------------------------------------------------------------------
true
5783e4bba914df78ac79ac0c33cb42e75193ac81
C++
GDW2018/GDW
/gdw_project/gdw/src/utilities/CharacterRecognition.cpp
GB18030
2,259
2.859375
3
[ "MIT" ]
permissive
#include <stdio.h> namespace gdwcore { namespace utilities { inline bool inRange(char input, char range_start, char range_end) { if (input >= range_start&&input <= range_end) return true; return false; } bool isGBK(const char* input) { if (input == NULL) return false; const char* p = input; while (*p != '\0') { char c = *p; if (inRange(c, 0, 0x7f)) { ++p; continue; } else if (*(++p) != '\0') { if ((inRange(c, 0xa1, 0xa9) && inRange(*p, 0xa1, 0xfe)) || (inRange(c, 0xb0, 0xf7) && inRange(*p, 0xa1, 0xfe)) || (inRange(c, 0x81, 0xb0) && (*p != 0x7f) && inRange(*p, 0x40, 0xfe)) || (inRange(c, 0xaa, 0xfe) && (*p != 0x7f) && inRange(*p, 0x40, 0xa0)) || (inRange(c, 0xa8, 0xa9) && (*p != 0x7f) && inRange(*p, 0x40, 0xa0)) || (inRange(c, 0xaa, 0xaf) && inRange(*p, 0xa1, 0xfe)) || (inRange(c, 0xf8, 0xfe) && inRange(*p, 0xa1, 0xfe)) || (inRange(c, 0xa1, 0xa7) && (*p != 0x7f) && inRange(*p, 0x40, 0xa0))) { ++p; } else { return false; } } else return false; } return true; } bool isContinousByteOfUTF_8(char c) { if ((c & 0xc0) == 0x80) return true; return false; } bool isUTF_8(const char* input) { if (input == NULL) return false; const char* p = input; while (*p != '\0') { char c = *p; int width = 1; if (c & 0x80 == 0) { //ֽλΪ0Ϊֽ ++p; continue; } else if ((c & 0xe0) == 0xc0) { //ֽǰλΪ110 if (p[1] != '\0'&&isContinousByteOfUTF_8(p[1])) { p = p + 2; continue; } return false; } else if ((c & 0xf0) == 0xe0) { if (p[1] != '\0'&&isContinousByteOfUTF_8(p[1]) && p[2] != '\0' && isContinousByteOfUTF_8(p[2])) { p = p + 3; continue; } return false; } else if ((c & 0xf8) == 0xf0) { if (p[1] != '\0'&&isContinousByteOfUTF_8(p[1]) && p[2] != '\0' && isContinousByteOfUTF_8(p[2]) && p[3] != '\0' && isContinousByteOfUTF_8(p[3])) { p = p + 3; continue; } return false; } return false; } return true; } } }
true
59b013d6d3353c76f6bef89c32e6207cef630664
C++
przemkovv/sphinx-cpp
/src/docker/v1/IOConnection.h
UTF-8
2,430
2.875
3
[]
no_license
#include <string> #include <boost/asio.hpp> #include <type_traits> #include <memory> namespace Sphinx { namespace Docker { namespace v1 { typedef boost::asio::ip::tcp::socket TCPSocket; typedef boost::asio::local::stream_protocol::socket UnixSocket; template<typename T> struct Endpoint { }; template<> struct Endpoint<UnixSocket> { using type = boost::asio::local::stream_protocol::endpoint; }; template<> struct Endpoint<TCPSocket> { using type = boost::asio::ip::tcp::endpoint; }; template <typename T> class IOConnection { private: using Socket = T; std::shared_ptr<boost::asio::io_service> svc; std::shared_ptr<Socket> socket; typename Endpoint<T>::type endpoint; public: template <typename U = Socket, typename = std::enable_if_t<std::is_same<U, TCPSocket>::value>> IOConnection(const std::string& address, unsigned short port) : svc(std::make_shared<boost::asio::io_service>()), socket(std::make_shared<Socket>(*svc)), endpoint(boost::asio::ip::address::from_string(address), port) { } template <typename U = Socket, typename = std::enable_if_t<std::is_same<U, UnixSocket>::value>> IOConnection(const std::string& socket_path) : svc(std::make_unique<boost::asio::io_service>()), socket(std::make_shared<Socket>(*svc)), endpoint(socket_path) { } IOConnection(IOConnection<T> &&other) = default; ~IOConnection() { socket->close(); } void close() { socket->close(); } void connect() { socket->connect(endpoint); } void reconnect() { close(); connect(); } void send(const std::string& data) { socket->send(boost::asio::buffer(data)); } std::string receive() { boost::system::error_code ec; std::string data; do { char buf[1024]; size_t bytes_transferred = socket->receive(boost::asio::buffer(buf), {}, ec); if (!ec) { data.append(buf, buf + bytes_transferred); } } while (!ec); return data; } private: /* data */ }; } // namespace v1 } // namespace Sphinx } // namespace Docker
true
fedab145a57758d130d122d580fbaa3434ddef04
C++
AlstonLin/iHear
/Arduino/iHear_Arduino_v1/iHear_Arduino_v1.ino
UTF-8
890
3.015625
3
[]
no_license
// Assume: 1 - left, 2 - middle, 3 - right #define MIC_1 A1 #define MIC_2 A2 #define MIC_3 A3 int MIC_OUT_1 = 3; int MIC_OUT_2 = 5; int MIC_OUT_3 = 6; void setup() { // put your setup code here, to run once: Serial.begin(115200); pinMode(MIC_OUT_1, OUTPUT); pinMode(MIC_OUT_2, OUTPUT); pinMode(MIC_OUT_3, OUTPUT); Serial.println("Initialized"); } void loop() { // put your main code here, to run repeatedly: int value1 = analogRead(MIC_1); delay(50); int value2 = analogRead(MIC_2); delay(50); int value3 = analogRead(MIC_3); value1 /= 5; value2 /= 5; value3 /= 5; //delay(50); Serial.println("-----"); //delay(50); Serial.println(value1); analogWrite(MIC_OUT_1, value1); // delay(50); Serial.println(value2); analogWrite(MIC_OUT_2, value2); // delay(50); Serial.println(value3); analogWrite(MIC_OUT_3, value3); delay(100); }
true
702b348b36f8fd70ffe2aba48d6ba0fea833a3e2
C++
papi656/a2ojLadder
/RatingLess1300/pythagoreanTheorem.cpp
UTF-8
295
2.578125
3
[]
no_license
#include <iostream> #include <cmath> #define lld long long int using namespace std; int main(){ lld n; cin >> n; lld cnt = 0; for(int i = 1; i < n; i++){ for(int j = i+1; j < n; j++){ lld c = i*i + j*j; lld d = sqrt(c); if(d*d == c && d <= n) cnt++; } } cout << cnt; }
true
17b58d6585c7538fc25316d9290e2c8e47275e88
C++
KeunhyoungLee/programmers
/Heap/더 맵게.cpp
UTF-8
1,647
3.0625
3
[]
no_license
#include <string> #include <vector> //#include <algorithm> #include <queue> #include <functional> using namespace std; int solution(vector<int> scoville, int K) { int count=0; priority_queue<int, vector<int>, greater<int>> scov; for(int i=0; i<scoville.size(); i++){ if(scoville[i]>=K) continue; scov.push(scoville[i]); } while(scov.top()<K){ if(scov.size() < 2) return -1; int a=scov.top(); scov.pop(); int b=scov.top(); scov.pop(); int sum=a+b*2; scov.push(sum); count ++; } return count; } /*sort(scoville.begin(), scoville.end());//정렬 - 제일 작은 스코빌 두 개만 사용하면 됨 for(int i=scoville.size()-1; i>=0; i--) // 스코빌 기준보다 높은 음식 스코빌 제외 if(scoville[i]>=K) scoville.pop_back(); else break; int count=0; int i=0; while(i <scoville.size()-1){ if(scoville[i+1]<K && scoville[i]<K){ count++; scoville[i+1]=scoville[i]+(scoville[i+1]*2); if(scoville[i+1]>=K){ scoville[i]=scoville[i+1]; i+=2; continue; } i++; sort(scoville.begin()+i, scoville.end()); continue; } } if(i==scoville.size()-2) return -1; else if(scoville[i+1]<K) return -1; else return count; */ /* deque<int> scov; for(int i=0; i<scoville.size(); i++){ scov[i]=scoville[i]; } */
true
0ba178bd2dd8209c688c2f01c136d13a592fe7ba
C++
Hackatonboiscaliswag/svpremespaghetti
/lista.cpp
UTF-8
827
3.703125
4
[]
no_license
#include <iostream> using namespace std; class nodo { public: nodo (int dato, nodo *siguiente = NULL) { int d = dato; nodo *sig = siguiente; } private: nodo *sig; int d; friend class lista; }; class lista { nodo *h; public: void inicializar(){ h = NULL; } void insertarPrincipio(int dato){ nodo *tmp; tmp = h; h->sig = tmp; h->d = dato; } void mostrar(){ nodo *tmp; tmp = h; while (h!=NULL){ cout << tmp->d << endl; tmp = tmp->sig; } } }; int main () { lista Lista; Lista.inicializar(); Lista.insertarPrincipio(3); Lista.insertarPrincipio(2); Lista.insertarPrincipio(1); Lista.mostrar(); }
true
f471dd86dd7c7f254b7f4aa71cdf85a6ca6499c4
C++
tmuttaqueen/MyCodes
/Online Judge Code/[Other] Online-Judge-Solutions-master_from github/TJU/2344 - Honeymoon Hike.cpp
UTF-8
1,863
2.828125
3
[]
no_license
#include <cstdio> #include <queue> using namespace std; #define max(x,y) (x)>(y)? (x):(y) #define min(x,y) (x)<(y)? (x):(y) struct node{ int x,y; node(){} node(int _x, int _y){ x = _x; y = _y; } }aux; int n,H[100][100],min_h,max_h; bool visited[100][100]; const int dx[] = {-1,1,0,0}, dy[] = {0,0,-1,1}; bool possible(int diff){ int x2,y2; for(int lo=min_h;lo<=max_h;++lo){ for(int i=0;i<n;++i) for(int j=0;j<n;++j) visited[i][j] = (H[i][j]<lo || H[i][j]>lo+diff); if(visited[0][0]) continue; queue<node> Q; Q.push(node(0,0)); visited[0][0] = true; while(!Q.empty()){ aux = Q.front(); Q.pop(); if(aux.x==n-1 && aux.y==n-1) return true; for(int i=0;i<4;++i){ x2 = aux.x+dx[i]; y2 = aux.y+dy[i]; if(x2>=0 && x2<n && y2>=0 && y2<n && !visited[x2][y2]){ Q.push(node(x2,y2)); visited[x2][y2] = true; } } } } return false; } int MinDiff(){ min_h = max_h = H[0][0]; for(int i=0;i<n;++i) for(int j=0;j<n;++j){ min_h = min(min_h,H[i][j]); max_h = max(max_h,H[i][j]); } int lo = 0,hi = max_h-min_h,mi; while(lo<hi){ mi = (lo+hi)/2; if(possible(mi)) hi = mi; else lo = mi+1; } return lo; } int main(){ int T; scanf("%d",&T); for(int tc=1;tc<=T;++tc){ scanf("%d",&n); for(int i=0;i<n;++i) for(int j=0;j<n;++j) scanf("%d",&H[i][j]); printf("Scenario #%d:\n%d\n\n",tc,MinDiff()); } return 0; }
true
edbe2e4cb73ae642a95d87f831ebbe784caf941e
C++
MarcoSDomingues/MicroMachines
/OrtogonalCamera.cpp
UTF-8
466
2.625
3
[]
no_license
#include "OrtogonalCamera.h" #include "AVTmathLib.h" OrtogonalCamera::OrtogonalCamera(float left, float right, float bottom, float top, float near, float far) { _left = left; _right = right; _bottom = bottom; _top = top; _near = near; _far = far; } void OrtogonalCamera::update(float ratio) { lookAt(0, 0, 0, 0, 0, 0, 0, 1, 0); if (ratio > 1) { ortho(-5 * ratio, 5 * ratio, -5, 5, -10, 10); } else { ortho(-5 , 5, -5 / ratio, 5 / ratio, -10, 10); } }
true
2246ef9846d249aae4a131dad91a2702d07a4306
C++
yy405145590/OpenglRipper
/OpenRipper/OpenglHook/Tools/TexTool.cpp
GB18030
3,314
2.53125
3
[]
no_license
// TexTool.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include "PVRTexture.h" //#include "png.h" #include <string> #include "DetoursGlDef.h" #include "PVRTextureUtilities.h" using namespace pvrtexture; #include <Windows.h> #include <math.h> #include <iostream> using namespace std; #define RGB2INT(r,g,b) (r*256*256 + g*256 + b) void SaveTGA( const char *filename, DWORD width, DWORD height, const byte *data ) { FILE *savefile = fopen(filename, "wb"); GLubyte header[18]={0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; header[12] = width & 0xFF; header[13] = ( width >> 8) & 0xFF; header[14] = (height) & 0xFF; header[15] = (height >> 8) & 0xFF; header[16] = 32; fwrite(header,sizeof(GLubyte),18, savefile); unsigned int image_size= 4*width*height; byte * invert_data = new byte [image_size]; memset( invert_data,0,image_size*sizeof( byte ) ); for( unsigned int i=0; i<image_size; i++ ) { invert_data[ i ] = data[ i ]; } // Swap red and blue,RGBתΪBGR for ( unsigned int cswap = 0; cswap < image_size; cswap += 4 ) { byte r = invert_data[cswap]; invert_data[cswap] = invert_data[cswap + 2]; invert_data[cswap + 2] = r; } fwrite( invert_data,image_size*sizeof( byte ),1,savefile ); fclose( savefile ); delete [] invert_data; } uint32 GetOGLFormat(uint32 oglformat) { switch (oglformat) { case GL_RGB: return OGL_RGB_888; case GL_RGBA: return OGL_RGBA_8888; default: break; } return OGL_RGBA_8888; } void MemoryToTGA(TexAttrib attrib, const char* pBuff, const std::string& fileName) { CPVRTextureHeader cHeader; if(attrib._internalFormat == 0) { attrib._internalFormat = attrib._format; } cHeader.setOGLESFormat(attrib._internalFormat, attrib._format, attrib._type); cHeader.setWidth(attrib._width); cHeader.setHeight(attrib._height); CPVRTexture cTexture(cHeader, pBuff); //Flip(cTexture, ePVRTAxisY); bool bRet = Transcode( cTexture, PVRStandard8PixelType, ePVRTVarTypeUnsignedByte, ePVRTCSpacelRGB ); std::string dstFile = fileName + ".tga"; SaveTGA(dstFile.c_str(), cTexture.getWidth(), cTexture.getHeight(), (const byte *)cTexture.getDataPtr()); } bool SaveOGLToTga(const std::string &fileName) { FILE* fp = fopen(fileName.c_str(), "rb"); const char* pBuff = NULL; TexAttrib attrib; if (fp) { fseek(fp, 0, SEEK_END); int len = ftell(fp); fseek(fp, 0, SEEK_SET); fread(&attrib, sizeof(attrib), 1, fp); pBuff = new char[len - sizeof(attrib)]; fread((void *)pBuff, len - sizeof(attrib), 1, fp); fclose(fp); } if (pBuff) { MemoryToTGA(attrib, pBuff, fileName); /*CPVRTextureHeader cHeader; if(attrib._internalFormat == 0) { attrib._internalFormat = attrib._format; } cHeader.setOGLESFormat(attrib._internalFormat, attrib._format, attrib._type); cHeader.setWidth(attrib._width); cHeader.setHeight(attrib._height); CPVRTexture cTexture(cHeader, pBuff); Flip(cTexture, ePVRTAxisY); Transcode( cTexture, PVRStandard8PixelType, ePVRTVarTypeUnsignedByte, ePVRTCSpacelRGB ); std::string dstFile = fileName + ".tga"; SaveTGA(dstFile.c_str(), cTexture.getWidth(), cTexture.getHeight(), (const byte *)cTexture.getDataPtr());*/ delete[] pBuff; return true; } return false; }
true
fb0a2317738979ce9777226ae2692f0fa19aead4
C++
ziolkowskid06/Cpp_Programming_An_Object_Oriented_Approach
/CH05 - Repetition/PR-5.17_FindingIfANumberIsAPrime.cpp
UTF-8
1,246
4.34375
4
[]
no_license
/****************************************************************** * Use a return statement to find if a number is a prime or not. * * The program returns from the main function as soon if finds * * if a number is 1 or composite. * ******************************************************************/ #include <iostream> using namespace std; int main () { // Declaration int num; // Input validation loop do { cout << "Enter a positive integer: " ; cin >> num; } while (num <= 0); // Testing if the input is 1 if (num == 1) { cout << "1 is not a composite nor a prime."; return 0; } // Testing for composite for (int i = 2; i < num ; i++) { if (num % i == 0) { cout << num << "is composite." << endl; cout << "The first divisor is " << i << endl; return 0; } } // Output Result cout << num << " is a prime." << endl; return 0; } /* Run: Enter a positive integer: 1 1 is not a composite nor a prime. Run: Enter a positive integer: 12 12 is composite. The first divisor is 2 Run: Enter a positive integer: 23 23 is a prime. Run: Enter a positive integer: 97 97 is a prime. */
true
ee6d5def36b663c9cc378a831889d25151a2dc3d
C++
jiuyewxy/Cpp-Primer-Plus
/ch2/Q07.cpp
UTF-8
295
3.359375
3
[]
no_license
#include <iostream> using namespace std; void fun(int a, int b) { cout<<"Enter the number of hours: "<<a<<endl; cout<<"Enter the number of minutes: "<<b<<endl; cout<<"Time: "<<a<<":"<<b<<endl; } int main() { int hour,min; cin>>hour>>min; fun(hour,min); return 0; }
true
aaa2353796c64f9cd6730be938282ae5c2b73ba0
C++
jitendrab/btp
/c_code/diarization_single/src/viterbi_realign.cpp
UTF-8
4,677
2.65625
3
[]
no_license
/* Written By: Jitendra Prasad Keer BTech, CSE, IIT Mandi */ #include "../include/viterbi_realign.h" /****************************************************************************** viterbi_realign : Perform Viterbi Realignment on given observation vectors inputs : Observation Space (pointer to all training feature vectors) same as Sequence of Observations, allMixtureMeans of GMMs - pointer to means of gmms, allMixtureVars of GMMs, (*numStates), numMixEachState, Transition matrix (not using currently), Emission probability matrix Bj(Ot), Initial probabilities (Pi) outputs : Most likely hidden state sequence to observation for each input observation vector ******************************************************************************/ int* viterbi( VECTOR_OF_F_VECTORS *features, hmm* mdHMM, int totalNumFeatures, float **posterior, int *numElemEachState, float *delta[], int *psi[], float *Pi, int *path){ float **B = (float **)calloc(totalNumFeatures, sizeof(float *)); int numStates = *(mdHMM->numStates); int i = 0, j = 0, k = 0; float A = (-1) * log(numStates); // uniform transition probabilities int max_prob_state; for(i = 0; i < totalNumFeatures; i++) B[i] = (float *)calloc(numStates * MIN_DUR, sizeof(float )); //clear any remainings for(i = 0; i < numStates; i++){ for(j = 0; j < totalNumFeatures; j++){ delta[i][j] = 0.0; //T1 as delta matrix(in book) psi[i][j] = 0; // T2 as Si matrix } } //calculate new B, copy probabilities for(i = 0; i < totalNumFeatures; i++){ for(j = 0; j < numStates; j++){ for(k = 0; k < MIN_DUR; k++) B[i][j*MIN_DUR + k] = posterior[j][i]; } } int scale = 0; // we are working on log scale } /****************************************************************************** Checkforminimumduration() : inputs : Observation Space (pointer to all training feature vectors) same as Sequence of Observations, allMixtureMeans of GMMs - pointer to means of gmms, allMixtureVars of GMMs, (*numStates), numMixEachState, Transition matrix (not using currently), Emission probability matrix Bj(Ot), Initial probabilities (Pi) outputs : check for minimum duration and drops any state which has less than MIN_DUR frames ******************************************************************************/ /*int* CheckMinDuration( int *hiddenStateSeq, int *numStates, int numFeatures, float **B){ int i = 0, j = 0, s = 0; float *segProb = (float *)calloc(*numStates, sizeof(float *)); //divide all voiced feature space into MIN_DUR segments printf("applying min-duration constraint....\n"); for(j = 0; j < numFeatures/MIN_DUR; j++){ for(s = 0; s < *numStates; s++) segProb[s] = 0.0; for(s = 0; s < *numStates; s++){ for(i = j*MIN_DUR; i < numFeatures, i < (j+1) * MIN_DUR; i++){ // this i will be a single block or segment segProb[s] += B[s][i]; } } //find max_state double max = -9999999; int max_s = 0; for(s = 0; s < *numStates; s++){ if(segProb[s] > max){ max = segProb[s]; max_s = s; } } //max_s is the state where this segment should belong for(i = j*MIN_DUR; i < numFeatures, i < (j+1) * MIN_DUR; i++){ // this i will be a single block or segment hiddenStateSeq[i] = max_s; } } free(segProb); return hiddenStateSeq; } */ int* CheckMinDuration( int *hiddenStateSeq, int *numStates, int numFeatures, float **B){ int i = 0, j = 0, s = 0; int *counter = (int *)calloc(*numStates, sizeof(int )); //divide all voiced feature space into MIN_DUR segments printf("applying min-duration constraint....\n"); for(j = 0; j < (numFeatures/MIN_DUR) +1; j++){ for(s = 0; s < *numStates; s++) counter[s] = 0; for(s = 0; s < *numStates; s++){ for(i = j*MIN_DUR; i < numFeatures, i < (j+1) * MIN_DUR; i++){ // this i will be a single block or segment int idx = hiddenStateSeq[i]; counter[idx]++; } } //assign this cluster to the maximum int max = -99999, max_s = 0; for(s = 0; s < *numStates; s++){ if(counter[s] > max){ max = counter[s]; max_s = s; } } for(i = j*MIN_DUR; i < numFeatures, i < (j+1) * MIN_DUR; i++){ // this i will be a single block or segment hiddenStateSeq[i] = max_s; } } return hiddenStateSeq; }
true
709f39cde3728156188a7af2271897c88c026d9d
C++
jasonchu237/fair-job-scheduler
/scheduler.cpp
UTF-8
7,777
3.4375
3
[]
no_license
#include "common.h" #include <string.h> #include <limits.h> extern Tree tree; extern Heap heap; extern ofstream out; void Insert(string operand) /*Insert into tree and heap*/ { /*Get the ID and total time*/ int comma = operand.find(","); int jobID = stoi(operand.substr(0, comma)); int totalTime = stoi(operand.substr(comma+1, operand.length()-comma)); TNode *tnode = tree.insert(jobID, totalTime); HNode *hnode = heap.insert(0, tnode); tnode->link = hnode; /*link between heap and tree*/ } void PrintJob(string operand) /*Print JobID and range JobID*/ { int comma = operand.find(","); int low, high; if(comma == -1) /*For one key*/ low = high = stoi(operand); else /*For keys in a range, set the high/low edges*/ { low = stoi(operand.substr(0, comma)); high = stoi(operand.substr(comma+1, operand.length()-comma)); } struct triple{ int jobID,execTime,totalTime; triple(int a1,int b1,int c1):jobID(a1),execTime(b1),totalTime(c1){} }; vector<triple> ans; /*Create a vector to store the found triplet for later print out*/ for(int i = low; i <= high; i++) { TNode *tnode = tree.search(i); // if not found, the search will return nil if(tnode != tree.nil) { HNode *hnode = tnode->link; ans.push_back(triple(tnode->jobID, hnode->execTime, tnode->totalTime)); } } if(ans.size()==0) /*Empty print (0,0,0)*/ out << "(0,0,0)"; else /*Print out the triplets*/ { for(unsigned i = 0; i < ans.size();i++) { out << "(" << ans[i].jobID <<","<<ans[i].execTime<<","<<ans[i].totalTime << ")"; if(i!=ans.size()-1) out << ","; } } out << endl; } void NextJob(string operand) /*Print out the sccessor*/ { int jobID = stoi(operand); TNode *tnode = tree.successor(jobID); if(tnode == tree.nil || tnode == NULL) out << "(0,0,0)" << endl; else { HNode *hnode = tnode->link; out << "(" << tnode->jobID << "," << hnode->execTime << "," << tnode->totalTime << ")" << endl; } } void PreviousJob(string operand) /*Print out the predecessor*/ { int jobID = stoi(operand); TNode *tnode = tree.predecessor(jobID); if(tnode == tree.nil || tnode == NULL) out << "(0,0,0)"<<endl; else { HNode *hnode = tnode->link; out << "(" << tnode->jobID << "," << hnode->execTime << "," << tnode->totalTime << ")" << endl; } } /* This array is similar to Intel's Instruction set. On the one hand it specifies what instructions our system can execute, Insert, PrintJob, NextJob...those operation are similar to mov add sub...True computer system use opcode to mark each operation, here we use it's name could be ok. On the other hand, it point out how to execute each instructions:function pointer, each instruction has an associated function handler. */ struct{ string op; void (*function)(string operand); }OpTable[4] = { {"Insert", Insert}, {"PrintJob", PrintJob}, {"NextJob", NextJob}, {"PreviousJob", PreviousJob} }; /* When creating a Scheduler object from main function, this constructed function will be called. it will do some initialization: 1.read all the commands from file, after our system was started, read file every time will cost much time 2.initialize system state: a. busy flag: if there are any job is executed now. b. eip: this is similar to the true instruction pointer register in computer system, it pointa to the next command's index in the array */ Scheduler::Scheduler(char *filename) { ifstream in(filename); if(!in) /*Unsuccessful reading a file*/ { exit(EXIT_FAILURE); } string str; while(getline(in, str)) { /*Use vector <command> to store a set of command with*/ int index = str.find(":"); /*each has time_appear and conmand instruction. */ Command command = { /*command, code segment ... */ .time_appear = atoi(str.substr(0, index).c_str()), /*Sample input format: 90: Insert(30,300), */ .command = string(str.substr(index+2, str.length()-(index+2))) /* 200: PrintJob(19) */ }; commands.push_back(command); } busy = false; eip = 0; sys_time = 0; } void Scheduler::run() { for(; sys_time < INT_MAX; sys_time++) { if(busy == true) /*This means there is one job is executed, we should update*/ { /*it's execute time, if execute time = total time, this job*/ current->execTime++; /*is completed, remove it from both data structures. */ left_time--; if(current->execTime >= current->link->totalTime) { tree.remove(current->link->jobID); heap.deleteMin(); busy = false; } else if(left_time == 0) /*The time slice is out of use, we need to request our system */ { /*for schedule. So set the busy flag, mean our system is free.*/ heap.siftDown(); /*The current job is not completed, but it's key in min-heap */ busy = false; /*has changed, we need to update the heap structure. */ } } nextCommand(); /*Check whether there is a command's appear time equal to global */ if(busy == false) /*time. If any, execute it. */ { /*If no command left and the heap is empty, all jobs has been done,*/ /*return to the main function */ if(heap.empty() && eip >= commands.size()) { out.close(); break; } /*If heap is not empty, then we find a job with smallest execute time*/ if(!heap.empty()) /*And set busy flag */ { current = heap.getMin(); busy = true; /*Assign left time depends on two conditions */ left_time = ((current->link->totalTime - current->execTime)<=5)?(current->link->totalTime-current->execTime):5; } } } } void Scheduler::nextCommand() { if(eip >= commands.size()) return; if(sys_time == commands.at(eip).time_appear) { string com = commands.at(eip).command; /*com = CommandType(int, int)*/ int lp = com.find("("); int rp = com.find(")"); string op = com.substr(0, lp); for(int i = 0; i < 4; i++) /*To distiquish what command shoud nextCommand execute*/ if(strcmp(OpTable[i].op.c_str(), op.c_str()) == 0) OpTable[i].function(com.substr(lp+1, rp-lp-1)); eip++; } }
true
2efba804cd64495b4edaa6dc80ba0d8d164ecfab
C++
HaRshA10D/codechef_solved
/AMR16D.cpp
UTF-8
221
2.546875
3
[]
no_license
#include <iostream> using namespace std; int main(){ int t,tot,pos; cin>>t; for(int i=0;i<t;i++){ cin>>tot>>pos; if((pos-1)/3 == pos/3) cout<<"yes"<<"\n"; else cout<<"no"<<"\n"; } return 0; }
true
b3a8f9722cb61e0cb6175cde768ff3d1ea5f9234
C++
jharmer95/cpp_named_concepts
/include/Swappable.hpp
UTF-8
225
2.75
3
[ "CC0-1.0" ]
permissive
#pragma once #include <concepts> namespace concepts { template<typename T> concept Swappable = std::swappable<T>; template<typename T, typename U> concept SwappableWith = std::swappable_with<T, U>; } // namespace concepts
true
d9d148f34dc844a14bf4915334e8653d02d353c5
C++
RaresC21/ProgrammingContests
/ICPC/Samara/X/I.cpp
UTF-8
1,219
2.5625
3
[]
no_license
#include "bits/stdc++.h" using namespace std; const int MOD = 1000000007; // Modulo int N; vector<int> mult(vector<int> P, vector<vector<int> > m) { vector<int> v(N); for (int i = 0; i < N; i++) { for (int k = 0; k < N; k++) { v[i] = (v[i] + (1LL * P[k] * m[i][k]) % MOD) % MOD; } } return v; } int main() { ios::sync_with_stdio(false); cin >> N; vector<vector<int> > A(N, vector<int>(N, 0)); vector<vector<int> > B(N, vector<int>(N, 0)); vector<vector<int> > C(N, vector<int>(N, 0)); for (int i = 0; i < N; i++) for (int k = 0; k < N; k++) cin >> A[i][k]; for (int i = 0; i < N; i++) for (int k = 0; k < N; k++) cin >> B[i][k]; for (int i = 0; i < N; i++) for (int k = 0; k < N; k++) { cin >> C[i][k]; } vector<int> P(N); for (int i = 0; i < N; i++) P[i] = rand(); vector<int> temp = mult(P, B); vector<int> L = mult(temp, A); vector<int> R = mult(P, C); for (int i = 0; i < N; i++) { if (L[i] != R[i]) { cout << "NO\n"; return 0; } } cout << "YES\n"; return 0; }
true
4d42734d197e6b85d2de9b3ce0a8036587a8b53f
C++
cslarsen/project-euler
/e033/eul33.cpp
UTF-8
899
2.71875
3
[]
no_license
#include <stdio.h> #include <string.h> #include <vector> int main() { std::vector nums, denums; for ( int a=1; a<10; ++a ) for ( int b=1; b<10; ++b ) for ( int c=1; c<10; ++c ) for ( int d=1; d<10; ++d ) { int n=a*10+b, de=c*10+d; if ( n==0 || de==0 || n==de ) continue; float v = (float)n/(float)de; if ( v>=1.0f ) continue; float vv; if ( b==c && d>0.0f ) { vv = (float)a/(float)d; if ( vv==v ) { printf("%d/%d == %d/%d == %f\n",n,de,a,d,v); nums.push_back(n); denums.push_back(de); } } if ( b==d && c>0.0f ) { vv = (float)a/(float)c; if ( vv==v ) printf("%d/%d == %d/%d == %f\n",n,de,a,c,v); } if ( a==d && c>0.0f ) { vv = (float)b/(float)c; if ( vv==v ) printf("%d/%d == %d/%d == %f\n",n,de,b,c,v); } if ( a==c && d>0.0f ) { vv = (float)b/(float)d; if ( vv==v ) printf("%d/%d == %d/%d == %f\n",n,de,b,d,v); } } }
true
ebe0524e973fbc069bdf5bee907d9c546eddb44d
C++
jmarmstrong1207/cppProject
/classes/mainMini.cpp
UTF-8
267
2.53125
3
[]
no_license
#include "MiniCar.h" int main() { MiniCar smallVan("Toyota","miniVan", "blue",2000,false ); std::cout << smallVan.getIsMiniCooper() << std::endl; smallVan.paintCar("green"); std::cout << smallVan.getColor() << std::endl; smallVan.startCar(); return 0; }
true
39883b9e0b3f0aaa5e7517456d2781cb4d3d1f26
C++
montalex/CS-112-i-CPP-Class-Project
/src/Stats/Stats.cpp
UTF-8
1,553
3.03125
3
[]
no_license
#include <Stats/Stats.hpp> #include <Application.hpp> void Stats::setActive(int id) { activeId = id; } void Stats::reset() { for(std::pair<const int, LabelledGraph> & g : graphs) { g.second.graph->reset(); } } void Stats::addGraph(int id, std::string const & label, std::vector<std::string> const & titles, double min, double max, Vec2d const& windowDimensions) { Graph* newG = new Graph(titles, windowDimensions, min, max); graphs[id].graph.reset(newG); graphs[id].label = label; setActive(id); } void Stats::update(sf::Time dt) { // Only update if the right interval has passed, otherwise // wait if (timeSinceUpdate < getAppConfig().stats_refresh_rate) { timeSinceUpdate += dt.asSeconds(); return; } // Each graph is updated for (std::pair<const int, LabelledGraph> & lg : graphs) { std::unordered_map<std::string, double> data = getAppEnv().fetchData(lg.second.label); if(!data.empty()) { lg.second.graph->updateData(sf::seconds(timeSinceUpdate), data); } } // Start to wait again timeSinceUpdate = 0; } void Stats::drawOn(sf::RenderTarget& target) const { graphs.at(activeId).graph->drawOn(target); } void Stats::focusOn(std::string graph_title) { for (std::pair<const int, LabelledGraph> & idToGraph : graphs) { if (idToGraph.second.label == graph_title) { idToGraph.second.graph->reset(); setActive(idToGraph.first); return; } } }
true
a699ea1e53682df8f7b6c01a79b2c373b55bb560
C++
rjc11a/AIProject2
/AIProj2/phase1.h
UTF-8
6,916
2.8125
3
[]
no_license
// // phase1.h // AIProj2 // // Created by Joseph on 4/3/17. // Copyright © 2017 JosephC. All rights reserved. // #ifndef phase1_h #define phase1_h #include <iostream> #include "geneticheap.h" //fitness function for phase 1 static int p1fitcalls = 0; void p1fitness(p1Node& specimen, const geneticSack& s) { p1fitcalls++; int tolwt=0; specimen.strength=0; for(int i=0; i<s.items; i++)//for every item { if(specimen.genome[i] == '1')//item i taken on the genome { tolwt += s.costs[i]; specimen.strength += s.values[i]; } } if(tolwt > s.capacity)//over capacity { specimen.strength = 0; } return; } void p1mutate(p1Node& a) { int i=0; // bool changed=false; while(a.genome[i] != 0)//0 term string { if((rand() % 1000) < 5)//0.5% flip chance { if(a.genome[i] == '1') a.genome[i] = '0'; else a.genome[i]='1'; // changed = true; } i++; } // return changed; } p1Node p1reproduce(const p1Node &a,const p1Node &b, const geneticSack &s) { p1Node baby1, baby2; baby1.genome=""; baby2.genome=""; int enda = rand() % (s.items-1); for(int i=0; i<= enda; i++) { baby1.genome+=a.genome[i]; baby2.genome+=b.genome[i]; } for(int i=enda+1; i<s.items; i++) { baby1.genome += b.genome[i]; baby2.genome += a.genome[i]; } // mutations go here p1mutate(baby1); p1mutate(baby2); // end mutations p1fitness(baby1, s); p1fitness(baby2, s); if(baby1.strength > baby2.strength)//baby1 is better return baby1; return baby2; } void p1cataclysm(Heap<p1Node>&h, const geneticSack& s) { p1Node * commies = new p1Node[101]; for(int o=1; o<101; o++) { commies[o] = h.data[o]; int i=0; while(commies[o].genome[i] != 0)//0 term string { if((rand() % 100) < 20)//20% flip chance { if(commies[o].genome[i] == '1') commies[o].genome[i] = '0'; else commies[o].genome[i]='1'; } i++; } } h.size=1; for(int i=1; i<101; i++) { p1fitness(commies[i], s); put(h,commies[i]);//put the stuff back in heap } delete [] commies; } void p1survive(Heap<p1Node> &h, const geneticSack& s)//initted heap { // int weight=0, val=0; cout<<"beginning survival:\n"; int converges = 0; p1Node secBest=h.data[1], frsBest=h.data[1], baby, sacrifice; //init the needed nodes for(int i=2; i<101; i++)//find the second and first strongest { if(h.data[i] > secBest) { if(h.data[i] > frsBest) { secBest = frsBest; frsBest = h.data[i]; } else secBest = h.data[i]; } } bool redo = true; int third = 3, second = 2, first = 1; while(redo) { cout<<"redoing.\n"; while(! (h.data[1].strength == frsBest.strength) ) { baby = p1reproduce(frsBest, secBest, s); if(baby > secBest) { if(baby > frsBest) { secBest = frsBest; frsBest = baby; } else secBest = baby; } put(h, baby); sacrifice = get(h); } bool alleq = true; for(int i=1; i<100; i++)//check if all same genome { if(h.data[i].strength != h.data[i+1].strength)//not same, repeat { // cout<<"not all eq yet\n"; alleq=false; i=100; } else { baby = p1reproduce(frsBest, secBest, s); if(baby > secBest) { if(baby > frsBest) { secBest = frsBest; frsBest = baby; } else secBest = baby; } put(h, baby); sacrifice = get(h); } } if(alleq) //was all same, checkem { converges++; cout<<"converged "<<converges<<" times, strength: "<<h.data[1].strength; third=second; second=first; first=h.data[1].strength; if(third == second && second == first) //we done 4 real tho { redo = false; } else//not done yet better cataclysmize { p1cataclysm(h, s); secBest=h.data[1]; frsBest=h.data[1]; for(int i=2; i<101; i++)//recheck 1st2ndbest { if(h.data[i] > secBest) { if(h.data[i] > frsBest) { secBest = frsBest; frsBest = h.data[i]; } else secBest = h.data[i]; } } } } } } p1Node beginp1Genetics(const geneticSack &s )//this is the first func, initializes heap { srand(time(NULL)); Heap<p1Node> h; initialize(h); string str1=""; for(int i=0; i<100; i++)//this is the number of genomes { cout<<"beginning p1, iteration "<<i<<endl; str1 = "";//init gen for(int iterations=0; iterations<s.items; iterations++)//this is the number of items { str1 += ('0' + rand() % 2); } p1Node a; a.genome = str1; p1fitness(a, s); put(h, a); } p1survive(h,s); return h.data[1]; } //lololololol maymays; //heap is complete /* cout<<"randomized initial heap: \n"; int k = 1; while(!isEmpty(h)) { cout<<"\ngenome "<<k<<": "; cout<<(get(h).genome)<<endl; k++; } */ /* cout<< "we have come to a standstill.\nThe best genomes are: "; int k = 1; while(!isEmpty(h)) { cout<<"\ngenome "<<k<<": "; genNode cur = get(h); cout<<"strength = "<<cur.strength<<endl; cout<< cur.genome <<endl; cout<<"translation: "; string readable=""; for(int i=0; i<f.steps * 2; i+=2) { if(cur.genome[i] == '1') { if(cur.genome[i+1] == '1')//11 readable+='N'; else //10 readable+='W'; } else { if(cur.genome[i+1] == '1')//01 readable+='E'; else //00 readable+='S'; } } cout<<readable<<endl; k++; } */ #endif /* phase1_h */
true
c2dfac57b4665eeb8e57eccc3a1b600a74faa1f6
C++
LawrenceFulton/RLAss2
/code/Cat.cpp
UTF-8
577
2.6875
3
[]
no_license
#include "header/Cat.h" #include "header/Mouse.h" Cat::Cat(){}; Cat::Cat(int r, int c, int maxRow, int maxCol, World* world):Agent::Agent(CAT_ID, r,c,maxRow,maxCol, world){ steps = 0; } Cat::~Cat(){ deleteStates(); }; State* Cat::getInternalState(){ return Agent::getInternalState(mouse->getR(),mouse->getC()); } char Cat::epsGreedy(int mode, double eps){ return Agent::epsGreedy(mouse->getR(),mouse->getC(),mode,eps); } char Cat::ucb(double c){ return Agent::ucb(mouse->getR(),mouse->getC(), c); } void Cat::setMouse(Mouse* mouse){ this->mouse = mouse; }
true
7b90c296e25fe912fd5a4b7c0e7fbd265b67242c
C++
trevorassaf/gpio14
/include/I2c/I2cClient.h
UTF-8
1,030
2.609375
3
[]
no_license
#pragma once #include <cstdint> #include <memory> #include <string> #include <utility> #include "I2c/I2cIoctlOps.h" #include "Utils/Fd.h" namespace I2c { class I2cClient { public: I2cClient(I2cIoctlOps *ioctlOps); I2cClient(I2cIoctlOps *ioctlOps, uint8_t slaveAddress); I2cClient(I2cIoctlOps *ioctlOps, std::unique_ptr<Utils::Fd> fd); I2cClient(I2cIoctlOps *ioctlOps, uint8_t slaveAddress, std::unique_ptr<Utils::Fd> fd); ~I2cClient(); I2cClient(I2cClient &&other); I2cClient& operator=(I2cClient &&other); bool IsOpen() const; void SetSlave(uint8_t slaveAddress); bool HasSlave() const; uint8_t GetSlave() const; void Close(); void Write(const uint8_t *buffer, size_t size); void Read(uint8_t *buffer, size_t size); private: I2cClient(const I2cClient &other) = delete; I2cClient& operator=(const I2cClient &other) = delete; private: void p_MaybeSetSlaveAddress(uint8_t slaveAddress); private: I2cIoctlOps *m_ioctlOps; uint8_t m_slaveAddress; std::unique_ptr<Utils::Fd> m_fd; }; } // namespace I2c
true
ef16f028955f14253d0b157a25fa2260bab50241
C++
sahuaman83/Competetive
/Recursion/sorting Stack(Recursion) II.cpp
UTF-8
634
3.734375
4
[]
no_license
/*The structure of the class is class SortedStack{ public: stack<int> s; void sort(); }; */ /* The below method sorts the stack s you are required to complete the below method */ void insert_stack(stack<int> &s,int x) { if(s.empty()) { s.push(x); return ; } if(x>=s.top()) { s.push(x); return ; } int t=s.top(); s.pop(); insert_stack(s,x); s.push(t); } void sorted(stack<int> &s) { if(s.size()==1) return; int x=s.top(); s.pop(); sorted(s); insert_stack(s,x); } void SortedStack :: sort() { sorted(s); }
true
639015f8d83dd7c9ad0dd1d717d6643006f29d2d
C++
mush-musha/University-Management-System-UML-AND-CODE
/Student.h
UTF-8
2,654
3.296875
3
[]
no_license
#pragma once #include"Courses.h" #include"AcademicRecord.h" #include<iostream> #include<string> #include<vector> using namespace std; class Student:public AcademicRecord { public: Student()=default; ~Student()=default; //Using polymorphism between methods void setName(string); void set_id(int); void set_address(string); void setEmail(string); void ShowStudentAcademicRecord(int); void ShowStudentCoursesInfo(Courses); //Overriding the getters from department class string getName(int); int get_id(int); string getEmail(int); string get_address(int); void set_payments(float, string, float) { } protected: /// <summary> /// Implementing the composition between the Student /// </summary> vector<string> student_name; vector<int> student_id; vector<string> student_email; vector<string> student_address; int index; }; void Student::set_id(int id) { student_id.push_back(id); } void Student::setEmail(string email) { student_email.push_back(email); } void Student::setName(string name) { student_name.push_back(name); } void Student::set_address(string saddress) { student_address.push_back(saddress); } string Student::getName(int index) { return student_name[index]; } int Student::get_id(int index) { return student_id[index]; } string Student::getEmail(int index) { return student_email[index]; } string Student::get_address(int index) { return student_address[index]; } void Student::ShowStudentAcademicRecord(int index) { cout << "\nThe Attandance percentage of student " << student_name[index] << " is " <<get_Attandance_percentage(index); cout << "\nThe CGPA of student " << student_name[index] << " is " << get_GCPA(index); cout << "\nThe Grade of student " << student_name[index] << " is " << get_student_grades(index); cout << "\nThe Grade of student " << student_name[index] << " is " << get_student_marks(index); } void Student::ShowStudentCoursesInfo(Courses studentCourses) { int size = studentCourses.get_total_no_courses(); for (int i = 0; i <size; i++) { cout << "\nThe course enrolled of student \n" << this->student_name[i] << " is " << studentCourses.get_courses_enrolled(i); } for (int i = 0; i < size; i++) { cout << "\nThe course_wise attandance percentage of student \n" << this->student_name[i] << " is " << studentCourses.get_coursewise_attendance_percentage(i); } for (int i = 0; i < size; i++) { cout << "\nThe course_wise attandance percentage of student \n"; cout<<this->student_name[i] << " is " << studentCourses.get_course_wise_marks(index); } cout << "\nThe total number of courses are " << studentCourses.get_total_no_courses(); }
true
e848da994a04eee9d0055d740c830c18c74477ba
C++
ElvisKwok/code
/ci/12_print1ToMaxOfNDigits.cc
UTF-8
2,190
3.859375
4
[]
no_license
#include <iostream> #include <cstring> // memset using namespace std; // file description: // print 1, 2, 3, 4, ..., (9............9) // |--n digits--| bool increment(char* num); void printNum(char* num); void print1ToMaxOfNDigits(int n) { if (n<=0) return; char* num = new char[n+1]; memset(num, '0', n); num[n] = '\0'; while (!increment(num)) printNum(num); delete []num; } bool increment(char* num) { bool isOverflow = false; int carry = 0; int len = strlen(num); for (int i=len-1; i>=0; --i) { int digit = num[i] - '0' + carry; if (i == len-1) ++digit; carry = digit / 10; if (carry) { if (i == 0) isOverflow = true; else num[i] = digit % 10 + '0'; } else { num[i] = digit + '0'; break; } } return isOverflow; } void printNum(char* num) { bool isStart0 = true; int len = strlen(num); for (int i=0; i<len; ++i) { if (isStart0 && num[i]!='0') isStart0 = false; if (isStart0 == false) cout << num[i]; } cout << "\t"; } // ============== recursively ============== void recursive(char* num, int length, int index); void print1ToMaxOfNDigits_2(int n) { if (n <= 0) return; char* num = new char[n+1]; memset(num, '0', n); num[n] = '\0'; for (int i=0; i<10; ++i) { num[0] = i + '0'; recursive(num, n, 0); } delete []num; } void recursive(char* num, int length, int index) { if (index == length-1) { printNum(num); return; } for (int i=0; i<10; ++i) { num[index+1] = i + '0'; recursive(num, length, index+1); } } // =====================Test Code===================== void test(int n) { cout << "test for " << n << " begins:" << endl; print1ToMaxOfNDigits(n); cout << endl; print1ToMaxOfNDigits_2(n); cout << endl; cout << "test for " << n << " ends." << endl; } int main() { test(1); test(2); test(3); test(0); test(-1); return 0; }
true
db0a1c22b45b34628a0ed2d2d0cfb0c2b5df44a0
C++
Overlord7667/Temperature
/DZ/Source.cpp
UTF-8
950
2.90625
3
[]
no_license
#include<iostream> using namespace std; void main() { setlocale(LC_ALL, "Russian"); int temperature; cout << "Введите температуру воздуха: "; cin >> temperature; if (temperature >= 70) { cout << "Вы на другой планате!" << endl; } else if (temperature >= 50) { cout << "Вы на экваторе" << endl; } else if (temperature >= 40) { cout << "Очень жарко" << endl; } else if (temperature >= 25) { cout << "Жарко" << endl; } else if (temperature >= 15) { cout << "Тепло" << endl; } else if (temperature >= 0) { cout << "Прохладно" << endl; } else if (temperature >= -9) { cout << "Прохладно" << endl; } else if (temperature >= -10) { cout << "Мороз" << endl; } else if (temperature >= -19) { cout << "Мороз" << endl; } else if (temperature <= -20) { cout << "Сильный мороз" << endl; } }
true
e1479876d2dfb1fe20e51de0a1c6f5f50e6535d2
C++
famousDeer/Jezyk_Cpp_Szkola_programowania
/Rozdzial_7/Zadanie_7/Zadanie_7.cpp
UTF-8
1,911
3.609375
4
[]
no_license
#include <iostream> const int Max = 5; //Protorypy funkcji double *fill_array(double * begin, double * end);//* zmodyfikować void show_array(const double * begin, double * end); // nie zmienia danych //* zmodyfikowac void revalue(double r, double * begin, double * end); //* zmodyfikowac int main(){ using namespace std; double properties[Max]; double *size = fill_array(properties, properties+Max); //* zmodyfikować show_array(properties, size); //* zmodyfikowac if(size > 0){ cout << "Podaj czynnik zmiany wartości: "; double factor; while(!(cin >> factor)){ cin.clear(); while (cin.get() != '\n') continue; cout << "Niepoprawna wartość; podaj liczbe: "; } revalue(factor, properties, properties+Max); //* zmodyfikowac show_array(properties, properties+Max); //* zmodyfikowac } cout << "Gotowe\n"; cin.get(); cin.get(); return 0; } double *fill_array(double * begin, double * end){ //* zmodyfikować using namespace std; double temp; double *ptr = begin; for(; ptr < end; ptr++){ cout << "Podaj wartosc nr " << (*ptr+1) <<": "; cin >> temp; if(!cin){ cin.clear(); while(cin.get() != '\n') continue; cout << "Bledne dane, wprowadzanie danych przerwane.\n"; break; } else if(temp < 0) break; *ptr = temp; } return ptr; } void show_array(const double *begin, double *end){ //* zmodyfikowac using namespace std; for(const double *i = begin; i < end; begin++){ cout << "Nieruchomosc nr " << (*i + 1) <<": "; cout << *i << endl; } } void revalue(double r, double *begin, double *end){ //* zmodyfikowac for(double *i = begin; i < end; begin++) *i *= r; }
true
8448a3116aad39a5beb4015fe70ac3631a60ee79
C++
SirKnightTG/brakeza3d
/src/2D/TextureAnimationDirectional.cpp
UTF-8
1,904
2.9375
3
[]
no_license
#include "../../headers/2D/TextureAnimationDirectional.h" #include "../../headers/Render/EngineSetup.h" TextureAnimationDirectional::TextureAnimationDirectional() { for (int d = 0; d <= 8 ; d++) { for (int j = 0; j < ANIMATION2D_MAX_FRAMES ; j++) { this->frames[d][j] = new Texture(); } } } void TextureAnimationDirectional::setup(std::string file, int numFrames, int fps, int maxTimes) { this->base_file = file; this->numFrames = numFrames; this->fps = fps; this->maxTimes = maxTimes; } void TextureAnimationDirectional::loadImages() { for (int d = 1; d <= 8 ; d++) { for (int i = 0; i < this->getNumFrames() ; i++) { std::string file = this->base_file + "/" + std::to_string(d) + "_" + std::to_string(i) + ".png"; this->frames[d][i]->loadTGA( file.c_str(), 1 ); } } } void TextureAnimationDirectional::loadImagesForZeroDirection() { int d = 0; for (int i = 0; i < this->getNumFrames() ; i++) { std::string file = this->base_file + "/" + std::to_string(d) + "_" + std::to_string(i) + ".png"; this->frames[0][i]->loadTGA( file.c_str(), 1 ); } } int TextureAnimationDirectional::getNumFrames() const { return numFrames; } Texture *TextureAnimationDirectional::getCurrentFrame(int direction) { return this->frames[direction][current]; } void TextureAnimationDirectional::nextFrame() { current++; if (current >= this->getNumFrames() ) { current = 0; times++; if ((maxTimes != -1 && times >= maxTimes)) { current = getNumFrames()-1; } } } void TextureAnimationDirectional::importTextures(TextureAnimationDirectional *origin, int numFrames) { for (int d = 0; d <= 8 ; d++) { for (int j = 0; j < numFrames ; j++) { this->frames[d][j] = origin->frames[d][j]; } } }
true
79b4080b7ced29f1f583300e52b8720c31aa5d8a
C++
smalls12/blokus
/src/Network.cpp
UTF-8
7,167
2.625
3
[ "MIT" ]
permissive
#include <string> /* ========================================================= * * Implements the network layer * * ========================================================= */ #include "Network.hpp" #include "spdlog/spdlog.h" Network::Network(std::string nodeName, ICompress& compress, IDecompress& decompress) : mNodeName(nodeName), mCompression(compress), mDecompression(decompress) { spdlog::get("console")->info("Network::Network() - Node {}", mNodeName); } Network::~Network() { spdlog::get("console")->info("Network::~Network()"); } // Connect into the network bool Network::Connect() { spdlog::get("console")->info("Network::Connect()"); // czmq sets the signal handler internally // we want to override that zsys_handler_set(NULL); mNode = zyre_new(mNodeName.c_str()); if ( !mNode ) { spdlog::get("stderr")->error("Network::Connect() - Error."); } mPoller = zpoller_new(zyre_socket(mNode), NULL); } // Disconnect from the network void Network::Disconnect() { spdlog::get("console")->info("Network::Disconnect()"); zpoller_destroy(&mPoller); zyre_destroy(&mNode); } bool Network::Start() { int rc = 0; rc = zyre_start(mNode); if ( rc != 0 ) { spdlog::get("stderr")->error("Network::JoinGroup() - Could not start node."); return false; } return true; } void Network::Stop() { zyre_stop(mNode); } // Disconnect from the network bool Network::Configure(std::string parameter) { spdlog::get("console")->info("Network::Configure()"); zyre_set_header(mNode, "X-BLOKUS", "%s", parameter.c_str()); } // Retrieve the name of the network std::string Network::GetName() { spdlog::get("console")->info("Network::GetName()"); return std::string( zyre_name( mNode ) ); } // Retrieve the unique identifier of the network std::string Network::GetUniqueIdentifier() { spdlog::get("console")->info("Network::GetUniqueIdentifier()"); return std::string( zyre_uuid( mNode ) ); } // Join a network lobby bool Network::JoinGroup(std::string groupName) { spdlog::get("console")->info("Network::JoinGroup()"); int rc = 0; rc = zyre_join(mNode, groupName.c_str()); if ( rc != 0 ) { spdlog::get("stderr")->error("Network::JoinGroup() - Could not join game."); } zclock_sleep(250); } // Leave a network lobby bool Network::LeaveGroup(std::string groupName) { spdlog::get("console")->info("Network::LeaveGroup()"); int rc = 0; rc = zyre_leave(mNode, groupName.c_str()); if ( rc != 0 ) { spdlog::get("stderr")->error("Network::LeaveGroup() - Could not leave group."); } } // Send to the network int Network::Send(std::string groupName, std::string message) { spdlog::get("console")->info("Network::Compressing message"); std::string compressed; mCompression.Compress(message, compressed); const char* c_compressed = compressed.c_str(); spdlog::get("console")->info("Network::Sending message size {}", compressed.size()); int rc = 0; // rc = zyre_shouts(mNode, groupName.c_str(), "%s", c_compressed); zmsg_t *msg = zmsg_new(); rc = zmsg_addmem(msg, compressed.c_str(), compressed.size()); rc = zyre_shout(mNode, groupName.c_str(), &msg); return rc; } // Send to the network bool Network::Poll() { spdlog::get("console")->trace("Network::Poll()"); zsock_t *which = (zsock_t *)zpoller_wait(mPoller, 0); if( !which ) { // spdlog::get("stderr")->error("ReadGameNotification::operator() - No event."); return false; } // zpoller_expired // zpoller_terminated return true; } // Receive from the network bool Network::Receive(std::string groupName, std::vector<std::string>& messages) { spdlog::get("console")->info("Network::Receive()"); zyre_event_t *event = zyre_event_new( mNode ); if( event ) { zyre_event_print( event ); const char *value = zyre_event_group(event); if( value ) { std::string group(value); spdlog::get("console")->trace("Network::Receive() - Notification from Group {}", group); if( group != groupName ) { spdlog::get("console")->warn("Network::Receive() - Not a notification for this game."); return false; } } else { spdlog::get("stderr")->warn("Network::Receive() - Not a notification for this game."); return false; } messages.push_back( std::string( zyre_event_peer_name( event ) ) ); messages.push_back( std::string( zyre_event_peer_uuid( event ) ) ); std::string type( zyre_event_type( event ) ); spdlog::get("console")->info("Network::Receive() - Type {}", type); messages.push_back( type ); zmsg_t *msg = zyre_event_get_msg( event ); if( msg ) { // spdlog::get("console")->info("Network::Message, raw size {}", zmsg_content_size(msg)); size_t raw_size = zmsg_content_size( msg ); char *raw_data = zmsg_popstr( msg ); if( raw_data ) { std::string raw_string( raw_data, raw_size ); free( raw_data ); std::string decompressed; mDecompression.Decompress(raw_string, decompressed); messages.push_back( decompressed ); } else { spdlog::get("console")->trace("Network::Receive() - 4"); messages.push_back( std::string( std::string("") ) ); } zmsg_destroy( &msg ); } else { messages.push_back( std::string( std::string("") ) ); } zyre_event_destroy( &event ); spdlog::get("console")->trace("Network::Receive() - Done"); return true; } else { spdlog::get("stderr")->error("Network::Receive() - Error"); return false; } } // Search for lobbies on network void Network::Search(std::vector<std::pair<std::string, std::string>>& lobbies) { spdlog::get("console")->trace("Network::Search()"); zlist_t* peers = zyre_peers(mNode); while(zlist_size(peers) > 0) { char *uuid; uuid = (char *)zlist_pop (peers); spdlog::get("console")->trace("Network::Search() - Peer {}", uuid); char *value = zyre_peer_header_value(mNode, uuid, "X-BLOKUS"); if( value ) { std::string header(value); zstr_free(&value); spdlog::get("console")->trace("Network::Search() - Header Value {}", header); // std::shared_ptr<ActiveGame> ag; // if( !mActiveGameManager.GameAlreadyActive(header, ag) ) // { // ag = std::make_shared<ActiveGame>(std::string(header), std::string(uuid)); // mActiveGameManager.AddActiveGame(std::string(header), ag); // } lobbies.push_back(std::pair<std::string, std::string>(header, uuid)); } } zlist_destroy (&peers); }
true
0dc3542cb460f8c84dfe44b317bcbeb493e42b4b
C++
jkwon0866/AoC2020
/day15.cpp
UTF-8
1,400
3.1875
3
[]
no_license
#include <iostream> #include <unordered_map> #include <vector> using namespace std; void ElfGame1(int rounds){ unordered_map<int,pair<int,int>> round_spoken({{2,{1,-1}},{1,{2,-1}},{10,{3,-1}},{11,{4,-1}},{0,{5,-1}},{6,{6,-1}}}); int last_spoken = 6; for(int round = round_spoken.size() + 1; round <= rounds; round++){ if(round_spoken[last_spoken].second == -1){ last_spoken = 0; } else{ last_spoken = round_spoken[last_spoken].second - round_spoken[last_spoken].first; } //cout << last_spoken << endl; if(round_spoken.find(last_spoken) == round_spoken.end()){ round_spoken[last_spoken] = {round,-1}; } else if(round_spoken[last_spoken].second == -1){ round_spoken[last_spoken].second = round; } else{ round_spoken[last_spoken].first = round_spoken[last_spoken].second; round_spoken[last_spoken].second = round; } } cout << last_spoken << endl; } void ElfGame2(int rounds){ unordered_map<int,int> round_spoken({{2,1},{1,2},{10,3},{11,4},{0,5},{6,6}}); vector<int> dp(rounds+1,0); dp[1] = 2; dp[2] = 1; dp[3] = 10; dp[4] = 11; dp[5] = 0; dp[6] = 6; for(int round = round_spoken.size() + 1; round <= rounds; round++){ dp[round] = round_spoken.find(dp[round-1]) == round_spoken.end() ? 0 : round - 1 - round_spoken[dp[round-1]]; round_spoken[dp[round-1]] = round -1; } cout << dp.back() << endl; } int main(){ ElfGame2(30000000); return 0; }
true
625d8599c30e9f8e153a6eb1e077db64acc99fae
C++
CGCC-CS/csc220summer18
/class13/threads.cpp
UTF-8
1,403
3.671875
4
[ "MIT" ]
permissive
#include<iostream> #include<thread> #include<mutex> // compile with: // g++ threads.cpp --std=c++11 -pedantic -Wall -pthread std::mutex m; // This funtion counts to 10 with 1 second delay between numbers // The tabs argument lets us differentiate between different // threads visually. void count_to_ten(int tabs) { for(int jj=0;jj<10;jj++) { // The next line locks the output stream so the threads don't // write over each other. Try commenting it out to see // what happens. std::unique_lock<std::mutex> lock(m); for(int ii=0;ii<tabs;ii++) { std::cout << "\t"; } std::cout << jj << std::endl; // Free the mutex lock.unlock(); // Wait a second std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } int main() { int ii; const int numThreads = 6; std::thread t[numThreads]; // This loop calls count_to_ten multiple times // Try changing the body to count_to_ten(ii) to see what it looks // like to not run multi-threaded. (you will also need to comment // out the join for loop. for(ii=0;ii<numThreads;ii++) { t[ii] = std::thread(count_to_ten, ii); } // Wait for each thread to return for(ii=0;ii<numThreads;ii++) { t[ii].join(); } return 0; }
true
1d78c9c64a4f47781e82f77bc17ebf5da2227373
C++
BrandonFowler/SchoolWork
/Later Work/C++ Introduction/305 Assignment 3/PackageException.h
UTF-8
616
2.71875
3
[]
no_license
/* Author: Brandon Fowler Class: CSCD305 Assignment: 3 Quarter: Summer 2014 Compilers Used: g++ and cl */ #pragma once #include "Package.h" using namespace std; class PackageException:public Package{ protected: string problem; public: PackageException(int trackingNumber, int weight, string problem, string type); virtual string description(); //Return package description, and why it is invalid for shipping virtual double getCost();//Needed to stub out because declared pure virtual in base class virtual double operator+(Package& rhs);//Needed to stub out because declared pure virtual in base class };
true
1b9cb68df10915358cfeafc529f47a18d4d21ecd
C++
bklimt/QueryWizard
/Table.cpp
UTF-8
1,401
3.015625
3
[]
no_license
#include "Table.h" CTable::CTable() { record = 0; } CTable::CTable( const CTable& table ) { data = table.data; columns = table.columns; record = table.record; } CTable CTable::operator=( const CTable& table ) { data = table.data; columns = table.columns; record = table.record; return *this; } void CTable::SetFieldNames( vector<string> names ) { columns = names; } void CTable::SetData( vector< vector< CVariant > > newdata ) { data = newdata; } vector<string> CTable::GetFieldNames() { return columns; } int CTable::GetColumnCount() { return columns.size(); } int CTable::GetRowCount() { return data.size(); } void CTable::MoveTo( int index ) { record = index; } void CTable::MoveNext() { record++; } bool CTable::IsAtEOF() { return ( record >= data.size() ); } bool CTable::IsEmpty() { return ( data.size() == 0 ); } CVariant CTable::operator[]( char* index ) { for ( int i=0; i<columns.size(); i++ ) { CString s1 = index; CString s2 = columns[i].c_str(); s1.MakeUpper(); s2.MakeUpper(); if ( s1 == s2 ) { return (*this)[i]; } } char temp[1000]; sprintf( temp, "bad: %s", index ); MessageBox( 0, temp, "", 0 ); return CVariant(); } CVariant CTable::operator[]( int index ) { if ( record >= 0 && record < data.size() && index >= 0 && index < data[record].size() ) { return data[record][index]; } else { return CVariant(); } }
true
b01cd3ab8ced50075bf1da5c3e7473e9881d5ba2
C++
nishinjohn/Container_Inventory
/CONTAINE.CPP
UTF-8
8,131
2.84375
3
[]
no_license
#include<iostream> //Remember to change this #include<conio.h> #include<process.h> #include<fstream> //Remember to change this #include<stdio.h> #include<string.h> using namespace std; //Remember to remove this char user[15],item[25]; int cap=0; class container { public: int contno,vol; float shipid,pass; void getdata_user(char user[15]) { cout<<"Enter item to ship "; cin.getline(item,sizeof item); cin.ignore(); // May get you in trouble cout<<"Enter volume required "; cin>>vol; if(vol<=cap) { // cout<<"shipment id is "<<shipid++; cap-=vol; cout<<"user id is"<<user; cout<<"Enter desired ship id"; cin>>shipid; cout<<"Enter desired password"; cin>>pass; } else { cout<<"sorry out of space."; cout<<"can u reduce the volume to "<<cap<<" or less "; } } void getdata() { cout<<"Enter container id"; cin>>contno; cout<<"Enter capacity"; cin>>cap; } void putdata() { cout<<"user name is : ";puts(user); cout<<"\nshipment id is : "<<shipid; cout<<"password cannot be displayed due to security reasons"; cout<<"\nitem is : ";puts(item); cout<<"\nvolume alloted is : "<<vol; } }; // *********** class finished *********************** void app() { container s; fstream f("missori.dat",ios::binary|ios::app); s.getdata(); f.write((char*)&s,sizeof(s)); f.close(); } // void app(char use[15]) void app_item() { container s; fstream f("missori.dat",ios::binary|ios::app|ios::out); //why out ?? // fstream f("missori.dat",ios::binary|ios::out); s.getdata_user(user);//s.getdata(use); f.write((char*)&s,sizeof(s)); f.close(); cout<<"Data added to file"; } void display() { container s; ifstream f("missori.dat",ios::binary|ios::in); if(!f) cout<<"File not opened"; while(f.read((char*)&s,sizeof(s))) { s.putdata(); cout<<" looping in display\n"; } /* else{ cout<<"Cannot read from File"; }*/ f.close(); } void Show() { container s; int kEy,rank=0; float id; cout<<"\n\t\t\t Enter shipment id - "; cin>>id; //cout<< " Details Parsed"; cout<<"\n\t\t\t Enter password - "; cin>>kEy; ifstream f("missori.dat",ios::binary|ios::in); if(!f) cout<<"File not opened"; while(f.read((char*)&s,sizeof(s))) { s.putdata(); if((s.shipid==id)&&(s.pass==kEy)) { cout<<"\n\t\t\t SHIPMENT DETAILS \n"; s.putdata(); rank=1; //break; } } /*else{ cout<<"Cannot read from File"; }*/ if(rank==0) cout<<"\n\t\t\t user not found "; f.close(); } void search() { container s; int exist=0; float id; cout<<"\n\t\t\t Enter shipment id - "; cin>>id; ifstream f("missori.dat",ios::binary|ios::in); while(f.read((char*)&s,sizeof(s))) { if(s.shipid==id) { cout<<"\n\t\t\t SHIPMENT DETAILS \n"; s.putdata(); exist=1; break; } } if(exist==0) cout<<"\n\t\t\t user not found "; f.close(); } void deletE() { container s; float id; cout<<"\n Enter shipment id to be deleted - "; cin>>id; ifstream f("missori.dat",ios::binary|ios::in); ofstream f1("temp.dat",ios::binary|ios::trunc); //truncated to discard previous data while(f.read((char*)&s,sizeof(s))) { cap+=s.vol; if(s.shipid!=id) { f1.write((char*)&s,sizeof(s)); } } f.close(); f1.close(); remove("missori.dat"); rename("temp.dat","missori.dat"); } void del() { container s; int kEy,exist=0; float id; cout<<"\n\t\t\t Enter shipment id - "; cin>>id; cout<<"\n\t\t\t Enter password - "; cin>>kEy; ifstream f("missori.dat",ios::binary|ios::in); ofstream f1("temp.dat",ios::binary|ios::trunc); while(f.read((char*)&s,sizeof(s))) { if((s.shipid==id)&&(s.pass==kEy)) { while(f.read((char*)&s,sizeof(s))) { cap+=s.vol; if(s.shipid!=id) { f1.write((char*)&s,sizeof(s)); } } f.close(); f1.close(); remove("missori.dat"); rename("temp.dat","missori.dat"); exist=1; break; } if(exist==0) { cout<<"\n\t\t\t user not found "; f.close(); f1.close(); } } } int main() // remember to change this { // clrscr(); // removing current data ifstream f("missori.dat",ios::binary|ios::out|ios::trunc); if(!f) cout<<"File not created"; f.close(); // float pass; int ch=0; char exit; do{ cout<<"Enter user name\n"; // gets(user); // cin.ignore(); cin.getline(user,sizeof user); if(strcmpi("admin",user)==0) { char password[5]; cout<<"Enter password \n"; cin>>password; if(strcmpi ("2k18",password)==0) { do{ cout<<"\n\n\n\t\t\t *************************MENU******************************"; cout<<"\n\t\t\t1.Add Container \n\t\t\t2.Display Shipments details \n\t\t\t3.Search shipments \n\t\t\t4.Delete shipments \n\t\t\t5.Exit "; cout<<"\n\t\t\t Enter choice- "; cin>>ch; switch(ch) { case 1: app(); break; case 2: display(); break; case 3: search(); break; case 4: deletE(); break; } }while(ch<5); } } else { do{ cout<<"\n\n\n\t\t\t *************************MENU******************************"; cout<<"\n\t\t\t1.Add Shipment \n\t\t\t2.Display Shipments details \n\t\t\t3.Delete Shipment details \n\t\t\t4.Exit "; cout<<"\n\t\t\t Enter choice- "; cin>>ch; cin.ignore(); // May get you in trouble switch(ch) { case 1: app_item();//app(user); break; case 2: Show(); break; case 3: del(); break; } }while(ch<4); } cout<<"are you sure u want to exit"; cin>>exit; cin.ignore(); // May get you in trouble }while(exit=='n'); return 0; }
true
98781dfe6c2402609cbe5dd1d03a4efd352d6153
C++
pycpp/sfinae
/push_front.h
UTF-8
1,501
2.875
3
[]
no_license
// :copyright: (c) 2017-2018 Alex Huszagh. // :license: MIT, see licenses/mit.md for more details. /** * \addtogroup PyCPP * \brief SFINAE detection for `push_front` and fail-safe implementation. * * Copy and add item to front of container. * * \synopsis * template <typename T> * struct has_push_front: implementation_defined * {}; * * struct push_front * { * template <typename T> * void operator()(T& t, typename T::const_reference v); * }; * * #if PYCPP_CPP14 * * template <typename T> * constexpr bool has_push_front_v = implementation-defined; * * #endif */ #pragma once #include <pycpp/sfinae/has_member_function.h> #include <pycpp/stl/type_traits.h> PYCPP_BEGIN_NAMESPACE // SFINAE // ------ PYCPP_HAS_MEMBER_FUNCTION(push_front, has_push_front, void (C::*)(typename C::const_reference)); /** * \brief Call `push_front` as a functor. */ struct push_front { template <typename T> enable_if_t<has_push_front<T>::value, void> operator()( T &t, typename T::const_reference v ) { t.push_front(v); } template <typename T> enable_if_t<!has_push_front<T>::value, void> operator()( T &t, typename T::const_reference v ) { t.insert(t.begin(), v); } }; #ifdef PYCPP_CPP14 // SFINAE // ------ template <typename T> constexpr bool has_push_front_v = has_push_front<T>::value; #endif PYCPP_END_NAMESPACE
true
88882eafcf881007330c00d9558d2bd87abec0ce
C++
uhini0201/CodeChefChallenges
/CodeChefLunchMay20/LOSTWKND.cpp
UTF-8
722
2.65625
3
[]
no_license
// Problem Link: https://www.codechef.com/LTIME84B/problems/LOSTWKND #include <bits/stdc++.h> using namespace std; #define whatis(x) cerr << #x << " is : " << x <<endl; typedef long long ll; typedef unsigned long long ull; int main(){ int t; cin >> t; while(t--){ ll arr[5]; ll p; for(int i=0; i<5; i++){ cin >> arr[i]; } cin >> p; for(int i=0; i<5; i++){ arr[i] *= p; arr[i] -= 24; } ll sum = 0; for(int i=0; i<5; i++){ sum += arr[i]; } if(sum > 0){ cout << "Yes" <<endl; }else{ cout << "No" << endl; } } return 0; }
true
3b5ab7110dddf05d3a8a229c2f909d1c1d983095
C++
seceast/shujujiegou
/栈和队列/LinkQuNodecode.cpp
UTF-8
2,071
3.375
3
[]
no_license
/* * @Author: seceast * @Date: 2020-10-19 15:39:44 * @LastEditors: seceast * @LastEditTime: 2020-10-21 17:08:20 */ #include <stdio.h> #include <stdlib.h> #include <malloc.h> typedef int ElemType; //链队中数据结点类型声明 typedef struct qnode { ElemType data; //存储元素 struct qnode *next; //下一个结点指针 }DataNode; //链队(头)结点声明 typedef struct{ DataNode * front; //指向队首结点 DataNode * rear; //指向队尾结点 }LinkQuNode; //初始化 void InitQueue(LinkQuNode *&q){ q=(LinkQuNode *)malloc(sizeof(LinkQuNode)); q->front=q->rear=NULL; } //销毁 void DestroyQueue(LinkQuNode *& q){ DataNode *pre=q->front, *p; //pre指向队首结点 if(pre!=NULL){ p=pre->next; //p指向pre的后继结点 while(p!=NULL){ //p不为空循环 free(pre); //释放pre pre=p;p=p->next; //pre和p同步后移 } free(pre); //释放最后一个数据结点 } free(q); //释放链队结点 } //判断空 return(q->rear==NULL) //进队 void enQueue(LinkQuNode *& q,ElemType e){ DataNode *p; p=(DataNode *)malloc(sizeof(DataNode)); p->data=e; p->next=NULL; if(q->rear==NULL) q->front=q->rear=p; //若链队为空,则新结点就hi首尾结点 else { q->rear->next=p; //若不为空,P链到队尾,并将rear指向p q->rear=p; } } //出队 bool deQueue(LinkQuNode *& q,ElemType &e){ DataNode *t; if(q->rear==NULL) //原队列为空,返回false return false; t=q->front; //t指向首结点 if(q->front==q->rear) //原来对列中只有一个数据结点时 q->front=q->rear=NULL; else //有两个或以上结点时 q->front=q->front->next; e=t->data; free(t); return true; }
true
3967caf7fbf209b22845656a14096af5af1c5d1c
C++
njozzer/shells_sort
/main.cpp
UTF-8
4,562
3.1875
3
[]
no_license
#include <iostream> #include <pthread.h> #include <stdlib.h> #include <time.h> #include <cstring> #include <vector> void print(int *arr,int n){ std::cout << '\n'; for( int i = 0; i < n; i++ ) { std::cout << arr[i] << ' '; } std::cout << '\n'; } void shell(int *A, int N) { unsigned i,j,k; int t; for( k = N / 2; k > 0; k /= 2 ) for( i = k; i < N; i++ ) { t = A[i]; for( j = i; j >= k; j -= k ) { if( t < A[j - k] ) A[j] = A[j - k]; else break; } A[j] = t; } } void simple_sort(int *arr, int n) { unsigned i,j,k; int t; for( k = n / 2; k > 0; k /= 2 ) for( i = k; i < n; i++ ) { //print(arr,n); t = arr[i]; for( j = i; j >= k; j -= k ) { if( t < arr[j - k] ) arr[j] = arr[j - k]; else break; } arr[j] = t; } } void merge_sort(int* arr,int n){ int i, key, j; for ( i = 1; i < n; i++ ) { key = arr[i]; j = i - 1; while ( j >= 0 && arr[j] > key ) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } struct B { int *arr; int i; int n; int k; int l; }; void *thread(void *args){ B *b = (B*)args; for( int i = 0; i < b->l; i++ ) { arr[i] = &b->arr[b->arr2[i]]; } for( int j = 0; j < n / k; j++ ) { arr2[j] = i + j * k; b->arr = arr; b->arr2 = arr2; b->n = n; b->l = l; //std::cout << arr2[j] << " "; } //i + j * k int i, key, j; for ( i = 1; i < n / k; i++ ) { key = arr[i][0]; j = i - 1; while ( j >= 0 && arr[j][0] > key ) { arr[j + 1][0] = arr[j][0]; j = j - 1; } arr[j + 1][0] = key; } delete b; } void func(int *arr,int n){ //print(arr,n); for( int k = n / 2; k > 1; k /= 2 ) { pthread_t *th = new pthread_t[k]; for( int i = 0; i < k; i++ ) { //arr2[j] = i + j * k; int l = n / k; int *arr2 = new int[l]; B *b = new B; b->arr = arr; b->k = k; b->i = i; b->n = n; for( int j = 0; j < n / k; j++ ) { //std::cout << arr2[j] << " "; } pthread_create(&th[i],NULL,thread,(void*)b); //std::cout << "" << '\n'; } for( int i = 0; i < num; i++ ) { pthread_join(th[i],NULL); } delete[] th; } merge_sort(arr,n); } void *some_func(void* args){ int *arr = (int*)args; for( int i = 0; i < 10000; i++ ) { std::cout << arr[i] << '\n'; } } void foo(){ int n = 10000; int *arr = new int[n]; for( int i = 0; i < n; i++ ) { arr[i] = rand() % 100000 - 500; } pthread_t *pt = new pthread_t; pthread_create(pt,NULL,some_func,(void*)arr); pthread_join(pt[0],NULL); std::cout << "/* message */" << '\n'; } class ShellsSort { private: int *arr; int n; public: void sort(void ( *sort_function )(int*,int) ){ sort_function(arr,n); } ShellsSort(int *arr,int n){ this->arr = new int[n]; memcpy(this->arr,arr,n * sizeof( int ) ); this->n = n; } }; void generate(int *arr,int n){ for( int i = 0; i < n; i++ ) { arr[i] = rand() % 10000 - 500; } } int main() { srand (time(NULL) ); int n = 1000; clock_t t1, t2, t3, t4; int *arr = new int[n]; int *arr2 = new int[n]; generate(arr,n); generate(arr2,n); ShellsSort sh(arr,n); ShellsSort sh2(arr2,n); /*for( int i = 0; i < n; i++ ) { std::cout << arr[i] << ' '; } std::cout << '\n'; */ //print(arr,n); //print(arr2,n); t1 = clock(); shell(arr,n); t2 = clock(); std::cout << "\nTIME without multithreading : " << ( t2 - t1 ) / (double)CLOCKS_PER_SEC << "\n"; t3 = clock(); //sh2.sort(func); func(arr2,n); t4 = clock(); //print(arr,n); //print(arr2,n); /* std::cout << '\n'; for( int i = 0; i < n; i++ ) { std::cout << arr2[i] << ' '; }*/ std::cout << "\nTIME with multithreading : " << ( t4 - t3 ) / (double)CLOCKS_PER_SEC << "\n"; return 0; }
true
acec6849fbd88e6c2a4a52a3f6353857f57e0f2f
C++
ppcamp/digital-image-processing-class
/PDItrabalhos/trab11.cpp
UTF-8
5,021
3.265625
3
[]
no_license
#include <cstdio> #include <opencv2/core.hpp> #include <opencv2\highgui.hpp> using namespace cv; #define MAX 256 #define MIN -1 /** * @brief Apply erosion into a image using the structuring element (SE) * @param image A Mat object monochromatic (grayscale) * @param SE Filter mask * @return Mat object that represent the eroded image. */ Mat erosion( Mat image, int SE[ ][7] ) { Mat output( image.rows, image.cols, image.type( ), Scalar( 0, 0, 0 ) ); // Auxiliar matrix to be base of (solve border problem). @see Gonzales, pg 652 Mat aux( image.rows + 6, image.cols + 6, image.type( ), Scalar( MIN, MIN, MIN ) ); // Put image in center with boders in black for ( int y = 3; y < aux.rows - 3; y++ ) for ( int x = 3; x < aux.cols - 3; x++ ) aux.at<uchar>( y, x ) = image.at<uchar>( y - 3, x - 3 ); // Apply Structuring element (non linear filter) int value, temp; for ( int row = 3; row < aux.rows - 3; row++ ) { for ( int col = 3; col < aux.cols - 3; col++ ) { value = MIN; // Iterate over SE for ( int SEi = 0; SEi < 3; SEi++ ) { for ( int SEj = 0; SEj < 3; SEj++ ) { // Subtract mask from image (Img - Mask) temp = aux.at<uchar>( row + SEi - 3, col + SEj - 3 ) - SE[SEi][SEj]; // Set max color value temp = ( temp < 0 ) ? 0 : ( temp > 255 ) ? 255 : temp; if ( temp > value ) value = temp; } } output.at<uchar>( row - 3, col - 3 ) = ( uchar ) ( ( int ) value ); } } return output; } /** * @brief Apply dilation into a image using the structuring element (SE) * @param image A Mat object monochromatic (grayscale) * @param SE Filter mask * @return Mat object that represent the eroded image. */ Mat dilation( Mat image, int SE[ ][7] ) { Mat output( image.rows, image.cols, image.type( ), Scalar( MAX, MAX, MAX ) ); // Auxiliar matrix to be base of (solve border problem). @see Gonzales, pg 652 Mat aux( image.rows + 6, image.cols + 6, image.type( ), Scalar( MAX, MAX, MAX ) ); // Put image in center with boders in black for ( int y = 3; y < aux.rows - 3; y++ ) for ( int x = 3; x < aux.cols - 3; x++ ) aux.at<uchar>( y, x ) = image.at<uchar>( y - 3, x - 3 ); // Apply Structuring element (non linear filter) int value, temp; for ( int row = 3; row < aux.rows - 3; row++ ) { for ( int col = 3; col < aux.cols - 3; col++ ) { value = MAX; // Iterate over SE for ( int SEi = 0; SEi < 3; SEi++ ) { for ( int SEj = 0; SEj < 3; SEj++ ) { // Subtract mask from image (Img - Mask) temp = aux.at<uchar>( row + SEi - 3, col + SEj - 3 ) + SE[SEi][SEj]; // Set max color value temp = ( temp < 0 ) ? 0 : ( temp > 255 ) ? 255 : temp; if ( temp < value ) value = temp; } } output.at<uchar>( row - 3, col - 3 ) = ( uchar ) ( ( int ) value ); } } return output; } int main( ) { // Load image uchar imgData[10][10] = { { 252, 46, 115, 18, 73, 203, 60, 229, 112, 183 }, { 109, 31, 20, 53, 225, 58, 54, 28, 170, 94 }, { 99, 73, 116, 115, 183, 146, 177, 88, 14, 141 }, { 79, 176, 132, 54, 144, 148, 231, 157, 244, 187 }, { 207, 28, 4, 194, 111, 122, 172, 61, 211, 71 }, { 185, 199, 124, 123, 40, 195, 134, 112, 17, 194 }, { 26, 3, 168, 251, 12, 85, 98, 205, 174, 34 }, { 234, 222, 166, 121, 99, 167, 33, 35, 43, 183 }, { 237, 102, 254, 45, 206, 234, 49, 144, 1, 70 }, { 17, 231, 44, 224, 67, 195, 148, 68, 127, 42 } }; //Mat image( 10, 10, CV_8UC1, &imgData ); Mat image = imread( "Assets/lena.jpg", IMREAD_GRAYSCALE ); // Load structuring element int SE[7][7] = { {0, 0, 0, 1, 0, 0, 0 }, {0, 0, 1, 10, 1, 0, 0 }, {0, 1, 10, 20, 10, 1, 0 }, {1, 10, 20, 40, 20, 10, 1 }, {0, 1, 10, 20, 10, 1, 0 }, {0, 0, 1, 10, 1, 0, 0 }, {0, 0, 0, 1, 0, 0, 0 } }; // Shows original image namedWindow( "Original Image", WINDOW_NORMAL ); imshow( "Original Image", image ); // Get erosion signal Mat erodedImage = erosion( image, SE ); /*for ( int i = 0; i < erodedImage.rows; i++ ) { for ( int j = 0; j < erodedImage.cols; j++ ) printf( "%d\t", ( int ) erodedImage.at<uchar>( i, j ) ); printf( "\n" ); }*/ namedWindow( "Eroded Image", WINDOW_NORMAL ); imshow( "Eroded Image", erodedImage ); // Get dilation signal Mat dilatedImage = dilation( image, SE ); namedWindow( "Dilated Image", WINDOW_NORMAL ); imshow( "Dilated Image", dilatedImage ); // Get morph gradient Mat morgphologicalGradient = dilatedImage - erodedImage; namedWindow( "morgphologicalGradient Image", WINDOW_NORMAL ); imshow( "morgphologicalGradient Image", morgphologicalGradient ); // Get morphological opening Mat morgphologicalOpening = dilation( erodedImage, SE ); namedWindow( "morgphologicalOpening Image", WINDOW_NORMAL ); imshow( "morgphologicalOpening Image", morgphologicalOpening ); // Get morphological closing Mat morgphologicalClosing = erosion( dilatedImage, SE ); namedWindow( "morgphologicalClosing Image", WINDOW_NORMAL ); imshow( "morgphologicalClosing Image", morgphologicalClosing ); // Wait image waitKey( ); }
true
fc67fabcd90bc92942778d3cad08fc5f93215fc3
C++
na-thy/C-
/desafio10.cpp
UTF-8
1,024
4.28125
4
[]
no_license
//crie um algoritmo que tenha uma função recebe 2 ponteiros //e troca o valor de referencia entre os dois. #include <iostream> using namespace std; void swap(int* &valor1, int* &valor2); int main() { float* valor1 = new float; float* valor2 = new float; cout << "Informe o valor 1: "; cin >> *valor1; cout << "Informe o valor 2: "; cin >> *valor2; cout << "O endereço de 1 antes da troca: " << &valor1 << "o valor de 1 antes da troca: " << *valor1 << endl; cout << "O endereço de 2 antes da troca: " << &valor2 << "o valor de 2 antes da troca: " << *valor2 << endl; cout << endl; swap(valor1, valor2); cout << "O endereço de 1 antes da troca: " << &valor1 << "o valor de 1 antes da troca: " << *valor1 << endl; cout << "O endereço de 2 antes da troca: " << &valor2 << "o valor de 2 antes da troca: " << *valor2 << endl; return 0; } void swap(float* &valor1, float* &valor2) { int tmp; tmp = *valor1; *valor1 = *valor2; *valor2 = tmp; }
true
6ae3bbcf53c2f25ff34c8592ee4229fc423e06aa
C++
krovma/FcyF
/Engine/Code/Engine/Core/Vertex_PCUNT.hpp
UTF-8
620
2.75
3
[]
no_license
#pragma once #include "Engine/Math/Vec3.hpp" #include "Engine/Core/Rgba.hpp" #include "Engine/Renderer/RenderBufferLayout.hpp" struct Vertex_PCUNT { public: static BufferAttribute Layout[]; static void VertexMasterCopyProc(void* dst, const VertexMaster* src, int count); public: Vertex_PCUNT(); explicit Vertex_PCUNT(const Vec3 &position, const Rgba &color, const Vec2 &uvTexCoords, const Vec3 &normal, const Vec3& tanget); const Vertex_PCUNT &operator=(const Vertex_PCUNT &copyFrom); public: Vec3 m_position; Rgba m_color; Vec2 m_uvTexCoords; Vec3 m_normal = Vec3(0, 0, 1); Vec3 m_tangent = Vec3(1, 0, 0); };
true
58cacfd2fbe7e085957ed5991c2353e695e9f463
C++
walkccc/LeetCode
/solutions/0465. Optimal Account Balancing/0465.cpp
UTF-8
861
3.109375
3
[ "MIT" ]
permissive
class Solution { public: int minTransfers(vector<vector<int>>& transactions) { vector<int> balance(21); vector<int> debt; for (const vector<int>& t : transactions) { const int from = t[0]; const int to = t[1]; const int amount = t[2]; balance[from] -= amount; balance[to] += amount; } for (const int b : balance) if (b > 0) debt.push_back(b); return dfs(debt, 0); } private: int dfs(vector<int>& debt, int s) { while (s < debt.size() && !debt[s]) ++s; if (s == debt.size()) return 0; int ans = INT_MAX; for (int i = s + 1; i < debt.size(); ++i) if (debt[i] * debt[s] < 0) { debt[i] += debt[s]; // debt[s] is settled ans = min(ans, 1 + dfs(debt, s + 1)); debt[i] -= debt[s]; // Backtrack } return ans; } };
true
513fcb3dbed9e4fc5afb48c90fd25efffb567e83
C++
lim-james/Wind
/Wind/Render.h
UTF-8
841
2.625
3
[]
no_license
#ifndef RENDER_H #define RENDER_H #include "Component.h" #include <Math/Vectors.hpp> #include <Events/Event.h> struct Render; namespace Events { struct TextureChange : Event { const unsigned previous; Render * const component; TextureChange(const unsigned& previous, Render * const component) : previous(previous) , component(component) {} }; } struct Render : Component { // size of UV in tilemap vec4f uvRect; vec4f tint; Render(); void Initialize() override; void SetActive(const bool& state) override; const unsigned& GetTexture() const; void SetTexture(const unsigned& _texture); void SetTilemapSize(const int& width, const int& height); void SetCellRect(const int& x, const int& y, const int& width, const int& height); private: unsigned texture; vec2f tilemapUnit; vec4f cellRect; }; #endif
true
aa365b16876a4808e1208c4de191501cec70eed2
C++
RockyYan1994/Algorithm
/242. Valid Anagram.cpp
UTF-8
1,148
3.65625
4
[]
no_license
/* 方法一:采用无序map记录一个string,然后判断。 */ //version 1(12 ms) class Solution { public: bool isAnagram(string s, string t) { unordered_map<char, int> um; for (auto ch : s) um[ch]++; for (auto ch : t) um[ch]--; for (auto &p : um) { if (p.second != 0) return false; } return true; } }; //version 2(8 ms) class Solution { public: bool isAnagram(string s, string t) { if (s.size() != t.size()) return false; unordered_map<char, int> um; for (int i=0; i<s.size(); i++) { um[s[i]]++; um[t[i]]--; } for (auto &p : um) { if (p.second != 0) return false; } return true; } }; //version 3(4 ms) class Solution { public: bool isAnagram(string s, string t) { if (s.size() != t.size()) return false; vector<int> alpha(26, 0); for (int i=0;i<s.size();i++) { alpha[s[i]-'a']++; alpha[t[i]-'a']--; } for (auto num : alpha) { if (num) return false; } return true; } };
true
ca6639c12c739672f0eb8c25f4d3d9a1c53f8e71
C++
stranxter/lecture-notes
/samples/01_programming 101/2015/functions/funct2.cpp
UTF-8
1,115
3.75
4
[ "MIT" ]
permissive
#include <iostream> using namespace std; int enterNumber (int a, int b) { int input; cout << "Please enter a number between " << a << " and " << b << "..."; do { cin >> input; } while (input < a || input > b); return input; } void printNumber (int x) { while (x != 0) { cout << x % 10; x /= 10; } } void printNumberRec (int x) { if (x < 10) { cout << x; } else { cout << x%10; printNumberRec (x/10); } } const int N = 10; bool isSubset (int a[N], int b[N]) { for (int i = 0; i < N; i++) { bool memberFound = false; for (int j = 0; j < N; j++) { if (a[i] == b[j]) memberFound = true; } //(*) if (!memberFound) return false; } return true; } bool f () { cout << "I am f\n"; return false; } bool g () { cout << "I am g\n"; return true; } int mystery (int x) { return x > 0 && mystery (x-1); cout << x << " "; } int main () { cout << mystery (5); /* if (f() || g ()) cout << "YEAH!"; */ //cout << enterNumber (0,100) / enterNumber (1,100) << endl; // printNumberRec (123456789); // cout << endl; }
true
89b7f91a5c83bbc4ec4b5c6a88e18f399d55c57d
C++
paulosuzart/graphic_editor
/src/Command.cpp
UTF-8
715
2.671875
3
[ "Apache-2.0" ]
permissive
/* * Command.cpp * * Created on: Jan 14, 2017 * Author: suzart */ #include "Command.h" #include <iostream> using namespace std; namespace paulosuzart { Command::Command(GraphEditor* editor, string command) : editor(editor), command(command) { } bool Command::run() { try { vector<string> v; split(v, command, is_space()); return parseCommand(v) && doRun(); } catch (const boost::bad_lexical_cast &e) { std::cerr << "Ignoring command '" << command << "' due to invalid input type" << std::endl; return true; } } bool Command::doRun() { return true; } bool Command::parseCommand(vector<string>& params) { return true; } Command::~Command() { } } /* namespace paulosuzart */
true
7c7e31c47ffec7c4b15ccf79b5f6a67e32322003
C++
youlive789/AlgorithmStudy
/Codeup/dp/3707.cpp
UTF-8
547
3.03125
3
[]
no_license
#include <iostream> using namespace std; unsigned long cache[100000]; unsigned long dfs(short number) { if (number == 0) { return 1; } if (cache[number]) { return cache[number]; } else { unsigned long sum = 0; for (int idx = 1; idx <= number; idx++) { sum += cache[number - idx] = dfs(number - idx); } return sum; } } int main() { short number; cin >> number; cout << dfs(number) - 1 << endl; return 0; }
true
e266dc82bfe615a9249db5e4cd022d82d0db1035
C++
ciscoruiz/emc2
/solutions/06_future/future.cpp
UTF-8
3,178
3.546875
4
[ "MIT" ]
permissive
#include <vector> #include <thread> #include <algorithm> #include <time.h> #include <sys/time.h> #include <iostream> #include <future> typedef std::vector<int> InputValues; double averageMethod (const InputValues& values) { long result = 0; for (int value : values) { result += value; } return result / values.size (); } int maxMethod (const InputValues& values) { auto ii = max_element (values.begin (), values.end ()); return *ii; } int minMethod (const InputValues& values) { auto ii = min_element (values.begin (), values.end ()); return *ii; } long millisecond () noexcept { struct timeval now; gettimeofday (&now, NULL); long result = now.tv_sec * 1000; return result + now.tv_usec / 1000; } void usual (const InputValues& values) { long init = millisecond (); double average = averageMethod (values); int max = maxMethod (values); int min = minMethod (values); double result = max - min / average; long end = millisecond (); std::cout << __func__ << " Result=" << result << " Time=" << end - init << " ms" << std::endl; } void averagePromise (std::promise <double>& prm, const InputValues& values) { prm.set_value (averageMethod (values)); } void maxPromise (std::promise <int>& promise, const InputValues& values) { promise.set_value (maxMethod (values)); } void minPromise (std::promise <int>& promise, const InputValues& values) { promise.set_value (minMethod (values)); } void promiseAndFuture (const std::vector<int>& values) { long init = millisecond (); std::promise <double> prmAvg; std::future <double> futAvg = prmAvg.get_future (); std::thread (averagePromise, std::ref (prmAvg), std::ref (values)).detach (); std::promise <int> prmMax; std::future <int> futMax = prmMax.get_future (); std::thread (maxPromise, std::ref (prmMax), std::ref (values)).detach (); std::promise <int> prmMin; std::future <int> futMin = prmMin.get_future (); std::thread (minPromise, std::ref (prmMin), std::ref (values)).detach (); double average = futAvg.get (); int max = futMax.get (); int min = futMin.get (); double result = max - min / average; long end = millisecond (); std::cout << __func__ << " Result=" << result << " Time=" << end - init << " ms" << std::endl; } void usingSync (const std::vector<int>& values) { long init = millisecond (); std::future <double> futAvg = std::async (std::launch::async, averageMethod, std::ref (values)); std::future <int> futMax = std::async (std::launch::async, maxMethod, std::ref (values)); std::future <int> futMin = std::async (std::launch::async, minMethod, std::ref (values)); double average = futAvg.get (); int max = futMax.get (); int min = futMin.get (); double result = max - min / average; long end = millisecond (); std::cout << __func__ << " Result=" << result << " Time=" << end - init << " ms" << std::endl; } int main () { InputValues values; for (int ii = 0; ii < 10000000; ++ ii) values.push_back (rand ()); usual (values); promiseAndFuture (values); usingSync (values); }
true
9be664eca1bc24d038af6967452c6329ad8c4e2b
C++
firewood/topcoder
/atcoder/abc_085/d.cpp
UTF-8
538
2.734375
3
[]
no_license
// D. #include <iostream> #include <cstdio> #include <vector> #include <algorithm> using namespace std; int main(int argc, char *argv[]) { int n, h; cin >> n >> h; vector<int> a(n), b(n); for (int i = 0; i < n; ++i) { cin >> a[i] >> b[i]; } sort(a.rbegin(), a.rend()); sort(b.rbegin(), b.rend()); int d = a[0]; int ans = 0, tot = 0; for (int i = 0; i < n; ++i) { if (b[i] > d) { ++ans; tot += b[i]; if (tot >= h) { break; } } } ans += (max(0, h - tot) + d - 1) / d; cout << ans << endl; return 0; }
true
08d5ba824be1be5516e86451cd3a34a0071d518b
C++
hoklavat/beginner-algorithms
/MORE/Dynamic(UglyNumbers).cpp
UTF-8
1,056
3.796875
4
[]
no_license
//Dynamic(UglyNumbers) //ugly numbers are numbers whose only prime factors are 2, 3 or 5. 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ... //Task: find nth ugly number. //Reference: dynamic programming. //Time Complexity: O(n). #include <iostream> using namespace std; unsigned findUglyNumber(unsigned n){ unsigned ugly[n]; unsigned i2 = 0, i3 = 0, i5 = 0; unsigned next_multiple_of_2 = 2; unsigned next_multiple_of_3 = 3; unsigned next_multiple_of_5 = 5; unsigned next_ugly_no = 1; ugly[0] = 1; //first ugly number. for(int i = 1; i < n; i++){ next_ugly_no = min(next_multiple_of_2, min(next_multiple_of_3, next_multiple_of_5)); ugly[i] = next_ugly_no; if(next_ugly_no == next_multiple_of_2){ i2 = i2+1; next_multiple_of_2 = ugly[i2]*2; } if(next_ugly_no == next_multiple_of_3){ i3 = i3+1; next_multiple_of_3 = ugly[i3]*3; } if(next_ugly_no == next_multiple_of_5){ i5 = i5+1; next_multiple_of_5 = ugly[i5]*5; } } return next_ugly_no; } int main(){ int n = 150; cout << findUglyNumber(n) << endl; return 0; }
true
b38107e2ffa965cb26678971b656965354768460
C++
mismayil/cs488
/A2/A2.hpp
UTF-8
2,472
2.8125
3
[]
no_license
#pragma once #include "cs488-framework/CS488Window.hpp" #include "cs488-framework/OpenGLImport.hpp" #include "cs488-framework/ShaderProgram.hpp" #include <glm/glm.hpp> #include <vector> // Set a global maximum number of vertices in order to pre-allocate VBO data // in one shot, rather than reallocating each frame. const GLsizei kMaxVertices = 1000; // Convenience class for storing vertex data in CPU memory. // Data should be copied over to GPU memory via VBO storage before rendering. class VertexData { public: VertexData(); std::vector<glm::vec2> positions; std::vector<glm::vec3> colours; GLuint index; GLsizei numVertices; }; struct line { glm::vec4 A; glm::vec4 B; }; struct plane { glm::vec4 P; glm::vec4 n; }; class A2 : public CS488Window { public: A2(); virtual ~A2(); protected: virtual void init() override; virtual void appLogic() override; virtual void guiLogic() override; virtual void draw() override; virtual void cleanup() override; virtual bool cursorEnterWindowEvent(int entered) override; virtual bool mouseMoveEvent(double xPos, double yPos) override; virtual bool mouseButtonInputEvent(int button, int actions, int mods) override; virtual bool mouseScrollEvent(double xOffSet, double yOffSet) override; virtual bool windowResizeEvent(int width, int height) override; virtual bool keyInputEvent(int key, int action, int mods) override; void createShaderProgram(); void enableVertexAttribIndices(); void generateVertexBuffers(); void mapVboDataToVertexAttributeLocation(); void uploadVertexDataToVbos(); void initLineData(); void setLineColour(const glm::vec3 & colour); void drawLine ( const glm::vec2 & v0, const glm::vec2 & v1 ); void reset(); void drawViewport(); void drawCube(); void drawModelCoord(); void drawWorldCoord(); glm::mat4 getProj(float fov, float aspect, float f, float n); glm::mat4 getViewport(glm::vec4 vp, float width, float height, float f, float n); void clip(line line, std::vector<plane> planes); ShaderProgram m_shader; GLuint m_vao; // Vertex Array Object GLuint m_vbo_positions; // Vertex Buffer Object GLuint m_vbo_colours; // Vertex Buffer Object VertexData m_vertexData; glm::vec3 m_currentLineColour; int mode; glm::mat4 VP; glm::mat4 VPMODEL; glm::mat4 PROJ; glm::mat4 VIEW; glm::mat4 MODEL; glm::mat4 CMODEL; glm::vec4 vpStart; float vpWidth; float vpHeight; float ASPECT; float FOV; float NP; float FP; };
true
50bc54202357ba4258723f0524cdc92738b505d8
C++
mzlogin/LeetCode
/algorithms/cpp/implementQueueUsingStacks/test.cpp
UTF-8
664
3.34375
3
[ "MIT" ]
permissive
#include "../catch.h" #include <stack> using std::stack; #include "solution.h" TEST_CASE("Implement Queue Using Stacks", "implementQueueUsingStacks") { Queue q; SECTION("test push and peek") { q.push(1); CHECK(q.peek() == 1); } SECTION("test queue order") { q.push(1); q.push(2); CHECK(q.peek() == 1); } SECTION("test pop") { q.push(1); q.push(2); q.pop(); CHECK(q.peek() == 2); } SECTION("test empty") { q.push(1); q.push(2); q.pop(); CHECK(q.empty() == false); q.pop(); CHECK(q.empty() == true); } }
true
7ac373415a2a147889a8b4cd3a5bdad135ddca2d
C++
jdflyfly/shootForOffer
/4.cpp
UTF-8
570
2.5625
3
[]
no_license
#include <stdio.h> #include <string.h> int main(void) { // freopen("in.txt","r",stdin); char str[1000001]; int len; int new_len; int i; int cnt; gets(str); len = strlen(str); cnt = 0; for (i = 0; i < len; ++i) { if (str[i] == ' ') ++cnt; } new_len = len + 2 * cnt; str[new_len] = '\0'; --len; --new_len; while (len >= 0) { if (str[len] != ' ') { str[new_len] = str[len]; --new_len; --len; } else { str[new_len] = '0'; str[new_len - 1] = '2'; str[new_len - 2] = '%'; new_len -= 3; --len; } } puts(str); return 0; }
true
59000145d4583b7aa81252c0af9ad84f08f89048
C++
LaiTial/CplusPlus
/BookPractice/Chapter2/비밀코드 맞추기/FindCode.cpp
UHC
740
3.5625
4
[]
no_license
/* 2019-08-31  c++ ó! chapter2 LAB1 ǻͰ ִ ڵ带 ϴ α׷ 97~122 => a~z */ #include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main() { char code = 97, ans; string locate; srand(unsigned int(time(NULL))); code += rand() % 26; do { cout << "ڵ带 纸: "; cin >> ans; if (code > ans) locate = " ڿ ."; else if (code < ans) locate = " տ ."; else { break; } cout << ans << locate << endl << endl; } while (code != ans); cout << "մϴ! ڵ带 ߼̽ϴ!" << endl; return 0; }
true
b1825769559265c13f1a44ec0db12fee5c7c2d25
C++
tianfangma/leetcode
/problem/201-300/213.cpp
UTF-8
730
3.328125
3
[]
no_license
/* 分成两种情况,1:偷第一家不偷最后一家;2偷最后一家不偷第一家 状态转移方程同198 */ class Solution { public: int rob(vector<int>& nums) { if(nums.empty()) { return 0; } else if(nums.size()==1) { return nums[0]; } return max(robrob(0,nums.size()-1,nums),robrob(1,nums.size(),nums)); } int robrob(int start,int end,vector<int>& nums) { int preMAX=0; int currentMAX=0; for(int i=start;i<end;++i) { int temp=currentMAX; currentMAX=max(preMAX+nums[i],currentMAX); preMAX=temp; } return max(currentMAX,preMAX); } };
true
4a80aa25635c65d9ba5c3e3940fe518aeff11231
C++
zer02001/csc-2010
/csc 2111 lab 08/csc 2111 lab 08.cpp
UTF-8
1,493
3.25
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; void getdata(string[], int[][5]); void getaverage(int[][5], double[]); void print(string[], int[][5], double[]); int main() { double avg; int grades[10][5]; string names[10]; double average[10]; int tot; getdata(names, grades); getaverage(grades, average); print(names, grades, average); system("pause"); return 0; } void print(string names[], int grades[][5], double avg[]) { int i, j; cout << "name\t test grades\taverage\tgrade\n"; for (i = 0; i < 10; i++) { cout << names[i] << "\t"; for (j = 0; j < 5; j++) cout << grades[i][j] << " "; cout << "\t" << avg[i] << "\t"; if (avg[i] >= 90) cout << "A" << endl; else if (avg[i] >= 80) cout << "B" << endl; else if (avg[i] >= 70) cout << "C\n"; else if (avg[i] >= 60) cout << "D\n"; else cout << "F\n"; } } void getaverage(int grades[][5], double avg[]) { int i, j, tot; for (i = 0; i < 10; i++) { tot = 0; for (j = 0; j < 5; j++) tot += grades[i][j]; avg[i] = tot / 5.; } } void getdata(string names[], int grades[][5]) { ifstream in; int i, j; in.open("testscores.txt"); //open file if (in.fail()) //is it ok? { cout << "file did not open please check it\n"; system("pause"); exit(1); } for (i = 0; i < 10; i++) { in >> names[i]; for (j = 0; j < 5; j++) in >> grades[i][j]; in.ignore('\n', 10); } }
true
3f35a044ce5a61c98b5fec6706a37a76eb0e3d82
C++
MachineGunLin/LeetCode_Solutions
/树/297. 二叉树的序列化与反序列化.cpp
UTF-8
2,822
4.21875
4
[]
no_license
/* 将二叉树先序遍历解码为一个序列字符串s,不同的数字之间用逗号分隔,如果遇到空节点,就只在s加上一个","。 如果不是空节点,就先加上当前节点的值,然后再加上逗号。 解码的时候,也是取两个逗号之间的值,如果逗号之间为空,则说明是空节点,否则new一个TreeNode出来,节点的值就是两个逗号之间的 子串的值转为int。 */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Codec { public: void encode(TreeNode* root, string &s) { if(root == NULL) { // 空节点在序列化的时候只加上一个逗号 s += ","; return ; } s += to_string(root -> val) + ","; // 非空节点在序列化的时候先加上节点值再加上逗号 encode(root -> left, s); // 先序遍历序列化二叉树 encode(root -> right, s); } // Encodes a tree to a single string. string serialize(TreeNode* root) { string s; encode(root, s); // 序列化编码的结果记录在字符串s里 return s; } TreeNode* decode(string &s, int &cur) { // 从字符串s反序列化二叉树,cur是当前解码的字符在字符串s中的下标,这里注意s和cur必须是引用 if(s[cur] == ',') { // 如果两个逗号之间什么也没有,说明是空节点 ++cur; return NULL; } int end = cur; // end记录下一个逗号的位置 while(end < s.size() && s[end] != ',') { ++end; } TreeNode* root = new TreeNode(stoi(s.substr(cur, end - cur))); // 两个逗号之间的子串的值转为int就是当前节点的值 cur = end + 1; // cur从下一个逗号的下一个位置开始解码 root -> left = decode(s, cur); // 先序遍历解码字符串s root -> right = decode(s, cur); return root; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { int cur = 0; // 从要解码的字符串的第0个字母开始解码 TreeNode* root = decode(data, cur); return root; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));
true
5c51caf3475585814b71c4b1b9075c46c4df877b
C++
xsatishx/cloud-repo
/parcel/parcel/src/tcp2udt.cpp
UTF-8
11,971
2.515625
3
[ "Apache-2.0" ]
permissive
/****************************************************************************** * * FILE : tcp2udt.cpp * PROJECT : parcel * * DESCRIPTION : This file contains functions for creating a TCP * server that accpts incomming connections, creates a * UDT connection to remote server, and proxies the * traffic through. * * LICENSE : 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.) * ******************************************************************************/ #include "parcel.h" EXTERN int tcp2udt_start(char *local_host, char *local_port, char *remote_host, char *remote_port) { /* * tcp2udt_start() - starts a UDT proxy server * * Starts a proxy server listening on local_host:local_port. * Incomming connections get their own thread and a proxied * connection to remote_host:remote_port. */ int mss = MSS; int udt_buffer_size = BUFF_SIZE*2; int udp_buffer_size = BUFF_SIZE; return tcp2udt_start_configurable(local_host, local_port, remote_host, remote_port, mss, udt_buffer_size, udp_buffer_size); } EXTERN int tcp2udt_start_configurable(char *local_host, char *local_port, char *remote_host, char *remote_port, int mss, int udt_buffer_size, int udp_buffer_size) { /* * tcp2udt_start() - starts a TCP-to-UDT proxy thread * * Starts a proxy server listening on local_host:local_port. * Incomming connections get their own thread and a proxied * connection to remote_host:remote_port. */ log("Proxy binding to local TCP socket [%s:%s] to remote UDT [%s:%s]", local_host, local_port, remote_host, remote_port); debug("MSS : %d", mss); debug("UDT_BUFFER_SIZE: %d", udt_buffer_size); debug("UDP_BUFFER_SIZE: %d", udp_buffer_size); addrinfo hints; addrinfo* res; int tcp_socket; int reuseaddr = 1; /******************************************************************* * Establish server socket ******************************************************************/ /* Setup address information */ memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; if (getaddrinfo(NULL, local_port, &hints, &res) != 0){ cerr << "illegal port number or port is busy: " << "[" << local_port << "]" << endl; return -1; } /* Create the server socket */ tcp_socket = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (tcp_socket < 0){ perror("Unable to create TCP socket"); return -1; } setsockopt(tcp_socket, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(int)); /* Bind the server socket */ log("Proxy binding to TCP socket [%s:%s]", local_host, local_port); if (bind(tcp_socket, res->ai_addr, res->ai_addrlen)){ perror("Unable to bind TCP socket"); return -1; } log("Proxy bound to local TCP socket [%s:%s] to remote UDT [%s:%s]", local_host, local_port, remote_host, remote_port); /* We no longer need this address information */ freeaddrinfo(res); /* Listen on the port for TCP connections */ debug("Calling socket listen"); if (listen(tcp_socket, 10)){ perror("Unable to call TCP socket listen"); return -1; } debug("Creating pipe2tcp server thread"); pthread_t tcp2udt_server_thread; server_args_t *args = (server_args_t*) malloc(sizeof(server_args_t)); args->remote_host = strdup(remote_host); args->remote_port = strdup(remote_port); args->tcp_socket = tcp_socket; args->mss = mss; args->udt_buffer_size = udt_buffer_size; args->udp_buffer_size = udp_buffer_size; if (pthread_create(&tcp2udt_server_thread, NULL, tcp2udt_accept_clients, args)){ perror("unable to create tcp2udt server thread"); free(args); return -1; } return 0; } EXTERN void *tcp2udt_accept_clients(void *_args_) { /* * udt2tcp_accept_clients() - Accepts incoming UDT clients * */ server_args_t *args = (server_args_t*) _args_; while (1) { int client_socket; sockaddr_storage clientaddr; socklen_t addrlen = sizeof(clientaddr); /* Wait for the next connection */ debug("Accepting incoming TCP connections"); client_socket = accept(args->tcp_socket, (sockaddr*)&clientaddr, &addrlen); if (client_socket < 0){ perror("Socket accept failed"); return 0; } debug("New TCP connection"); /******************************************************************* * Create proxy threads ******************************************************************/ /* Create transcriber thread args */ transcriber_args_t *transcriber_args = (transcriber_args_t *) malloc(sizeof(transcriber_args_t)); transcriber_args->udt_socket = 0; // will be set by thread_tcp2udt transcriber_args->tcp_socket = client_socket; transcriber_args->remote_host = args->remote_host; transcriber_args->remote_port = args->remote_port; transcriber_args->mss = args->mss; transcriber_args->udt_buffer_size = args->udt_buffer_size; transcriber_args->udp_buffer_size = args->udp_buffer_size; /* Create tcp2udt thread */ pthread_t tcp_thread; if (pthread_create(&tcp_thread, NULL, thread_tcp2udt, transcriber_args)){ perror("Unable to TCP thread"); free(transcriber_args); return 0; } else { pthread_detach(tcp_thread); } /* Create udt2tcp thread */ pthread_t udt_thread; if (pthread_create(&udt_thread, NULL, thread_udt2tcp, transcriber_args)){ perror("Unable to TCP thread"); free(transcriber_args); return 0; } else { pthread_detach(udt_thread); } } return NULL; } int connect_remote_udt(transcriber_args_t *args) { /* * connect_remote_udt() - Creates client connection to UDT server * */ debug("Connecting to remote UDT at [%s:%s]", args->remote_host, args->remote_port); UDTSOCKET udt_socket; int mss = args->mss; int udt_buff = args->udt_buffer_size; int udp_buff = args->udp_buffer_size; /* Create address information */ struct addrinfo hints, *local, *peer; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; if (0 != getaddrinfo(NULL, args->remote_port, &hints, &local)){ cerr << "incorrect network address.\n" << endl; return -1; } /* Create UDT socket */ udt_socket = UDT::socket(local->ai_family, local->ai_socktype, local->ai_protocol); freeaddrinfo(local); /* Set UDT options */ UDT::setsockopt(udt_socket, 0, UDT_MSS, &mss, sizeof(int)); UDT::setsockopt(udt_socket, 0, UDT_SNDBUF, &udt_buff, sizeof(int)); UDT::setsockopt(udt_socket, 0, UDP_SNDBUF, &udp_buff, sizeof(int)); UDT::setsockopt(udt_socket, 0, UDT_RCVBUF, &udt_buff, sizeof(int)); UDT::setsockopt(udt_socket, 0, UDP_RCVBUF, &udp_buff, sizeof(int)); /* Get address information */ if (0 != getaddrinfo(args->remote_host, args->remote_port, &hints, &peer)){ cerr << "incorrect server/peer address. " << args->remote_host << ":" << args->remote_port << endl; freeaddrinfo(peer); return -1; } /* Connect to the server */ debug("Connecting to remote UDT server"); if (UDT::ERROR == UDT::connect(udt_socket, peer->ai_addr, peer->ai_addrlen)){ cerr << "connect: " << UDT::getlasterror().getErrorMessage() << endl; freeaddrinfo(peer); return -1; } freeaddrinfo(peer); return udt_socket; } void *thread_tcp2udt(void *_args_) { /* * thread_tcp2udt() - * */ transcriber_args_t *args = (transcriber_args_t*) _args_; /******************************************************************* * Setup proxy procedure ******************************************************************/ /* * I've made the design choice that the tcp2udt thread is not * responsible for the tcp socket, because it is reading from it, * not writing. Therefore, we will wait for an external entity to * set args->tcp_socket to be a valid descriptor (it may already * be valid as set by a _start() method). */ debug("Waiting on TCP socket ready"); while (!args->tcp_socket){ // TODO: Add semaphore on socket ready, usleep is a // lazy solution for now usleep(100); } debug("TCP socket ready: %d", args->tcp_socket); /* * Similarly I've made the design choice that the tcp2udt thread * IS responsible for the udt socket, because it is writing to it, * not reading. Therefore, we will attempt to connect to a remote * server via udt. However, if there is already an existing udt * connection, then by golly, someone wants us to use it (that * someone is me or you?). */ if (!args->udt_socket){ if ((args->udt_socket = connect_remote_udt(args)) <= 0){ close(args->udt_socket); free(args); return NULL; } } /******************************************************************* * Begin proxy procedure ******************************************************************/ CircularBuffer *cbuffer = new CircularBuffer(CIRCULAR_BUFF_SIZE); /* Create pipe, read from 0, write to 1 */ int pipefd[2]; if (pipe(pipefd) == -1) { perror("pipe"); free(args); return NULL; } /* Create UDT to pipe thread */ pthread_t tcp2pipe_thread; tcp_pipe_args_t *tcp2pipe_args = (tcp_pipe_args_t*)malloc(sizeof(tcp_pipe_args_t)); tcp2pipe_args->tcp_socket = args->tcp_socket; tcp2pipe_args->pipe = cbuffer; debug("Creating tcp2pipe thread"); if (pthread_create(&tcp2pipe_thread, NULL, tcp2pipe, tcp2pipe_args)){ perror("unable to create tcp2pipe thread"); free(args); return NULL; } /* Create pipe to TCP args */ udt_pipe_args_t *pipe2udt_args = (udt_pipe_args_t*)malloc(sizeof(udt_pipe_args_t)); pipe2udt_args->udt_socket = args->udt_socket; pipe2udt_args->pipe = cbuffer; debug("Calling pipe2udt"); pipe2udt(pipe2udt_args); // There is no reason not to block on this now void *ret; pthread_join(tcp2pipe_thread, &ret); delete cbuffer; return NULL; }
true
e06f31eeb00364708e6d7bb84443ca2552d33e7b
C++
wallband/verklegt1-2017
/Verk1R/verk1Aii/main.cpp
UTF-8
625
3.296875
3
[]
no_license
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ofstream fout; fout.open("textFileB.txt", ios::app); if (fout.is_open()) { string str; cout << "Please write a sentence: " << endl; while(str[0] != '\\') { getline(cin, str); if (str[0] == '\\') { return 0; } else { fout << str << endl; } } fout.close(); }else { cout << "File could not be openend!" << endl; } return 0; }
true
8f0dd020b1b37293ee0c7dcb8882829ac29b06ff
C++
tanmay017/Data-Structure-and-Algorithms-Learning
/14. Trees/children_sum_property.cpp
UTF-8
807
3.328125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; struct Node { int key; Node *left; Node *right; Node(int k) { key = k; left = right = NULL; } }; bool isCSum(Node *root) { if (root == NULL) return true; if (root->left == NULL && root->right == NULL) return true; int sum = 0; if (root->left != NULL) sum += root->left->key; if (root->right != NULL) sum += root->right->key; return (root->key == sum && isCSum(root->left) && isCSum(root->right)); } int main() { Node *root = new Node(30); root->left = new Node(17); root->right = new Node(13); root->left->left = new Node(10); root->left->right = new Node(7); root->right->right = new Node(13); if (isCSum(root)) cout << "Yes"; }
true
fad1b911503c7a1a28a88b0380b2308bc77d8f11
C++
KirylShakh/BlobGameStudy
/Source/Blob/BlobGameMode.cpp
UTF-8
2,721
2.625
3
[]
no_license
// Copyright Epic Games, Inc. All Rights Reserved. #include "BlobGameMode.h" #include "BlobPawn.h" #include "Tile.h" #include "Obstacle.h" #include "Droplet.h" ABlobGameMode::ABlobGameMode() { PrimaryActorTick.bCanEverTick = true; } void ABlobGameMode::BeginPlay() { Super::BeginPlay(); CreateInitialTiles(); } void ABlobGameMode::CreateInitialTiles() { for (int i = 0; i < NumInitialTiles; i++) { AddTile(); } } void ABlobGameMode::AddTile() { ATile* Tile = GetWorld()->SpawnActor<ATile>(TileClass, NextSpawnPoint); if (Tile) { CreatePlacebles(Tile); NextSpawnPoint = FTransform(FVector(0.f, 0.f, NextSpawnPoint.GetTranslation().Z - TileHeight)); } } void ABlobGameMode::CreatePlacebles(ATile* Tile) { float RandDeltaY = FMath::FRandRange(0.f, ObstacleWidth); float Y = LeftBorder + RandDeltaY + ObstacleWidth / 2.f; float MaxY = RightBorder - ObstacleWidth / 2.f; // Make a list of potential starting Y-positions for obstacles TArray<float> PotentialSpawnPoints; while (Y <= MaxY) { PotentialSpawnPoints.Add(Y); Y += ObstacleWidth; } int32 NumObstacles = FMath::FloorToInt(FMath::FRandRange(0.f, MaxObstaclesPerTile)); for (int32 i = 0; i < NumObstacles; i++) { int32 Index = FMath::FloorToInt(FMath::FRandRange(0.f, (float)PotentialSpawnPoints.Num() - .6f)); Tile->AddPlaceble(CreateObstacle(PotentialSpawnPoints[Index])); PotentialSpawnPoints.RemoveAt(Index); } int32 NumDroplets = FMath::FloorToInt(FMath::FRandRange(0.f, MaxDropletsPerTile)); for (int32 i = 0; i < NumDroplets; i++) { int32 Index = FMath::FloorToInt(FMath::FRandRange(0.f, (float)PotentialSpawnPoints.Num() - .6f)); Tile->AddPlaceble(CreateDroplet(PotentialSpawnPoints[Index])); PotentialSpawnPoints.RemoveAt(Index); } } AObstacle* ABlobGameMode::CreateObstacle(float SpawnY) { FActorSpawnParameters SpawnParameters; SpawnParameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; float SpawnZ = FMath::FRandRange(NextSpawnPoint.GetTranslation().Z, NextSpawnPoint.GetTranslation().Z + TileHeight); const FTransform SpawnTransform = FTransform(FVector(0.f, SpawnY, SpawnZ)); return GetWorld()->SpawnActor<AObstacle>(ObstacleClass, SpawnTransform, SpawnParameters); } ADroplet* ABlobGameMode::CreateDroplet(float SpawnY) { FActorSpawnParameters SpawnParameters; SpawnParameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; float SpawnZ = FMath::FRandRange(NextSpawnPoint.GetTranslation().Z, NextSpawnPoint.GetTranslation().Z + TileHeight); const FTransform SpawnTransform = FTransform(FVector(0.f, SpawnY, SpawnZ)); return GetWorld()->SpawnActor<ADroplet>(DropletClass, SpawnTransform, SpawnParameters); }
true
6b29c0c783a9b1c69e4e92b4eb5472fab878b752
C++
duixin111/CPlusPlus
/singleNumber2.cpp
UTF-8
322
2.609375
3
[]
no_license
class Solution { public: int singleNumber(vector<int>& nums) { map<int, int> q; for(int num: nums) ++q[num]; for(auto [num, occ] : q) { if(occ == 1) { return num; break; } } return -1; } };
true
16acc9b553c11f791b0ee1c940539d0b05fc449a
C++
s5063638/ChristosEngine2
/src/game_engine/Component.h
UTF-8
1,023
2.78125
3
[]
no_license
#ifndef _COMPONENT_H_ #define _COMPONENT_H_ #include <memory> #include "Engine.h" namespace game_engine { class Entity; class Engine; class Keyboard; class Transform; class Component { private: friend class Entity; std::weak_ptr<Entity> entity; public: virtual void OnInit(); /*!< Initialises the Component*/ virtual void OnBegin(); virtual void OnDisplay(); /*!< Used to display in the Renderer component*/ virtual void OnUpdate(); /*!< Updates the Component*/ std::shared_ptr<Entity> GetEntity(); /*!< Shortcut that returns the Entity that the current Component is attached to*/ std::shared_ptr<Engine> GetEngine(); /*!< Shortcut that returns the Engine */ std::shared_ptr<Keyboard> GetKeyboard(); /*!< Shortcut that returns the Keyboard*/ std::shared_ptr<Entity> AddEntity(); /*!< Shortcut to add a new Entity to the game*/ std::shared_ptr<Transform> GetTransform(); /*!< Shortcut that returns the Transform component of the current Entity*/ }; } #endif // !_COMPONENT_H_
true
e457da756b0bb82c286e6f9c81c2f056c47576ba
C++
OriginQ/QPanda-2
/ThirdParty/EigenUnsupported/Eigen/src/Skyline/SkylineInplaceLU.h
UTF-8
11,332
2.765625
3
[ "Apache-2.0" ]
permissive
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Guillaume Saupin <guillaume.saupin@cea.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_SKYLINEINPLACELU_H #define EIGEN_SKYLINEINPLACELU_H namespace Eigen { /** \ingroup Skyline_Module * * \class SkylineInplaceLU * * \brief Inplace LU decomposition of a skyline matrix and associated features * * \param MatrixType the type of the matrix of which we are computing the LU factorization * */ template<typename MatrixType> class SkylineInplaceLU { protected: typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::Index Index; typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar; public: /** Creates a LU object and compute the respective factorization of \a matrix using * flags \a flags. */ SkylineInplaceLU(MatrixType& matrix, int flags = 0) : /*m_matrix(matrix.rows(), matrix.cols()),*/ m_flags(flags), m_status(0), m_lu(matrix) { m_precision = RealScalar(0.1) * Eigen::dummy_precision<RealScalar > (); m_lu.IsRowMajor ? computeRowMajor() : compute(); } /** Sets the relative threshold value used to prune zero coefficients during the decomposition. * * Setting a value greater than zero speeds up computation, and yields to an imcomplete * factorization with fewer non zero coefficients. Such approximate factors are especially * useful to initialize an iterative solver. * * Note that the exact meaning of this parameter might depends on the actual * backend. Moreover, not all backends support this feature. * * \sa precision() */ void setPrecision(RealScalar v) { m_precision = v; } /** \returns the current precision. * * \sa setPrecision() */ RealScalar precision() const { return m_precision; } /** Sets the flags. Possible values are: * - CompleteFactorization * - IncompleteFactorization * - MemoryEfficient * - one of the ordering methods * - etc... * * \sa flags() */ void setFlags(int f) { m_flags = f; } /** \returns the current flags */ int flags() const { return m_flags; } void setOrderingMethod(int m) { m_flags = m; } int orderingMethod() const { return m_flags; } /** Computes/re-computes the LU factorization */ void compute(); void computeRowMajor(); /** \returns the lower triangular matrix L */ //inline const MatrixType& matrixL() const { return m_matrixL; } /** \returns the upper triangular matrix U */ //inline const MatrixType& matrixU() const { return m_matrixU; } template<typename BDerived, typename XDerived> bool solve(const MatrixBase<BDerived> &b, MatrixBase<XDerived>* x, const int transposed = 0) const; /** \returns true if the factorization succeeded */ inline bool succeeded(void) const { return m_succeeded; } protected: RealScalar m_precision; int m_flags; mutable int m_status; bool m_succeeded; MatrixType& m_lu; }; /** Computes / recomputes the in place LU decomposition of the SkylineInplaceLU. * using the default algorithm. */ template<typename MatrixType> //template<typename _Scalar> void SkylineInplaceLU<MatrixType>::compute() { const size_t rows = m_lu.rows(); const size_t cols = m_lu.cols(); eigen_assert(rows == cols && "We do not (yet) support rectangular LU."); eigen_assert(!m_lu.IsRowMajor && "LU decomposition does not work with rowMajor Storage"); for (Index row = 0; row < rows; row++) { const double pivot = m_lu.coeffDiag(row); //Lower matrix Columns update const Index& col = row; for (typename MatrixType::InnerLowerIterator lIt(m_lu, col); lIt; ++lIt) { lIt.valueRef() /= pivot; } //Upper matrix update -> contiguous memory access typename MatrixType::InnerLowerIterator lIt(m_lu, col); for (Index rrow = row + 1; rrow < m_lu.rows(); rrow++) { typename MatrixType::InnerUpperIterator uItPivot(m_lu, row); typename MatrixType::InnerUpperIterator uIt(m_lu, rrow); const double coef = lIt.value(); uItPivot += (rrow - row - 1); //update upper part -> contiguous memory access for (++uItPivot; uIt && uItPivot;) { uIt.valueRef() -= uItPivot.value() * coef; ++uIt; ++uItPivot; } ++lIt; } //Upper matrix update -> non contiguous memory access typename MatrixType::InnerLowerIterator lIt3(m_lu, col); for (Index rrow = row + 1; rrow < m_lu.rows(); rrow++) { typename MatrixType::InnerUpperIterator uItPivot(m_lu, row); const double coef = lIt3.value(); //update lower part -> non contiguous memory access for (Index i = 0; i < rrow - row - 1; i++) { m_lu.coeffRefLower(rrow, row + i + 1) -= uItPivot.value() * coef; ++uItPivot; } ++lIt3; } //update diag -> contiguous typename MatrixType::InnerLowerIterator lIt2(m_lu, col); for (Index rrow = row + 1; rrow < m_lu.rows(); rrow++) { typename MatrixType::InnerUpperIterator uItPivot(m_lu, row); typename MatrixType::InnerUpperIterator uIt(m_lu, rrow); const double coef = lIt2.value(); uItPivot += (rrow - row - 1); m_lu.coeffRefDiag(rrow) -= uItPivot.value() * coef; ++lIt2; } } } template<typename MatrixType> void SkylineInplaceLU<MatrixType>::computeRowMajor() { const size_t rows = m_lu.rows(); const size_t cols = m_lu.cols(); eigen_assert(rows == cols && "We do not (yet) support rectangular LU."); eigen_assert(m_lu.IsRowMajor && "You're trying to apply rowMajor decomposition on a ColMajor matrix !"); for (Index row = 0; row < rows; row++) { typename MatrixType::InnerLowerIterator llIt(m_lu, row); for (Index col = llIt.col(); col < row; col++) { if (m_lu.coeffExistLower(row, col)) { const double diag = m_lu.coeffDiag(col); typename MatrixType::InnerLowerIterator lIt(m_lu, row); typename MatrixType::InnerUpperIterator uIt(m_lu, col); const Index offset = lIt.col() - uIt.row(); Index stop = offset > 0 ? col - lIt.col() : col - uIt.row(); //#define VECTORIZE #ifdef VECTORIZE Map<VectorXd > rowVal(lIt.valuePtr() + (offset > 0 ? 0 : -offset), stop); Map<VectorXd > colVal(uIt.valuePtr() + (offset > 0 ? offset : 0), stop); Scalar newCoeff = m_lu.coeffLower(row, col) - rowVal.dot(colVal); #else if (offset > 0) //Skip zero value of lIt uIt += offset; else //Skip zero values of uIt lIt += -offset; Scalar newCoeff = m_lu.coeffLower(row, col); for (Index k = 0; k < stop; ++k) { const Scalar tmp = newCoeff; newCoeff = tmp - lIt.value() * uIt.value(); ++lIt; ++uIt; } #endif m_lu.coeffRefLower(row, col) = newCoeff / diag; } } //Upper matrix update const Index col = row; typename MatrixType::InnerUpperIterator uuIt(m_lu, col); for (Index rrow = uuIt.row(); rrow < col; rrow++) { typename MatrixType::InnerLowerIterator lIt(m_lu, rrow); typename MatrixType::InnerUpperIterator uIt(m_lu, col); const Index offset = lIt.col() - uIt.row(); Index stop = offset > 0 ? rrow - lIt.col() : rrow - uIt.row(); #ifdef VECTORIZE Map<VectorXd > rowVal(lIt.valuePtr() + (offset > 0 ? 0 : -offset), stop); Map<VectorXd > colVal(uIt.valuePtr() + (offset > 0 ? offset : 0), stop); Scalar newCoeff = m_lu.coeffUpper(rrow, col) - rowVal.dot(colVal); #else if (offset > 0) //Skip zero value of lIt uIt += offset; else //Skip zero values of uIt lIt += -offset; Scalar newCoeff = m_lu.coeffUpper(rrow, col); for (Index k = 0; k < stop; ++k) { const Scalar tmp = newCoeff; newCoeff = tmp - lIt.value() * uIt.value(); ++lIt; ++uIt; } #endif m_lu.coeffRefUpper(rrow, col) = newCoeff; } //Diag matrix update typename MatrixType::InnerLowerIterator lIt(m_lu, row); typename MatrixType::InnerUpperIterator uIt(m_lu, row); const Index offset = lIt.col() - uIt.row(); Index stop = offset > 0 ? lIt.size() : uIt.size(); #ifdef VECTORIZE Map<VectorXd > rowVal(lIt.valuePtr() + (offset > 0 ? 0 : -offset), stop); Map<VectorXd > colVal(uIt.valuePtr() + (offset > 0 ? offset : 0), stop); Scalar newCoeff = m_lu.coeffDiag(row) - rowVal.dot(colVal); #else if (offset > 0) //Skip zero value of lIt uIt += offset; else //Skip zero values of uIt lIt += -offset; Scalar newCoeff = m_lu.coeffDiag(row); for (Index k = 0; k < stop; ++k) { const Scalar tmp = newCoeff; newCoeff = tmp - lIt.value() * uIt.value(); ++lIt; ++uIt; } #endif m_lu.coeffRefDiag(row) = newCoeff; } } /** Computes *x = U^-1 L^-1 b * * If \a transpose is set to SvTranspose or SvAdjoint, the solution * of the transposed/adjoint system is computed instead. * * Not all backends implement the solution of the transposed or * adjoint system. */ template<typename MatrixType> template<typename BDerived, typename XDerived> bool SkylineInplaceLU<MatrixType>::solve(const MatrixBase<BDerived> &b, MatrixBase<XDerived>* x, const int transposed) const { const size_t rows = m_lu.rows(); const size_t cols = m_lu.cols(); for (Index row = 0; row < rows; row++) { x->coeffRef(row) = b.coeff(row); Scalar newVal = x->coeff(row); typename MatrixType::InnerLowerIterator lIt(m_lu, row); Index col = lIt.col(); while (lIt.col() < row) { newVal -= x->coeff(col++) * lIt.value(); ++lIt; } x->coeffRef(row) = newVal; } for (Index col = rows - 1; col > 0; col--) { x->coeffRef(col) = x->coeff(col) / m_lu.coeffDiag(col); const Scalar x_col = x->coeff(col); typename MatrixType::InnerUpperIterator uIt(m_lu, col); uIt += uIt.size()-1; while (uIt) { x->coeffRef(uIt.row()) -= x_col * uIt.value(); //TODO : introduce --operator uIt += -1; } } x->coeffRef(0) = x->coeff(0) / m_lu.coeffDiag(0); return true; } } // end namespace Eigen #endif // EIGEN_SKYLINELU_H
true
aac63637708ec6f3403e09e89bd8e64276c57551
C++
ninellekam/ALGRORITHMS_MAIL
/dz3/e.cpp
UTF-8
2,279
2.609375
3
[]
no_license
#include <stdio.h> #include <string.h> #include <unistd.h> #include <iostream> using namespace std; const int LEN = 10002; int main() { FILE *src = fopen("input.txt", "r"); FILE *dst = fopen("output.txt", "w"); FILE *f_merge = fopen("temp_3.txt", "w+"); FILE *f_1 = fopen("temp_1.txt", "w+"); FILE *f_2 = fopen("temp_2.txt", "w+"); char s[LEN]; char s1[LEN]; char s2[LEN]; unsigned int count = 0, n = 0; // считываем все из файла while(fgets(s, LEN, src)) { ++n; fputs(s,f_merge); } fputc('\n',f_merge); //размеры наших пробных файлов unsigned int series_size = 1, merge_size = 2; while(merge_size < 2*n) { truncate("temp_3.txt", ftell(f_merge)); // сжать файл до размера f_merge rewind(f_merge); // установить смещение на начало файла rewind(f_1); rewind(f_2); bool file1 = true; count = 0; while(fgets(s, LEN, f_merge)) { ++count; fputs(s, file1 ? f_1 : f_2); // строки пишем в f_1 f_2 взависимости от переполнения if(count == series_size) { count = 0; file1 = !file1; } } truncate("temp_1.txt", ftell(f_1)); truncate("temp_2.txt", ftell(f_2)); rewind(f_1); rewind(f_2); rewind(f_merge); unsigned int i = 0, j = 0; auto k1 = fgets(s1, LEN, f_1); auto k2 = fgets(s2, LEN, f_2); while(k1 && k2) { while(k1 && k2) { if(strcmp(s1,s2)<0) { fputs(s1, f_merge); k1 = fgets(s1, LEN, f_1); if(++i == series_size) break; } else { fputs(s2, f_merge); k2 = fgets(s2, LEN, f_2); if(++j == series_size) break; } } while(k1) { if(i == series_size) break; fputs(s1, f_merge); k1 = fgets(s1, LEN, f_1); ++i; } while(k2) { if(j == series_size) break; fputs(s2, f_merge); k2 = fgets(s2, LEN, f_2); ++j; } i = 0; j = 0; } while(k1) { fputs(s1, f_merge); k1 = fgets(s1, LEN, f_1); } while(k2) { fputs(s2, f_merge); k2 = fgets(s2, LEN, f_2); } series_size = merge_size; merge_size = merge_size * 2; } rewind(f_merge); count = 0; while(fgets(s, LEN, f_merge)) fputs(s, dst); return 0; }
true
ce52ffa40e4192952945e520d38c95c5944d815c
C++
tater1337/cplusplus-fvtc
/4-15-2014 test/main.cpp
UTF-8
1,084
2.796875
3
[]
no_license
//created because I cannot create a default C++ templpate to start all my programs with //i Proboably could but not when I am also using VS2012 for other classes #include <stdio.h> //used for getchar not in codeblocks? #include <iostream> //used for cin and cout #include <iomanip> //used to modify text strings setprecision #include <string> //needed for strings #include <math.h> #include "businessLayerLinux.h" // is numeric, string to double, string to int #include "CollectionLinux.h" //aray stuffs using namespace std; //initialize functions here int main() { bool quit = false; while (quit == false) { // 90378: Computer Programming C++ 90378 // Tater Schuld 500139932 // // insert comments here // // 1 declare variables we need // 2 get variables from user // 3 do calculations c.add(1); c.add(2); cout << c; // 4 output results cout << endl; cout << "output" << endl; cout << "\nPress any key to loop or q to quit"; //char c = _getch(); char c = 'q'; if (c == 'q' || c == 'Q') { quit = true; } } return 1; }
true
004416a28970cfb8267e86e30bc366208125c167
C++
jaya6400/Coding
/Graph/bellman.cpp
UTF-8
1,262
3.015625
3
[]
no_license
// { Driver Code Starts #include<bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: int isNegativeWeightCycle(int n, vector<vector<int>>edges){ vector<int> dis(n, INT_MAX); dis[0] = 0; for(int i = 0; i < n-1; i++){ for(int j = 0; j < edges.size(); j++){ if(dis[edges[j][0]] != INT_MAX && dis[edges[j][0]] + edges[j][2] < dis[edges[j][1]]) dis[edges[j][1]] = dis[edges[j][0]] + edges[j][2]; } } int flag = 0; for(int j = 0; j < edges.size(); j++){ if(dis[edges[j][0]] != INT_MAX && dis[edges[j][0]] + edges[j][2] < dis[edges[j][1]]){ flag = 1; break; } } if(!flag) { for(int i = 0;i<n;i++) { cout << i << " " << dis[i] << endl; } } return flag; } }; // { Driver Code Starts. int main(){ int tc; cin >> tc; while(tc--){ int n, m; cin >> n >> m; vector<vector<int>>edges; for(int i = 0; i < m; i++){ int x, y, z; cin >> x >> y >> z; edges.push_back({x,y,z}); } Solution obj; int ans = obj.isNegativeWeightCycle(n, edges); cout << ans <<"\n"; } return 0; } // } Driver Code Ends
true
e84885734dccc33a303faf421cc2b0ac5d19007a
C++
Caffrey/CPipeline
/Raytracing/Intrucdtion/Realistic Ray Tracing/DynSphere.h
UTF-8
545
2.578125
3
[]
no_license
#pragma once #include "Common.h" #include "Shape.h" #include "Vector.h" #include "Ray.h" #include "Color.h" class DynSphere : public Shape { public: DynSphere(const Vector3& _ocenter, RFLOAT _radius, const Color& _color, RFLOAT min_time, RFLOAT max_time); bool hit(const Ray& r, float tmin, float tmax, RFLOAT time, HitRecord& record) const ; bool shadowHit(const Ray& r, float tmin, float tmax, RFLOAT time) const; Vector3 getCenter(RFLOAT time) const; Vector3 ocenter; RFLOAT mintime, maxtime, radius; Color color; };
true
f08e76787419701c12fa0b0b1083765248ffb114
C++
ganli2015/Hope_Love
/SentenceAnalysisAlgorithm/Punctuator.cpp
WINDOWS-1252
2,071
2.921875
3
[]
no_license
#include "StdAfx.h" #include "Punctuator.h" #include "../DataCollection/Character.h" #include "../DataCollection/Sentence.h" #include "../DataCollection/LanguageFunc.h" using namespace DataCollection; using namespace std; Punctuator::Punctuator(std::string longSen):_unpunctuated(new Sentence(longSen)) { } Punctuator::~Punctuator(void) { } bool Punctuator::Punctuate( shared_ptr<DataCollection::Sentence>& punctuated ) { vector<shared_ptr<Character>> unpun=_unpunctuated->GetRawSentence(); if(unpun.empty()) return false; vector<shared_ptr<Character>>::iterator sen_it=unpun.begin(); do { vector<shared_ptr<Character>>::iterator chara_it=find_if(sen_it,unpun.end(),LanguageFunc::IsPuncEndofSentence); //if there is no punctuation in the end, then add the remaining sentence. if(chara_it==unpun.end()) { vector<shared_ptr<Character>> aSen(sen_it,chara_it); punctuated->AddSubSentence(aSen); break; } vector<shared_ptr<Character>> subSen=ComputeSubSentence(unpun, sen_it, chara_it); punctuated->AddSubSentence(subSen); if(chara_it==unpun.end()) break; } while (sen_it!=unpun.end()); return true; } vector<shared_ptr<Character>> Punctuator::ComputeSubSentence(const vector<shared_ptr<Character>>& unpun, vector<shared_ptr<Character>>::iterator& sen_it, vector<shared_ptr<Character>>::iterator& chara_it) { vector<shared_ptr<Character>> res; //Find the next character which is not a punctuation. //There may be several continuous punctuation around <chara_it>. //For example, á. //We need to skip those punctuations and include all of them in the current sub sentence. do { ++chara_it; if (chara_it == unpun.end()) { vector<shared_ptr<Character>> aSen(sen_it, chara_it); res = aSen; break; } else if (LanguageFunc::IsPuncEndofSentence(*chara_it) || LanguageFunc::IsPuncRightside(*chara_it)) continue; else { vector<shared_ptr<Character>> aSen(sen_it, chara_it); res = aSen; sen_it = chara_it; break; } } while (chara_it != unpun.end()); return res; }
true
fe71d565880e27c45710973df3437f7d3c7b1bdb
C++
kdimmick001/kdimmick001-CSCI21-Spring2018
/Week10/movie_search.cpp
UTF-8
1,131
3.578125
4
[]
no_license
#include <string> #include <iostream> #include <cstdlib> #include <iomanip> #include <sstream> #include <list> using namespace std; int main() { //Creating an input stream ifstream fin; //To open a text file to get the string information. fin.open(file.c_str()); //A check to make sure that the desired file opened. if(!fin.is_open()){ cout << "Unable to open file." << endl; } //Declaring a movie list. list<string> movie_list; //First movie to compare. string first_movie; //Second movie to compare. string second_movie; while(!fin.eof()){ fin >> first_movie; fin >> second_movie; if (first_movie > second_movie){ if (movie_list.size() == 0){ movie_list.push(second_movie); movie_list.push(first_movie); } } if (second_movie > first_movie){ if (movie_list.size() == 0){ movie_list.push(first_movie); movie_list.push(second_movie); } } } }
true
56af0ea9c3e6a1b8182cd169aa6489d2f659652e
C++
ashish25-bit/data-structure-algorithms
/Trees/AVL.cpp
UTF-8
4,035
3.734375
4
[]
no_license
#include <bits/stdc++.h> using namespace std; class Node { public: int data; Node* left; Node* right; int height; Node(int key) { data = key; left = NULL; right = NULL; height = 1; } }; int height(Node *node) { if (!node) return 0; return node->height; } // difference between left subtree and right subtree int getdiff(Node* root) { if (!root) return 0; return height(root->left) - height(root->right); } Node* leftRotate(Node* node) { Node *temp1 = node->right; Node *temp2 = temp1->left; temp1->left = node; node->right = temp2; node->height = max(height(node->left), height(node->right)) + 1; temp1->height = max(height(temp1->left), height(temp1->right)) + 1; return temp1; } Node* rightRotate(Node *node) { Node *temp1 = node->left; Node *temp2 = temp1->right; temp1->right = node; node->left = temp2; node->height = max(height(node->left), height(node->right)) + 1; temp1->height = max(height(temp1->left), height(temp1->right)) + 1; return temp1; } Node* insert(Node* root, int key) { if (!root) return new Node(key); if (key < root->data) root->left = insert(root->left, key); else if (key > root->data) root->right = insert(root->right, key); else return root; root->height = 1 + max(height(root->left), height(root->right)); int diff = getdiff(root); // left left if (diff > 1 && key < root->left->data) return rightRotate(root); // right right if (diff < -1 && key > root->right->data) return leftRotate(root); // left right if (diff > 1 && key > root->left->data) { root->left = leftRotate(root->left); return rightRotate(root); } // right left if (diff < -1 && key < root->right->data) { root->right = rightRotate(root->right); return leftRotate(root); } return root; } void preOrder(Node* root, int &n, string str = "root") { if (!root) return; n++; cout << str << ": " << root->data << "\n"; preOrder(root->left, n, str + " left"); preOrder(root->right, n, str + " right"); } Node* deleteNode(Node* root, int key) { if (!root) return root; if (root->data > key) { root->left = deleteNode(root->left, key); return root; } else if (root->data < key) { root->right = deleteNode(root->right, key); return root; } // leaf node if (!root->left && !root->right) { delete(root); return NULL; } // only left child if (root->left && !root->right) { Node* left = root->left; delete(root); return left; } // only right child if (root->right && !root->left) { Node* right = root->right; delete(root); return right; } // both left and right children are present Node* minValue = root->right; while (minValue->left) minValue = minValue->left; root->data = minValue->data; root->right = deleteNode(root->right, minValue->data); // balancing the tree if (!root) return root; root->height = 1 + max(height(root->left), height(root->right)); int diff = getdiff(root); // left left if (diff > 1 && getdiff(root->left) >= 0) return rightRotate(root); // right right if (diff < -1 && getdiff(root->right) <= 0) return leftRotate(root); // left right if (diff > 1 && getdiff(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // right left if (diff < -1 && getdiff(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root; } int main() { vector<int> arr = {14, 11, 19, 7, 12, 17, 53, 4, 8, 13, 16, 20, 60}; Node* root = NULL; for (int x: arr) root = insert(root, x); int n = 0; preOrder(root, n); cout << "Total Node: " << n << "\n\n"; // delete data from avl tree vector<int> dn = {8, 7, 11, 14, 17}; for (int key: dn) { root = deleteNode(root, key); cout << "DELETED NODE " << key << "\n"; int n = 0; preOrder(root, n); cout << "Total Node: " << n << "\n\n"; } return 0; }
true
a92b18de94fc1f648af81ba36c5c692ebe86cd6b
C++
MaggieLee01/Coding
/25_02_MergeSortedArray/MergeSortedArray.cpp
GB18030
1,003
3.71875
4
[]
no_license
/* A B A ĩ㹻Ļռ B дһ B ϲ A ʼ A B ԪֱΪ m n : A = [1,2,3,0,0,0], m = 3 B = [2,5,6], n = 3 : [1,2,2,3,5,6] https://leetcode-cn.com/problems/sorted-merge-lcci */ #include<vector> using std::vector; void merge(vector<int>& A, int m, vector<int>& B, int n) { int aIndex = m - 1, bIndex = n - 1, ansIndex = n + m - 1; while (bIndex >= 0) { //˴ӦʣaIndexΪ-1֮߼ʽֱΪ1IJжϣԲԽ if (aIndex == -1 || A[aIndex] <= B[bIndex]) { A[ansIndex] = B[bIndex]; bIndex--; } else { A[ansIndex] = A[aIndex]; aIndex--; } ansIndex--; } } //⣬ûиõķ int main(void) { vector<int> a = { 7,8,9,0,0,0 }; vector<int> b = { 1,2,3 }; merge(a, 3, b, 3); return 0; }
true
2cbe2ef00771106835ca7528e51322f0c66b6ad4
C++
PawelWorwa/SFMLnake
/sources/states/game/snake.hpp
UTF-8
1,328
2.765625
3
[ "MIT" ]
permissive
#ifndef SNAKE_H #define SNAKE_H #include <SFML/Graphics/Sprite.hpp> #include <SFML/Graphics/RenderWindow.hpp> #include "gameSprites.hpp" #include "direction.hpp" class Snake { private: bool moved; bool suspendGrowth; GameSprites &sprites; std::vector< sf::Sprite > parts; Direction currentDirection; Direction newDirection; Direction randomDirection (); void orientateHead ( sf::Sprite &head ); void orientateHeadUp ( sf::Sprite &head ); void orientateHeadRight ( sf::Sprite &head ); void orientateHeadDown ( sf::Sprite &head ); void orientateHeadLeft ( sf::Sprite &head ); void moveBodyParts(); sf::Vector2f getNewHeadPosition (); public: explicit Snake ( GameSprites &sprites ); virtual ~Snake (); void createHead ( sf::Vector2f position ); void draw ( sf::RenderWindow &window ); void setNewDirection ( Direction direction ); void move (); bool isMoved (); bool isSuspendGrowth () const; void setMoved ( bool moved ); sf::FloatRect getHeadElementFloatRect (); std::vector< sf::Sprite > getParts(); void grow (); void deleteBodyPart (); Direction getDirection(); }; #endif // SNAKE_H
true
bd98af651eba1c22bc5017a95f09e7d1cb66667a
C++
smadala/IIIT-PG11
/os/6/assignment6/pra/sample.cpp
UTF-8
218
2.703125
3
[]
no_license
#include<iostream> #include<map> using namespace std; struct node{ int size; map<int,node*> links; }; int main(){ map<int,node*> f; struct node *p=new node(); f=p->links; cout<<sizeof(node)<<endl; return 0; }
true
178f79075212dec7296b3d766e2eebe69c4a5a36
C++
ahmedasad236/Social_Media
/Profile.h
UTF-8
958
2.9375
3
[]
no_license
#pragma once #include <iostream> #include <cstring> #define Max_Followers_Following 1000 using namespace std; class Profile { private: char* name; int followersNum; int followingNum; protected: Profile* followers[Max_Followers_Following]; Profile* following[Max_Followers_Following]; public: Profile(const char* n); //Setters & Getters void setName(const char* n); void setFollowersNum(int num); void setFollowingNum(int num); int getFollowingNum() const; int getFollowersNum() const; const char* getName() const; //Profile Functions bool IsFollow(Profile*); bool IsFollowed(Profile*); void DeleteFromFollowers(Profile*); void DeleteFromFollowings(Profile*); //Virtual Functions virtual void AddToFollowers(Profile*) = 0; virtual void AddToFollowing(Profile*) = 0; virtual void Follow(Profile*) = 0; virtual void Unfollow(Profile*); virtual void PrintInfo() const; virtual ~Profile(); };
true
464f65733c2b953ce4da24b598c68cdc9830171f
C++
Karbust/Processing-Models-Generated-on-Blender
/ProjetoPOO/Face.cpp
UTF-8
6,852
3.21875
3
[]
no_license
// // Created by Karbust on 30/10/2019. // #include <iostream> #include "Face.h" Vertice * Face::CalcularCoordVetor(Vertice *V1, Vertice *V2){ float dx = V2->ReturnVX() - V1->ReturnVX(); float dy = V2->ReturnVY() - V1->ReturnVY(); float dz = V2->ReturnVZ() - V1->ReturnVZ(); return new Vertice(dx, dy, dz); } void Face::CalcularArea(){ for (size_t i = 0; i < Vertices.size() - 1; i++) { auto *F = new Face(); auto *V = new Vertice(Vertices[0]->ReturnVX(), Vertices[0]->ReturnVY(), Vertices[0]->ReturnVZ()); auto *V1 = new Vertice(Vertices[i]->ReturnVX(), Vertices[i]->ReturnVY(), Vertices[i]->ReturnVZ()); auto *V2 = new Vertice(Vertices[i + 1]->ReturnVX(), Vertices[i + 1]->ReturnVY(),Vertices[i + 1]->ReturnVZ()); F->Add(i, i, V); F->Add(i, i, V1); F->Add(i, i, V2); Vertice *AB = CalcularCoordVetor(F->Vertices[0], F->Vertices[1]); Vertice *AC = CalcularCoordVetor(F->Vertices[0], F->Vertices[2]); //Produto Externo float ProdVector1 = AB->ReturnVY() * AC->ReturnVZ() - AB->ReturnVZ() * AC->ReturnVY(); float ProdVector2 = AB->ReturnVZ() * AC->ReturnVX() - AB->ReturnVX() * AC->ReturnVZ(); float ProdVector3 = AB->ReturnVX() * AC->ReturnVY() - AB->ReturnVY() * AC->ReturnVX(); area += sqrt(pow(ProdVector1, 2) + pow(ProdVector2, 2) + pow(ProdVector3, 2)) / 2; delete AB; delete AC; delete V; delete V1; delete V2; delete F; } } void Face::CalcularFaceNormal(){ float NormalX = 0.0f, NormalY = 0.0f, NormalZ = 0.0f; //Algoritmo de Newell for(size_t i = 0; i < Vertices.size() - 1; i++){ auto *V1 = new Vertice(Vertices[i]->ReturnVX(), Vertices[i]->ReturnVY(), Vertices[i]->ReturnVZ()); auto *V2 = new Vertice(Vertices[(i+1) % Vertices.size()]->ReturnVX(), Vertices[(i+1) % Vertices.size()]->ReturnVY(), Vertices[(i+1) % Vertices.size()]->ReturnVZ()); NormalX += (((V1->ReturnVY()) - (V2->ReturnVY())) * ((V2->ReturnVZ()) + (V1->ReturnVZ()))); NormalY += (((V1->ReturnVZ()) - (V2->ReturnVZ())) * ((V2->ReturnVX()) + (V1->ReturnVX()))); NormalZ += (((V1->ReturnVX()) - (V2->ReturnVX())) * ((V2->ReturnVY()) + (V1->ReturnVY()))); delete V1; delete V2; } float k = sqrt(pow(NormalX, 2) + pow(NormalY, 2) + pow(NormalZ, 2)); NormalX /= k; NormalY /= k; NormalZ /= k; Normal = new Vertice(NormalX, NormalY, NormalZ); } void Face::CalcularD(){ for (size_t i = 0; i < Vertices.size() - 1; i++) { auto *F = new Face(); auto *V = new Vertice(Vertices[0]->ReturnVX(), Vertices[0]->ReturnVY(), Vertices[0]->ReturnVZ()); auto *V1 = new Vertice(Vertices[i]->ReturnVX(), Vertices[i]->ReturnVY(), Vertices[i]->ReturnVZ()); auto *V2 = new Vertice(Vertices[i + 1]->ReturnVX(), Vertices[i + 1]->ReturnVY(),Vertices[i + 1]->ReturnVZ()); F->Add(i, i, V); F->Add(i, i, V1); F->Add(i, i, V2); Vertice *AB = CalcularCoordVetor(F->Vertices[0], F->Vertices[1]); Vertice *AC = CalcularCoordVetor(F->Vertices[0], F->Vertices[2]); //Produto Externo W1 += AB->ReturnVY() * AC->ReturnVZ() - AB->ReturnVZ() * AC->ReturnVY(); W2 += AB->ReturnVZ() * AC->ReturnVX() - AB->ReturnVX() * AC->ReturnVZ(); W3 += AB->ReturnVX() * AC->ReturnVY() - AB->ReturnVY() * AC->ReturnVX(); D = ((-1) * W1 * Vertices[0]->ReturnVX()) - ((-1) * W2 * Vertices[0]->ReturnVY()) - ((-1) * W3 * Vertices[0]->ReturnVZ()); delete AB; delete AC; delete V; delete V1; delete V2; delete F; } } bool Face::Intersecao(float Ax, float Ay, float Az, float Vx, float Vy, float Vz){ CalcularD(); float Den = (W1 * Vx) + (W2 * Vy) + (W3 * Vz); if(fabs(Den) <= TOL) return false; T = ((-1) * D - (W1 * Ax) - (W2 * Ay) - (W3 * Az)) / Den; return fabs(T) > TOL; } Vertice *Face::CalcularIntersecao(float Ax, float Ay, float Az, float Vx, float Vy, float Vz){ float Xi, Yi, Zi; Xi = Ax + (T * Vx); Yi = Ay + (T * Vy); Zi = Az + (T * Vz); auto *V = new Vertice(Xi, Yi, Zi); return V; } bool Face::EstaNaFace(Vertice *V){ float p1, p2; vector<vector<float>> Valores; //Vetor1 AB Valores.push_back({Vertices[1]->ReturnVX() - Vertices[0]->ReturnVX(), Vertices[1]->ReturnVY() - Vertices[0]->ReturnVY(), Vertices[1]->ReturnVZ() - Vertices[0]->ReturnVZ()}); //Vetor2 BC Valores.push_back({Vertices[2]->ReturnVX() - Vertices[1]->ReturnVX(), Vertices[2]->ReturnVY() - Vertices[1]->ReturnVY(), Vertices[2]->ReturnVZ() - Vertices[1]->ReturnVZ()}); //Vetor3 CA Valores.push_back({Vertices[0]->ReturnVX() - Vertices[2]->ReturnVX(), Vertices[0]->ReturnVY() - Vertices[2]->ReturnVY(), Vertices[0]->ReturnVZ() - Vertices[2]->ReturnVZ()}); //Vetor4 AI Valores.push_back({V->ReturnVX() - Vertices[0]->ReturnVX(), V->ReturnVY() - Vertices[0]->ReturnVY(), V->ReturnVZ() - Vertices[0]->ReturnVZ()}); //Vetor5 BI Valores.push_back({V->ReturnVX() - Vertices[1]->ReturnVX(), V->ReturnVY() - Vertices[1]->ReturnVY(), V->ReturnVZ() - Vertices[1]->ReturnVZ()}); //Vetor6 CI Valores.push_back({V->ReturnVX() - Vertices[2]->ReturnVX(), V->ReturnVY() - Vertices[2]->ReturnVY(), V->ReturnVY() - Vertices[2]->ReturnVY()}); p1 = ((Valores[0][1] * Valores[3][2]) - (Valores[3][1] * Valores[0][2])) * ((Valores[1][1] * Valores[4][2]) - (Valores[4][1] * Valores[1][2])) + ((Valores[0][2] * Valores[3][0]) - (Valores[3][2] * Valores[0][0])) * ((Valores[1][2] * Valores[4][0]) - (Valores[4][2] * Valores[1][0])) + ((Valores[0][0] * Valores[3][1]) - (Valores[3][0] * Valores[0][1])) * ((Valores[1][0] * Valores[4][1]) - (Valores[4][0] * Valores[1][1])); //Produto Interno p2 = ((Valores[0][1] * Valores[3][2]) - (Valores[3][1] * Valores[0][2])) * ((Valores[2][1] * Valores[5][2]) - (Valores[5][1] * Valores[2][2])) + ((Valores[0][2] * Valores[3][0]) - (Valores[3][2] * Valores[0][0])) * ((Valores[2][2] * Valores[5][0]) - (Valores[5][2] * Valores[2][0])) + ((Valores[0][0] * Valores[3][1]) - (Valores[3][0] * Valores[0][1])) * ((Valores[2][0] * Valores[5][1]) - (Valores[5][0] * Valores[2][1])); //Produto Interno Valores.clear(); return ((p1 > 0) && (p2 > 0)) || ((p1 < 0) && (p2 < 0)); } vector<Face *> Face::DeterminarFacesVizinhas(const vector<Face *>& Faces) const { set<Face *, LessByFaceId> Lista; for (const auto& V1 : Vertices) for (const auto& Face : Faces) for (const auto& V2 : Face->ReturnVertices()) if (Utils::CompararVertice(V2, V1) && Face->ReturnfID() != FaceID) Lista.insert(Face); return {Lista.begin(), Lista.end()}; }
true
f0dd4b2bb1a2bfadca0135ef8f0ab7c9397cdd9a
C++
wmichalski/UNIX-shell
/source/Environment.cpp
UTF-8
3,599
3.25
3
[]
no_license
#include <Environment.h> void Environment::setEnvVariable(std::string key, std::string value) { hashmap[key] = value; } std::string Environment::getEnvVariable(std::string key) { char *ret = getenv(key.c_str()); if (ret != NULL) return std::string(ret); if (hashmap[key] != "") { return hashmap[key]; } return ""; } bool Environment::iterateEnvVariables(std::vector<std::string> &tokens) { for (auto &token : tokens) { replaceEnvVariables(token); createEnvVariables(token); removeQuotes(token); } tokens = checkExport(tokens); if(tokens.size() == 1 && tokens[0] == "") { return false; } return true; } std::vector<std::string> Environment::checkExport(std::vector<std::string> tokens) { if (tokens[0] == "export") { if (tokens.size() == 1) return {"export"}; if (tokens.size() > 1) { std::string varName = ""; for (auto character : tokens[1]) { if(character == '=') break; varName.push_back(character); } unsetenv(varName.c_str()); setenv(varName.c_str(), getEnvVariable(varName).c_str(), 1); return {""}; } } else { return {tokens}; } } void Environment::removeQuotes(std::string &token) { std::string new_ = ""; for (auto character : token) { if (character != '\'') new_.push_back(character); } token = new_; } void Environment::createEnvVariables(std::string &token) { //removing quotas: std::string varName = ""; std::string varValue = ""; bool lookingForName = 1; for (auto character : token) { if (lookingForName) { if (character == '\'') { return; } if (character == '=') { lookingForName = 0; continue; } varName.push_back(character); } else { if (character == '\'') { continue; } varValue.push_back(character); } if (!lookingForName) setEnvVariable(varName, varValue); } } void Environment::replaceEnvVariables(std::string &token) { std::string old_ = token; std::string new_ = ""; bool readingVarName = 0; std::string varName = ""; for (auto character : old_) { if (character == '$') { if(readingVarName == 1) { new_ += getEnvVariable(varName); varName = ""; } else{ readingVarName = 1; continue; } } if (!readingVarName) { new_.push_back(character); } else { if (character == '\'') { readingVarName = 0; if (varName.size() == 0) new_ += '$'; else { new_ += getEnvVariable(varName); new_ += character; } varName = ""; } else { varName.push_back(character); } } } if (readingVarName) { if (varName.size() == 0) new_ += '$'; else { new_ += getEnvVariable(varName); } } token = new_; }
true
a53f5a4da4e615152302ac2f4264ec1519290e99
C++
reddrinkbro/directPortal
/DIRECT3D/particle.h
UHC
1,531
2.65625
3
[]
no_license
#pragma once //ƼŬ ü typedef struct tagPARTICLE_VERTEX { D3DXVECTOR3 pos; // ġ float size; //ƼŬ DWORD color; // ÷ enum { FVF = D3DFVF_XYZ | D3DFVF_PSIZE | D3DFVF_DIFFUSE }; }PARTICLE_VERTEX, *LPPARTICLE_VERTEX; typedef vector<D3DXCOLOR> VEC_COLOR; typedef vector<float> VEC_SCALE; // ϳ class particle { public: transform _transform; //ƼŬ ġ boundBox _boundBox; private: bool _isLive; //Ȱȭ float _totalLiveTime; // Ȱȭ ð float _deltaLiveTime; //Ȱȭ ð float _normalizeLiveTime; //Ȱȭ ð(0~1) D3DXVECTOR3 _velocity; //ƼŬ ӵ D3DXVECTOR3 _acceleration; //ʴ ϴ float _scale; //⺻ ϰ public: void start( float liveTime, //̺Ÿ const D3DXVECTOR3* pos, // ġ const D3DXVECTOR3* velocity, //ۼӵ const D3DXVECTOR3* acceleration, //ӵ float scale //⺻ ); void update(); //ڽ LPPATICLE_VERTEX ־ش. void getParticleVertex( LPPARTICLE_VERTEX pOut, const VEC_COLOR& colors, const VEC_SCALE& scales ); bool getIsLive() { return _isLive; } void setnormalizeLiveTime(float normalizeLiveTime) { _normalizeLiveTime = normalizeLiveTime; } particle() : _isLive(false) {} ~particle() {} };
true
2ffd9a6f543e60f47815dbe75b5ba7cf3e7ce273
C++
JacobLetko/IntroToCpp
/Assesment/textanimations.h
UTF-8
353
2.671875
3
[]
no_license
#pragma once void colorFunction(int x);//changes color for the lines not entire console void delay(int delay, std::string text);//prints each char slowly in a string void delaySkip(int delay, std::string text); //prints lines and skips one void test(int x, int y); //test the colors of color fuction between certin numbers int powers(int x, int y);
true
74bfc360002c6d00ec5cf4d0ba0550af6ebce48a
C++
HaoYang0123/LeetCode
/Capitalize_the_Title.cpp
UTF-8
918
3.46875
3
[]
no_license
// Leetcode 2129 class Solution { public: string capitalizeTitle(string title) { string res = ""; vector<string> words; title += ' '; string cur = ""; for(int i=0; i<title.length(); ++i) { if(title[i] != ' ') { if(title[i] >= 'a' && title[i] <= 'z') cur += title[i]; else cur += char('a' + int(title[i] - 'A')); } else { words.push_back(cur); cur = ""; } } for(int i=0; i<words.size(); ++i) { string neww = get_word(words[i]); res += neww + ' '; } return res.substr(0, res.length()-1); } inline string get_word(string & word) { if(word.length() <= 2) return word; word[0] = char('A' + int(word[0] - 'a')); return word; } };
true
0d47bf90a7ba4859577173c9c026bedc16428f63
C++
tlecoeuv/piscine_cpp
/day_06/ex01/main.cpp
UTF-8
1,211
3.671875
4
[]
no_license
#include <iostream> #include <string> struct Data { std::string s1; int n; std::string s2; }; void* serialize(void) { char *ret = new char[16 + sizeof(int)]; std::string alnum("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); std::srand(time(NULL)); std::cout << "values during serialize:" << std::endl; for (int i = 0; i < 8; i++) ret[i] = alnum[rand() % 62]; std::cout << "s1: " << std::string(ret, 8) << std::endl; int random = std::rand(); *(reinterpret_cast<int*>(ret + 8)) = random; std::cout << "n: " << random << std::endl; for (int i = 12; i < 20; i++) ret[i] = alnum[rand() % 62]; std::cout << "s1: " << std::string(ret + 12, 8) << std::endl; return ret; } Data* deserialize(void *raw) { Data *data = new Data; char *rawdata = reinterpret_cast<char*>(raw); data->s1 = std::string(rawdata, 8); data->n = *(reinterpret_cast<int*>(rawdata + 8)); data->s2 = std::string(rawdata + 8 + sizeof(int), 8); return data; } int main() { void *raw; Data *data; raw = serialize(); data = deserialize(raw); std::cout << "after deserialize:\n" << "s1: " << data->s1 << "\n" << "n: " << data->n << "\n" << "s2: " << data->s2 << std::endl; }
true
e3a7eff5eec75b813a24ceb86a2c342c0a78071d
C++
Beom-portfolio/Direct3D-Team-DirectX9-
/SRTeam_Project/Engine/Utility/Codes/Rect_Texture.cpp
UHC
1,966
2.546875
3
[]
no_license
#include "..\Headers\Rect_Texture.h" USING(Engine) CRect_Texture::CRect_Texture(LPDIRECT3DDEVICE9 pGraphicDev) : CVIBuffer(pGraphicDev) { } CRect_Texture::CRect_Texture(const CRect_Texture & rhs) : CVIBuffer(rhs) { } CRect_Texture::~CRect_Texture() { } HRESULT CRect_Texture::Ready_Buffer(void) { m_iVertexSize = sizeof(VTXTEX); m_iVertexCnt = 4; m_dwVertexFVF = D3DFVF_XYZ | D3DFVF_TEX1; m_iIndexSize = sizeof(INDEX16); m_IndexFmt = D3DFMT_INDEX16; m_iTriCnt = 2; if (FAILED(CVIBuffer::Ready_Buffer())) return E_FAIL; if (nullptr == m_pVB) return E_FAIL; VTXTEX* pVertex = nullptr; // Lock : ٸ尡 ´. ( ϴ ̴ϱ) // : ּҸ ´.( Ϸ) m_pVB->Lock(0, 0, (void**)&pVertex, 0); pVertex[0].vPosition = _vec3(-1.0f, 1.0f, 0.0f); pVertex[0].vTexUV = _vec2(0.0f, 0.f); pVertex[1].vPosition = _vec3(1.0f, 1.0f, 0.0f); pVertex[1].vTexUV = _vec2(1.f, 0.f); pVertex[2].vPosition = _vec3(1.0f, -1.0f, 0.0f); pVertex[2].vTexUV = _vec2(1.f, 1.f); pVertex[3].vPosition = _vec3(-1.0f, -1.0f, 0.0f); pVertex[3].vTexUV = _vec2(0.f, 1.f); m_pVB->Unlock(); INDEX16* pIndex = nullptr; m_pIB->Lock(0, 0, (void**)&pIndex, 0); pIndex[0]._0 = 0; pIndex[0]._1 = 1; pIndex[0]._2 = 2; pIndex[1]._0 = 0; pIndex[1]._1 = 2; pIndex[1]._2 = 3; m_pIB->Unlock(); return NOERROR; } void CRect_Texture::Render_Buffer(void) { CVIBuffer::Render_Buffer(); } CComponent * CRect_Texture::Clone(void) { return new CRect_Texture(*this); } CRect_Texture * CRect_Texture::Create(LPDIRECT3DDEVICE9 pGraphicDev) { CRect_Texture * pInstance = new CRect_Texture(pGraphicDev); if (FAILED(pInstance->Ready_Buffer())) { MessageBox(0, L"CRect_Texture Created Failed", nullptr, MB_OK); Engine::Safe_Release(pInstance); } return pInstance; } _ulong CRect_Texture::Free(void) { return Engine::CVIBuffer::Free(); }
true
45a376398827d46056e8a0f4fc1fb7766c5fcbc6
C++
stiltskincode/lemur-game
/TextureManager.h
UTF-8
475
2.6875
3
[]
no_license
#ifndef TEXTUREMANAGER_H_ #define TEXTUREMANAGER_H_ #include <string> #include <deque> #include "TGAImage.h" class TextureManager { public: struct Texture { std::string name; GLuint tex; }; static void setLocation(std::string loc) {location=loc;} static GLuint get(std::string name, bool mipmaps = true); static void clean(); private: static std::string location; static std::deque<Texture> textures; TextureManager(); }; #endif /* TEXTUREMANAGER_H_ */
true
dfb5656c037f774f2ab8359c9a6b2c1eea5f7fe5
C++
N4G170/pathfind_ui
/src/include/clock.hpp
UTF-8
1,682
3.515625
4
[ "MIT" ]
permissive
#ifndef CLOCK_H #define CLOCK_H #include <string> #include <memory> #include <mutex> #include <chrono> #include <map> /** * \brief Basic SINGLETON class to manage a small clock to be used by Euler Problems functions */ class Clock { public: virtual ~Clock(); /** * \brief Get a std::unique_ptr to the singleton instance */ static std::unique_ptr<Clock>& Instance(); //we delete the copy constructor and the assign operator to avoid the accidental copy of our main instance Clock(Clock const&) = delete; void operator=(Clock const&) = delete; /** * \brief Starts a new timer * \return Id to the new timer running */ unsigned long StartClock(); /** * \brief Stops a specific timer * \return std::string with the time in miliseconds */ std::string StopAndReturnClock(unsigned long id); private: /** * \brief Private constructor to avoid "external" instance creation */ Clock();//private default constructor /** * \brief std::unique_ptr to the static instance */ static std::unique_ptr<Clock> s_instance; /** * \brief Counter to generate ids for new timers */ unsigned long m_id_counter; /** * \brief std::map storing the timers currently running */ std::map<unsigned long, std::chrono::time_point<std::chrono::steady_clock> > m_clocks; /** * \brief std::mutex to control id counter access */ std::mutex m_mutex; }; #endif // CLOCK_H
true
c7081aa96daa7ace73b8c95a9f122b45eddc3c66
C++
H-Shen/Collection_of_my_coding_practice
/Leetcode/825/825.cpp
UTF-8
1,553
2.71875
3
[]
no_license
class Solution { public: int numFriendRequests(vector<int>& ages) { sort(ages.begin(),ages.end()); int counter = 0; int n = (int)ages.size(); for (int x = 0; x < n; ++x) { if (ages[x] >= 100) { int lower, upper; if (ages[x] & 1) { lower = (int)(ages[x]*0.5+7) + 1; } else { lower = ages[x]/2+8; } upper = ages[x]; if (lower <= upper) { int lower_pos = lower_bound(ages.begin(),ages.end(),lower) - ages.begin(); int upper_pos = (--upper_bound(ages.begin(),ages.end(),upper)) - ages.begin(); counter += upper_pos - lower_pos; } } else { if (0.5*ages[x]+7 >= 100) { continue; } int lower, upper; if (ages[x] & 1) { lower = (int)(ages[x]*0.5+7) + 1; } else { lower = ages[x]/2+8; } upper = min(100, ages[x]); if (lower <= upper) { int lower_pos = lower_bound(ages.begin(),ages.end(),lower) - ages.begin(); int upper_pos = (--upper_bound(ages.begin(),ages.end(),upper)) - ages.begin(); counter += upper_pos - lower_pos; } } } return counter; } };
true
c44722bce7e7904d0e003e353dd3658d872ee07a
C++
mukulaggarwal/Codes
/codechef/palidrome.cpp
UTF-8
621
2.5625
3
[]
no_license
#include<cstdio> #include<iostream> #include<cstring> #include<cmath> using namespace std; #define M 1000000007 long long int power(long long int n) { if(n==0) return 26; if(n==1) return 26; long long int x=power(n/2); x=(x*x)%M; if(n%2) x=(x*26)%M; return x; } int main() { int t; scanf("%d",&t); while(t--) { long long int n,i,ans=0; scanf("%lld",&n); if(n==1) printf("26\n"); else { if(n%2==0) { } printf("%lld\n",ans); } } return 0; }
true