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
f427f54e6c928de91b2448a0234e06b2b1ffd1e2
C++
misdake/Grid
/src/program/Generator.cpp
UTF-8
2,620
2.90625
3
[]
no_license
#include "Generator.h" #include <random> #include <ctime> std::mt19937 rng; std::uniform_int_distribution<> oprand_full_dist(-3, 3); std::uniform_int_distribution<> oprand_reg_dist(0, 7); std::uniform_int_distribution<> oprand_negative_dist(-3, -1); std::uniform_int_distribution<> oprand_positive_dist(1, 3); std::binomial_distribution<> oprand_binomial_dist(6, 0.5); std::poisson_distribution<> program_length_binomial_dist(10); uint8_t Generator::opIndex() const { std::discrete_distribution<> opcode_dist(weights.begin(), weights.end()); int r = opcode_dist(rng); return static_cast<uint8_t>(r); } int8_t Generator::oprand_full() const { int r = oprand_full_dist(rng); return static_cast<int8_t>(r); } int8_t Generator::oprand_reg() const { int r = oprand_reg_dist(rng); return static_cast<int8_t>(r); } int8_t Generator::oprand_positive() const { int r = oprand_positive_dist(rng); return static_cast<int8_t>(r); } int8_t Generator::oprand_negative() const { int r = oprand_negative_dist(rng); return static_cast<int8_t>(r); } int8_t Generator::oprand_binomial() const { int r = oprand_binomial_dist(rng) - 3; return static_cast<int8_t>(r); } Generator::Generator() { rng.seed((unsigned int) std::time(nullptr)); } //Generator::Generator(uint32_t seed) { // rng.seed(seed); //} void Generator::registerInstruction(const InstGenEntry& entry) { weights.push_back(static_cast<int>(entry.weight)); entries.push_back(entry); } InstructionEx Generator::generateInstruction() const { InstructionEx r{}; int index = opIndex(); const InstGenEntry& entry = entries[index]; r.opcode = entry.opcode; r.oprand0 = oprand(entry.oprand0rnd); r.oprand1 = oprand(entry.oprand1rnd); r.oprand2 = oprand(entry.oprand2rnd); r.cost = entry.costFunction; return r; } int8_t Generator::oprand(OprandRnd rnd) const { switch (rnd) { case OprandRnd::NONE: return 0; case OprandRnd::REG: return oprand_reg(); case OprandRnd::FULL: return oprand_full(); case OprandRnd::POSITIVE: return oprand_positive(); case OprandRnd::NEGATIVE: return oprand_negative(); case OprandRnd::BINOMIAL: return oprand_binomial(); } } ProgramEx Generator::generateProgram() const { int length = program_length_binomial_dist(rng); ProgramEx program{}; for (int i = 0; i < length; i++) { InstructionEx instEx = generateInstruction(); program.instructionExList.push_back(instEx); program.instructions.push_back(instEx.toInstruction()); } return program; }
true
fb8e88133690f7c416aa7d5bbcdf6f5b160d869e
C++
ChadyG/MUGE
/src/Graphics/Camera.h
UTF-8
3,874
2.53125
3
[]
no_license
/* Camera.h My Unnamed Game Engine Created by Chad Godsey on 12/9/09. Copyright 2009 BlitThis! studios. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CAMERA_H #define CAMERA_H #include <Gosu/Gosu.hpp> #include <map> struct CameraTransform { double x, y, rot, zoom; }; class Camera { public: Camera() : m_FocusX(0.f), m_FocusY(640), m_Width(480), m_Scale(1.f), m_Zoom(1.f), m_Rot(0.f) {} /// Set the window size of the camera /// @param _w The width of the window /// @param _h The height void setExtents(int _w, int _h) { m_Width = _w; m_Height = _h; } /// Set the scaling factor of the window /// This determines the world pixel resolution to the screen (world/screen) /// @param _scale scaling factor void setScale( double _scale ) { m_Scale = _scale; } /// Set the zoom factor of the camera /// same effect as changing the scale, but meant to be dynamic /// @param _zoom the zoom factor (default 1) void setZoom( double _zoom ) { m_Zoom = _zoom; } /// Set the rotation angle (degrees) /// @param _rot angle to rotate by void setRotation( double _rot ) { m_Rot = _rot; } /// Set the world coordinates to center the camera on /// @param _x World X /// @param _y World Y void setFocus(double _x, double _y) { m_FocusX = _x, m_FocusY = _y; } double X() { return m_FocusX; } double Y() { return m_FocusY; } double Zoom() { return m_Zoom; } double Scale() { return m_Scale; } double Rotation() { return m_Rot; } int Width() { return m_Width; } int Height() { return m_Height; } /// This tells the Render Manager where on screen a world coordinate currently is. /// When creating your own camera, this method must be implemented. /// @param _x World X /// @param _y World Y /// @param _z World Z (in Gosu layers) /// @return CameraTransform screen coordinates with rotation for displaying on screen virtual CameraTransform worldToScreen(double _x, double _y, Gosu::ZPos _z); /// This tells the Render Manager where on screen a world coordinate currently is. /// When creating your own camera, this method must be implemented. /// @param _x World X /// @param _y World Y /// @param _z World Z (in Gosu layers) /// @return CameraTransform screen coordinates with rotation for displaying on screen virtual CameraTransform screenToWorld(double _x, double _y, Gosu::ZPos _z); protected: double m_FocusX, m_FocusY; int m_Width, m_Height; double m_Scale, m_Zoom, m_Rot; }; /// Parallax Camera /// Uses Gosu layers with individual scaling factors to create a parallax effect class Camera_Parallax : public Camera { public: Camera_Parallax() {} void addLayer(int _layer, double _dist); /// Come up with a batch mechanism CameraTransform worldToScreen(double _x, double _y, Gosu::ZPos _z); CameraTransform screenToWorld(double _x, double _y, Gosu::ZPos _z); private: std::map< int, double > m_LayerScales; }; #endif
true
c7f64ae44c616989deb764868d8d6ac16f6364e2
C++
hutuyingxiong/HotPants
/hotpants/core/Src/Module/ModuleCache.hpp
UTF-8
1,570
2.703125
3
[]
no_license
/* * ModuleCache.hpp * * Maintains a cache of Voice sub-modules; filters, amp and modulations. * Most of the time new notes will be generated without getParameters being * changed. If so, we can clone these saved modules and refresh them * when getParameters are actually changed. * * Created on: 24 Jul 2010 * Author: Jonathan Crooke (jc9873@bris.ac.uk) */ #ifndef MODULECACHE_H_ #define MODULECACHE_H_ #include "../Interface/Interfaces.hpp" #include "FilterModule.hpp" #include "AmpModule.hpp" #include "ModModule.hpp" namespace hotpants { class ModuleCache: public Component { public: explicit ModuleCache(HotPantsCore& c) : Component(c), cachedFilterModule(c), cachedAmpModule(c), cachedModModule(c) {} // module access const FilterModule& getFilterModule() { return cachedFilterModule; } const AmpModule& getAmpModule() { return cachedAmpModule; } const ModModule& getModModule() { return cachedModModule; } // module mutator void setFilterModule(FilterModule& x) { cachedFilterModule = x; } void setAmpModule(AmpModule& x) { cachedAmpModule = x; } void setModModule(ModModule& x) { cachedModModule = x; } private: FilterModule cachedFilterModule; AmpModule cachedAmpModule; ModModule cachedModModule; }; } #endif /* MODULECACHE_H_ */
true
32e29ce0879d6029064c63f2234fe5960e061fa6
C++
dkevin77/ENGG1340---Group-101---Money-Management-System
/statistics/stat_yearly.h
UTF-8
730
2.828125
3
[]
no_license
#ifndef YEARLY #define YEARLY #include <vector> #include "struct.h" using namespace std; //Function : void countDataYearly //Input : -a vector of records named data // -int year // -int dataCount (pass-by-reference) //Output : None (void type) //Change the value of dataCount based on the ocurrences of record //that have .year==year void countDataYearly(vector <record> data,int year,int &dataCount); //Function : void getYearlyStat //Input : -a vector of records named data // -int year // -int dataCount // -string username //Output : None (void type) //Present yearly statistical report to a file void getYearlyStat(vector <record> data, int year,int dataCount, string username); #endif
true
7a8e1f6fcc3bf05e0138a382bebd5807a127d7ad
C++
LucaTorriani/MinimizationMethods
/src/Monomial.cc
UTF-8
246
2.640625
3
[]
no_license
#include <cmath> #include "Monomial.hh" double Monomial::eval (Point const & P) const { double value = 1; for (std::size_t dim = 0; dim < powers.size (); ++dim) value *= pow (P.get_coord (dim), powers[dim]); return coeff * value; }
true
a580199a8a4fa6e2f0f1305f723f09704097cfc5
C++
Zoezxb/learngit
/algorithm/leetcode_452_用最少数量的箭引爆气球.cpp
UTF-8
496
2.84375
3
[]
no_license
/* leetcode 452 用最少数量的箭引爆气球 贪心 */ class Solution { public: int findMinArrowShots(vector<vector<int>>& points) { sort(points.begin(),points.end(),[](vector<int>a,vector<int>b){ return a[1]<b[1]; }); int res = 1 , r = points[0][1]; for(int i = 1;i<points.size();i++) { if(r<points[i][0]) { res++; r = points[i][1]; } } return res; } };
true
9766315fc3a9262abfcc9742b15d395697b97dcf
C++
victor-timoshin/Switch
/src/Switch.System/include/Switch/System/Diagnostics/TraceOptions.hpp
UTF-8
2,881
2.703125
3
[ "MIT" ]
permissive
/// @file /// @brief Contains Switch::System::Diagnostics::TraceOptions enum. #pragma once #include <Switch/System/Enum.hpp> /// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more. namespace Switch { /// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. namespace System { /// @brief The System::Diagnostics namespace provides classes that allow you to interact with system processes, event logs, and performance counters. namespace Diagnostics { /// @brief Specifies trace data options to be written to the trace output. /// @par Library /// Switch.System /// @remarks This enumeration is used by trace listeners to determine which options, or elements, should be included in the trace output. Trace listeners store the trace options in the TraceOutputOptions property. enum class TraceOptions { /// @brief Do not write any elements. None = 0, /// @brief Write the logical operation stack, which is represented by the return value of the CorrelationManager.LogicalOperationStack property. LogicalOperationStack = 0b1, /// @brief Write the date and time. DateTime = 0b10, /// @brief Write the timestamp, which is represented by the return value of the GetTimestamp method. Timestamp = 0b100, /// @brief Write the process identity, which is represented by the return value of the Process.Id property. ProcessId = 0b1000, /// @brief Write the thread identity, which is represented by the return value of the Thread.ManagedThreadId property for the current thread. ThreadId = 0b10000, /// @brief Write the call stack, which is represented by the return value of the Environment.StackTrace property. Callstack = 0b100000 }; } } } /// @cond template <> class AddFlagOperators<System::Diagnostics::TraceOptions> : public TrueType {}; template<> struct EnumRegister<System::Diagnostics::TraceOptions> { void operator()(System::Collections::Generic::IDictionary<System::Diagnostics::TraceOptions, string>& values, bool& flags) { values[System::Diagnostics::TraceOptions::None] = "None"; values[System::Diagnostics::TraceOptions::LogicalOperationStack] = "LogicalOperationStack"; values[System::Diagnostics::TraceOptions::DateTime] = "DateTime"; values[System::Diagnostics::TraceOptions::Timestamp] = "Timestamp"; values[System::Diagnostics::TraceOptions::ProcessId] = "ProcessId"; values[System::Diagnostics::TraceOptions::ThreadId] = "ThreadId"; values[System::Diagnostics::TraceOptions::Callstack] = "Callstack"; flags = true; } }; /// @endcond using namespace Switch;
true
1baffb3d634051c9f264adf09bb8d5e4feaf1383
C++
JackLiu56/Sampling-based-Motion-Planning
/src/comprobfall2018-hw2/ackermann/ackermann_client/gnn.cpp
UTF-8
17,062
2.546875
3
[]
no_license
/** * @file gnn.cpp * * @copyright Software License Agreement (BSD License) * Copyright (c) 2017, Rutgers the State University of New Jersey, New Brunswick * All Rights Reserved. * For a full description see the file named LICENSE. * * Authors: Zakary Littlefield, Kostas Bekris * */ #include "gnn.hpp" #include <cassert> #include <limits> #include <vector> #include <queue> using namespace std; namespace gnn { proximity_node_t::proximity_node_t() { neighbors = (unsigned int*)malloc(INIT_CAP_NEIGHBORS*sizeof(unsigned int)); nr_neighbors = 0; added_index = 0; cap_neighbors = INIT_CAP_NEIGHBORS; } proximity_node_t::~proximity_node_t() { free( neighbors ); } int proximity_node_t::get_index() { return index; } void proximity_node_t::set_index( int indx ) { index = indx; } unsigned int* proximity_node_t::get_neighbors( int* nr_neigh ) { *nr_neigh = nr_neighbors; return neighbors; } void proximity_node_t::add_neighbor( unsigned int nd ) { if( nr_neighbors >= cap_neighbors-1 ) { cap_neighbors = 2*cap_neighbors; neighbors = (unsigned int*)realloc( neighbors, cap_neighbors*sizeof(unsigned int)); } neighbors[nr_neighbors] = nd; nr_neighbors++; } void proximity_node_t::delete_neighbor( unsigned int nd ) { int index; for( index=0; index<nr_neighbors; index++ ) { if( neighbors[index] == nd ) break; } assert( index < nr_neighbors ); for( int i=index; i<nr_neighbors-1; i++ ) neighbors[i] = neighbors[i+1]; nr_neighbors--; } void proximity_node_t::replace_neighbor( unsigned prev, int new_index ) { int index; for( index=0; index<nr_neighbors; index++ ) { if( neighbors[index] == prev ) break; } assert( index < nr_neighbors ); neighbors[index] = new_index; } graph_nearest_neighbors_t::graph_nearest_neighbors_t(std::function<bool (proximity_node_t*,proximity_node_t*)> l,std::function<double (proximity_node_t*,proximity_node_t*)> d, std::function<double (proximity_node_t*,proximity_node_t*)> dis2line ) { distance_function = d; localvalid_function=l; dis2line_function=dis2line; added_node_id = 0; nodes = (proximity_node_t**)malloc(INIT_NODE_SIZE*sizeof(proximity_node_t*)); nr_nodes = 0; cap_nodes = INIT_NODE_SIZE; second_nodes = (proximity_node_t**)malloc( MAX_KK *sizeof(proximity_node_t*)); second_distances = (double*)malloc( MAX_KK *sizeof(double)); } graph_nearest_neighbors_t::~graph_nearest_neighbors_t() { free( nodes ); free( second_nodes ); free( second_distances); } bool graph_nearest_neighbors_t::add_node( proximity_node_t* graph_node ) { if( nr_nodes >= cap_nodes-1 ) { cap_nodes = 2 * cap_nodes; nodes = (proximity_node_t**)realloc(nodes, cap_nodes*sizeof(proximity_node_t*)); } nodes[nr_nodes] = graph_node; graph_node->set_index(nr_nodes); nr_nodes++; return true; } void graph_nearest_neighbors_t::add_nodes( proximity_node_t** graph_nodes, int nr_new_nodes) { if( nr_nodes + nr_new_nodes >= cap_nodes - 1 ) { cap_nodes = nr_nodes + nr_new_nodes + 10; nodes = (proximity_node_t**)realloc(nodes, cap_nodes*sizeof(proximity_node_t*)); } for( int i=0; i<nr_new_nodes; i++ ) { int k = percolation_threshold(); int new_k = find_k_close( (proximity_node_t*)(graph_nodes[i]), second_nodes, second_distances, k ); nodes[nr_nodes] = graph_nodes[i]; graph_nodes[i]->set_index(nr_nodes); nr_nodes++; for( int j=0; j<new_k; j++ ) { graph_nodes[i]->add_neighbor( second_nodes[j]->get_index() ); second_nodes[j]->add_neighbor( graph_nodes[i]->get_index() ); } } } void graph_nearest_neighbors_t::remove_node( proximity_node_t* graph_node ) { int nr_neighbors; unsigned int* neighbors = graph_node->get_neighbors( &nr_neighbors ); for( int i=0; i<nr_neighbors; i++ ) { nodes[ neighbors[i] ]->delete_neighbor( graph_node->get_index() ); } int index = graph_node->get_index(); if( index < nr_nodes-1 ) { nodes[index] = nodes[nr_nodes-1]; nodes[index]->set_index( index ); neighbors = nodes[index]->get_neighbors( &nr_neighbors ); for( int i=0; i<nr_neighbors; i++ ) { nodes[ neighbors[i] ]->replace_neighbor( nr_nodes-1, index ); } } nr_nodes--; if( nr_nodes < (cap_nodes-1)/2 ) { cap_nodes *= 0.5; nodes = (proximity_node_t**)realloc(nodes,cap_nodes*sizeof(proximity_node_t*)); } } void graph_nearest_neighbors_t::average_valence() { int nr_neigh; unsigned int* neighs; double all_neighs = 0; for( int i=0; i<nr_nodes; i++ ) { neighs = nodes[i]->get_neighbors( &nr_neigh ); all_neighs += nr_neigh; } all_neighs /= (double)nr_nodes; } proximity_node_t* graph_nearest_neighbors_t::find_closest( proximity_node_t* state, double* the_distance ) { int min_index = -1; return basic_closest_search( state, the_distance, &min_index ); } int graph_nearest_neighbors_t::find_k_close( proximity_node_t* state, proximity_node_t** close_nodes, double* distances, int k ) { if( nr_nodes == 0 ) { return 0; } // if(k > MAX_KK) // { // k = MAX_KK; // } // else if( k >= nr_nodes ) // { // for( int i=0; i<nr_nodes; i++ ) // { // close_nodes[i] = nodes[i]; // distances[i] = distance_function(nodes[i],state ); // } // sort_proximity_nodes( close_nodes, distances, 0, nr_nodes-1 ); // return nr_nodes; // } // clear_added(); int min_index = -1; close_nodes[0] = basic_closest_search( state, &(distances[0]), &min_index ); if(min_index>-1) { nodes[min_index]->added_index = added_node_id; return 1; } else return 0; } int graph_nearest_neighbors_t::find_delta_close_and_closest( proximity_node_t* state, proximity_node_t** close_nodes, double* distances, double delta ) { if( nr_nodes == 0 ) { return 0; } clear_added(); int min_index = -1; close_nodes[0] = basic_closest_search( state, &(distances[0]), &min_index ); if( distances[0] > delta ) { return 1; } nodes[min_index]->added_index = added_node_id; int nr_points = 1; for( int counter = 0; counter<nr_points; counter++ ) { int nr_neighbors; unsigned int* neighbors = close_nodes[counter]->get_neighbors( &nr_neighbors ); for( int j=0; j<nr_neighbors; j++ ) { proximity_node_t* the_neighbor = nodes[neighbors[j]]; if( does_node_exist( the_neighbor ) == false ) { the_neighbor->added_index = added_node_id; double distance = distance_function(the_neighbor, state ); if( distance < delta && nr_points < MAX_KK) { close_nodes[ nr_points ] = the_neighbor; distances[ nr_points ] = distance; nr_points++; } } } } if( nr_points > 0 ) { sort_proximity_nodes( close_nodes, distances, 0, nr_points - 1 ); } return nr_points; } int graph_nearest_neighbors_t::find_delta_close( proximity_node_t* state, proximity_node_t** close_nodes, double* distances, double delta ) { if( nr_nodes == 0 ) { return 0; } clear_added(); int min_index = -1; close_nodes[0] = basic_closest_search( state, &(distances[0]), &min_index ); if( distances[0] > delta ) { return 0; } nodes[min_index]->added_index = added_node_id; int nr_points = 1; for( int counter = 0; counter<nr_points; counter++ ) { int nr_neighbors; unsigned int* neighbors = close_nodes[counter]->get_neighbors( &nr_neighbors ); for( int j=0; j<nr_neighbors; j++ ) { proximity_node_t* the_neighbor = nodes[neighbors[j]]; if( does_node_exist( the_neighbor ) == false ) { the_neighbor->added_index = added_node_id; double distance = distance_function(the_neighbor, state ); if( distance < delta && nr_points < MAX_KK) { close_nodes[ nr_points ] = the_neighbor; distances[ nr_points ] = distance; nr_points++; } } } } if( nr_points > 0 ) { sort_proximity_nodes( close_nodes, distances, 0, nr_points - 1 ); } return nr_points; } void graph_nearest_neighbors_t::sort_proximity_nodes( proximity_node_t** close_nodes, double* distances, int low, int high ) { if( low < high ) { int left, right, pivot; double pivot_distance = distances[low]; proximity_node_t* pivot_node = close_nodes[low]; double temp; proximity_node_t* temp_node; pivot = left = low; right = high; while( left < right ) { while( left <= high && distances[left] <= pivot_distance ) { left++; } while( distances[right] > pivot_distance ) { right--; } if( left < right ) { temp = distances[left]; distances[left] = distances[right]; distances[right] = temp; temp_node = close_nodes[left]; close_nodes[left] = close_nodes[right]; close_nodes[right] = temp_node; } } distances[low] = distances[right]; distances[right] = pivot_distance; close_nodes[low] = close_nodes[right]; close_nodes[right] = pivot_node; sort_proximity_nodes( close_nodes, distances, low, right-1 ); sort_proximity_nodes( close_nodes, distances, right+1, high ); } } int graph_nearest_neighbors_t::resort_proximity_nodes( proximity_node_t** close_nodes, double* distances, int index ) { double temp; proximity_node_t* temp_node; while( index > 0 && distances[ index ] < distances[ index-1 ] ) { temp = distances[index]; distances[index] = distances[index-1]; distances[index-1] = temp; temp_node = close_nodes[index]; close_nodes[index] = close_nodes[index-1]; close_nodes[index-1] = temp_node; index--; } return index; } bool graph_nearest_neighbors_t::does_node_exist( proximity_node_t* query_node ) { return query_node->added_index==added_node_id; } proximity_node_t* graph_nearest_neighbors_t::basic_closest_search( proximity_node_t* state, double* the_distance, int* the_index ) { if( nr_nodes == 0 ) { return NULL; } int nr_samples = sampling_function(); double min_distance = std::numeric_limits<double>::max(); int min_index = -1; int index; for( int i=0; i<nr_samples; i++ ) { index = i; double dis2line = dis2line_function(nodes[index],state); if(dis2line<min_distance) { min_distance = dis2line; min_index = index; } } *the_distance = min_distance; *the_index = min_index; if(min_index==-1) return NULL; else return nodes[min_index]; } void graph_nearest_neighbors_t::clear_added() { added_node_id++; } void graph_nearest_neighbors_t::add_node_deserialize( proximity_node_t* graph_node ){ if( nr_nodes >= cap_nodes-1 ) { cap_nodes = 2 * cap_nodes; nodes = (proximity_node_t**)realloc(nodes, cap_nodes*sizeof(proximity_node_t*)); } nodes[nr_nodes] = graph_node; nr_nodes++; } proximity_node_t* graph_nearest_neighbors_t::get_node_by_index(int index){ proximity_node_t** nodes = this->nodes; //don't need linear search if nodes are in order by index for(int i = 0; i < this->nr_nodes; i++){ if((*(nodes+i))->get_index() == index){ return *(nodes+i); } } } void graph_nearest_neighbors_t::DFSUtil(proximity_node_t* graph_node, bool visited[]) { int nr_neighbors; unsigned int* neighbors = graph_node->get_neighbors( &nr_neighbors ); // Mark the current node as visited visited[graph_node->get_index()] = true; // Recur for all the vertices adjacent to this vertex for( int i=0; i<nr_neighbors; i++ ) { if(!visited[nodes[ neighbors[i] ]->get_index()]) DFSUtil(nodes[ neighbors[i] ], visited); } } int graph_nearest_neighbors_t::connectedComponents() { int nr_components = 0; // Mark all the nodes as not visited bool *visited = new bool[nr_nodes]; for(int v = 0; v < nr_nodes; v++) visited[nodes[v]->get_index()] = false; for (int v=0; v<nr_nodes; v++) { if (visited[nodes[v]->get_index()] == false) { DFSUtil(nodes[v], visited); nr_components++; } } return nr_components; } bool graph_nearest_neighbors_t::isSameComponents(int node1_index, int node2_index) { bool isSameComponent = false; // Mark all the nodes as not visited bool *visited = new bool[nr_nodes]; for(int v = 0; v < nr_nodes; v++) visited[nodes[v]->get_index()] = false; DFSUtil(nodes[node1_index], visited); isSameComponent = visited[node2_index]; return isSameComponent; } int graph_nearest_neighbors_t::count_edges() { int nr_neigh; unsigned int* neighs; int sum = 0; for( int i=0; i<nr_nodes; i++ ) { neighs = nodes[i]->get_neighbors( &nr_neigh ); sum += nr_neigh; } // The count of edge is always even because in undirected graph every // edge is connected twice between two vertices return sum/2; } int graph_nearest_neighbors_t::minEdgeBFS(proximity_node_t* start_node, proximity_node_t* goal_node) { // visited[n] for keeping track of visited node in BFS vector<bool> visited(nr_nodes, 0); // Initialize distances as 0 vector<int> distance(nr_nodes, 0); // queue to do BFS. queue <int> Q; distance[start_node->get_index()] = 0; Q.push(start_node->get_index()); visited[start_node->get_index()] = true; while (!Q.empty()) { int x = Q.front(); Q.pop(); proximity_node_t* temp_node = get_node_by_index(x); int nr_neighbors; unsigned int* neighbors = temp_node->get_neighbors( &nr_neighbors ); for (int i=0; i<nr_neighbors; i++) { if (visited[nodes[ neighbors[i] ]->get_index()]) continue; // update distance for i distance[nodes[ neighbors[i] ]->get_index()] = distance[x] + 1; Q.push(nodes[ neighbors[i] ]->get_index()); visited[nodes[ neighbors[i] ]->get_index()] = 1; } } return distance[goal_node->get_index()]; } }
true
b0341e534f3597c2d5241a341d30d7d74251df2e
C++
beru/DrawCircleTest
/graphics/graphics_impl_common.cpp
UTF-8
561
2.71875
3
[]
no_license
#include "graphics_impl_common.h" namespace Graphics { bool RectIntersect(const Rect& a, const Rect& b, Rect& c) { int16_t minX = max(a.x, b.x); int16_t maxX = min(a.x+a.w, b.x+b.w); int16_t minY = max(a.y, b.y); int16_t maxY = min(a.y+a.h, b.y+b.h); c.x = minX; c.w = (maxX > minX) ? (maxX - minX) : 0; c.y = minY; c.h = (maxY > minY) ? (maxY - minY) : 0; return c.w && c.h; } bool RectContains(const Rect& r, int16_t x, int16_t y) { return r.x <= x && x < (r.x + r.w) && r.y <= y && y < (r.y + r.h) ; } }
true
ae606c9e305c485fb58ba60f5c2a30acd9ce6c5a
C++
mimiliaogo/CS_I2P_2
/1694 - I2P(II)2019_Lee_HW8/12279 - Binary Search Tree With Iterator (Preorder)/main.cpp
UTF-8
508
2.578125
3
[]
no_license
#include <iostream> #include "function.h" using namespace std; int main() { int G, N, tmp; BST bst; cin>>N>>G; for(int i=0;i<N;++i) { cin>>tmp; bst.push_back(tmp); } auto it = bst.begin(); auto it2 = bst.begin(); auto end = bst.end(); while( it != end ) { if( it2 != end ) it2++; if( it2 != end ) it2++; cout << *it + G << endl; it++; } return 0; }
true
91df214ee6ab53646e0770ee6b4d5869bf85cebe
C++
ohwada/MAC_cpp_Samples
/vmime/smtp/file_util.hpp
UTF-8
3,934
3.15625
3
[]
no_license
#pragma once /** * vmime sample * 2020-07-01 K.OHWADA */ // file utility // read write text file #include <fstream> #include <string> #include <vector> #include <ctime> #include <sys/stat.h> #include <dirent.h> // prototype bool existsFile(std::string file); int file_exists (char *filename) ; bool readTextFile( std::string file, std::string &text ); bool writeTextFile(std::string file, std::string data ); void getTimestampFileName(std::string prefix, std::string ext, std::string &filename); void getTimestamp(std::string &timestamp); bool getFileList(std::string str_path, std::string ext, std::vector<std::string> &vec, std::string &error); bool isDir(char* path); bool match_ext(std::string str, std::string ext); /** * existsFile */ bool existsFile(std::string file) { int ret = file_exists( (char *)file.c_str() ); bool res = (ret == 0)?true:false; return res; } /** * file_exists * @ return 0 : exists, 1 : stat failed */ int file_exists (char *filename) { struct stat buffer; return stat(filename, &buffer); } /** * readTextFile */ bool readTextFile( std::string file, std::string &text ) { const std::string LF = "\n"; std::ifstream fin; // open input file fin.open(file, std::ios::in); if (fin.fail()){ return false; } // read text by one line std::string line; while( getline(fin, line) ) { text += line + LF; } return true; } /** * writeTextFile */ bool writeTextFile(std::string file, std::string data ) { std::ofstream fout; // open input file fout.open(file, std::ios::out); if (fout.fail()){ return false; } // write to output file fout<< data; fout.close(); return true; } /** * getTimestampFileName */ void getTimestampFileName(std::string prefix, std::string ext, std::string &filename) { std::string timestamp; getTimestamp(timestamp); filename = prefix + std::string("_") + timestamp + std::string(".") + ext; } /** * getTimestamp */ void getTimestamp(std::string &timestamp) { const std::string format("%Y%m%d%H%M%S"); const size_t BUFSIZE = 100; char buf[BUFSIZE]; time_t now = std::time(nullptr); std::tm *tm = std::localtime(&now); std::strftime(buf, BUFSIZE, (char *)format.c_str(), tm); timestamp = std::string( buf ); } /** * getFileList */ bool getFileList(std::string str_path, std::string ext, std::vector<std::string> &vec, std::string &error) { char* path = (char *)str_path.c_str(); int ret = isDir(path); if(ret == -1) { error = std::string("not found: ") + path; return false; } else if (ret == 0) { error = std::string("not directory: ") + path; return false; } DIR *dir; dir = opendir(path); if (!dir) { error = strerror(errno) + std::string(" : ") +path; return false; } const std::string DOT = (char *)"."; const std::string TWO_DOT = (char *)".."; struct dirent * ent; while ((ent = readdir (dir)) != NULL) { std::string file = std::string( ent->d_name ); if (( file == DOT )||( file == TWO_DOT )){ continue; } bool ret = match_ext(file, ext); if(ret) { vec.push_back( std::string( ent->d_name ) ); } } // while closedir (dir); return true; } /** * isDir */ bool isDir(char* path) { struct stat sb; int ret = stat(path, &sb); if(ret != 0){ return false; } mode_t m = sb.st_mode; bool res = ( S_ISDIR(m) )? true: false; return res; } /** * match_ext */ bool match_ext(std::string str, std::string ext) { const std::string DOT = (char *)"."; std::string dot_ext = DOT + ext; int pos = str.rfind(dot_ext ); bool ret = (pos == std::string::npos)?false:true; return ret; }
true
9a16d6d8378a980c01b6e587f53057b5f7aed264
C++
IreNox/games_academy
/CS410/PRO_2018_FRA/Code/ExampleCode/Pointer.cpp
UTF-8
835
3.328125
3
[]
no_license
#include <memory> void runPointer() { // C# //public class Stuff //{ // private int m_value; // // public Stuff( int value ) // { // m_value = value; // } // // public void doStuff() // { // m_value += 2; // } // // public int Value() // { // get{ return m_value; } // } //}; // //Stuff myStuff = new Stuff( 7 ); //myStuff.doStuff(); //int result = myStuff.Value; // C++ class Stuff { public: int m_value; Stuff( int value ) { m_value = value; } void doStuff() { m_value += 2; } int getValue() { return m_value; } }; //Stuff* myStuff = new Stuff( 7 ); //std::shared_ptr< Stuff > myStuff = std::make_shared< Stuff >( 7 ); //myStuff->doStuff(); //int result = myStuff->getValue(); Stuff myStuff = Stuff( 7 ); myStuff.doStuff(); int result = myStuff.getValue(); }
true
0a09b074835619fcec2449a573917678a2823822
C++
kyberdrb/GCD
/numberPair/NumberPair.cpp
UTF-8
2,175
3.25
3
[]
no_license
#include <cstdlib> #include <cstring> #include <iostream> #include "NumberPair.h" #include "../utils/Utils.h" #include <thread> NumberPair* createNumberPairs(int *numbers, int const &numberOfElements, Index_Pair *index_pairs) { const int numberOfAllIterations = computeNumberOfAllIterations(numberOfElements); int const & numberOfGcdPairs = numberOfAllIterations; auto* numberPairs = (NumberPair *) calloc((size_t) numberOfGcdPairs, sizeof(NumberPair)); if (numberPairs == nullptr) { std::cout << "Couldn't allocate memory for numberPairs" << std::endl; throw std::bad_alloc(); } const int &numberOfThreads = numberOfAllIterations; std::thread threads[numberOfThreads]; auto** threadInfoStructs = (NumberPairThreadInfo**) calloc((size_t) numberOfThreads, sizeof(NumberPairThreadInfo*)); for (int i = 0; i < numberOfThreads; ++i) { threadInfoStructs[i] = (NumberPairThreadInfo*) calloc(1, sizeof(NumberPairThreadInfo)); threadInfoStructs[i]->index = i; threadInfoStructs[i]->numberPairs = numberPairs; threadInfoStructs[i]->index_pairs = index_pairs; threadInfoStructs[i]->numbers = numbers; threads[i] = std::thread(addNumberPair, threadInfoStructs[i]); } for (int i = 0; i < numberOfThreads; ++i) { threads[i].join(); free(threadInfoStructs[i]); } free(threadInfoStructs); return numberPairs; } void* addNumberPair(NumberPairThreadInfo* additionalDataForThread) { auto* threadInfo = (NumberPairThreadInfo*) additionalDataForThread; NumberPair numberPair; int index = threadInfo->index; int indexOfFirstNumber = threadInfo->index_pairs[index].indexOfFirstNumber; numberPair.firstNumber = makeNumberPositive(threadInfo->numbers[indexOfFirstNumber]); int indexOfSecondNumber = threadInfo->index_pairs[index].indexOfSecondNumber; numberPair.secondNumber = abs(threadInfo->numbers[indexOfSecondNumber]); memmove(&threadInfo->numberPairs[index], &numberPair, sizeof(NumberPair)); return nullptr; } int makeNumberPositive(const int negativeNumber) { return abs(negativeNumber); }
true
cd71cc5495b15e59bbca9b0810aff2645856fec5
C++
Akshayshingte/project1
/BluetoothControlCarUsingArduino.ino
UTF-8
4,497
2.71875
3
[ "MIT" ]
permissive
#define LMP 2 #define LMN 3 #define RMP 4 #define RMN 5 #define ENA 9 #define ENB 10 //int firstSensor = 0; // first analog sensor //int secondSensor = 0; // second analog sensor //int thirdSensor = 0; // digital sensor int inByte = 0; // incoming serial byte //char BYTE; boolean status_unlock; boolean status_bluetooth; //long interval = 1000; // interval at which to blink (milliseconds) //long previousMillis = 0; // will store last time LED was update //int minite,sec; void setup() { // start serial port at 9600 bps: Serial.begin(9600); //pinMode(2, INPUT); // digital sensor is on digital pin 2 //establishContact(); // send a byte to establish contact until receiver responds pinMode(LMP, OUTPUT); pinMode(LMN, OUTPUT); pinMode(RMP, OUTPUT); pinMode(RMN, OUTPUT); pinMode(ENA, OUTPUT); pinMode(ENB, OUTPUT); digitalWrite(LMP, LOW); // switch off MOTOR digitalWrite(LMN, LOW); // switch off MOTOR digitalWrite(RMP, LOW); // switch off MOTOR digitalWrite(RMN, LOW); // switch off MOTOR status_bluetooth = true; status_unlock = false; // sec = 0; } void loop() { if (Serial.available() > 0) { inByte = Serial.read(); // get incoming byte: Serial.print(inByte); if(inByte == 'A') { analogWrite(ENA, 250); analogWrite(ENB, 250); digitalWrite(LMP, HIGH); digitalWrite(LMN, LOW); digitalWrite(RMP, HIGH); digitalWrite(RMN, LOW); inByte = 0; } if(inByte == 'B') { analogWrite(ENA, 250); analogWrite(ENB, 250); digitalWrite(LMP, LOW); digitalWrite(LMN, HIGH); digitalWrite(RMP, LOW); digitalWrite(RMN, HIGH); inByte = 0; } if(inByte == 'D') { analogWrite(ENA, 250); analogWrite(ENB, 250); digitalWrite(LMP, HIGH); digitalWrite(LMN, LOW); digitalWrite(RMP, LOW); digitalWrite(RMN, LOW); inByte = 0; } if(inByte == 'C') { analogWrite(ENA, 250); analogWrite(ENB, 250); digitalWrite(LMP, LOW); digitalWrite(LMN, LOW); digitalWrite(RMP, HIGH); digitalWrite(RMN, LOW); //Serial.print('D', BYTE); inByte = 0; } if(inByte == 'E') { analogWrite(ENA, 250); analogWrite(ENB, 250); digitalWrite(LMP, LOW); digitalWrite(LMN, LOW); digitalWrite(RMP, LOW); digitalWrite(RMN, LOW); //Serial.print('E', BYTE); inByte = 0; } if(inByte == 'G') { analogWrite(ENA, 250); analogWrite(ENB, 250); digitalWrite(LMP, HIGH); digitalWrite(LMN, LOW); digitalWrite(RMP, LOW); digitalWrite(RMN, HIGH); inByte = 0; } if(inByte == 'F'){ analogWrite(ENA, 250); analogWrite(ENB, 250); digitalWrite(LMP, LOW); digitalWrite(LMN, HIGH); digitalWrite(RMP, HIGH); digitalWrite(RMN, LOW); // Serial.print('G', BYTE); inByte = 0; } /*if(inByte == 'S'){ Serial.print('S', BYTE); // send a char status_bluetooth = true; sec = 0; } */ } // if(Serial /* unsigned long currentMillis = millis(); if(currentMillis - previousMillis > interval) { previousMillis = currentMillis; // save the last time you blinked the LED sec++; if(status_unlock==true){ if(sec== 11){ digitalWrite(LED_PIN1, HIGH); // switch on LED delay(800); digitalWrite(LED_PIN1, LOW); // switch off LED status_unlock = false; sec = 0; } } else sec = 0; } */ } //Loop /*void establishContact() { while (Serial.available() <= 0) { Serial.print('.', BYTE); // send a capital A delay(500); } } */
true
194c69f87532c63caa34d3a254f2eb0cda0e4cbc
C++
braathwaate/strategoevaluator
/manager/ai_controller.cpp
UTF-8
1,819
2.875
3
[]
no_license
#include <sstream> #include "game.h" #include "stratego.h" #include "ai_controller.h" using namespace std; /** * Queries the AI program to setup its pieces. Stores the setup in a st * @implements Controller::QuerySetup * @param * @returns A MovementResult */ MovementResult AI_Controller::QuerySetup(const char * opponentName, std::string setup[]) { switch (colour) { case Piece::RED: if (!SendMessage("RED %s %d %d", opponentName, Game::theGame->theBoard.Width(), Game::theGame->theBoard.Height())) return MovementResult::BAD_RESPONSE; break; case Piece::BLUE: if (!SendMessage("BLUE %s %d %d", opponentName, Game::theGame->theBoard.Width(), Game::theGame->theBoard.Height())) return MovementResult::BAD_RESPONSE; break; case Piece::NONE: case Piece::BOTH: return MovementResult::COLOUR_ERROR; break; } for (int y = 0; y < 4; ++y) { if (!GetMessage(setup[y], timeout)) return MovementResult::BAD_RESPONSE; } return MovementResult::OK; } /** * Queries the AI program to make a move * @implements Controller::QueryMove * @param buffer String which stores the AI program's response * @returns A MovementResult which will be MovementResult::OK if a move was made, or MovementResult::NO_MOVE if the AI did not respond */ MovementResult AI_Controller::QueryMove(string & buffer) { if (!Running()) return MovementResult::NO_MOVE; //AI has quit Game::theGame->theBoard.Print(output, colour); //Game::theGame->logMessage("DEBUG: About to get message from %d\n", colour); if (!GetMessage(buffer,timeout)) { return MovementResult::NO_MOVE; //AI did not respond (within the timeout). It will lose by default. } //Game::theGame->logMessage("DEBUG: Got message \"%s\" from %d\n", buffer.c_str(), colour); return MovementResult::OK; //Got the message }
true
3bc18c72b68ba80b0f3cb5a4893e9af97153a72d
C++
k0204/loli_profiler
/src/memgraphicsview.cpp
UTF-8
3,231
2.671875
3
[ "BSD-3-Clause", "CC-BY-4.0", "MIT", "Apache-2.0", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include "memgraphicsview.h" #include <QDebug> #include <cmath> void MemSectionItem::setWidth(double width) { rect_.setX(pos().x()); rect_.setY(pos().y()); rect_.setWidth(width); rect_.setHeight(std::ceil(size_ / width) * rowHeight_); prepareGeometryChange(); } void MemSectionItem::addAllocation(double addr, double size) { bool merged = false; for (int i = allocations_.size() - 1; i > 0; i--) { auto& curAddr = allocations_[i]; if (addr < curAddr.first) continue; if (addr >= curAddr.first && addr + size <= curAddr.first + curAddr.second) { merged = true; curAddr.second = std::max(curAddr.second, addr - curAddr.first + size); } } if (!merged) allocations_.push_back(qMakePair(addr, size)); prepareGeometryChange(); } void MemSectionItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { auto freeColor = QColor(100, 255, 100); auto allocColor = QColor(255, 100, 100); painter->setPen(Qt::PenStyle::NoPen); painter->setBrush(freeColor); painter->drawRect(rect_); const auto startX = rect_.x(), startY = rect_.y(), width = rect_.width(); painter->setBrush(allocColor); for (auto& pair : allocations_) { auto row = static_cast<int>(std::floor(pair.first / width)); auto curY = row * rowHeight_; auto curX = pair.first - row * width; auto curSize = pair.second; while (curSize > 0) { auto growth = std::min(width - curX, curSize); painter->drawRect(static_cast<int>(startX + curX), static_cast<int>(startY + curY), static_cast<int>(growth), static_cast<int>(rowHeight_)); curSize -= growth; curY += rowHeight_; curX = 0; } } } MemGraphicsView::MemGraphicsView(QWidget* parent) : CustomGraphicsView(parent) { } void MemGraphicsView::drawBackground(QPainter* painter, const QRectF& r) { QGraphicsView::drawBackground(painter, r); } void MemGraphicsView::drawForeground(QPainter *painter, const QRectF &r) { QGraphicsView::drawForeground(painter, r); auto drawGrid = [&](double gridStep) { QRect windowRect = rect(); QPointF tl = mapToScene(windowRect.topLeft()); QPointF br = mapToScene(windowRect.bottomRight()); double left = std::floor(tl.x() / gridStep - 0.5); double right = std::floor(br.x() / gridStep + 1.0); double bottom = std::floor(tl.y() / gridStep - 0.5); double top = std::floor(br.y() / gridStep + 1.0); // vertical lines for (int xi = int(left); xi <= int(right); ++xi) { QLineF line(xi * gridStep, bottom * gridStep, xi * gridStep, top * gridStep ); painter->drawLine(line); } // horizontal lines for (int yi = int(bottom); yi <= int(top); ++yi) { QLineF line(left * gridStep, yi * gridStep, right * gridStep, yi * gridStep ); painter->drawLine(line); } }; QPen pfine(QColor(60, 60, 60), 1.0); painter->setPen(pfine); drawGrid(16); QPen p(QColor(25, 25, 25), 1.0); painter->setPen(p); drawGrid(160); }
true
20339d119a132cde1dd15d3b5bc61b58f448d049
C++
SupreDingus/PersonalEngine
/OpenGLStuff/RigidBody.h
UTF-8
1,564
2.8125
3
[]
no_license
/*****************************************************************************/ /*! Rigid body component. Handles physics stuff. Works with Transform and Collider. */ /*****************************************************************************/ #pragma once #include "Component.h" //GLM #include <glm\glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> class Transform; class Collider; class PlayerController; class RigidBody : public Component { public: RigidBody(); ~RigidBody(); RigidBody(const RigidBody& rhs) = delete; void Initialize(); void Update(float dt); void Destroy(); void Serialize(std::fstream file); void Deserialize(std::fstream file); //Getters. Transform* GetTransform() const; glm::vec3 GetVelocity() const; bool IsStatic() const; //Setters. void SetVelocity(glm::vec3 vec); void AddVelocity(glm::vec3 vec); void ChangeStatic(bool change); void SetTransform(); void SetCollider(); void SetController(); //Applies friction by reducing the x-axis. void ApplyFriction(); //If true, it's moving. bool moving; private: //Pointers to relevant components. Transform* trans; Collider* collide; PlayerController* player; //Velocity. Use with Transform's position. glm::vec3 velocity; //Static vs. Dynamic. Static objects (true) never move, dynamic objects (false) can. bool stat; //If the object is bouncy (used with dynamic) bool bouncy; //If the object is said to be on the ground. Used with player controller. bool grounded; };
true
e0cc4f168e176c8aa68b52509e8541e59dd8a05e
C++
Vikas-Jethwani/Geeks4Geeks-Solutions
/Hashing/05 - Find all four sum numbers.cpp
UTF-8
2,263
2.953125
3
[]
no_license
// Fall 7 times and Stand-up 8 #include <bits/stdc++.h> // StAn using namespace std; // Requires Sorted Array vector<vector<int>> n_sum(vector<int>& nums, int N=2, int target=0, int pos=0) { vector<vector<int>> ans; if (N == 2) { int left = pos; int right = nums.size()-1; while (left < right) { if (nums[left] + nums[right] == target) { ans.push_back({nums[left], nums[right]}); // Comment 4 lines below this if you dont want distinct solution while (left < right && nums[left] == nums[left+1]) left++; while (left < right && nums[right] == nums[right-1]) right--; left++; right--; continue; } else if (nums[left]+nums[right] < target) left++; else right--; } return ans; } else if (N >= 3) { for (int i=pos; i<nums.size(); i++) { // Comment 2 lines below this if you DONT want distinct solution if (i > pos && nums[i] == nums[i-1]) continue; int req = target - nums[i]; vector<vector<int>> prev_ans = n_sum(nums, N-1, req, i+1); for (int j=0; j<prev_ans.size(); j++) { vector<int> temp; temp.push_back(nums[i]); for (int k=0; k<N-1; k++) temp.push_back(prev_ans[j][k]); ans.push_back(temp); } } return ans; } else // N < 2 { return vector<vector<int>> (0); } } int main() { int T; cin>>T; while(T--) { int n, k; cin>>n>>k; vector<int> nums(n); for (int i=0; i<n; i++) cin>>nums[i]; sort(nums.begin(), nums.end()); vector<vector<int>> ans = n_sum(nums, 4, k); if (ans.size() == 0) cout<<-1; for (int i=0; i<ans.size(); i++) { for (int j=0; j<ans[i].size(); j++) cout<<ans[i][j]<<" "; cout<<"$"; } cout<<endl; } return 0; }
true
e29025da8638e395df684532f8a3af72ab26ce83
C++
quanghm/UVA-online-judge
/200.cpp
UTF-8
2,105
3.09375
3
[]
no_license
/* * ===================================================================================== * * Filename: 200.cpp * * Description: Rare order * * Version: 1.0 * Created: 09/01/2016 09:36:43 * Revision: none * Compiler: gcc * * Author: Quang M. Hoang (QH), quanghm@gmail.com * Company: * * ===================================================================================== */ #include <iostream> #include <string> #include <vector> using namespace std; void visit(char i, vector<bool> &isInList, vector<vector<bool> > &order, vector<char> &orderedList){ if (!isInList[i]) return; isInList[i] = 0; for (int j = 0; j<26; j++){ if (order[i][j]) visit(j, isInList, order, orderedList); } orderedList.push_back(i+'A'); } int main(){ string s1, s2; string::iterator i1, i2; for (;;){ if(!(cin>> s1) ) break; // if (s1.length() == 0) break; vector<bool> isInList(26,0); vector<vector<bool> > order(26,vector<bool>(26)); for (i1 = s1.begin(); i1 != s1.end(); i1++){ isInList[*i1-'A'] = 1; } // build the orders for(;;){ cin>>s2; if (s2[0] == '#') break; for (i2 = s2.begin(); i2 != s2.end(); i2++){ isInList[*i2-'A'] = 1; } // compare two strings i1=s1.begin(), i2=s2.begin(); while (*i1 == *i2) { i1++, i2++; } if ( *i1 && *i2 ){ // no string at end order[*i1-'A'][*i2 - 'A'] = 1; } swap(s1, s2); } // get the ordered list vector<char> orderedList; for (char i = 0; i< 26; i++){ visit(i,isInList, order, orderedList); } // print for (vector<char>::reverse_iterator rit = orderedList.rbegin(); rit != orderedList.rend(); rit++){ cout<< *rit; } cout<<"\n"; } }
true
293f1811e6e08ed8518a315d35a58b205e0a4896
C++
qqlizhn/Simple-MSP430-Music-Player-
/mainRunner.cpp
UTF-8
5,432
2.5625
3
[]
no_license
/* * Final Project * Hammad Ajmal * Neil Patel */ #include <msp430.h> #include <string.h> //For mem copy #include "MMC.h" #include "hal_SPI.h" #include "hal_MMC_hardware_board.h" #include "ringbuffer.h" //Ring buffer class. //Red onboard LED on if sd card is successfully read. int i = 0;//index for block array. int j = 0;//index for looping volatile unsigned long int pointerToWord(unsigned char* p) { return ((unsigned long int)p[0]) << 24 | ((unsigned long int)p[1]) << 16 | ((unsigned long int)p[2]) << 8 | ((unsigned long int)p[3]); } RingBuffer RB; //Buffer to get values to play. const unsigned char LED = BIT0; #pragma vector=TIMER1_A0_VECTOR __interrupt void TA1CCR0_INT(void) { TA1CCR2 = (RB.pop()+256); //pop next value for left channel and add 256 to convert to unsigned int (which makes it sound better). TA1CCR1 = (RB.pop()+256); //pop next value for left channel and add 256 to convert to unsigned int (which makes it sound better). //Tell main to update the buffer LPM1_EXIT; } void main(void) { LPM4_EXIT; mmcUnmountBlock();//in case of reset. //Turn off the watchdog timer WDTCTL = WDTPW + WDTHOLD; P1DIR |= LED; P1OUT &= ~LED; //Set the green LED to output //P1DIR |= BIT6; //Set up output from Timer A0.1 //P1SEL |= BIT6; //16MHz //Set DCO to 16 MHz calibrated DCOCTL = CALDCO_16MHZ; BCSCTL1 = CALBC1_16MHZ; //setup 2.1 and 2.4 to output from TA1.0 P2DIR |= BIT4; P2DIR |= BIT1; P2SEL |= BIT4; P2SEL |= BIT1; TA1CCR0 = 2000;//8khz sample @16Mhz clock rate TA1CCTL0 = CCIE; //enable capture control interrupt TA1CTL = TASSEL_2 + MC_1 + ID_0; //count up and select timer 2 _BIS_SR(LPM0_bits + GIE); //enter lpm0 cause keeping it low power, GIE enables all interrupts TA1CCTL1 = OUTMOD_7; //pwm TA1CCTL2 = OUTMOD_7; //pwm __enable_interrupt(); //Reset SD card by cycling power //Credit to Boris Cherkasskiy and his blog post on Launchpad+MMC P2DIR |= BIT2; P2OUT &= ~BIT2; __delay_cycles(1600000); // 100ms @ 16MHz P2OUT |= BIT2; __delay_cycles(1600000); // 100ms @ 16MHz //Initialize MMC library while (MMC_SUCCESS != mmcInit()); //Verify card ready while (MMC_SUCCESS != mmcPing()); //Check the memory card size volatile unsigned long size = mmcReadCardSize(); //Toggle the LED to indicate that reading was successful P1OUT ^= LED; //Test that the SD card is working //Read in the OEM name and version in bytes 3-10 // Read in a 512 byte sector // This is a multipart process. // First you must mount the block, telling the SD card the relative offset // of your subsequent reads. Then you read the block in multiple frames. // We do this so we don't need to allocate a full 512 byte buffer in the // MSP430's memory. Instead we'll use smaller 64 byte buffers. This // means that an entire block will take 8 reads. The spiReadFrame command // reads in the given number of bytes into the byte array passed to it. // After reading all of the data in the block it should be unmounted. //volatile char result = mmcReadBlock(0, 64, block); //volatile char result = mmcMountBlock(0, 512); //unsigned int long long j = ; unsigned char block[128] = {0}; unsigned long int offset1 =566; volatile long int offset = (unsigned long int)offset1 * 512; //^^ 566*512 for actual text, 534*512 for file name, 62*512 for FAT16 MSDOS, 0*512 MBR volatile char result = mmcMountBlock(offset, 512); int x = 3; //bool check for sector end, we read 2 sectors before playing the song. //Read the 24 byte header spiReadFrame(block, 24); unsigned long int* words = (unsigned long int*)block; //These are stored in big-endian format volatile unsigned long int snd_offset = pointerToWord(block+4); volatile long int snd_size = pointerToWord(block+8); //We will only play 8bit PCM (decimal 2) volatile unsigned char data_encoding = pointerToWord(block+12); //We will only play rates up to 16kHz volatile unsigned int sample_rate = pointerToWord(block+16); volatile unsigned char channels = pointerToWord(block+20); //Fill the buffer before starting to play the song. spiReadFrame(block,128); //read in first 128 bytes of song to fill block with. for(j = 0; j<128; j++){ RB.push(block[j]);//push in those values. } spiReadFrame(block,128); //pre read the next 128 bytes. volatile long int offset2=0; //song just started playing so this offset is 0. while (1){ if(RB.isFull())LPM1;//enter LPM1 once buffer is full. RB.push(block[i]); //push next value to be played in buffer. ++i; //increase block index if(i>127){ //if we hit the end of a block spiReadFrame(block,128); //read in the next 128 values. x++; //increase location in sector. i = 0; //set block index back to 0. if(x>=4){ //if we hit the end of the current sector unmount and increase the sector than remount. mmcUnmountBlock(); ++offset1; //next sector offset = offset1*512; //figure out start address offset2 = offset2 + 512; //figure out the end of the song. if(offset2>(snd_size+512))break; //if offset2 is greater than send size we just break and exit to loop. mmcMountBlock(offset,512); //mount the new block x = 0; //set the current location in the sector back to 0. } } } mmcUnmountBlock(); //once song is finished unmount block. LPM4; //enter LPM4 to use the least power. }
true
a43e3ef0aa7e462e8008bf59805628fefaa0e73a
C++
browner342/DronPodwodny
/project/inc/dno.hh
UTF-8
414
2.625
3
[]
no_license
#ifndef DNO_HH #define DNO_HH #include "powierzchnia.hh" /** * Klasa jest reprezentacja graficzna dna w programie. */ class Dno:public Powierzchnia{ public: /** * Tworzy powierzchnie dna na zakresie od poczatek do koniec * * @param[in] poczatek - wektorowy poczatek zakresu * @param[in] koniec - wektorowy koniec zakresu */ Dno(Wektor3D poczatek, Wektor3D koniec); }; #endif
true
f42cb2a365fe188bc1914bf6e0e450e41bf24688
C++
zzyzy/LeetCode
/Weekly20/DetectCapital.cpp
UTF-8
1,433
4.0625
4
[]
no_license
/* * LeetCode Weekly Contest 20 * Detect Capital * Written by Zhen Zhi Lee in C++11 */ #include <iostream> bool IsStringUpper(std::string word) { for (auto c : word) { if (!isupper(c)) return false; } return true; } bool IsStringLower(std::string word) { for (auto c : word) { if (isupper(c)) return false; } return true; } bool IsStringCapital(std::string word) { if (word.length() > 1) { for (auto i = 1; i < word.length(); ++i) { if (isupper(word[i])) return false; } return isupper(word[0]); } return false; } // Naive solution in O(n*3) time bool DetectCapitalUse(std::string word) { return IsStringUpper(word) || IsStringLower(word) || IsStringCapital(word); } // Better solution in O(n) time //bool DetectCapitalUse(const std::string &word) { // size_t count = 0; // for (auto c : word) { if (isupper(c)) ++count; } // return count == word.length() || // All letters in this word are capitals // count == 0 || // All letters in this word are not capitals // count == 1 && isupper(word[0]); // Only the first letter in this word is capital // // if it has more than one letter //} int main() { std::string word; std::cin >> word; std::cout << std::boolalpha << DetectCapitalUse(word) << std::endl; return 0; }
true
2cc62e1f3a7f78cea6bdec2608bbe53872e2625e
C++
eksime/SDLport
/Cthulhu.cpp
UTF-8
716
2.640625
3
[]
no_license
#include "Cthulhu.h" #include "player.h" Cthulhu::Cthulhu(Coords c) : Entity(c) { setTexture("cthulhu"); entType = CTHULHU; health = 100; maxHealth = 100; invincible = false; collisionRadius = 32; } void Cthulhu::move() { Coords distance; distance = player->coords - coords; if (fabsf(distance.x) > fabsf(distance.y)) { movement.x = distance.x > 0 ? 1 : -1; movement.y = distance.y / fabsf(distance.x); } else { movement.y = distance.y > 0 ? 1 : -1; movement.x = distance.x / fabsf(distance.y); } movement.x = movement.x * (3.5f - 3 * (health / 100.0f)); movement.y = movement.y * (3.5f - 3 * (health / 100.0f)); coords = coords + movement; } Cthulhu::~Cthulhu() {};
true
d22e372314027fae8253701f2fbc567cd7311fd5
C++
HyeonseopJeong/Algorithm
/exhaustive-search/permutation.cc
UTF-8
1,038
3.421875
3
[]
no_license
#include <cstdio> #include <algorithm> #include <vector> using namespace std; int elems[10] = {0,1,2,3,4,5,6,7,8,9}; int result[10]; int cnt; void _perm(int n, int idx) { if(idx == n) { printf("( "); for(int i = 0; i < n; i++) printf("%d ", result[i]); printf(")\n"); cnt++; } else { for(int i = idx; i < n; i++) { swap(result[idx], result[i]); _perm(n, idx + 1); swap(result[idx], result[i]); } } } void doPermutation(int n, int m, int M) { if(n < m) return; if(m == 0) { _perm(M, 0); } else { result[m - 1] = elems[n - 1]; doPermutation(n - 1, m - 1, M); doPermutation(n - 1, m, M); } } /* n개 중에서 m개를 고른 다음골라진 m개에 순서를 바꿔서 m!개 출력. 즉, combination을 먼저 한 결과에 모든 순서를 만들어서 출력. */ int main() { doPermutation(10, 3, 3); printf("cnt = %d\n", cnt); return 0; }
true
dcad733bf727630070158abef0059f6fb592e34d
C++
geosteffanov/up-2016-2017
/week07/solutions/task5.cpp
UTF-8
1,009
3.1875
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; int main() { double first[10]; double second[10]; double result[10]; int size; cout << "Enter size: "; cin >> size; //въвеждаме от клавиатурата двата масива for (int i = 0; i < size; i++) { cout << "first[" << i << "]= "; cin >> first[i]; } for (int i = 0; i < size; i++) { cout << "second[" << i << "]= "; cin >> second[i]; } //третият не го въвеждаме от клавиатурата, защото //неговите елементи се полчават от средно аритметичното //на елементите на първите два for (int i = 0; i < size; i++) { result[i] = (first[i] + second[i]) / 2; } //печатаме резултата for (int i = 0; i < size; i++) { cout << "result[" << i << "]= " << result[i] << endl; } }
true
64d4e7d34909cf6768eca51badc7dc9da36262e1
C++
IvanYukish/C-plas-plas-Ilash
/first_group/lab1.1_4/Labirint.h
UTF-8
1,948
2.8125
3
[]
no_license
// // Created by yukish on 19.05.19. // #ifndef STRDATA_LABIRINT_H #define STRDATA_LABIRINT_H #include <iostream> #include <vector> using namespace std; const int rows = 7, cols = 7; int a[rows][cols] = { 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1}; typedef struct{int x; int y;} POINT; typedef vector<POINT> state; bool add_point(POINT& p, state& s) { if (p.x<1 || p.x>cols || p.y<1 || p.y>rows) return false; if (a[rows-p.y][p.x-1]>0) return false; for (auto it = s.begin(); it != s.end(); it++) if (it->x == p.x && it->y == p.y) return false; s.push_back(p); return true; } vector<state> steps(state& s) { POINT p = s.back(); vector<state> r; for (int dx = -1; dx <= 1; dx++) for (int dy = -1; dy <= 1; dy++) { if (abs(dx) == abs(dy)) continue; POINT pd; pd.x = p.x + dx; pd.y = p.y + dy; state sd = s; if (add_point(pd, sd)) r.push_back(sd); } return r; } bool is_solved(state& s) { POINT p = s.back(); return p.x==1 || p.x==cols || p.y==1 || p.y==rows; } vector<state> start_state() { POINT p; p.x = 5; p.y = 4; state s; s.push_back(p); vector<state> r; r.push_back(s); return r; } vector<state> solve_wide(vector<state> ss) { vector<state> r, ns; for (auto it = ss.begin(); it != ss.end(); it++) { state s = *it; if (is_solved(s)) r.push_back(s); else { vector<state> css = steps(s); ns.insert(ns.end(), css.begin(), css.end()); } } return !r.empty() ? r : ns.empty() ? ns : solve_wide(ns); } void show_state(state& s) { for (auto it = s.begin(); it != s.end(); it++) cout << "(" << it->x << ", " << it->y << ")" << endl; } #endif //STRDATA_LABIRINT_H
true
8f2a05b5ae26e77cc76ecad4f910ccee8131f79f
C++
radtek/jsonparsercpp
/inc_common/JsonParser.h
UTF-8
6,885
2.6875
3
[ "MIT" ]
permissive
#ifndef JSONPARSER_H #define JSONPARSER_H #include <string> #include <fstream> #include <iostream> #include "staticjson/document.hpp" #include "staticjson/staticjson.hpp" #include "rapidjson/schema.h" #include "rapidjson/prettywriter.h" namespace MsgPacker { class JsonParseStatus { public: std::string mSchemaViolationReport; std::string mInvalidSchema; std::string mInvalidSchemaKeyWord; std::string mInvalidDocument; void reset() { mSchemaViolationReport.clear(); mInvalidSchema.clear(); mInvalidSchemaKeyWord.clear(); mInvalidDocument.clear(); } friend std::ostream& operator<<(std::ostream& o, const JsonParseStatus & obj) { o<<"mSchemaViolationReport:"<<obj.mSchemaViolationReport<<std::endl; o<<"mInvalidSchema:"<<obj.mInvalidSchema<<std::endl; o<<"mInvalidSchemaKeyWord:"<<obj.mInvalidSchemaKeyWord<<std::endl; o<<"mInvalidDocument:"<<obj.mInvalidDocument<<std::endl; return o; } }; /** * This class is base for all application message classes. * it will be providing all necessary json parsing and validation functionality. * */ template<typename DerivedT> class JsonParser { private: static rapidjson::SchemaValidator* schemaValidator; static rapidjson::SchemaDocument* schemaDocument; public: /* * FUNCTION:JsonParser() * * @param[in] * @param[out] * */ explicit JsonParser() { } /* * FUNCTION:~JsonParser() * * @param[in] * @param[out] * */ ~JsonParser() { } /* * FUNCTION:readJsonFile() * * @return void * * @param[in] filename - json file name to be read * @param[out] jsonBuffer - json buffer loaded from file * * @Usage call this method to read the json file and load buffer in string */ static void readJsonFile(const std::string& filename, std::string& jsonBuffer) { std::cout<<"trying to open file: "<<filename<<std::endl; std::ifstream infile(filename); getline(infile, jsonBuffer, std::string::traits_type::to_char_type( std::string::traits_type::eof())); //std::cout<<"Content in json schema file:"<<jsonBuffer<<std::endl; } /* * FUNCTION:encode() * * @return void * * @param[in] json buffer to be filled * * @Usage call this method to encode the json data into the jsonBuffer */ void encode(std::string& jsonBuffer) { auto derived = static_cast<DerivedT*>(this); jsonBuffer = staticjson::to_json_string(*derived); } /* * FUNCTION:loadSchemaValidator() * * @return boolean * * @param[in] jsonBuffer - json schema buffer * @param[out] ParseStatus- schema parse result * * @Usage call this method to load the json schema into validator */ static int loadSchemaValidator(const std::string& jsonSchema, staticjson::ParseStatus& result) { rapidjson::Document tempDoc; if (!staticjson::from_json_string(jsonSchema.c_str(), &tempDoc, &result)) { return 1; } schemaDocument = new(rapidjson::SchemaDocument)(tempDoc); schemaValidator = new(rapidjson::SchemaValidator)(*schemaDocument); return 0; } /* * FUNCTION:deleteSchemaValidator() * * @return * * @param[in] * @param[out] * * @Usage call this method to delete the json schema validators */ static void deleteSchemaValidator() { if (nullptr != schemaValidator) { //std::cout << "Deleting schemaValidator" << std::endl; delete schemaValidator; schemaValidator = nullptr; } if (nullptr != schemaDocument) { //std::cout << "Deleting schemaDocument" << std::endl; delete schemaDocument; schemaDocument = nullptr; } } /* * FUNCTION:decode() * * @return * * @param[in] jsonBuffer - input json buffer * @param[out] ParseStatus - result of parsing * * @Usage call this method to decode the json bufer into the c++ class data structure */ int decode(const std::string& jsonBuffer, staticjson::ParseStatus& result, JsonParseStatus *parseStatus ) { auto derived = static_cast<DerivedT*>(this); if (NULL == schemaValidator) { if (!staticjson::from_json_string(jsonBuffer.c_str(), derived, &result)) { return 1; } return 0; } rapidjson::Document d; schemaValidator->Reset(); if (!staticjson::from_json_string(jsonBuffer.c_str(), &d, &result)) { std::cout<<"json to string failed"<<std::endl; return 1; } if (!d.Accept(*schemaValidator)) { //populate schema violation errors from rapid json error object // and schemaValidator if (nullptr != parseStatus) { std::cout<<"filling reason of failure"<<std::endl; rapidjson::StringBuffer sb; schemaValidator->GetInvalidSchemaPointer().StringifyUriFragment(sb); parseStatus->mInvalidSchema = sb.GetString(); parseStatus->mInvalidSchemaKeyWord = schemaValidator->GetInvalidSchemaKeyword(); sb.Clear(); schemaValidator->GetInvalidDocumentPointer().StringifyUriFragment(sb); parseStatus->mInvalidDocument = sb.GetString(); // Detailed violation report is available as a JSON value //sb.Clear(); //rapidjson::PrettyWriter<rapidjson::StringBuffer> w(sb); //schemaValidator->GetError().Accept(w); //parseStatus->mSchemaViolationReport = sb.GetString(); } std::cout<<"json Accept failed"<<std::endl; return 1; } if (!staticjson::from_json_document(d, derived, &result)) { std::cout<<"json to string failed"<<std::endl; return 1; } return 0; } }; template <typename T> rapidjson::SchemaValidator* JsonParser<T>::schemaValidator = NULL; template <typename T> rapidjson::SchemaDocument* JsonParser<T>::schemaDocument = NULL; } #endif
true
888580bde8299ee71127e33ff8d13b3101a05e1e
C++
Tomasmansi/nuevo
/LISTAUT.cpp
UTF-8
5,512
3.28125
3
[]
no_license
/* LISTAS SIMPLEMENTE ENLAZADAS */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> using namespace std ; class NODO { public : char NOM[20] ; NODO * SIG ; NODO ( char * ); ~NODO() ; }; NODO::NODO(char * S) { strcpy ( NOM , S ); } NODO::~NODO() { cout << "\n\n MATANDO A .... " << NOM << "\n"; getchar() ; } class LISTA { private : NODO * INICIO ; void PONER_P(NODO *); void PONER_F(NODO *); void INSERT(NODO *); NODO * MINIMO() ; NODO * MAXIMO() ; NODO * BUSCAR ( char * ); void MATAR(NODO *); void SACAR(NODO *); public : LISTA() ; ~LISTA() ; void AGREGAR_P(char *); void AGREGAR_F(char *); void INSERTAR(char *); void MIRAR() ; void MENOR() ; void MAYOR() ; void ELIMINAR(char *); void ORDENAR1() ; void ORDENAR2() ; }; LISTA::LISTA() { INICIO = NULL ; } LISTA::~LISTA() { cout << "\n\n DESTRUYENDO TODOS LOS NODOS \n"; cout << "\n\n ESTA ES PARA USTEDES !!! .... \n"; getchar() ; } void LISTA::AGREGAR_P(char * S) { NODO * P ; P = new NODO(S) ; PONER_P(P) ; } void LISTA::PONER_P(NODO * PN) { PN->SIG = INICIO ; INICIO = PN ; } void LISTA::AGREGAR_F(char * S) { NODO * P ; P = new NODO(S) ; PONER_F(P) ; } void LISTA::PONER_F(NODO * PN) { NODO * P ; P = INICIO ; PN->SIG = NULL ; if ( ! INICIO ) { /* LISTA VACIA */ INICIO = PN ; return ; } /* LISTA NO VACIA */ while ( P->SIG ) P = P->SIG ; // LLEVO P HASTA EL ULTIMO NODO P->SIG = PN ; } void LISTA::INSERTAR(char * S) { NODO * P ; P = new NODO(S) ; INSERT(P) ; } void LISTA::INSERT(NODO * PN) { NODO * P , * ANT ; P = INICIO ; ANT = NULL ; if ( ! INICIO ) { /* LISTA VACIA */ PN->SIG = NULL ; INICIO = PN ; return ; } /* LISTA NO VACIA */ while ( P ) { if ( strcmp (P->NOM , PN->NOM) < 0 ) { /* BARRIDO */ ANT = P ; P = P->SIG ; } else { /* EUREKA !!! */ if ( ANT ) { /* NODO INTERMEDIO */ PN->SIG = P ; ANT->SIG = PN ; return ; } /* PRIMER NODO */ PN->SIG = INICIO ; INICIO = PN ; return ; } /* else */ } /* while */ /* NUEVO ULTIMO NODO */ PN->SIG = NULL ; ANT->SIG = PN ; } void LISTA::MIRAR() { NODO * P ; cout << "\n\n\n\t\t\t CONTENIDO DE LA LISTA \n\n"; P = INICIO ; while (P) { cout << "\n\n\t\t\t " << P->NOM ; P = P->SIG ; } getchar(); } void LISTA::MENOR() { if ( INICIO ) cout << "\n\n EL MENOR ES " << MINIMO()->NOM ; } NODO * LISTA::MINIMO() { NODO * P , * PMIN ; PMIN = P = INICIO ; while ( P ) { if ( strcmp (P->NOM,PMIN->NOM) < 0 ) PMIN = P ; P = P->SIG ; } return PMIN ; } void LISTA::MAYOR() { if ( INICIO ) cout << "\n\n EL MAYOR ES " << MAXIMO()->NOM ; } NODO * LISTA::MAXIMO() { NODO * P , * PMAX ; PMAX = P = INICIO ; while ( P ) { if ( strcmp (P->NOM,PMAX->NOM) > 0 ) PMAX = P ; P = P->SIG ; } return PMAX ; } NODO * LISTA::BUSCAR( char * S ) { NODO * P ; P = INICIO ; while ( P ) { if ( ! strcmp ( P->NOM , S ) ) return P ; P = P->SIG ; } return NULL ; } void LISTA::ELIMINAR(char * S) { NODO * P ; P = BUSCAR(S) ; if ( P ) MATAR(P) ; } void LISTA::MATAR( NODO * PELIM ) { NODO * P ; P = INICIO ; if ( INICIO == PELIM ) { /* PRIMER NODO */ INICIO = PELIM->SIG ; delete PELIM ; return ; } /* NO ES PRIMER NODO */ while ( P->SIG != PELIM && P ) P = P->SIG ; /* P APUNTA AL NODO ANTERIOR A PELIM */ if (P) { // P->SIG = PELIM->SIG ; P->SIG = P->SIG->SIG ; delete PELIM ; } } void LISTA::SACAR( NODO * PELIM ) { NODO * P ; P = INICIO ; if ( INICIO == PELIM ) { /* PRIMER NODO */ INICIO = PELIM->SIG ; return ; } /* NO ES PRIMER NODO */ while ( P->SIG != PELIM && P ) P = P->SIG ; /* P APUNTA AL NODO ANTERIOR A PELIM */ if (P) P->SIG = P->SIG->SIG ; } void LISTA::ORDENAR1() { NODO * P , * AUXINI ; AUXINI = NULL ; while ( INICIO ) { P = MAXIMO() ; SACAR(P) ; P->SIG = AUXINI ; AUXINI = P ; } INICIO = AUXINI ; } void LISTA::ORDENAR2() { NODO * P ; LISTA AUXL ; while ( INICIO ) { SACAR(P = INICIO) ; AUXL.INSERT(P) ; } INICIO = AUXL.INICIO ; AUXL.INICIO = NULL ; } char * GENERANOM(); int main() { LISTA L ; char BUF[20] ; strcpy ( BUF , GENERANOM() ); while ( strcmp(BUF,"FIN") ) { L.AGREGAR_F(BUF) ; strcpy ( BUF , GENERANOM() ); } L.MIRAR() ; // L.MENOR() ; // L.MAYOR() ; // cout << "\n\n\t NOMBRE A ELIMINAR : "; // cin >> BUF ; // L.ELIMINAR(BUF) ; L.ORDENAR2() ; L.MIRAR() ; printf("\n\n\n\n FIN DEL PROGRAMA\n\n"); return 0 ; } char * GENERANOM() { static int I = 0 ; static char NOM[][20] = {"FELIPE","ANA","LAURA","CACHO", "PEPE","LOLA","LUIS","PACO", "LUCRECIA","CAROLINA","ENZO","BETO","FIN"}; return NOM[I++] ; }
true
e431f858171dd4937c5f5d29b2292e85dc7883c0
C++
Shanaconda/CPSC2720
/Assignments/inventory-system/include/Complete.h
UTF-8
1,073
2.71875
3
[]
no_license
#ifndef COMPLETE_H #define COMPLETE_H #include "State.h" #include "Paper.h" #include <string> class Complete: public State { public: Complete() {} /** * add orders * implements state interface * @return true or false */ bool addProduct(); /** * edit order * implements state interface * @return true or false */ bool edit(); /** * submit order * implements state interface * @return true or false */ bool submit(); /** * cancel order * implements state interface * @return true or false */ bool cancel(); /** * submit to waitlist * implements state interface * @return true or false */ bool addToWaitlist(); /** * display status * implements state interface */ void display() { std::cout<< "Complete"; } /** * getter method * implements state interface * @return status */ std::string getStatus() {return "Complete";} private: Order* ord; }; #endif
true
b11ca3ffb94355c44ed611e3821ea068f3452ce0
C++
guojunping/XNet
/XNetFrame/BlockingQueue.h
UTF-8
2,034
2.890625
3
[]
no_license
#ifndef __BlockingQueue_H #define __BlockingQueue_H #include "TypesDn.h" #include "Event.h" #include <assert.h> namespace XNetFrame{ template <class TYPE> class CBlockingQueue { public: CBlockingQueue():m_nMax(-1),m_bDrop(false) { } ~CBlockingQueue() { if(!m_bDrop) Destory(); } void Push(TYPE& type) { m_cMonitor.enter() ; while ( m_nMax > 0 && (sint32)m_qQueue.size() >= m_nMax) { #ifdef WIN32 m_hPushEvent.reset(); #endif m_cMonitor.leave() ; if( m_bDrop ) return; m_hPushEvent.wait(); m_cMonitor.enter() ; } m_qQueue.push(type); //printf("push queue size=%d\n",(sint32)m_qQueue.size()); m_cMonitor.leave(); m_hPopEvent.set(); } void Insert(TYPE& type) { m_cMonitor.enter() ; while( m_nMax > 0 && (sint32)m_qQueue.size() >= m_nMax) { #ifdef WIN32 m_hPushEvent.reset(); #endif m_cMonitor.leave(); if( m_bDrop ) return; m_hPushEvent.wait(); m_cMonitor.enter() ; } m_qQueue.push(type); //printf("insert queue size=%d\n",(sint32)m_qQueue.size()); m_cMonitor.leave(); m_hPopEvent.set(); } TYPE Pop() { TYPE type; m_cMonitor.enter() ; while (m_qQueue.empty()) { #ifdef WIN32 m_hPopEvent.reset(); #endif m_cMonitor.leave(); if( m_bDrop ) return type; m_hPopEvent.wait(); m_cMonitor.enter() ; } type = m_qQueue.front(); m_qQueue.pop(); //printf("pop queue size=%d\n",(sint32)m_qQueue.size()); m_cMonitor.leave(); m_hPushEvent.set(); return type; } int GetQueueCount() { int nCount = 0; nCount = (sint32)m_qQueue.size(); return nCount; } void SetMaxCount(int nMax = -1) { synchronized sync(&m_cMonitor); m_nMax = nMax; } void Destory() { m_bDrop=true; m_hPushEvent.set(); m_hPopEvent.set(); } int GetMaxCount() { return m_nMax; } private: CMonitor m_cMonitor; queue<TYPE> m_qQueue; CAutomaticResetEvent m_hPopEvent; CAutomaticResetEvent m_hPushEvent; sint32 m_nMax; bool m_bDrop; }; } #endif
true
a26c17b0f08c4f5ad55781a391ddbaf2e6028aa6
C++
divakar9819/C-data-structer
/arrayOperation.cpp
UTF-8
7,210
3.484375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; //#define max 100 /* // reverse an array using auxilary pace void reverseArrayAux(int *A , int n) { int B[n],i,j; for(i=n-1, j=0; i>=0, j<n; i--, j++){ B[j] = A[i]; } cout<<"Reverse of array "; for(i=0;i<n;i++){ cout<<B[i]<<" "; } } void swapElement(int *a , int *b ) { int temp; temp = *a; *a = *b; *b = temp; } void reverseArray(int *arr , int n) { int i,j; for(i=0,j=n-1; i<j; i++ , j--){ swapElement(&arr[i],&arr[j]); } cout<<"Reverse array using swaping : "; for(i=0;i<n;i++){ cout<<arr[i]<<" "; } } // Left shift void leftShift(int *arr , int n) { int temp , i; temp = arr[0]; for(i=1;i<n;i++){ arr[i-1] = arr[i]; } // arr[n] = temp; cout<<"Left shift of array "; for(i=0;i<n-1;i++){ cout<<arr[i]<<" "; } } // Check weather an array is sorted or not int isSorted(int *arr , int n) { int i; for(i=0;i<n;i++){ if(arr[i] > arr[i+1]){ return 0; break; } } return 1; } // Insert an element in sorted array void insertSorted(int *arr , int n,int item) { int i ; i = n-1; while(arr[i]>item){ arr[i+1] = arr[i]; i--; } arr[i+1] = item; for(i=0;i<n+1;i++){ cout<<arr[i]<<" "; } } int main() { int A[7] = {8,13,20,25,28,33}; int n = sizeof(A)/sizeof(A[0]); // cout<<n; //reverseArrayAux(A,n); // cout<<endl; // reverseArray(A,n); // cout<<endl; //leftShift(A,n); int k =18; cout<<isSorted(A,n); return 0; } */ // Arranging an array one side negative and one side positive /* void swapElement(int *a , int *b ) { int temp; temp = *a; *a = *b; *b = temp; } void arrangeArray(int *arr , int n) { int i =0 , j = n-1; while(i<j){ while(arr[i]<0){ i++; } while(arr[j] >= 0){ j++; } if (i<j){ swapElement(&arr[i],&arr[j]); } } cout<<"Arranging array : "; for(i=0;i<n;i++){ cout<<arr[i]<<" "; } } int main() { int arr[] = {-6,5,33,-2,8,-9,11,-7}; int n = sizeof(arr)/sizeof(arr[0]); arrangeArray(arr,n); return 0; } */ // marge an array /* void mergeArray(int *arr1 , int *arr2,int m,int n) { int arr3[m+n]; int i , j,k; i = 0; j = 0; k = 0; while(i>m && j>n) { if(arr1[i]>arr2[j]){ arr3[k++] = arr1[i++]; } else { arr3[k++] = arr2[j++]; } } while(i<m){ arr3[k++] = arr1[i++] ; } while(j<n){ arr3[k++] = arr2[j++]; } cout<<"The merge array is : "; for(i=0;i<m+n;i++){ cout<<arr3[i]<<" "; } } int main() { int arr1[] = {3,8,16,20,25}; int arr2[] = {4,10,12,22,23}; int m = sizeof(arr1)/sizeof(arr1[0]); int n = sizeof(arr2)/sizeof(arr2[0]); mergeArray(arr1,arr2,m,n); return 0; } */ // Find missing in n natural number /* void missingNatural(int *arr , int n) { int sum = 0,s; for(int i=0;i<n;i++){ sum += arr[i]; } int s1 = arr[n-1]; s = (s1*(s1+1))/2; cout<<"Missing Number is : "<<(s-sum); } // Find missing in n natural number when the given number is not contineous natural number void missing(int *arr , int n) { int diff = arr[0] - 0; for(int i=0;i<n;i++){ if(arr[i]-i != diff) { cout<<"Missing Number is : "<<diff + i ; break; } } } int main() { int arr[] = {6,7,8,9,10,11,13}; int n = sizeof(arr)/sizeof(arr[0]); missing(arr,n); return 0; } */ // Find multiple missing value in the given indax /* void missingMulti(int *arr , int n) { int diff = arr[0] - 0; for(int i=0;i<n;i++){ if(arr[i]-i != diff) { while(diff < arr[i]-i){ cout<<diff+i<<" "; diff++; } } } } // Find missing value of unsorted array /* void missingUnsorted(int *arr , int n) { int h = *max_element(arr , arr+n); int l = *min_element(arr,arr+n); int H[h]; for(int i=0;i<n;i++){ H[arr[i]]++; } for(int i=l;i<=h;i++){ if(H[i]==0){ cout<<i<<" "; } } } int main() { int arr[] = {3,7,4,9,12,6,1,11,2,10}; int n = sizeof(arr)/sizeof(arr[0]); missingUnsorted(arr,n); return 0; } */ // Finding duplicate in array /* void duplicate(int *arr , int n) { int lastDuplicate = 0; for(int i=0;i<n;i++){ if((arr[i] == arr[i+1]) && (arr[i] != lastDuplicate)){ cout<<arr[i]<<" "; lastDuplicate = arr[i]; } } } // counting number of duplicate and its value void duplicateNumber(int *arr , int n) { int j,i ; for(i=0;i<n;i++){ if(arr[i] == arr[i+1]){ j = i+1; while(arr[j]==arr[i]){ j++; } cout<<arr[i]<<" ->"<<j-i<<" "; i = j-1; } } } int main() { int arr[] = {3,6,8,8,10,12,15,15,15,20}; int n = sizeof(arr)/sizeof(arr[0]); duplicateNumber(arr,n); return 0; } */ // Finding duplicate on unsorted array /* void duplicateUnsorted(int *arr , int n) { int i , j,temp; for(i=0;i<n;i++){ temp = 1; for(j=1;j<n;j++){ if(arr[i] == arr[j]){ temp++; arr[j] = -1; } } } if(temp>1){ cout<<arr[i]<<" "<<temp<<endl; } } //Finding duplicate element using hash table void dupliateHash(int *arr , int n) { int l = *min_element(arr,arr+n); int h = *max_element(arr,arr+n); //cout<<l; int H[h] ; for(int i=0;i<=h;i++){ H[i] = 0; } //cout<<H[h]; for(int i=0;i<n;i++){ H[arr[i]]++; } for(int i=l;i<h;i++){ if(H[i]>1 ){ cout<<i<<" "<<H[i]<<endl; } } } int main() { int arr[] = {3,6,8,8,10,4,4,4,4,12,15,15,15,20}; int n = sizeof(arr)/sizeof(arr[0]); duplicateUnsorted(arr,n); return 0; } */ // Find a pair with sum k (a + b = k) void findPair(int *arr , int n , int k) { vector<pair<int,int>>vp; int i , j; for(i=0;i<n;i++){ for(j=1;j<n;j++){ if((arr[i] + arr[j]) == k) vp.push_back(make_pair(arr[i],arr[j])); } } cout<<"Pair which equal to the given number : "; for(int i =0 ; i<vp.size();i++){ cout<<vp[i].first<<" "<<vp[i].second<<endl; } } int main() { int arr[] = {2,3,6,7,8,9,10,14,16}; int n = sizeof(arr)/sizeof(arr[0]); int k = 10; findPair(arr,n,k); return 0; }
true
012a7aa3dc10b24c6446d6df0a923aace7e94fed
C++
hesitationer/miscvision
/sift_correspond.hh
UTF-8
1,717
2.734375
3
[]
no_license
#ifndef __SIFT_CORRESPOND_HH #define __SIFT_CORRESPOND_HH #include <cv/sift_feature_detector.hh> namespace sift { typedef cv::Image<float> image_t; typedef std::vector<ScalePoint> pvector_t; typedef std::vector<sift::Descriptor<> > dvector_t; /** Finds corresponding points between im1 and im2 using SIFT features * @param im1 grey scale floating point image (scaled 0 to 256) * @param im2 grey scale floating point image (scaled 0 to 256) * @param pts1 output vector of ScalePoint (input should be size 0) * @param pts2 output vector of ScalePoint (input should be size 0) * @param keys1 output vector of sift::Descriptor (input size should be 0) * @param keys2 output vector of sift::Descriptor (input size should be 0) */ int correspond(const image_t & im1, const image_t & im2, pvector_t & pts1, pvector_t & pts2, dvector_t * keys1 = NULL, dvector_t * keys2 = NULL){ sift::FeatureTracker detector(0.06); std::vector<ScalePoint> features; std::vector<sift::Descriptor<> > descriptors; // do feature detection on first image detector.track(im1); // copy points and descriptors features.insert(features.end(), detector.begin(), detector.end()); descriptors.insert(descriptors.end(), detector.descriptors().begin(), detector.descriptors().end()); detector.track(im2); for(int i=0; i<features.size(); i++){ sift::FeatureTracker::iterator it = detector.labels()[i]; if(it!= detector.end()){ pts1.push_back( features[i] ); pts2.push_back( *it ); //if(keys1!=NULL) keys1->push_back( descriptors[ i ] ); //if(keys2!=NULL) keys2->push_back( detector.descriptors()[i] ); } } return pts1.size(); } } // namespace sift #endif // __SIFT_CORRESPOND
true
03cba9065cad0edf5c86e7d7a6d5c7b219ff94f8
C++
AndreaMarangoni/WidgetList
/src/ListWidget.cpp
UTF-8
1,028
2.953125
3
[ "MIT" ]
permissive
#include <QVBoxLayout> #include "ListWidget.h" ListWidget::ListWidget(QWidget *parent) : QWidget(parent), layout_(new QVBoxLayout(this)) { layout_->setContentsMargins(0, 0, 0, 0); layout_->setSpacing(0); this->setLayout(layout_); } ListWidget::~ListWidget() { } void ListWidget::addWidget(QWidget* widget, int stretch, Qt::Alignment alignment) { layout_->QVBoxLayout::addWidget(widget, stretch, alignment); } void ListWidget::insertWidget(int index, QWidget* widget, int stretch, Qt::Alignment alignment) { layout_->QVBoxLayout::insertWidget(index, widget, stretch, alignment); } void ListWidget::removeWidget(QWidget* widget) { layout_->removeWidget(widget); } QList<QWidget*> ListWidget::getListWidget() const { QWidgetList list; for (int i = 0; i < layout_->count(); ++i) { list.push_back(layout_->itemAt(i)->widget()); } return list; } QWidget* ListWidget::getWidget(int index) const { return layout_->itemAt(index)->widget(); } int ListWidget::count() const { return layout_->count(); }
true
657467b4059a8ccaa15ab52352710eb4305c69d0
C++
Jeffrey-P-McAteer/ros_object_recognition
/src/hsv_filter/include/hsv_filter/hsv_filter.h
UTF-8
1,134
2.875
3
[ "MIT" ]
permissive
/** \file * \brief Definition of the HSVFilter class. */ #ifndef HSV_FILTER_HSV_FILTER_H #define HSV_FILTER_HSV_FILTER_H // ROS & OpenCV headers. #include <opencv2/core/core.hpp> // cv::Mat // object-detection headers. #include <object_detection_2d/filter.h> namespace hsv_filter { class ParameterManager; /** \brief Filter for filtering images according to their HSV pixel-values. */ class HSVFilter : public object_detection_2d::Filter { public: /** \brief Creates an HSVFilter and initializes its parameter-manager. * * \param[in] pm Pointer to a valid ParameterManager. */ explicit HSVFilter(ParameterManager* pm); /** \brief Filters the given image. * * Only pixels whose Hue, Saturation and Value values lie inside * adjustable ranges pass through. * * \param[in] bgr_image Image that is filtered. * \return New image, containing the filtered image. */ cv::Mat filter(const cv::Mat& bgr_image) override; private: cv::Mat threshold(const cv::Mat& hsv_image) const; // Data members. ParameterManager* param_manager_; }; } // hsv_filter #endif // HSV_FILTER_HSV_FILTER_H
true
6d8a827a68376426a8023a8d188f52bd9cbc13f8
C++
jason967/algorithm
/Algo/10216_CCG.cpp
UTF-8
991
2.671875
3
[]
no_license
#include<cstdio> #include<algorithm> #include<cmath> using namespace std; int p[3001]; int N, T; struct _G { int y, x, R; }G[3001]; int find(int n) { if (p[n] == n) return p[n]; return p[n] = find(p[n]); } void merge(int a, int b) { a = find(a); b = find(b); if (a == b) return; p[b] = a; } int dist(int y1, int x1, int y2, int x2) { int a = abs(y1 - y2); int b = abs(x1 - x2); a = pow(a, 2); b = pow(b, 2); return a+b; } int main() { scanf("%d", &T); for (int tc = 0; tc < T; tc++) { scanf("%d", &N); for (int i = 1; i <= N; i++) p[i] = i; for (int i = 1; i <= N; i++) { scanf("%d %d %d", &G[i].y, &G[i].x, &G[i].R); } for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { if (i == j) continue; int R = G[i].R + G[j].R; if (dist(G[i].y, G[i].x, G[j].y, G[j].x) <=R*R) { merge(find(i), find(j)); } } } int ans = 0; for (int i = 1; i <= N; i++) { if (p[i] == i) ans++; } printf("%d\n", ans); } }
true
5b6a66051243b99efc87a26fa3960c72d581ad48
C++
dphuoc432000/DuyTan_2nd
/Computer Science for Practicing Engineers (Software Construction)/tree and Binary tree/AVLTree.cpp
UTF-8
2,846
3.390625
3
[]
no_license
#include <iostream> #include <queue> using namespace std; class AVLTree{ struct TNode{ int data; TNode *left, *right; TNode(int x){ data = x; left = right = NULL; } TNode(int x, TNode* ll, TNode* rr){ data = x; left = ll; right = rr; } }; TNode *root; public: int cao(TNode *T){ if(T == NULL) return 0; else return 1 + max(cao(T->left), cao(T->right)); } TNode *chenx(TNode *&T, int x){ if(T == NULL) T = new TNode(x); else if(x == T->data) cout << "Da co trong cay"; else{ if(x < T->data) T->left = chenx(T->left,x); else T->right = chenx(T->right,x); int h1 = cao(T->left), h2 = cao(T->right); if(h1 > h2+1){ int h11 = cao(T->left->left); int h12 = cao(T->left->right); if(h11>h12) qL(T); else qLR(T); } else if(h2 > h1+ 1){ int h22 = cao(T->right->right); int h21 = cao(T->right->left); if(h22 > h21) qR(T); else qRL(T); } } return T; } TNode *qL(TNode *&T){ TNode *x = T; TNode *y = x->left; x->left = y->right; y->right = x; T = y; return T; } TNode *qLR(TNode *&T){ TNode * x = T; TNode * y = x->left; TNode * z = y->right; y->right = z->left; x->left = z->right; z->left = y; z->right = x; T = z; return T; } TNode *qR(TNode *&T){ TNode *x = T; TNode *y = x->right; x->right = y->left; y->left = x; T = y; return T; } TNode *qRL(TNode *&T){ TNode *x = T; TNode *y = x->right; TNode *z = y->left; y->left = z->right; x->right = z->left; z->left = x; z->right = y; T = z; return T; } void chenx(int x){ chenx(root, x); } void chieuRong(){ queue<TNode*> Q; if(root != NULL){ Q.push(root); } else{ cout << "Cay rong"; return; } while(!Q.empty()){ TNode * x = Q.front(); Q.pop(); cout << x->data << " "; if(x->left!= NULL) Q.push(x->left); if(x->right) Q.push(x->right); } } }; main(){ AVLTree a; a.chenx(20); a.chenx(37); a.chenx(3); a.chenx(34); a.chenx(36); a.chenx(10); a.chenx(5); a.chenx(40); a.chenx(50); a.chieuRong(); cout << endl; // // AVLTree a1; // a1.chenx(27); // a1.chenx(11); // a1.chenx(35); // a1.chenx(29); // a1.chenx(24); // a1.chenx(26); // a1.chenx(53); // a1.chenx(44); // a1.chenx(10); // a1.chenx(16); // a1.chenx(13); // a1.chieuRong(); // // cout << endl << "cau b: "; // AVLTree b; // b.chenx(20); // b.chenx(10); // b.chenx(17); // b.chenx(41); // b.chenx(55); // b.chenx(5); // b.chenx(60); // b.chenx(72); // b.chenx(4); // b.chenx(1); // b.chenx(18); // b.chenx(27); // b.chenx(35); // b.chieuRong(); AVLTree c; c.chenx(5); c.chenx(9); c.chenx(11); c.chenx(3); c.chenx(7); c.chenx(6); c.chenx(13);; c.chieuRong(); }
true
db298d53fb48b9a9bcea63264eb72bded76f402c
C++
mauro7x/argentum
/Common/src/Socket/SocketWrapper.cpp
UTF-8
4,783
3.015625
3
[ "MIT" ]
permissive
#include "../../includes/Socket/SocketWrapper.h" //----------------------------------------------------------------------------- #include <endian.h> //----------------------------------------------------------------------------- // Métodos privados SocketWrapper::SocketWrapper(const int fd) : Socket(fd) {} //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // API Pública SocketWrapper::SocketWrapper() : Socket() {} SocketWrapper::SocketWrapper(const std::string& port, const int max_queued_clients) : Socket(port, max_queued_clients) {} SocketWrapper::SocketWrapper(const std::string& hostname, const std::string& port) : Socket(hostname, port) {} SocketWrapper::SocketWrapper(SocketWrapper&& other) : Socket(std::move(other)) {} SocketWrapper& SocketWrapper::operator=(SocketWrapper&& other) { Socket::operator=(std::move(other)); return *this; } SocketWrapper SocketWrapper::accept() const { if (!fd_valid) { throw Exception("Invalid socket file descriptor."); } int peer_socket = ::accept(fd, NULL, NULL); if (peer_socket == -1) { throw ClosedSocketException("Error in function: Socket::accept()"); } return std::move(SocketWrapper(peer_socket)); } //----------------------------------------------------------------------------- // Sobrecarga de operadores size_t SocketWrapper::operator<<(char c) const { return send(&c, sizeof(c)); } size_t SocketWrapper::operator>>(char& c) const { return recv(&c, sizeof(c)); } size_t SocketWrapper::operator<<(const uint8_t& n) const { return send((char*)&n, sizeof(n)); } size_t SocketWrapper::operator>>(uint8_t& n) const { uint8_t received; size_t n_received; n_received = recv((char*)&received, sizeof(received)); n = received; return n_received; } size_t SocketWrapper::operator<<(const uint32_t& n) const { uint32_t _n = htole32(n); return send((char*)&_n, sizeof(_n)); } size_t SocketWrapper::operator>>(uint32_t& n) const { uint32_t _received; size_t n_received; n_received = recv((char*)&_received, sizeof(_received)); n = le32toh(_received); return n_received; } size_t SocketWrapper::operator<<(const std::string& s) const { size_t sent = 0, last_sent = 0; // Primero enviamos la longitud uint32_t size = s.size(); sent += this->operator<<(size); if (sent != sizeof(size)) { return 0; } // Enviamos el string last_sent = send(s.c_str(), size); if (last_sent) { sent += last_sent; } else { return 0; } return sent; } size_t SocketWrapper::operator>>(std::string& s) const { size_t received = 0, last_received = 0; s.clear(); s.shrink_to_fit(); // Primero recibimos la longitud uint32_t size; received += this->operator>>(size); if (received != sizeof(size)) { return 0; } // Recibimos el string s.reserve(size); char byte; for (unsigned int i = 0; i < size; i++) { last_received += this->operator>>(byte); if (last_received) { received += last_received; s += byte; } else { return 0; } } return received; } size_t SocketWrapper::operator<<(const std::vector<uint8_t>& v) const { size_t sent = 0, last_sent = 0; // Primero enviamos la longitud uint32_t size = v.size(); sent += this->operator<<(size); if (sent != sizeof(size)) { return 0; } // Enviamos el vector uint8_t byte; for (unsigned int i = 0; i < size; i++) { byte = v.at(i); last_sent = this->operator<<(byte); if (last_sent) { sent += last_sent; } else { return 0; } } return sent; } size_t SocketWrapper::operator>>(std::vector<uint8_t>& v) const { size_t received = 0, last_received = 0; v.clear(); v.shrink_to_fit(); // Primero recibimos la longitud uint32_t size; received += this->operator>>(size); if (received != sizeof(size)) { return 0; } // Recibimos el vector v.reserve(size); uint8_t byte; for (unsigned int i = 0; i < size; i++) { last_received += this->operator>>(byte); if (last_received) { received += last_received; v.push_back(byte); } else { return 0; } } return received; } //----------------------------------------------------------------------------- SocketWrapper::~SocketWrapper() {} //-----------------------------------------------------------------------------
true
2d89a1b73a358762dffdaa1c62c0cf111b38f220
C++
duxingyi-charles/pattern-viewer
/3rdparty/LearningQuadrangulationsCore/polygon_enumeration.h
UTF-8
5,980
2.828125
3
[]
no_license
#ifndef POLYGON_ENUMERATION_H #define POLYGON_ENUMERATION_H #include "polygon_forest.h" namespace vcg { namespace tri { // namespace pl: patch learning namespace pl { /** * @brief The PolygonEnumerator class provides a simplified interface to PolygonForest * for the enumeration of polygons. */ template < typename PolyMeshType > class PolygonEnumerator { public: typedef pl::PolygonForest<PolyMeshType> PolygonForest; typedef typename PolygonForest::PolygonTree PolygonTree; typedef typename PolygonForest::CornersType CornersType; typedef pl::PolygonRegister<PolyMeshType> PolygonRegister; typedef pl::PatchLearner<PolyMeshType> PatchLearner; /** * @brief PolygonEnumerator Default constructor. */ PolygonEnumerator() { } /** * @brief PolygonEnumerator Constructor initializing the size of the forest. * @param size The number of trees in the forest. */ PolygonEnumerator(const num_type size) : _forest(size) { } /** * @brief PolygonEnumerator Copy constructor. * @param enumerator The PolygonEnumerator to copy. */ PolygonEnumerator(const PolygonEnumerator &enumerator) : _forest(enumerator._forest) { } #if __cplusplus >= 201103L || _MSC_VER >= 1800 /** * @brief PolygonEnumerator Move contructor. * @param enumerator The PolygonEnumerator to move. */ PolygonEnumerator(PolygonEnumerator&& enumerator) : _forest(std::move(enumerator._forest)) { enumerator.resize(0); } #endif /** * @brief ~PolygonEnumerator Default destructor. */ virtual ~PolygonEnumerator() { } /** * @brief operator = Copy assignment operator. * @param enumerator The PolygonEnumerator to copy. * @return A reference to this. */ PolygonEnumerator & operator = (const PolygonEnumerator &enumerator) { if (&enumerator != this) _forest = enumerator._forest; return *this; } #if __cplusplus >= 201103L || _MSC_VER >= 1800 /** * @brief operator = Move assignment operator. * @param enumerator The PolygonEnumerator to move. * @return A reference to this. */ PolygonEnumerator & operator = (PolygonEnumerator&& enumerator) { if (&enumerator != this) { _forest = std::move(enumerator._forest); enumerator.resize(0); } return *this; } #endif /** * @brief size gives the number of PolygonTrees in the forest. * @return The size of the forest. */ virtual num_type size() const { return _forest.size(); } /** * @brief resize changes the size of the forest. * @param size The new size. */ virtual void resize(const num_type size) { _forest.resize(size); } /** * @brief operator [] gives access to the tree at index. * @param index The index of the tree. * @return A reference to the tree at index. */ virtual PolygonTree & operator [] (const num_type index) { return _forest[index]; } /** * @brief operator [] gives access to the tree at index. * @param index The index of the tree. * @return A const reference to the tree at index. */ virtual const PolygonTree & operator [] (const num_type index) const { return _forest[index]; } /** * @brief numberOfPolygons gives the total number of enumerated polygons. * @return The total number of enumerated polygons. */ virtual count_type numberOfPolygons() const { return _forest.numberOfPolygons(); } /** * @brief maxNumberOfSides gives the maximum number of sides of any enumerated polygon over the whole mesh. * @return The maximum number of sides of any enumerated polygon. */ virtual n_corners_type maxNumberOfSides() const { return _forest.maxNumberOfSides(); } /** * @brief maxNumberOfSingularities gives the maximum number of singularities of any enumerated polygon over the whole mesh. * @return The maximum number of singularities of any enumerated polygon. */ virtual n_corners_type maxNumberOfSingularities() const { return _forest.maxNumberOfSingularities(); } /** * @brief enumerate finds all the polygons in mesh with at most maxNFaces. * @param mesh The input mesh. * @param polygonRegister The register which filters out the duplicated polygons. * @param patchLearner The acquisition engine. * @param minNFaces The minimum number of per-polygon faces for counting and template storing. * @param maxNFaces The maximum number of faces each polygon is allowed to have. * @param cornersType The type of corners allowed. * @param bindPolygon true if the template patch must be linked to the polygon whre it's been found, false otherwise. * @param collapsePolygon true if the polygons must be simplified before acquisition, false otherwise. * @param keepInMemory true if all the enumerated polygons must be kept in memory, false otherwise. */ virtual void enumerate(PolyMeshType &mesh, PolygonRegister *polygonRegister, PatchLearner &patchLearner, const num_type minNFaces = 0, const num_type maxNFaces = std::numeric_limits<num_type>::max(), const CornersType cornersType = CornersType::CONVEX, const bool bindPolygon = false, const bool collapsePolygon = true, const bool keepInMemory = false) { // check if the forest size is the same if (_forest.size() != (num_type)mesh.face.size()) _forest.resize(mesh.face.size()); // enumerate for (num_type i = 0; i < _forest.size(); ++i) _forest.buildPolygonTreeAt(mesh, i, polygonRegister, patchLearner, minNFaces, maxNFaces, cornersType, bindPolygon, collapsePolygon, keepInMemory); } protected: PolygonForest _forest; ///< The set of trees of convex polygons for each face of the mesh. }; } // end namespace pl } // end namespace tri } // end namespace vcg #endif // POLYGON_ENUMERATION_H
true
cce231169268a4c37c7f4f6b22252c33072efdca
C++
amanbharti0302/data-structure
/leetcode/graph/1042. Flower Planting With No Adjacent.cpp
UTF-8
1,653
3.671875
4
[]
no_license
/* You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers. All gardens have at most 3 paths coming into or leaving it. Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists. Example 1: Input: n = 3, paths = [[1,2],[2,3],[3,1]] Output: [1,2,3] Explanation: Gardens 1 and 2 have different types. Gardens 2 and 3 have different types. Gardens 3 and 1 have different types. Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1]. Example 2: Input: n = 4, paths = [[1,2],[3,4]] Output: [1,2,1,2] Example 3: Input: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]] Output: [1,2,3,4] */ class Solution { public: vector<int> gardenNoAdj(int n, vector<vector<int>>& paths) { vector<int>ans(n,0); vector<int>adj[n+2]; for(int i = 0;i<paths.size();i++){ adj[paths[i][0]].push_back(paths[i][1]); adj[paths[i][1]].push_back(paths[i][0]); } for(int i = 1;i<=n;i++){ int col[5]={0}; for(int to :adj[i]){ col[ans[to-1]]++; } for(int j= 1;j<=4;j++)if(col[j]==0){ans[i-1] = j;break;} } return ans; } };
true
1a629d98244b2a3dca7cf202e87eff71b32d0461
C++
Renrenrenrenrenren/Project_26
/Date/Date_cpp/src/Date.cpp
UTF-8
12,191
3.5625
4
[]
no_license
#include "Date.h" void Date::SetDate(int valDay, int valMonth, int valYear) //setting the date value { bool x = false; if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)//checking for leap year { x = true; //if year is leap } day = valDay; month = valMonth; year = valYear; while (day > 31 && (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)) //If the days in January, March, May, July, August, October, December are more than 31 { cout << "Incorrect date value"; exit(0); } while (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11)) //If there are more than 30 days in April, June, September, November { cout << "Incorrect date value"; exit(0); } while (month == 2 && x == 1 && day > 29) //If the year is a leap year and the number of days in February is more than 29 { cout << "Incorrect date value"; exit(0); } while (month == 2 && x == 0 && day > 28) //If the year is not a leap year and the number of days in February is more than 28 { cout << "Incorrect date value"; exit(0); } while (month > 12 || month < 1 || day < 1) //If months are more than 12, or months are less than 1, or days are less than 1 { cout << "Incorrect date value"; exit(0); } } Date::Date()//Constructor { day = 1; month = 1; year = 0; } bool Date::operator == (const Date& date2) //Operator "==" reboot { return this->year == date2.year && this->month == date2.month && this->day == date2.day; } bool Date::operator !=(const Date& date2) //Operator "!=" reboot { return !(this->year == date2.year && this->month == date2.month && this->day == date2.day); } bool Date::operator >(const Date& date2) //Operator ">" reboot { return this->year > date2.year || (this->month > date2.month && this->year == date2.year) || (this->day > date2.day && this->month == date2.month && this->year == date2.year); } bool Date::operator <(const Date& date2) //Operator "<" reboot { return this->year < date2.year || (this->month < date2.month&& this->year == date2.year) || (this->day < date2.day&& this->month == date2.month && this->year == date2.year); } bool Date::operator >=(const Date& date2) //Operator ">=" reboot { return this->year >= date2.year || (this->month >= date2.month && this->year == date2.year) || (this->day >= date2.day && this->month == date2.month && this->year == date2.year); } bool Date::operator <=(const Date& date2) //Operator "<=" reboot { return this->year <= date2.year || (this->month <= date2.month && this->year == date2.year) || (this->day <= date2.day && this->month == date2.month && this->year == date2.year); } void Date::operator =(const Date& date2) // Operator "=" reboot { this->day = date2.day; this->month = date2.month; this->year = date2.year; } Date Date::operator + (const Date& date2) // Operator "+" reboot { Date h, date3 = date2; Date date1; date1.day = this->day; date1.month = this->month; date1.year = this->year; int n = date1.DaysBetween(); h = date3.add_days(n); return h; } Date Date::operator - (const Date& date2) // Operator "-" reboot { Date h, date3 = date2; Date date1; date1.day = this->day; date1.month = this->month; date1.year = this->year; int n = date3.DaysBetween(); h = date1.subtract_days(n); return h; } string Date::WeekDay() //determining the day of the week { string s; Date date1; date1.day = this->day; date1.month = this->month; date1.year = this->year; Date date2; date2.SetDate(7, 12, 2020); //Let the accounting be kept from December 7, 2020 int n = date1.DaysBetween(date2); if (date1 > date2) { switch (n % 7) { case 0: s = "Monday"; break; case 1: s = "Tuesday"; break; case 2: s = "Wednesday"; break; case 3: s = "Thursday"; break; case 4: s = "Friday"; break; case 5: s = "Saturday"; break; case 6: s = "Sunday"; break; } } else { switch (n % 7) { case 0: s = "Monday"; break; case 6: s = "Tuesday"; break; case 5: s = "Wednesday"; break; case 4: s = "Thursday"; break; case 3: s = "Friday"; break; case 2: s = "Saturday"; break; case 1: s = "Sunday"; break; } } return s; } int Date::DaysBetween(const Date& date2) //determines the number of days between two dates { Date date1; date1.day = this->day; date1.month = this->month; date1.year = this->year; if (date1 < date2) { int i = 0; Date s; for (; date1 != date2; i++) { s = date1.add_days(1); date1 = s; } return i; } else if (date1 > date2) { int i = 0; Date s; for (; date1 != date2; i++) { s = date1.subtract_days(1); date1 = s; } return i; } else return 0; } int Date::DaysBetween() //Determine the number of days between the date and the zero year { Date date1; date1.day = this->day; date1.month = this->month; date1.year = this->year; Date date2; int i = date2.DaysBetween(date1); return i; } Date Date::subtract_days(int days) //substracts "days" days from the date { Date date1; date1.day = this->day; date1.month = this->month; date1.year = this->year; if (days == 0) { return date1; } else { Date sub; for (int i = 0; i < days; i++) { date1.PreDate(sub); date1 = sub; } return sub; } } Date Date::add_days(int days) //adds "days" days to the date { Date date1; date1.day = this->day; date1.month = this->month; date1.year = this->year; if (days == 0) { return date1; } else { Date sum; for (int i = 0; i < days; i++) { date1.NextDate(sum); date1 = sum; } return sum; } } void Date::PreDate(Date& yesterday) //determining the previous day's date value { if (month == 1 && day == 1) //if the given date is January 1 some year { yesterday.SetDate(31, 12, year - 1); } else if ((month == 2 || month == 4 || month == 6 || month == 8 || month == 9 || month == 11) && day == 1) //if the given date is 1 day of February, or April, or July, or August, or September, or November some year { yesterday.SetDate(31, month - 1, year); } else if ((month == 5 || month == 7 || month == 10 || month == 12) && day == 1) //if the given date is 1 day of May, or June, or October, or December some year { yesterday.SetDate(30, month - 1, year); } else if (day == 1 && month == 3) //if the given date is March 1 some year { bool x = false; if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) //checking a leap year { x = true; //if year is a leap } if (x) { yesterday.SetDate(29, month - 1, year); } else { yesterday.SetDate(28, month - 1, year); } } else //if the given date is not the start of the month { yesterday.SetDate(day - 1, month, year); } } void Date::NextDate(Date& nextday) //determining the next day's date value { if (month != 12 && day == 31) //if the given date is 31 day of some month (except December) some year { nextday.SetDate(1, month + 1, year); } else if (month == 12 && day == 31) // if the given date is December 31 some year { nextday.SetDate(1, 1, year + 1); } else if (day == 30 && (month == 4 || month == 6 || month == 9 || month == 11)) //if the given date is 30 day of April, or June, or September or November some year { nextday.SetDate(1, month + 1, year); } else if (day == 29 && month == 2) //if the given date is February 29 some year { nextday.SetDate(1, month + 1, year); } else if (day == 28 && month == 2) ////if the given date is February 28 some year { bool x = false; if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ////checking a leap year { x = true; //if year is a leap } if (x) { nextday.SetDate(29, month, year); } else { nextday.SetDate(1, month + 1, year); } } else //if the given date is not the end of the month { nextday.SetDate(day + 1, month, year); } } string Date::DateToStr() //create a string for output { string s=""; if (year == 0) { s+="The Gregorian calendar actually does not have a campaign, so this is actually the first year BC only a leap year \n"; } if (day < 10) { s+= '0' +to_string(day) + '.'; } if (day >= 10) { s+= to_string(day)+'.'; } if (month < 10) { s+= '0' + to_string(month) + '.' + to_string(year) + '\n' + to_string(day) + ' '; } if (month >= 10) { s+= to_string(month) + '.' + to_string(year) + '\n' + to_string(day) + ' ';} switch (month) { case 1: s+= "January "; s+= to_string(year); break; case 2: s+= "Fabruary "; s+= to_string(year); break; case 3: s+= "March "; s+= to_string(year); break; case 4: s+= "April "; s+= to_string(year); break; case 5: s+= "May "; s+= to_string(year); break; case 6: s+= "June "; s+= to_string(year); break; case 7: s+= "July "; s+= to_string(year); break; case 8: s+= "August "; s+= to_string(year); break; case 9: s+= "September "; s+= to_string(year); break; case 10: s+= "October "; s+= to_string(year); break; case 11: s+= "November "; s+= to_string(year); break; case 12: s+= "December "; s+= to_string(year); break; } s+="\n"; return s; }
true
00ba52f4f98608299e462f35c70bca30cc2f5bac
C++
mpmilano/nlp-final-project
/cppsrc/Product.hpp
UTF-8
1,074
2.609375
3
[]
no_license
#pragma once #include <string> #include <set> #include <memory> #include <unordered_map> #include <cassert> #include <boost/serialization/export.hpp> #include "Memoize.hpp" #include "StringUtils.hpp" #include "Review.hpp" class Review; class Product; typedef std::weak_ptr<Product> Product_p; typedef std::shared_ptr<Product> Product_pp; class Product : public Memoizeable<Product_pp> { public: const std::string productID; const std::string title; const double price; std::set<Review_p> reviews; std::string productType; const smart_int id; private: Product(smart_int id, const std::string &productID, const std::string &title, const double &price, const std::string& productType) :productID(productID),title(title),price(price),productType(productType),id(id) { } public: Product(const Product &) = delete; class Memo; friend class Memo; Memo_p pack() const; Memo pod_pack() const; class builder; friend class builder; int compareTo(const Product &o) const { return (this == &o) ? 0 : (id < o.id ? -1 : id == o.id ? 0 : 1); } };
true
3064ab29d123996300ad00817757fedef77c2e34
C++
yourslab/gg-ipc-test
/test.cpp
UTF-8
5,573
2.53125
3
[]
no_license
#include <aws/crt/Api.h> #include <aws/ipc/GGIpcClient.h> #include <cstdio> #include <iostream> using namespace Aws::Eventstreamrpc; class TestLifecycleHandler : public ConnectionLifecycleHandler { public: TestLifecycleHandler() { isConnected = false; lastErrorCode = AWS_OP_ERR; } void OnConnectCallback() override { std::cout << "OnConnectCallback" << std::endl; isConnected = true; } void OnDisconnectCallback(int errorCode) override { std::cout << "OnDisconnectCallback: " << errorCode << std::endl; lastErrorCode = errorCode; } bool OnErrorCallback(int errorCode) override { std::cout << "OnErrorCallback: " << errorCode << std::endl; std::cout << aws_error_str(errorCode) << std::endl; lastErrorCode = errorCode; return true; } public: int isConnected; int lastErrorCode; }; class CustomSubscribeHandler : public Ipc::SubscribeToTopicStreamHandler { void OnStreamEvent(Ipc::SubscriptionResponseMessage *response) override { auto binaryMessage = response->GetBinaryMessage(); Aws::Crt::JsonObject serializedResponse; if (binaryMessage.has_value()) { binaryMessage.value().SerializeToJsonObject(serializedResponse); } std::cout << "This is the response " << serializedResponse.View().WriteReadable() << std::endl; } }; void test_publish(Aws::Crt::String topic) { Aws::Crt::Allocator *allocator = Aws::Crt::g_allocator; Aws::Crt::ApiHandle apiHandle(allocator); Aws::Crt::Io::TlsContextOptions tlsCtxOptions = Aws::Crt::Io::TlsContextOptions::InitDefaultClient(); Aws::Crt::Io::TlsContext tlsContext(tlsCtxOptions, Aws::Crt::Io::TlsMode::CLIENT, allocator); Aws::Crt::Io::TlsConnectionOptions tlsConnectionOptions = tlsContext.NewConnectionOptions(); Aws::Crt::Io::EventLoopGroup eventLoopGroup(0, allocator); UnixSocketResolver unixSocketResolver(eventLoopGroup, 8, allocator); Aws::Crt::Io::ClientBootstrap clientBootstrap(eventLoopGroup, unixSocketResolver, allocator); clientBootstrap.EnableBlockingShutdown(); TestLifecycleHandler lifecycleHandler; std::cout << "creating client" << std::endl; Ipc::GreengrassIpcClient client(clientBootstrap); std::cout << "attempting connect" << std::endl; auto connectedStatus = client.Connect(lifecycleHandler); std::cout << "get connect status" << std::endl; connectedStatus.get(); std::cout << "create operation" << std::endl; // Ipc::PublishToTopicOperation operation = client.NewPublishToTopic(); Aws::Crt::String messageString("Hello World"); Aws::Crt::Vector<uint8_t> messageData( {messageString.begin(), messageString.end()}, allocator); Ipc::BinaryMessage binaryMessage(allocator); binaryMessage.SetMessage(messageData); Ipc::PublishMessage publishMessage(allocator); publishMessage.SetBinaryMessage(binaryMessage); // Ipc::PublishMessage publishMessage(allocator); std::cout << "create request" << std::endl; Ipc::PublishToTopicRequest publishRequest(allocator); publishRequest.SetTopic(topic); publishRequest.SetPublishMessage(publishMessage); CustomSubscribeHandler streamHandler; Ipc::SubscribeToTopicOperation subscribeOperation = client.NewSubscribeToTopic(streamHandler); // Ipc::PublishMessage publishMessage(allocator); Ipc::SubscribeToTopicRequest subscribeRequest(allocator); subscribeRequest.SetTopic(topic); std::cout << "subscribing" << std::endl; auto subscribeActivate = subscribeOperation.Activate(subscribeRequest, nullptr); subscribeActivate.wait(); std::cout << "getting response" << std::endl; auto futureResponse = subscribeOperation.GetOperationResult(); auto response = futureResponse.get(); if (response) { std::cout << "Sent successfully" << std::endl; Ipc::SubscribeToTopicResponse *subscribeToTopicResponse = static_cast<Ipc::SubscribeToTopicResponse *>( response.GetOperationResponse()); } else { auto errorType = response.GetResultType(); if (errorType == OPERATION_ERROR) { /* User can cast this to whatever "Error" type they desire e.g. auto *error = static_cast<Ipc::UnauthorizedError*>(response.GetOperationError()); Although, normally, we are only concerned about the error message. */ auto *error = response.GetOperationError(); std::cout << error->GetMessage().value() << std::endl; } else { std::cout << response.GetRpcError() << std::endl; } } auto publishOperation = client.NewPublishToTopic(); std::cout << "publishing" << std::endl; auto publishActivate = publishOperation.Activate(publishRequest, nullptr); publishActivate.wait(); std::cout << "getting response" << std::endl; auto publishFutureResponse = publishOperation.GetOperationResult(); auto publishResponse = publishFutureResponse.get(); if (publishResponse) { std::cout << "Sent successfully" << std::endl; } else { auto errorType = publishResponse.GetResultType(); if (errorType == RPC_ERROR) { std::cout << publishResponse.GetRpcError() << std::endl; } else { auto *error = publishResponse.GetOperationError(); (void)error; } } // Sleep so that we give some time to receive std::this_thread::sleep_for(std::chrono::seconds(20)); client.Close(); } int main(int argc, char *argv[]) { printf("arguments:\n"); for (int i = 0; i < argc; i++) { printf("%s\n", argv[i]); } test_publish(Aws::Crt::String("topic")); return 0; }
true
58f846ee3a68503aebf974cb16c9963f8291e4f3
C++
BackupTheBerlios/egmg-svn
/branches/problem-branch/trunk/src/egmg/Relaxation/ZebraLineGS.cpp
UTF-8
2,977
2.8125
3
[]
no_license
/** \file ZebraLineGS.cpp * \author Andre Oeckerath * \brief ZebraLineGS.cpp contains the implementation of the class ZebraLineGS. * \see ZebraLineGS.h * \todo clean up ninepointxzebra, ninepointyzebra, xzebra and yzebra by * doing redudant things in seperate functions */ #include <iostream> #include "ZebraLineGS.h" namespace mg { void ZebraLineGS::ninePointX( NumericArray &u, const NumericArray &f, const Stencil &stencil, const Index nx, const Index ny) const { if (nx > 2) { solveNinePointXLine(u,f,u,stencil,nx,ny,1,1,SW,S,SE); for(Index sy=3; sy<ny-1 ; sy+=2) solveNinePointXLine(u,f,u,stencil,nx,ny,1,sy,W,C,E); solveNinePointXLine(u,f,u,stencil,nx,ny,1,ny-1,NW,N,NE); for(Index sy=2; sy<ny ; sy+=2) solveNinePointXLine(u,f,u,stencil,nx,ny,1,sy,W,C,E); } else { gsRedBlack_.relax(u,f,stencil,nx,ny); } } void ZebraLineGS::ninePointY( NumericArray &u, const NumericArray &f, const Stencil &stencil, const Index nx, const Index ny) const { if (ny > 2) { solveNinePointYLine(u, f, u, stencil, nx, ny, 1, 1, SW, W, NW); for(Index sx=3; sx<nx-1 ; sx+=2) solveNinePointYLine(u, f, u, stencil, nx, ny, sx, 1, S, C, N); solveNinePointYLine(u, f, u, stencil, nx, ny, nx-1, 1, SE, E, NE); for(Index sx=2; sx<nx ; sx+=2) solveNinePointYLine(u, f, u, stencil, nx, ny, sx, 1, S, C, N); } else { gsRedBlack_.relax(u,f,stencil,nx,ny); } } void ZebraLineGS::fullX( NumericArray &u, const NumericArray &f, const Stencil &stencil, const Index nx, const Index ny) const { if((ny > 4) && (nx > 4)) { solveFullXLine(u, f, u, stencil, nx, ny, 1, 1, SW, S, SE); for(Index sy=3; sy < ny-2; sy+=2) solveFullXLine(u, f, u, stencil, nx, ny, 1, sy, W, C, E); solveFullXLine(u, f, u, stencil, nx, ny, 1, ny-1, NW, N, NE); for(Index sy=2; sy<ny-1; sy+=2) solveFullXLine(u, f, u, stencil, nx, ny, 1, sy, W, C, E); } else //nx,ny to small { for(int i=0; i<2; i++) { gsRedBlack_.relax(u,f,stencil,nx,ny); } } } void ZebraLineGS::fullY( NumericArray &u, const NumericArray &f, const Stencil &stencil, const Index nx, const Index ny) const { if ((ny > 4) && (nx > 4)) { solveFullYLine(u, f, u, stencil, nx, ny, 1, 1, SW, W, NW); for(Index sx=3; sx<nx-2; sx+=2) solveFullYLine(u, f, u, stencil, nx, ny, sx, 1, S, C, N); solveFullYLine(u, f, u, stencil, nx, ny, nx-1, 1, SE, E, NE); for(Index sx=2; sx<nx-1; sx+=2) solveFullYLine(u, f, u, stencil, nx, ny, sx, 1, S, C, N); } else { for(int i=0; i<2; i++) { gsRedBlack_.relax(u,f,stencil,nx,ny); } } } }
true
84c379a6ec7e0215fc5294ffadbe13f5e8eacb21
C++
rugi252126/RE_Transmitter
/lib/RE_Menu/RE_Menu.h
UTF-8
4,524
2.90625
3
[]
no_license
/** @file RE_Menu.h @brief This handles the different menu and browse menu in the system. In main menu, user can choose what to control(e.g. robot, drone, etc..) and can set the controller mode. Basically, it can set the controller configuration. And in browse menu, user can see the actual settings of the controller and the status like connection, battery, throttle, direction, etc.. @author Alfonso, Rudy Manalo @version */ #ifndef RE_MENU_H_ #define RE_MENU_H_ #include "RE_Rte.h" /*! @defined @abstract Defines module cyclic time @discussion This constant defines the module cyclic time. The time is in milli-second form. */ #define MENU_CYCLIC_TIME_K 200u // 200ms /*! @defined @abstract Time to enter main menu @discussion When the menu switch is pressed continously within 3sec., the system will enter in main menu. */ #define MENU_MAIN_DEBOUNCE_TIME_K (3000u/MENU_CYCLIC_TIME_K) // 3sec. /*! @defined @abstract Switch state @discussion The enumeration defines the different switch state for digital IO switch. */ enum menu_switch_state_et { MENU_SWITCH_PRESSED_E ,MENU_SWITCH_NOT_PRESSED_E ,MENU_SWITCH_MAX_E }; class Menu { public: /*! @method @abstract Menu abstract constructor @discussion Menu class abstract constructor needed to create the abstract base class. */ Menu(); /*! @function @abstract Module initialization @discussion It sets the initial state of the module. @param none @return none */ void menuF_Init(void); /*! @function @abstract Return main menu status @Discussion Returns whether its inside the main menu or not. @param none @return {[true/false] true=inside main menu; false=otherwise} */ // bool menuF_getMainmenuStatus(void); /*! @function @abstract Module cyclic function @discussion Tasks within the module that need to be called cyclically will be done here. @param none @return none */ void menuF_Cyclic(void); protected: enum main_menu_et main_menu_e_; // main menu options enum browse_menu_et browse_menu_e_; // browse menu options enum menu_switch_state_et menu_switch_browse_state_e_; // browse menu switch state(pressed/not pressed) bool main_menu_status_b_; // true = inside main menu; false = otherwise bool main_menu_entry_exit_b_; // mani menu exit status bool browse_menu_status_b_; // true = inside browse menu; false = otherwise uint8_t browse_menu_ctr_; // counter to go to the list of browse menu options uint8_t main_menu_ctr_; // counter to go to the list of main menu options uint16_t main_menu_entry_exit_debounce_time_; // main menu debounce time private: /*! @function @abstract Main menu debounce time check @discussion If main menu switch is pressed, the debounce time will start to increment. And if pressed for at least 3sec., it will enter in main menu. @param none @return none */ void menuLF_checkMainMenuDebounceTime(void); /*! @function @abstract Menu switch status check @discussion Checks whether menu switch is pressed or not. @param none @return none */ void menuLF_checkMenuSwitchStatus(void); /*! @function @abstract Browse menu @discussion Every pressed and not pressed of the switch, the browse menu will go from one option to another. @param none @return none */ void menuLF_browseMenu(void); /*! @function @abstract Main menu @discussion Every pressed and not pressed of the switch, the main menu will go from one option to another. Controller settings can be done here. @param none @return none */ //void menuLF_mainMenu(void); /*! @function @abstract Update Rte Information @discussion Rte data will be updated here to make the information available to other modules. @param none @return none */ void menuLF_updateRteData(void); }; // class Menu #endif // RE_MENU_H_
true
90eb212ae4e46eb87da5b59ea3f0a4e61ceeda2e
C++
oscilios/dap
/src/threadsafe/AtomicLock.h
UTF-8
648
2.90625
3
[]
no_license
#ifndef DAP_THREADSAFE_ATOMIC_LOCK_H #define DAP_THREADSAFE_ATOMIC_LOCK_H namespace dap { namespace threadsafe { class AtomicLock; } } class dap::threadsafe::AtomicLock { std::atomic<bool>& m_mtx; public: explicit AtomicLock(std::atomic<bool>& mtx) : m_mtx(mtx) { while (m_mtx.exchange(true)) { } } AtomicLock(const AtomicLock&) = delete; AtomicLock(AtomicLock&&) = delete; ~AtomicLock() { m_mtx = false; } AtomicLock& operator=(const AtomicLock&) = delete; AtomicLock& operator=(AtomicLock&&) = delete; }; #endif // DAP_THREADSAFE_ATOMIC_LOCK_H
true
5f0bf72f674f75e0d7b62a85d79c9eda3de540a9
C++
RaymondSHANG/cpp_from_control_to_objects_8e
/ch7/range-for.cpp
UTF-8
603
3.875
4
[]
no_license
#include <iostream> #include <vector> #include <cmath> using namespace std; int main () { // Range based for loop std::string song[] {"99","bottles","of","beer","on","the","wall"}; for (auto x : song) { std::cout << x << " "; } std::cout << "Attempting to modify loop in range based for" << endl; for (auto x : song) { x = "Something else"; std::cout << x << " "; } std::cout << "\n"; std::cout << "But range based for loops create copies of values" << endl; for (auto x : song) { std::cout << x << " "; } return 0; }
true
183be303d5c1573afe4d4668f90951af8ca9895c
C++
CrazyIEEE/algorithm
/算法竞赛入门经典/第4章/洪水_UVa815.cpp
UTF-8
1,341
3.296875
3
[]
no_license
#include "iostream" #include "vector" #include "algorithm" int main() //emmmmmmm,题目不是很好理解,理解了之后还是很轻松的,关键在于如何判定洪水向下淹没下一个格子,之后还要在海平面平齐的时候判定等等 { int n = 0, m = 0; std::cin >> n >> m; std::vector<int> altitude(n * m, 0); for (int i = 0; i < n * m; i++) { std::cin >> altitude[i]; } std::sort(altitude.begin(), altitude.end()); int rainV = 0; std::cin >> rainV; rainV /= 100; for (int k = 1; k <= n * m; k++) { rainV += altitude[k - 1]; if (rainV / k < altitude[k]) { std::cout << k << std::endl; return 0; } } std::cout << n * m << std::endl; return 0; } //另附网上的思路 // 可以把n*m块地的海拔高度a[i],按从小到大排成一列。 // 然后对输入的洪水体积,先除以100,这样一来,题目中的所有数据就统一了数量单位。 // 如样例的洪水体积为10000,转化为高度就是sum=100。 // 接着设一个偏移量k,代表洪水从左往右淹到第k块地时停止。 // 算法为k从1开始递增遍历,洪水每路过一块地,就把地的高度加入sum,退出条件就是洪水的平均高度不大于下一块地:sum/k < a[k+1]。
true
6ee71b810e12635ed8972e524de8bf89f4f31a99
C++
duranterich/controlLaptop
/controlFinalV4RPM/controlFinalV4RPM.ino
UTF-8
6,374
2.9375
3
[]
no_license
// Overblown Fan Control // by: Richard Durante #include <PWM.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #define TempPIN 0 // Analog Pin 0 #define TempPINAmb 1 // Analog Pin 1 float ardVolt = 4.95; // Arduino Output Voltage 5V measured int temperatureSense; // Temperature of sensor int temperatureAmb; // Ambient Temperature Sensor // Fan Pins const byte fanPWM = 9; // fan control connected to digital pin 3 const byte fanRPMPin = 2; // fan RPM readings // Fan Duty Cycle int dutyCycleStart = 50; // startup duty cycle (0-255) int dutyCycleFan; // For Looping Temperature Readings const byte numReadings = 50; // number of readings to average int rawVal[numReadings]; // setup array for calculating the raw value byte index = 0; // index for for loop int total = 0; // running total // For Looping Temperature Readings const byte numReadings2 = 50; // number of readings to average int rawVal2[numReadings2]; // setup array for calculating the raw value byte index2 = 0; // index for for loop int total2 = 0; // running total int fanRPMVal; // variable to output fan RPM int rpmCounter; // counter for number of interrupts (hall effect) per second int32_t pwmFrequency = 24000; // set PWM frequency for system to 27.5kHz void setup() { InitTimersSafe(); // initialize all timers except for 0, to save time keeping functions Serial.begin(115200); delay(100); // RPM Counter Setup pinMode(fanRPMPin, INPUT); attachInterrupt(fanRPMPin, rpm, RISING); // Temperature Sensor Setup pinMode(TempPIN, INPUT); pinMode(TempPINAmb, INPUT); // 120mm Radiator Fans Setup SetPinFrequencySafe(fanPWM,pwmFrequency); pinMode(fanPWM, OUTPUT); pwmWrite(fanPWM,dutyCycleStart); delay(10000); Serial.print("TemperatureSurface(C), TemperatureAmb(C), FanRPM, FanDuty(%)"); Serial.println(""); // init temperatureSense // rawVal = analogRead(TempPIN); // temperatureSense = tempSensor(rawVal); // prevTemp = temperatureSense; for (index = 0; index < numReadings; index++) { // fill the array for faster startup rawVal[index] = analogRead(TempPIN); total = total + rawVal[index]; } index = 0; // reset for (index2 = 0; index2 < numReadings2; index2++) { // fill the array for faster startup rawVal2[index2] = analogRead(TempPINAmb); total2 = total2 + rawVal2[index2]; } index2 = 0; // reset } // Interrupt to count the fan RPM void rpm() { rpmCounter++; } void loop() { total = total - rawVal[index]; // subtract the last reading rawVal[index] = analogRead(TempPIN); // one unused reading to clear ghost charge rawVal[index] = analogRead(TempPIN); // read from the sensor total = total + rawVal[index]; // add the reading to the total index = index + 1; // advance to the next position in the array if (index >= numReadings){ // if we're at the end of the array index = 0; // wrap around to the beginning } temperatureSense = tempSensor((total/numReadings)); // read ADC and convert it to Celsius total2 = total2 - rawVal2[index2]; // subtract the last reading rawVal2[index2] = analogRead(TempPINAmb); // one unused reading to clear ghost charge rawVal2[index2] = analogRead(TempPINAmb); // read from the sensor total2 = total2 + rawVal2[index2]; // add the reading to the total index2 = index2 + 1; // advance to the next position in the array if (index2 >= numReadings2){ // if we're at the end of the array index2 = 0; // wrap around to the beginning } temperatureAmb = tempSensor((total2/numReadings2)); // read ADC and convert it to Celsius // Control for PWM dutyCycleFan = 75.369 * exp(0.0305 * temperatureSense); // fan curve based on excel spreadsheet if(dutyCycleFan > 255){ // if temperatures exceed actuals, error check dutyCycleFan = 255; // this should be corrected from previous error check } else if(dutyCycleFan < 0){ dutyCycleFan = 0; } pwmWrite(fanPWM,dutyCycleFan); // write duty cycle to fan fanRPMVal = fanRPMOutput(rpmCounter); //Serial.print("Temperature(Celsius): "); Serial.print(temperatureSense); // display Celsius Serial.print(","); // delimeter Serial.print(temperatureAmb); // display Ambient Serial.print(","); // delimeter Serial.print(fanRPMVal); // display RPMs Serial.print(","); // delimter Serial.print(dutyCycleFan); // display Duty Cycle Serial.println(""); delay(1000); // data logging interval } int fanRPMOutput(int freqFan) { int fanRPM; freqFan = 0; // reset rotation counter to 0 sei(); // enable interrupts delay(1000); // pause 1 second cli(); // disable interrupts fanRPM = (freqFan * 60) / 2; // take count of interrupts over 1 second, multiply by 60 (for minute) and div by 2 for bipolar hall effect sensor Serial.print("Fan RPM: "); // output fan RPM Serial.println(fanRPM, DEC); return fanRPM; } float tempSensor(float RawADC) { float TempSurface; // Dual-Purpose variable to save space. RawADC = RawADC * ardVolt; RawADC /= 1024.0; TempSurface = (RawADC - 0.5) * 100 ; //converting from 10 mv per degree wit 500 mV offset return TempSurface; }
true
d90406e8b254c9cf6a936072f54e06c03003a0a9
C++
vei123/PATTestAdvanced
/C++/1067用"0交换"排序.cpp
UTF-8
3,938
3.546875
4
[]
no_license
#include<iostream> using namespace std; int n, unmatch = 0, cnt = 0; int f[100005], a[100005]; int getroot(int i) { return f[i] == i ? i : f[i] = getroot(f[i]); } signed main() { ios::sync_with_stdio(0); cin >> n; for (int i = 0; i < n; i++) f[i] = i; for(int i = 0; i < n; i++) { cin >> a[i]; if (a[i] != i) { f[getroot(i)] = getroot(a[i]); unmatch++; } } for (int i = 0; i < n; i++) if (f[i] == i) cnt++; int res = 2 * unmatch + cnt - n - 2; cout << (a[0] ? res : res + 2); return 0; } /*一道纯数学题,自己半天推导出如下一个经验公式: 需要进行的交换数 = 2 * 初始不匹配数 + 数列“连通分量”个数 - 数字总个数 - 2 对应于代码中的 int res = 2 * unmatch + cnt - n - 2; 特别地,对于0一开始就在开头的情况,需要在上述结果的基础上加上2 对应于代码中的 (a[0] ? res : res + 2) 下面来解释公式中的名词: 初始不匹配数:对应于下面程序中的unmatch变量,表示开始时,不在正确的 位置上的数字个数,举个例子,以题目中的{4, 0, 2, 1, 3}为例子, index : 0 1 2 3 4 a[i] : 4 0 2 1 3 可以发现不在正确位置上的数字有4, 0, 1, 3,而2在自己正确的位置上,所以unmatch = 4; 数列“连通分量”数:这个概念有点抽象,但学过图论的应该对图论的连通分量有了解, 可以结合图论的连通分量来理解: 还是以上面的数列为例: 我们可以把这个数列中的数字分为如下2个集合 {0, 4, 3, 1}, {2} 这是什么意思呢? 假设我们从index中的数字0出发,找到位置0对应的数字a[0] = 4, 再从index = 4找到对应的数字a[4] = 3, 再从index = 3找到对应的数字a[3] = 1, 再从index = 1找到对应的数字a[1] = 0, 这里又回到了开始的index即0,我们发现子数列{0, 4, 3, 1}构成了一个“循环”, 我们把这个循环成为数列的一个连通分量,表示从其中的任何一个数字出发,可以到达 数列中的任何其它一个数字,但却到不了任何不在这个数列中的数字 对于子数列{2},同理 我们来计算一下结果 res = 2 * 4 + 2 - 5 - 2 = 3, 又由于a[0]!=0,故不需要加上2,所以答案为3 再以题目中的样例为例子: {3 5 7 2 6 4 9 0 8 1} 初始只有数字8在正确的位置上,所以不匹配数unmatch = 10 - 1 = 9 index: 0 1 2 3 4 5 6 7 8 9 a[i] : 3 5 7 2 6 4 9 0 8 1 连通分量有{0, 3, 2, 7}, {1, 5, 4, 6, 9}, {8} 结果:res = 2 * 9 + 3 - 10 - 2 = 9,同理由于a[0]!=0, 不需要加2 对于a[0]等于0的情况,比如 index: 0 1 2 3 4 a[i] : 0 3 4 1 2 res = 2 * 4 + 3 - 5 - 2 = 4,需要在res的基础上再加2, 即res的正确结果为res = 4 + 2 = 6 下面来解释这个公式的正确性: 其实这个公式的更好理解的形式如下:(之所以写成上面那样是程序实现时的遗留产物...) 不匹配数 + 除开匹配正确的数字之外的连通分量数 - 2 (对于a[0]==0仍需加二) 除开匹配正确的数字之外的联通分量,以之前的例子: index : 0 1 2 3 4 a[i] : 4 0 2 1 3 那就是除开{2}之外的连通分量,只有{0, 4, 3, 1} 所以res = 4 + 1 - 2 = 3,由于a[0]!=0,故不需要加二 到这里,如果数学好,你可能就明白含义了: 简单说来就是 ①对于同一个连通分量内的数字,可以进行一组连贯的0交换来让其中的 数字都在正确位置上 ②对于多个连通分量的情况下,不同连通分量之间的切换需要额外的一个0交换开销 ③对于0开始在正确的位置上的情况,更多两个开销(先把0放到某一个连通分量内,最后 还得换回来) 所以公式其实就是这三点的一个反应而已,如果还没理解可以自己推敲 代码实现中使用了并查集来计算连通分量,所以复杂度很低,总复杂度接近于O(n), 至于并查集怎么实现的可以自行去学习 */
true
f7c765a19525f556ba34d0d000c5bdea58d720d9
C++
huijian3139/pat
/pat-b/1009.cpp
UTF-8
325
2.8125
3
[]
no_license
#include"iostream" #include"vector" #include"string" #include"sstream" using namespace std; int main() { vector<string> vs; string s; char a[100]; cin.getline(a,100); stringstream ss(a); while(ss>>s) { vs.push_back(s); } for(int i=vs.size()-1;i>=0;i--) {if(i!=vs.size()-1)cout<<" "; cout<<vs[i]; } return 0; }
true
689a314cb3f18ac1a84bd969bdb5776b18917e4b
C++
mousepadsan/Project-2
/CppApplication_6/main.cpp
UTF-8
7,475
3.34375
3
[]
no_license
/* * File: main.cpp * Author: Dale Rios * Created on June 8, 2014, 5:27 PM * Purpose: Project 2 (Text based game) */ //System Libraries #include <iostream> #include <iomanip> #include <cstdlib> using namespace std; //Global Constants //Function Prototypes void title();//Title void intro();//Story void charInf(int, int);//character info char slime();//Loot Drop void plant(int, int);//plant monster int btleCmd(int,int,int,int,int);//Commands void prntCmd();//Print commands //void dmgCalc1(int,int);//Damage calculator //not used //void dmgCalc2(int,int);//Damage calculator //not used void monAct(int,int);//Monster Action generator int slmeAtk(int);//Slime Monster attack int slmeHP(int);//Slime monster HP void slmeEff(int &);//Slime's hidden power void slmeEff2(int *);//Slime's hidden power int main(int argc, char** argv) { //Random seed generator srand(static_cast<unsigned int>(time(0))); //Variables int choice, choice2, col=5; int attack, crtStrk, guard, block;//Hero Actions int atkDmg, HP=50;//Hero damage and health int m1HP, m1Atk;// Monster(1) damage and health int jeloCnc; //Chance of Jello lot being edible //title title(); cout<<endl<<endl; //Story intro(); cout<<"What do you want to do?\n"; cout<<"Enter the number of the command you want do.\n"; m1HP=slmeHP(m1HP); do{ prntCmd(); cin>>choice; cout<<"\n"; btleCmd(choice,attack,crtStrk,guard,block);//commands atkDmg=btleCmd(choice,attack,crtStrk,guard,block);//attack damage value m1HP-=atkDmg; if(m1HP>0){ cout<<"The monster only has "<<m1HP<<" HP left.\n\n"; monAct(m1Atk,HP); } else{ cout<<"The monster had fallen.\n"; } }while(m1HP>0); cout<<"You have successfully defeated an extremely weak monster.\n" "Congratulations!\n"; cout<<"The monster dropped some items on the floor.\n"; cout<<"Jello: A Jello-like looking object. Might be edible.\n"; cout<<"Dimension Transporter: A transporter so you can go back home.\n"; jeloCnc=rand()%100+1; cout<<"What are you going to do with the items?\n"; cout<<"1. Eat the jello.\n"; cout<<"2. Use the transporter to go home.\n"; //ask for command cin>>choice2; if (choice2==1){ slmeEff(choice2); } else if(choice2==2){ slmeEff2(&choice2); } switch(choice2){ case 1:{ cout<<"Oh noes! Killing the slime gives a secret hidden effect.\n"; cout<<"It made you eat the jello instead of using the transporter.\n"; if(jeloCnc>1){ cout<<"You died. Its not Jello.\n"; } else if(jeloCnc=1){ cout<<"Its jello."; } }break; case 2:{ cout<<"Oh noes! Killing the slime gives a secret hidden effect.\n"; cout<<"It made you use the transporter instead of eating the Jello.\n"; for(int i=0;col>i;i++){ cout<<"*\n"; } cout<<"You made it home safely."; }break; } return 0; } void slmeEff(int &a){ a=2; } void slmeEff2(int *a){ *a=1; } void monAct(int b,int c){ b=rand()%5+1; int a; a=rand()%10+1;//Random Action Generator if(a<=2){ cout<<"The monster is readying itself.\n"; } else{ cout<<"The monster attacked you for "<<b<<" damage.\n"; cout<<"You only have "<<c<<" HP left.\n\n"; } } void charInfo(int atk, int hp){ cout<<"Attack Damage"<<setw(5)<<atk; cout<<"HP"<<setw(16)<<hp; } //void dmgCalc1(int hDmg,int mHP){ // mHP-=hDmg; // // return mHP; //} //void dmgCalc2(int mDmg, int hHP){ // hHP-=mDmg; // // return hHP; //} int slmeAtk(int atk1){ atk1=rand()%3+1; return atk1; } int slmeHP(int Hp1){ Hp1=10; return Hp1; } void prntCmd(){ cout<<"1. Attack: Attack the monster.\n"; cout<<"2. Guard: Ready yourself for the monster's attack.\n"; } int btleCmd(int a, int b, int c, int d, int e){ int crit,blockRt; switch(a){ case 1:{ b=rand()%4+6;//Attack damage generator crit=rand()%100+1; if(crit<=10){//Crit hit chance 10% c=(b)*(2); cout<<"You attacked the monster.\n"; cout<<"It's a critical hit.\n"; cout<<"You did "<<c<<" damage to the monster\n"; } else{ cout<<"You attacked the monster.\n"; cout<<"You did "<<b<<" damage to the monster\n"; } }break; case 2:{ d=rand()%5+1;//Monster damage reduce blockRt=rand()%100+1;//Block damage completely if(blockRt<=10){//Block chance 10% e=(d)*(50); } }break; case 3:{ charInfo(a,50); }break; } return b; } void intro(){ cout<<"Press any key to start.\n"; cin.ignore(); cout<<"You're girlfriend just broke up with you and you're feeling depressed.\n"; cout<<"Press any key to continue\n"; cin.ignore(); cout<<"You grabbed your phone and googled the nearest cliff in your area to finally end all of your suffering.\n"; cout<<"Press any key to continue\n"; cin.ignore(); cout<<"You found the nearest and stiffest cliff in the area\n"; cout<<"Press any key to continue\n"; cin.ignore(); cout<<"You started savoring the scenery as you about to take the plunge.\n"; cin.ignore(); cout<<"The perfect background music for this moment plays in your head.\n"; cin.ignore(); cout<<"-I used to think that could not go onnnnnnnnnnn-\n"; cin.ignore(); cout<<"You suddenly had a change of heart and have decided to live and move on.\n"; cin.ignore(); cout<<"-And life was nothing but an awful songggggg-\n"; cin.ignore(); cout<<"As you were turning around, the ground beneath your feet started crumbling down.\n"; cout<<"-But now I know the meaning of true loveeeee-\n"; cin.ignore(); cout<<"Just when you were about to fall of the cliff, you grabbed the roots of a nearby tree.\n"; cout<<"-I'm leaning on the everlasting arms-\n"; cin.ignore(); } void title(){ int col=81; int row=2; for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ cout<<"*"; }cout<<endl; } cout<<"=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=" <<endl<<"=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=" <<endl<<"=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=" <<endl<<"=+=+=+=+=+=+=+=+=+=+=+=+=+=+= Project =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=" <<endl<<"=+=+=+=+=+=+=+=+=+=+=+=+=+=+= Rushed =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=" <<endl<<"=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=" <<endl<<"=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=" <<endl; for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ cout<<"*"; }cout<<endl; } }
true
d94bf81ec74a2d3d886c0328c8a5f91b389500d4
C++
princeodd47/cs221_p3
/ConsoleApplication8/BookRecord.cpp
UTF-8
4,175
3.40625
3
[]
no_license
/******************************************************************* * BookRecord.cpp * Steven Powell * Programming Assignment 2 - Book Inventory * * This program is entirely my own work *******************************************************************/ #include "BookRecord.h" #include <cstring> #include <iostream> using namespace std; //-------------------------------------------------------- // Default class constructor //-------------------------------------------------------- BookRecord::BookRecord() { strcpy(m_sTitle, ""); m_lStockNum = 0; m_iClassification = 0; m_dCost = 0.0; m_iCount = 0; m_pNext = NULL; } //-------------------------------------------------------- // Overloaded class constructor //-------------------------------------------------------- BookRecord::BookRecord(const char *title, long sn, int cl, double cost) { strcpy(m_sTitle, title); m_lStockNum = sn; m_iClassification = cl; m_dCost = cost; m_iCount = 1; m_pNext = NULL; } //-------------------------------------------------------- // Default class destructor //-------------------------------------------------------- BookRecord::~BookRecord() { } //-------------------------------------------------------- // Sets character array pointer argument title to m_stitle //-------------------------------------------------------- void BookRecord::getTitle(char *title) { strcpy(title, m_sTitle); } //-------------------------------------------------------- // Sets m_sTitle to array pointer argument //-------------------------------------------------------- void BookRecord::setTitle(const char *title) { strcpy(m_sTitle, title); } //-------------------------------------------------------- // Returns m_lStockNum //-------------------------------------------------------- long BookRecord::getStockNum() { return m_lStockNum; } //-------------------------------------------------------- // Sets m_lStockNum to sn argument //-------------------------------------------------------- void BookRecord::setStockNum(long sn) { m_lStockNum = sn; } //-------------------------------------------------------- // Sets integer argument cl to m_iClassification //-------------------------------------------------------- int BookRecord::getClassification() { return m_iClassification; } //-------------------------------------------------------- // Sets m_iClassification to argument cl //-------------------------------------------------------- void BookRecord::setClassification(int cl) { m_iClassification = cl; } //-------------------------------------------------------- // //-------------------------------------------------------- double BookRecord::getCost() { return m_dCost; } //-------------------------------------------------------- // Sets m_dCost to argument c //-------------------------------------------------------- void BookRecord::setCost(double c) { m_dCost = c; } //-------------------------------------------------------- // Returns m_iCount //-------------------------------------------------------- int BookRecord::getNumberInStock() { return m_iCount; } //-------------------------------------------------------- // Sets m_iCount to argument count //-------------------------------------------------------- void BookRecord::setNumberInStock(int count) { m_iCount = count; } //-------------------------------------------------------- // Prints BookRecord object // // Title Stock_Num Classification Cost In Stock // For example: // Introduction to C++ 12345 613 49.95 5 //-------------------------------------------------------- void BookRecord::printRecord() { cout << m_sTitle << " " << m_lStockNum << " " << m_iClassification << " " << m_dCost << " " << m_iCount << endl; } //-------------------------------------------------------- // //-------------------------------------------------------- void BookRecord::setNext(BookRecord *next) { m_pNext = next; } //-------------------------------------------------------- // //-------------------------------------------------------- BookRecord *BookRecord::getNext() { return m_pNext; }
true
0c716ad09170b503d8d973a0ecc2ba024d35944d
C++
woodk/KBot2010
/KBot2010/strategy/StrategyCurveRight.h
UTF-8
720
2.625
3
[]
no_license
#ifndef STRATEGY_CURVE_RIGHT_H #define STRATEGY_CURVE_RIGHT_H #include "Strategy.h" #include "KBotDrive.h" /* The strategy used to curve right, looking for targets */ class StrategyCurveRight : public Strategy { public: // Constructor initializes object StrategyCurveRight(KBot* kbot); // Destructor cleans up ~StrategyCurveRight(); // Returns the next state: Spin if time expires or Track if a target is spotted eState apply(); void init(); private: //Pickup *m_pickup; // The number of times this strategy has been called int m_nCallCount; // Check if we should keep going bool getKeepMoving(); // Look for a target bool TargetInSight(); }; #endif
true
de74312fbc95eae6891accd4a8637cbb5ac75965
C++
sahil-adhav/CPP
/Lecture_8_Arrays/Arrange_Numbers_in_Array.cpp
UTF-8
616
3.59375
4
[]
no_license
#include <iostream> using namespace std; void arrange(int *arr, int n) { int left = 0; int right = n - 1; int counter = 1; while (left <= right) { if (counter % 2 == 1) { arr[left] = counter; counter ++; left ++; }else{ arr[right] = counter; counter ++; right --; } } } int main() { int t; cin >> t; while (t--) { int n; cin >> n; int *arr = new int[n]; arrange(arr, n); for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; delete [] arr; } }
true
bbf1cc93d752c97d6a90a8a3ac477958099d9ec5
C++
jiaolaura/recipes
/topk/word_freq_shards_basic.cc
UTF-8
9,992
2.5625
3
[ "BSD-3-Clause" ]
permissive
/* sort word by frequency, sharding version. 1. read input file, shard to N files: word 2. assume each shard file fits in memory, read each shard file, count words and sort by count, then write to N count files: count \t word 3. merge N count files using heap. Limits: each shard must fit in memory. */ #include <assert.h> #include "absl/container/flat_hash_map.h" #include "absl/strings/str_format.h" #include "muduo/base/Logging.h" #include <algorithm> #include <fstream> #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <vector> #include <boost/program_options.hpp> #include <fcntl.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/times.h> #include <unistd.h> using std::string; using std::string_view; using std::vector; using std::unique_ptr; const int kBufferSize = 128 * 1024; int kShards = 10; bool verbose = false, keep = false; const char* shard_dir = "."; inline double now() { struct timeval tv = { 0, 0 }; gettimeofday(&tv, nullptr); return tv.tv_sec + tv.tv_usec / 1000000.0; } struct CpuTime { double userSeconds = 0.0; double systemSeconds = 0.0; double total() const { return userSeconds + systemSeconds; } }; const int g_clockTicks = static_cast<int>(::sysconf(_SC_CLK_TCK)); CpuTime cpuTime() { CpuTime t; struct tms tms; if (::times(&tms) >= 0) { const double hz = static_cast<double>(g_clockTicks); t.userSeconds = static_cast<double>(tms.tms_utime) / hz; t.systemSeconds = static_cast<double>(tms.tms_stime) / hz; } return t; } class Timer { public: Timer() : start_(now()), start_cpu_(cpuTime()) { } string report(int64_t bytes) const { CpuTime end_cpu(cpuTime()); double end = now(); return absl::StrFormat("%.2fs real %.2fs cpu %.2f MiB/s %ld bytes", end - start_, end_cpu.total() - start_cpu_.total(), bytes / (end - start_) / 1024 / 1024, bytes); } private: const double start_ = 0; const CpuTime start_cpu_; }; class OutputFile // : boost::noncopyable { public: explicit OutputFile(const string& filename) : file_(::fopen(filename.c_str(), "w+")) { assert(file_); ::setbuffer(file_, buffer_, sizeof buffer_); } ~OutputFile() { close(); } void append(string_view s) { assert(s.size() < 255); uint8_t len = s.size(); ::fwrite(&len, 1, sizeof len, file_); ::fwrite(s.data(), 1, len, file_); ++items_; } /* void append(uint64_t x) { // FIXME: htobe64(x); ::fwrite(&x, 1, sizeof x, file_); } */ void flush() { ::fflush(file_); } void close() { if (file_) ::fclose(file_); file_ = nullptr; } int64_t tell() { return ::ftell(file_); } int fd() { return ::fileno(file_); } size_t items() { return items_; } private: FILE* file_; char buffer_[kBufferSize]; size_t items_ = 0; OutputFile(const OutputFile&) = delete; void operator=(const OutputFile&) = delete; }; class Sharder // : boost::noncopyable { public: Sharder() : files_(kShards) { for (int i = 0; i < kShards; ++i) { char name[256]; snprintf(name, sizeof name, "%s/shard-%05d-of-%05d", shard_dir, i, kShards); files_[i].reset(new OutputFile(name)); } assert(files_.size() == static_cast<size_t>(kShards)); } void output(string_view word) { size_t shard = hash(word) % files_.size(); files_[shard]->append(word); } void finish() { int shard = 0; for (const auto& file : files_) { // if (verbose) printf(" shard %d: %ld bytes, %ld items\n", shard, file->tell(), file->items()); ++shard; file->close(); } } private: std::hash<string_view> hash; vector<unique_ptr<OutputFile>> files_; }; int64_t shard_(int argc, char* argv[]) { Sharder sharder; Timer timer; int64_t total = 0; for (int i = optind; i < argc; ++i) { LOG_INFO << "Processing input file " << argv[i]; double t = now(); char line[1024]; FILE* fp = fopen(argv[i], "r"); char buffer[kBufferSize]; ::setbuffer(fp, buffer, sizeof buffer); while (fgets(line, sizeof line, fp)) { size_t len = strlen(line); if (len > 0 && line[len-1] == '\n') line[len-1] = '\0'; sharder.output(line); } size_t len = ftell(fp); fclose(fp); total += len; double sec = now() - t; LOG_INFO << "Done file " << argv[i] << absl::StrFormat(" %.3f sec %.2f MiB/s", sec, len / sec / 1024 / 1024); } sharder.finish(); LOG_INFO << "Sharding done " << timer.report(total); return total; } // ======= count_shards ======= int64_t count_shard(int shard, int fd, const char* output) { const int64_t len = lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET); double t = now(); LOG_INFO << absl::StrFormat("counting shard %d: input file size %ld", shard, len); { void* mapped = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); assert(mapped != MAP_FAILED); const uint8_t* const start = static_cast<const uint8_t*>(mapped); const uint8_t* const end = start + len; // std::unordered_map<string_view, uint64_t> items; absl::flat_hash_map<string_view, uint64_t> items; int64_t count = 0; for (const uint8_t* p = start; p < end;) { string_view s((const char*)p+1, *p); items[s]++; p += 1 + *p; ++count; } LOG_INFO << "counting " << count << " unique " << items.size(); if (verbose) printf(" count %.3f sec %ld items\n", now() - t, items.size()); t = now(); vector<std::pair<size_t, string_view>> counts; for (const auto& it : items) { if (it.second > 1) counts.push_back(make_pair(it.second, it.first)); } if (verbose) printf(" select %.3f sec %ld\n", now() - t, counts.size()); t = now(); std::sort(counts.begin(), counts.end()); if (verbose) printf(" sort %.3f sec\n", now() - t); t = now(); { std::ofstream out(output); for (auto it = counts.rbegin(); it != counts.rend(); ++it) { out << it->first << '\t' << it->second << '\n'; } for (const auto& it : items) { if (it.second == 1) { out << "1\t" << it.first << '\n'; } } } //if (verbose) //printf(" output %.3f sec %lu\n", now() - t, st.st_size); t = now(); if (munmap(mapped, len)) perror("munmap"); } // printf(" destruct %.3f sec\n", now() - t); return len; } void count_shards() { Timer timer; int64_t total = 0; for (int shard = 0; shard < kShards; ++shard) { Timer timer; char buf[256]; snprintf(buf, sizeof buf, "%s/shard-%05d-of-%05d", shard_dir, shard, kShards); int fd = open(buf, O_RDONLY); if (!keep) ::unlink(buf); snprintf(buf, sizeof buf, "count-%05d-of-%05d", shard, kShards); int64_t len = count_shard(shard, fd, buf); ::close(fd); total += len; struct stat st; ::stat(buf, &st); LOG_INFO << "shard " << shard << " done " << timer.report(len) << " output " << st.st_size; } LOG_INFO << "count done "<< timer.report(total); } // ======= merge ======= class Source // copyable { public: explicit Source(std::istream* in) : in_(in), count_(0), word_() { } bool next() { string line; if (getline(*in_, line)) { size_t tab = line.find('\t'); if (tab != string::npos) { count_ = strtol(line.c_str(), NULL, 10); if (count_ > 0) { word_ = line.substr(tab+1); return true; } } } return false; } bool operator<(const Source& rhs) const { return count_ < rhs.count_; } void outputTo(std::ostream& out) const { out << count_ << '\t' << word_ << '\n'; } private: std::istream* in_; int64_t count_; string word_; }; int64_t merge(const char* output) { Timer timer; vector<unique_ptr<std::ifstream>> inputs; vector<Source> keys; int64_t total = 0; for (int i = 0; i < kShards; ++i) { char buf[256]; snprintf(buf, sizeof buf, "count-%05d-of-%05d", i, kShards); struct stat st; if (::stat(buf, &st) == 0) { total += st.st_size; inputs.emplace_back(new std::ifstream(buf)); Source rec(inputs.back().get()); if (rec.next()) { keys.push_back(rec); } if (!keep) ::unlink(buf); } else { perror("Unable to stat file:"); } } LOG_INFO << "merging " << inputs.size() << " files of " << total << " bytes in total"; { std::ofstream out(output); std::make_heap(keys.begin(), keys.end()); while (!keys.empty()) { std::pop_heap(keys.begin(), keys.end()); keys.back().outputTo(out); if (keys.back().next()) { std::push_heap(keys.begin(), keys.end()); } else { keys.pop_back(); } } } LOG_INFO << "merging done " << timer.report(total); return total; } int main(int argc, char* argv[]) { /* int fd = open("shard-00000-of-00010", O_RDONLY); double t = now(); int64_t len = count_shard(0, fd); double sec = now() - t; printf("count_shard %.3f sec %.2f MB/s\n", sec, len / sec / 1e6); */ int opt; const char* output = "output"; while ((opt = getopt(argc, argv, "ko:s:t:v")) != -1) { switch (opt) { case 'k': keep = true; break; case 'o': output = optarg; break; case 's': kShards = atoi(optarg); break; case 't': shard_dir = optarg; break; case 'v': verbose = true; break; } } Timer timer; LOG_INFO << argc - optind << " input files, " << kShards << " shards, output " << output <<" , temp " << shard_dir; int64_t input = 0; input = shard_(argc, argv); count_shards(); int64_t output_size = merge(output); LOG_INFO << "All done " << timer.report(input) << " output " << output_size; }
true
182b5ef2130948d2fae0e1ce5c1e8ec3795ac564
C++
riodoro1/z80asm
/Program.cpp
UTF-8
4,305
2.984375
3
[]
no_license
// // Program.cpp // z80asm // // Created by Rafał Białek on 07/11/2016. // Copyright © 2016 Rafał Białek. All rights reserved. // #include "Program.h" Program::Program(string source) { readSource(source); } Program::~Program() { } Program::LineType Program::getType(string line) { if ( line.find(":") != string::npos ) return symbolDeclaration; else if ( line.find(".") != string::npos ) return dataDeclaration; else if ( line.length() == 0 ) return emptyLine; else return instruction; } string Program::trimLine(string line) { string trimmed; if(line.length() == 0) return trimmed; string::const_iterator lineIter = line.cbegin(); string::const_iterator lineEnd = line.cend(); while(lineIter != lineEnd && isspace(*lineIter)) lineIter++; //ommit whitespace while (lineIter != lineEnd && *lineIter != ';') { trimmed+=*(lineIter++); //read to the end or to the start of comment } while(isspace(trimmed[trimmed.length() - 1])) { trimmed.pop_back(); //remove spaces at the back } return trimmed; } unsigned int Program::readInstruction(string line) { Instruction *instruction = new Instruction(line, instructionTable); machineCode.push_back(instruction); return instruction->getLength(); } unsigned int Program::readData(string line) { DataBlock *data = new DataBlock(line); machineCode.push_back(data); return data->getLength(); } void Program::readSymbol(string line, long address) { string name; string::const_iterator line_iter = line.cbegin(); string::const_iterator line_end = line.cend(); while (line_iter != line_end && *line_iter != ':') { char current = *line_iter++; if(isspace(current)) throw new MalformedSymbolDeclarationException(line); name += tolower(current); } symbolTable.declareSymbol(name, address); } void Program::resolveInstructions() { list<BinaryBlock*>::iterator iterator; for(iterator = machineCode.begin(); iterator != machineCode.end(); iterator++) { Instruction *instruction = dynamic_cast<Instruction*>(*iterator); if ( instruction != nullptr) instruction->resolve(symbolTable); } } string Program::getHex() { stringstream hexStream; list<BinaryBlock*>::iterator iterator; for(iterator = machineCode.begin(); iterator != machineCode.end(); iterator++) { Instruction *instruction = dynamic_cast<Instruction*>(*iterator); if ( instruction != nullptr ) { assert(instruction->isResolved()); } hexStream<<(*iterator)->getHexString(); } return hexStream.str(); } void Program::readSource(string source) { if (source.length() == 0) return; istringstream sourceStream(source); string line; unsigned int lineCounter = 1; unsigned int currentAddress = 0; while (getline(sourceStream, line)) { //process line by line string trimmed = trimLine(line); LineType type = getType(trimmed); try { switch (type) { case symbolDeclaration: readSymbol(trimmed, currentAddress); break; case dataDeclaration: currentAddress += readData(trimmed); break; case instruction: currentAddress += readInstruction(trimmed); break; case emptyLine: default: break; } } catch ( ProgramException *e ) { e->setLine(lineCounter); throw e; } lineCounter++; } resolveInstructions(); } string Program::delcarationAtAddress(long address) { long counter=0; list<BinaryBlock*>::iterator iterator; for(iterator = machineCode.begin(); iterator != machineCode.end(); iterator++) { long start = counter, end = counter + (*iterator)->getLength(); if ( address >= start && address < end ) return (*iterator)->getDeclaration(); counter = end; } return ""; }
true
5031ae5bbebeea023b973ad88f82dfeccb6f1a38
C++
pamart24/MARP_2021
/aventuraAmazonas/aventuraAmazonas/aventuraAmazonas.cpp
UTF-8
1,772
2.96875
3
[]
no_license
#include <iostream> #include <fstream> #include <climits> #include "IndexPQ.h" #include "DigrafoValorado.h" using namespace std; class AventuraAmazonas { public: AventuraAmazonas(DigrafoValorado<int> const& g, int orig) : origen(orig), dist(g.V(), INF), ulti(g.V()), pq(g.V()) { dist[origen] = 0; pq.push(origen, 0); while (!pq.empty()) { int v = pq.top().elem; pq.pop(); for (auto a : g.ady(v)) relajar(a); } } bool hayCamino(int v) const { return dist[v] != INF; } int distancia(int v) const { return dist[v]; } private: const int INF = INT_MAX; int origen; std::vector<int> dist; std::vector<AristaDirigida<int>> ulti; IndexPQ<int> pq; void relajar(AristaDirigida<int> a) { int v = a.desde(), w = a.hasta(); if (dist[w] > dist[v] + a.valor()) { dist[w] = dist[v] + a.valor(); ulti[w] = a; pq.update(w, dist[w]); } } }; // resuelve un caso de prueba, leyendo de la entrada la // configuración, y escribiendo la respuesta bool resuelveCaso() { int N; cin >> N; if (!std::cin) // fin de la entrada return false; DigrafoValorado<int> Amazonas(N); for (int s = 0; s < N - 1; ++s) { for (int i = N - 1; i > s; --i) { int coste; cin >> coste; Amazonas.ponArista(AristaDirigida<int>(s, N - i + s, coste)); } } for (int s = 0; s < N - 1; ++s) { AventuraAmazonas aventura(Amazonas, s); for (int i = N - 1; i > s; --i) { cout << aventura.distancia(N - i + s) << " "; } cout << "\n"; } return true; } int main() { while (resuelveCaso()); return 0; }
true
cd651a12e8d7751da7723993482a8bfa08a58c18
C++
verevic/http-client
/httpClient/test/httpClientTest.cpp
UTF-8
1,740
2.515625
3
[]
no_license
#include "pch.h" #include <gtest/gtest.h> #include "http_request.h" #include "http_client.h" #include "tcp_client.h" #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> TEST(HttpClientTests, TestSendRequest) { // sendReceive("archeologia.ru", 80, "/modules/gallery/displayimage.php", "album=lastup&cat=0&pos=4"); // std::cout << "encoded:\"" << "/modules/gallery/displayimage.php" << urlEncode("?album=lastup&cat=0&pos=4") << std::endl; std::unique_ptr<http_request> httpRequest(http_request::GET("http://archeologia.ru/modules/gallery/displayimage.php?album=lastup&cat=0&pos=4")); http_client httpClient(httpRequest->host(), httpRequest->port()); ostream_chunk_consumer consumer(std::cout); httpClient.send_recv(*httpRequest, consumer); } struct TestStatusData { std::string input; int status; std::string comment; }; static std::regex statusRegex("([^/]+)\\/([^ ]+) (\\d+) (.+)"); void testStatus(const TestStatusData& test) { std::smatch match; EXPECT_TRUE(std::regex_match(test.input, match, statusRegex)); std::string strStatus(match[3].first, match[3].second); int status = std::stoi(strStatus); EXPECT_EQ(test.status, status); std::string msg(match[4].first, match[4].second); EXPECT_EQ(test.comment, msg); } static TestStatusData statusTestData[] = { {"HTTP/1.1 200 OK", 200, "OK"}, {"HTTP/1.1 400 Bad request", 400, "Bad request"}, {"HTTP/1.1 404 Not Found", 404, "Not Found"}, }; TEST(HttpClientTests, TestStatus) { for (const auto& test : statusTestData) testStatus(test); } TEST(HttpClientTests, TestChunkSize) { EXPECT_EQ(31, std::stoi("1f", 0, 16)); EXPECT_EQ(43, std::stoi("2B", 0, 16)); EXPECT_EQ(12, std::stoi("C", 0, 16)); }
true
dd8afc54145d2c28c18b69cc6030ab4695c75f6d
C++
renweizhukov/CodeLiteProjects
/Power/main.cpp
UTF-8
873
3.671875
4
[]
no_license
#include <iostream> #include <climits> using namespace std; double pow(double x, int n) { if (n < 0) { if (n > LONG_MIN) { return 1.0/pow(x, -n); } else { return 1.0/pow(x, LONG_MAX)/x; } } else if (n == 0) { return 1.0; } else { if (n == 1) { return x; } double y = pow(x, n/2); if (n & 1) { return y*y*x; } else { return y*y; } } } int main() { double x = 0.0; cout << "Please input a double x = "; cin >> x; cout << endl; int n = 0; cout << "Please input an integer n = "; cin >> n; cout << endl; double res = pow(x, n); cout << "Pow(x, n) = " << res << endl; return 0; }
true
11f83eda11fe535e74dfa99baaf92a02c60fb160
C++
nevinhappy/hexrays-demo
/decompiler.cpp
UTF-8
13,490
2.6875
3
[ "MIT" ]
permissive
#include <map> #include "context.h" #include "decompiler.h" /** * Representation of function: * int __cdecl ack(int a1, int a2) * { * int v3; // eax * * if ( !m ) * return n + 1; * if ( !n ) * return ack(m - 1, 1); * v3 = ack(m, n - 1); * return ack(m - 1, v3); * } */ Function fnc_ack = { "ack", 0x804851C, 0x8048577, { // int __cdecl ack(int a1, int a2) {Token::Kind::TYPE, 0x804851C, "int"}, {Token::Kind::WHITE_SPACE, 0x804851C, " "}, {Token::Kind::LITERAL_SYM, 0x804851C, "__cdecl"}, {Token::Kind::WHITE_SPACE, 0x804851C, " "}, {Token::Kind::ID_FNC, 0x804851C, "ack"}, {Token::Kind::PUNCTUATION, 0x804851C, "("}, {Token::Kind::TYPE, 0x804851C, "int"}, {Token::Kind::WHITE_SPACE, 0x804851C, " "}, {Token::Kind::ID_ARG, 0x804851C, "m"}, {Token::Kind::PUNCTUATION, 0x804851C, ","}, {Token::Kind::WHITE_SPACE, 0x804851C, " "}, {Token::Kind::TYPE, 0x804851C, "int"}, {Token::Kind::WHITE_SPACE, 0x804851C, " "}, {Token::Kind::ID_ARG, 0x804851C, "n"}, {Token::Kind::PUNCTUATION, 0x804851C, ")"}, {Token::Kind::NEW_LINE, 0x804851C, "\n"}, // { {Token::Kind::PUNCTUATION, 0x804851C, "{"}, {Token::Kind::NEW_LINE, 0x804851C, "\n"}, // int v3; // eax {Token::Kind::WHITE_SPACE, 0x804851C, " "}, {Token::Kind::TYPE, 0x804851C, "int"}, {Token::Kind::WHITE_SPACE, 0x804851C, " "}, {Token::Kind::ID_VAR, 0x804851C, "v3"}, {Token::Kind::PUNCTUATION, 0x804851C, ";"}, {Token::Kind::WHITE_SPACE, 0x804851C, " "}, {Token::Kind::COMMENT, 0x804851C, "// eax"}, {Token::Kind::NEW_LINE, 0x804851C, "\n"}, // {Token::Kind::NEW_LINE, 0x804851C, "\n"}, // if ( !m ) {Token::Kind::WHITE_SPACE, 0x8048526, " "}, {Token::Kind::KEYWORD, 0x8048526, "if"}, {Token::Kind::WHITE_SPACE, 0x8048526, " "}, {Token::Kind::PUNCTUATION, 0x8048526, "("}, {Token::Kind::WHITE_SPACE, 0x8048526, " "}, {Token::Kind::OPERATOR, 0x8048526, "!"}, {Token::Kind::ID_ARG, 0x8048526, "m"}, {Token::Kind::WHITE_SPACE, 0x8048526, " "}, {Token::Kind::PUNCTUATION, 0x8048526, ")"}, {Token::Kind::NEW_LINE, 0x8048526, "\n"}, // return n + 1; {Token::Kind::WHITE_SPACE, 0x804852B, " "}, {Token::Kind::KEYWORD, 0x804852B, "return"}, {Token::Kind::WHITE_SPACE, 0x804852B, " "}, {Token::Kind::ID_ARG, 0x804852B, "n"}, {Token::Kind::WHITE_SPACE, 0x804852B, " "}, {Token::Kind::OPERATOR, 0x804852B, "+"}, {Token::Kind::WHITE_SPACE, 0x804852B, " "}, {Token::Kind::LITERAL_INT, 0x804852B, "1"}, {Token::Kind::PUNCTUATION, 0x804852B, ";"}, {Token::Kind::NEW_LINE, 0x804852B, "\n"}, // if ( !n ) {Token::Kind::WHITE_SPACE, 0x8048534, " "}, {Token::Kind::KEYWORD, 0x8048534, "if"}, {Token::Kind::WHITE_SPACE, 0x8048534, " "}, {Token::Kind::PUNCTUATION, 0x8048534, "("}, {Token::Kind::WHITE_SPACE, 0x8048534, " "}, {Token::Kind::OPERATOR, 0x8048534, "!"}, {Token::Kind::ID_ARG, 0x8048534, "n"}, {Token::Kind::WHITE_SPACE, 0x8048534, " "}, {Token::Kind::PUNCTUATION, 0x8048534, ")"}, {Token::Kind::NEW_LINE, 0x8048534, "\n"}, // return ack(m - 1, 1); {Token::Kind::WHITE_SPACE, 0x8048547, " "}, {Token::Kind::KEYWORD, 0x8048547, "return"}, {Token::Kind::WHITE_SPACE, 0x8048547, " "}, {Token::Kind::ID_FNC, 0x8048547, "ack"}, {Token::Kind::PUNCTUATION, 0x8048547, "("}, {Token::Kind::ID_ARG, 0x8048544, "m"}, {Token::Kind::WHITE_SPACE, 0x8048544, " "}, {Token::Kind::OPERATOR, 0x8048544, "-"}, {Token::Kind::WHITE_SPACE, 0x8048544, " "}, {Token::Kind::LITERAL_INT, 0x8048539, "1"}, {Token::Kind::PUNCTUATION, 0x8048539, ","}, {Token::Kind::WHITE_SPACE, 0x8048539, " "}, {Token::Kind::LITERAL_INT, 0x804853C, "1"}, {Token::Kind::PUNCTUATION, 0x804853C, ")"}, {Token::Kind::PUNCTUATION, 0x804853C, ";"}, {Token::Kind::NEW_LINE, 0x804853C, "\n"}, // v3 = ack(m, n - 1); {Token::Kind::WHITE_SPACE, 0x804855E, " "}, {Token::Kind::ID_VAR, 0x804855E, "v3"}, {Token::Kind::WHITE_SPACE, 0x804855E, " "}, {Token::Kind::OPERATOR, 0x804855E, "="}, {Token::Kind::WHITE_SPACE, 0x804855E, " "}, {Token::Kind::ID_FNC, 0x804855E, "ack"}, {Token::Kind::PUNCTUATION, 0x804855E, "("}, {Token::Kind::ID_ARG, 0x804855B, "m"}, {Token::Kind::PUNCTUATION, 0x804855B, ","}, {Token::Kind::WHITE_SPACE, 0x804855B, " "}, {Token::Kind::ID_ARG, 0x8048554, "n"}, {Token::Kind::WHITE_SPACE, 0x8048554, " "}, {Token::Kind::OPERATOR, 0x8048554, "-"}, {Token::Kind::WHITE_SPACE, 0x8048554, " "}, {Token::Kind::LITERAL_INT, 0x8048551, "1"}, {Token::Kind::PUNCTUATION, 0x8048551, ")"}, {Token::Kind::PUNCTUATION, 0x8048551, ";"}, {Token::Kind::NEW_LINE, 0x8048551, "\n"}, // return ack(m - 1, v3); {Token::Kind::WHITE_SPACE, 0x8048575, " "}, {Token::Kind::KEYWORD, 0x8048575, "return"}, {Token::Kind::WHITE_SPACE, 0x8048575, " "}, {Token::Kind::ID_FNC, 0x8048570, "ack"}, {Token::Kind::PUNCTUATION, 0x8048570, "("}, {Token::Kind::ID_ARG, 0x804856D, "m"}, {Token::Kind::WHITE_SPACE, 0x804856D, " "}, {Token::Kind::OPERATOR, 0x804856D, "-"}, {Token::Kind::WHITE_SPACE, 0x804856D, " "}, {Token::Kind::LITERAL_INT, 0x8048566, "1"}, {Token::Kind::PUNCTUATION, 0x8048566, ","}, {Token::Kind::WHITE_SPACE, 0x8048566, " "}, {Token::Kind::ID_VAR, 0x8048569, "v3"}, {Token::Kind::PUNCTUATION, 0x8048569, ")"}, {Token::Kind::PUNCTUATION, 0x8048569, ";"}, {Token::Kind::NEW_LINE, 0x8048569, "\n"}, // } {Token::Kind::PUNCTUATION, 0x8048576, "}"}, // Do not add new line at the end. // For whatever reason, the last line is not displayed if the max // place's X coordinate isn't 0. // So always put only one token at the last line. } }; /** * Representation of function: * int __cdecl main(int argc, const char **argv, const char **envp) * { * int v4; // [esp+14h] [ebp-Ch] * int v5; // [esp+18h] [ebp-8h] * int v6; // [esp+1Ch] [ebp-4h] * * v6 = 0; * v5 = 0; * v4 = 0; * __isoc99_scanf(\"%d %d\", &v5, &v4); * v6 = ack(v5, v4); * printf("ackerman( %d , %d ) = %d\n", v5, v4, v6); * return v6; * } */ Function fnc_main = { "main", 0x8048577, 0x80485F6, { // int __cdecl main(int argc, const char **argv, const char **envp) {Token::Kind::TYPE, 0x8048577, "int"}, {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::LITERAL_SYM, 0x8048577, "__cdecl"}, {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::ID_FNC, 0x8048577, "main"}, {Token::Kind::PUNCTUATION, 0x8048577, "("}, {Token::Kind::TYPE, 0x8048577, "int"}, {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::ID_ARG, 0x8048577, "argc"}, {Token::Kind::PUNCTUATION, 0x8048577, ","}, {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::TYPE, 0x8048577, "const char"}, {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::OPERATOR, 0x8048577, "*"}, {Token::Kind::OPERATOR, 0x8048577, "*"}, {Token::Kind::ID_ARG, 0x8048577, "argv"}, {Token::Kind::PUNCTUATION, 0x8048577, ","}, {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::TYPE, 0x8048577, "const char"}, {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::OPERATOR, 0x8048577, "*"}, {Token::Kind::OPERATOR, 0x8048577, "*"}, {Token::Kind::ID_ARG, 0x8048577, "envp"}, {Token::Kind::PUNCTUATION, 0x8048577, ")"}, {Token::Kind::NEW_LINE, 0x8048577, "\n"}, // { {Token::Kind::PUNCTUATION, 0x8048577, "{"}, {Token::Kind::NEW_LINE, 0x8048577, "\n"}, // int v4; // [esp+14h] [ebp-Ch] {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::TYPE, 0x8048577, "int"}, {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::ID_VAR, 0x8048577, "v4"}, {Token::Kind::PUNCTUATION, 0x8048577, ";"}, {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::COMMENT, 0x8048577, "// [esp+14h] [ebp-Ch]"}, {Token::Kind::NEW_LINE, 0x8048577, "\n"}, // int v5; // [esp+18h] [ebp-8h] {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::TYPE, 0x8048577, "int"}, {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::ID_VAR, 0x8048577, "v5"}, {Token::Kind::PUNCTUATION, 0x8048577, ";"}, {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::COMMENT, 0x8048577, "// [esp+18h] [ebp-8h]"}, {Token::Kind::NEW_LINE, 0x8048577, "\n"}, // int v6; // [esp+1Ch] [ebp-4h] {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::TYPE, 0x8048577, "int"}, {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::ID_VAR, 0x8048577, "v6"}, {Token::Kind::PUNCTUATION, 0x8048577, ";"}, {Token::Kind::WHITE_SPACE, 0x8048577, " "}, {Token::Kind::COMMENT, 0x8048577, "// [esp+1Ch] [ebp-4h]"}, {Token::Kind::NEW_LINE, 0x8048577, "\n"}, // {Token::Kind::NEW_LINE, 0x8048577, "\n"}, // v6 = 0; {Token::Kind::WHITE_SPACE, 0x8048580, " "}, {Token::Kind::ID_VAR, 0x8048580, "v6"}, {Token::Kind::WHITE_SPACE, 0x8048580, " "}, {Token::Kind::OPERATOR, 0x8048580, "="}, {Token::Kind::WHITE_SPACE, 0x8048580, " "}, {Token::Kind::LITERAL_INT, 0x8048580, "0"}, {Token::Kind::PUNCTUATION, 0x8048580, ";"}, {Token::Kind::NEW_LINE, 0x8048580, "\n"}, // v5 = 0; {Token::Kind::WHITE_SPACE, 0x8048588, " "}, {Token::Kind::ID_VAR, 0x8048588, "v5"}, {Token::Kind::WHITE_SPACE, 0x8048588, " "}, {Token::Kind::OPERATOR, 0x8048588, "="}, {Token::Kind::WHITE_SPACE, 0x8048588, " "}, {Token::Kind::LITERAL_INT, 0x8048588, "0"}, {Token::Kind::PUNCTUATION, 0x8048588, ";"}, {Token::Kind::NEW_LINE, 0x8048588, "\n"}, // v4 = 0; {Token::Kind::WHITE_SPACE, 0x8048590, " "}, {Token::Kind::ID_VAR, 0x8048590, "v4"}, {Token::Kind::WHITE_SPACE, 0x8048590, " "}, {Token::Kind::OPERATOR, 0x8048590, "="}, {Token::Kind::WHITE_SPACE, 0x8048590, " "}, {Token::Kind::LITERAL_INT, 0x8048590, "0"}, {Token::Kind::PUNCTUATION, 0x8048590, ";"}, {Token::Kind::NEW_LINE, 0x8048590, "\n"}, // __isoc99_scanf(\"%d %d\", &v5, &v4); {Token::Kind::WHITE_SPACE, 0x80485AF, " "}, {Token::Kind::ID_FNC, 0x80485AF, "__isoc99_scanf"}, {Token::Kind::PUNCTUATION, 0x80485AF, "("}, {Token::Kind::LITERAL_STR, 0x80485A8, "\"%d %d\""}, {Token::Kind::PUNCTUATION, 0x80485A8, ","}, {Token::Kind::WHITE_SPACE, 0x80485A8, " "}, {Token::Kind::OPERATOR, 0x80485A4, "&"}, {Token::Kind::ID_VAR, 0x80485A4, "v5"}, {Token::Kind::PUNCTUATION, 0x80485A4, ","}, {Token::Kind::WHITE_SPACE, 0x80485A4, " "}, {Token::Kind::OPERATOR, 0x804859C, "&"}, {Token::Kind::ID_VAR, 0x804859C, "v4"}, {Token::Kind::PUNCTUATION, 0x804859C, ")"}, {Token::Kind::PUNCTUATION, 0x804859C, ";"}, {Token::Kind::NEW_LINE, 0x804859C, "\n"}, // v6 = ack(v5, v4); {Token::Kind::WHITE_SPACE, 0x80485C8, " "}, {Token::Kind::ID_VAR, 0x80485C8, "v6"}, {Token::Kind::WHITE_SPACE, 0x80485C8, " "}, {Token::Kind::OPERATOR, 0x80485C8, "="}, {Token::Kind::WHITE_SPACE, 0x80485C8, " "}, {Token::Kind::ID_FNC, 0x80485C3, "ack"}, {Token::Kind::PUNCTUATION, 0x80485C3, "("}, {Token::Kind::ID_VAR, 0x80485C0, "v5"}, {Token::Kind::PUNCTUATION, 0x80485C0, ","}, {Token::Kind::WHITE_SPACE, 0x80485C0, " "}, {Token::Kind::ID_VAR, 0x80485BC, "v4"}, {Token::Kind::PUNCTUATION, 0x80485BC, ")"}, {Token::Kind::PUNCTUATION, 0x80485BC, ";"}, {Token::Kind::NEW_LINE, 0x80485BC, "\n"}, // printf("ackerman( %d , %d ) = %d\n", v5, v4, v6); {Token::Kind::WHITE_SPACE, 0x80485EB, " "}, {Token::Kind::ID_FNC, 0x80485EB, "printf"}, {Token::Kind::PUNCTUATION, 0x80485EB, "("}, {Token::Kind::LITERAL_STR, 0x80485E4, "\"ackerman( %d , %d ) = %d\\n\""}, {Token::Kind::PUNCTUATION, 0x80485E4, ","}, {Token::Kind::WHITE_SPACE, 0x80485E4, " "}, {Token::Kind::ID_VAR, 0x80485E0, "v5"}, {Token::Kind::PUNCTUATION, 0x80485E0, ","}, {Token::Kind::WHITE_SPACE, 0x80485E0, " "}, {Token::Kind::ID_VAR, 0x80485DC, "v4"}, {Token::Kind::PUNCTUATION, 0x80485DC, ","}, {Token::Kind::WHITE_SPACE, 0x80485DC, " "}, {Token::Kind::ID_VAR, 0x80485D8, "v6"}, {Token::Kind::PUNCTUATION, 0x80485D8, ")"}, {Token::Kind::PUNCTUATION, 0x80485D8, ";"}, {Token::Kind::NEW_LINE, 0x80485D8, "\n"}, // return v6; {Token::Kind::WHITE_SPACE, 0x80485F4, " "}, {Token::Kind::KEYWORD, 0x80485F4, "return"}, {Token::Kind::WHITE_SPACE, 0x80485F4, " "}, {Token::Kind::ID_VAR, 0x80485F4, "v6"}, {Token::Kind::PUNCTUATION, 0x80485F4, ";"}, {Token::Kind::NEW_LINE, 0x80485F4, "\n"}, // } {Token::Kind::PUNCTUATION, 0x80485F5, "}"}, // Do not add new line at the end. // For whatever reason, the last line is not displayed if the max // place's X coordinate isn't 0. // So always put only one token at the last line. } }; using Functions = std::map<ea_t, Function>; Functions functions = { {fnc_ack.getStart(), fnc_ack}, {fnc_main.getStart(), fnc_main} }; Function* Decompiler::decompile(ea_t ea) { Function* ret = nullptr; auto it = functions.upper_bound(ea); if (it == functions.begin()) { // Before the first -> no function. ret = nullptr; } else if (it == functions.end() && !functions.empty()) { // After the last -> check the last function. auto& last = functions.rbegin()->second; ret = last.ea_inside(ea) ? &last : nullptr; } else if (it != functions.end()) { // In the middle -> check the previous. --it; auto& prev = it->second; ret = prev.ea_inside(ea) ? &prev : nullptr; } if (ret) { demo_msg("Decompiler::decompile(%a): %s\n", ea, ret->toString().c_str() ); } else { demo_msg("Decompiler::decompile(%a): cannot decompile\n", ea); } return ret; }
true
400e62e635a8691eef931e0a0900cf4027262a10
C++
bigship/leetcode_solutions
/1048_LongestStringChain.cpp
UTF-8
1,371
3.578125
4
[]
no_license
// 1048. Longest String Chain /* * Given a list of words, each word consists of English lowercase letters. Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For example, "abc" is a predecessor of "abac". A word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on. Return the longest possible length of a word chain with words chosen from the given list of words. Example 1: Input: ["a","b","ba","bca","bda","bdca"] Output: 4 Explanation: one of the longest word chain is "a","ba","bda","bdca". Note: 1 <= words.length <= 1000 1 <= words[i].length <= 16 words[i] only consists of English lowercase letters. */ class Solution { public: int longestStrChain(vector<string>& words) { std::sort(words.begin(), words.end(), [](string a, string b) { return a.size() < b.size(); }); unordered_map<string, int> dp; int ans = 0; for (auto& cur : words) { for (int i = 0; i < w.size(); i++) { string prev = w.substr(0, i) + w.substr(i+1); dp[cur] = max(dp[cur], dp[prev] + 1); } res = max(res, dp[cur]); } return res; } };
true
6d94f63020b4f59c2a767a4650c128b1f33d660a
C++
aliefhooghe/View
/src/widget_container/map_wrapper.cpp
UTF-8
4,696
2.5625
3
[ "BSD-3-Clause" ]
permissive
#include <cmath> #include "map_wrapper.h" namespace View { map_wrapper_widget_holder::map_wrapper_widget_holder( map_wrapper& parent, float x, float y, std::unique_ptr<widget>&& children) : widget_holder<>{parent, 0.f, 0.f, std::move(children)}, _parent{&parent} { (void)x, (void)y; } void map_wrapper_widget_holder::invalidate_rect(const rectangle<>& rect) { const auto scale = _parent->_scale; const auto parent_rect = rectangle<>{0.f, _parent->height(), 0.f, _parent->width()}; const auto parent_redraw_rect = rect.scale(_parent->_scale).translate(-_parent->_origin_x, -_parent->_origin_y); rectangle<> intersection; if (parent_rect.intersect(parent_redraw_rect, intersection)) _parent->invalidate_rect(intersection); } void map_wrapper_widget_holder::invalidate_widget() { // Everything in content must be redrawn : Invalidate the map wrapper _parent->invalidate(); } /** * map wrapper implementation **/ map_wrapper::map_wrapper( std::unique_ptr<widget>&& root, float width, float height) : widget_wrapper_base{std::move(root), 0.f, 0.f, width, height} {} map_wrapper::map_wrapper( std::unique_ptr<widget>&& root, float width, float height, size_constraint width_constrain, size_constraint height_constrain) : widget_wrapper_base{std::move(root), 0.f, 0.f, width, height, width_constrain, height_constrain} {} void map_wrapper::reset_view() noexcept { _set_origin(0.f, 0.f); _scale = 1.f; invalidate(); } bool map_wrapper::on_mouse_move(float x, float y) { return widget_wrapper_base::on_mouse_move(_x_to_content(x), _y_to_content(y)); } bool map_wrapper::on_mouse_button_down(const mouse_button button, float x, float y) { return widget_wrapper_base::on_mouse_button_down(button, _x_to_content(x), _y_to_content(y)); } bool map_wrapper::on_mouse_button_up(const mouse_button button, float x, float y) { return widget_wrapper_base::on_mouse_button_up(button, _x_to_content(x), _y_to_content(y)); } bool map_wrapper::on_mouse_dbl_click(float x, float y) { return widget_wrapper_base::on_mouse_dbl_click(_x_to_content(x), _y_to_content(y)); } bool map_wrapper::on_mouse_drag(const mouse_button button, float x, float y, float dx, float dy) { if (!widget_wrapper_base::on_mouse_drag(button, _x_to_content(x), _y_to_content(y), dx / _scale, dy / _scale)) { _translate_origin(-dx, -dy); invalidate(); } return true; } bool map_wrapper::on_mouse_drag_start(const mouse_button button, float x, float y) { widget_wrapper_base::on_mouse_drag_start(button, _x_to_content(x), _y_to_content(y)); return true; } bool map_wrapper::on_mouse_drag_end(const mouse_button button, float x, float y) { widget_wrapper_base::on_mouse_drag_end(button, _x_to_content(x), _y_to_content(y)); return true; } void map_wrapper::draw(NVGcontext *vg) { // Clip the drawing area nvgIntersectScissor(vg, 0, 0, widget_wrapper_base::width(), widget_wrapper_base::height()); // Translate and draw nvgSave(vg); nvgTranslate(vg, -_origin_x, -_origin_y); nvgScale(vg, _scale, _scale); widget_wrapper_base::draw(vg); nvgRestore(vg); } void map_wrapper::draw_rect(NVGcontext* vg, const rectangle<>& area) { // Clip the drawing area nvgIntersectScissor(vg, area.left, area.right, area.width(), area.height()); // Translate and draw nvgSave(vg); nvgTranslate(vg, -_origin_x, -_origin_y); nvgScale(vg, _scale, _scale); widget_wrapper_base::draw_rect(vg, _rect_to_content(area)); nvgRestore(vg); } bool map_wrapper::on_mouse_wheel(float x, float y, float distance) { if (!widget_wrapper_base::on_mouse_wheel(_x_to_content(x), _y_to_content(y), distance)) { const auto factor = std::pow(1.0625f, distance); _scale *= factor; _origin_x = factor * (_origin_x + x) - x; _origin_y = factor * (_origin_y + y) - y; invalidate(); } return true; } void map_wrapper::_translate_origin(float dx, float dy) noexcept { _origin_x += dx; _origin_y += dy; } void map_wrapper::_set_origin(float x, float y) noexcept { _origin_x = x; _origin_y = y; } }
true
26877fefce66f52d79aa71c0f683fbdbb9dd58b9
C++
pcasamiquela/IA_PracticaFinal
/source/PracticaFinalState.h
UTF-8
1,865
2.546875
3
[]
no_license
#include "Engine/EngineFramework.h" #include "Player.h" #include "Boid.h" #include "Locker.h" #include "ConeEnemyAgent.h" #include "ErrorManagement.h" #include <fstream> #include <iostream> #include <map> #include "PathfindingUtils.h" using namespace std; class PracticaFinalState : public BaseState{ public: virtual void Init() override; virtual void Clean() override; virtual void Update(float deltaTime) override; virtual void Render() override; private: //Level State enum LevelState { LEVEL_01 }; //PathFinding HeuristicFunction heuristicFunction = &HeuristicUtils::ManhattanDistance; bool steppedExecutionFinished = true; bool isInLocker = false; bool alert = false; Grid grid; //Textures Texture arrowTexture; Texture questionTexture; //Obstacles LOS_Obstacle *obstacle; int obstacleNumber; //Entities Player *player; Player *playerToShow; //GenericPool<Boid>* soldiersPool vector<ConeEnemyAgent*> soldiersPool; vector<Locker*> lockersPool; Level *level_01; int numSoldiers; Vector2D exitPosition; vector <int> numNodes; //Simple Path //vector <vector<SimplePath>> simplePathVector; SimplePath *tempPath; map<int, SimplePath> simplePathMap; SimplePath path1; StateManager manager; void ReadFromFile(LevelState _levelState, int _LevelArray[LEVEL_WIDTH][LEVEL_HEIGHT]); void CreatePlayer(int x, int y); void CreateSoldier(int soldierNumber); void CreateLocker(int lockerID, int x, int y); void LoadEntities(int* levelArray, Vector2D levelOrigin,int levelWidth, int levelHeight,int tileImageWidth, int tileImageHeight, Vector2D tileImageScale); void ReadPathFromFile(int cont); void CreateGrid(int* levelArray); void StartPathfinding(ConeEnemyAgent &currentEnemy, Vector2D targetPos); void ResetPathfinding(ConeEnemyAgent& currentEnemy); void CallPathFinding(int soldierNumber, Vector2D targetPosition); };
true
78b5b55ae1e0db0c29d325deedce33b697addd24
C++
kaust-cs249-2020/alejandro_amador
/chapter12/clusters.cpp
UTF-8
2,833
3.171875
3
[]
no_license
#include "clusters.h" double maxDataCenterDist(vector<vector<double>>& data, vector<vector<double>>& centers) { double result = 0; for (auto& x : data) { double temp = dataPointCenterDist(x, centers); if (temp > result) { result = temp; } } return result; } double dataPointCenterDist(vector<double>& point, vector<vector<double>>& centers) { double result = 99999; for (auto& x : centers) { double temp = euclideanDistance(point, x); if (temp < result) { result = temp; } } return result; } double euclideanDistance(vector<double>& x, vector<double>& y) { double result = 0; for (int i = 0; i < x.size(); i++) { result += (x[i] - y[i])*(x[i] - y[i]); } result = sqrt(result); return result; } vector<vector<double>> farthestFirstTraversal(vector<vector<double>> data, double k) { vector<vector<double>> dato(data); vector<vector<double>> centers = { dato[0] }; dato.erase(dato.begin()); while (centers.size() < k) { int maximizer = 0; double max = dataPointCenterDist(dato[0], centers); for (int i = 1; i < dato.size(); i++) { double temp = dataPointCenterDist(dato[i], centers); if (temp > max) { max = temp; maximizer = i; } } centers.push_back(dato[maximizer]); dato.erase(dato.begin() + maximizer); } return centers; } double dataCenterDistorsion(vector<vector<double>>& data, vector<vector<double>>& centers) { int size = data.size(); double result = 0; for (int i = 0; i < size; i++) { result += pow(dataPointCenterDist(data[i], centers), 2); } result /= size; return result; } vector<double> centerOfGravity(vector<vector<double>>& data) { vector<double> gravity = data[0]; for (int i = 1; i < data.size(); i++) { for (int j = 0; j < gravity.size(); j++) { gravity[j] += data[i][j]; } } int size = data.size(); for (auto& x : gravity) { x /= size; } return gravity; } vector<vector<double>> lloydAlgorithm(vector<vector<double>>& data, int k) { vector<vector<double>> centers; for (int i = 0; i < k; i++) { centers.push_back(data[i]); } vector<vector<double>> lastCenters(centers); while (true) { vector<vector<vector<double>>> clusters(k); for (auto& x : data) { double max = 99999; int closer = -1; for (int i = 0; i < k; i++) { double temp = euclideanDistance(x, centers[i]); if (temp < max) { max = temp; closer = i; } } clusters[closer].push_back(x); } for (int i = 0; i < k; i++) { vector<double> temp = centerOfGravity(clusters[i]); centers[i] = temp; } if (lastCenters == centers) { break; } else { lastCenters = centers; } } return centers; }
true
f0881af76faaaaec3a1d9741ff7a158d9dc36d17
C++
caaarllosR/C-Cpp
/URI/solved/URI1247.cpp
UTF-8
379
2.640625
3
[]
no_license
#include <stdio.h> #include <math.h> int main(){ int vf, vg, dx; float dg, df = 12.0, tg, tf; while(scanf("%d %d %d", &dx, &vf, &vg)!=EOF){ dg = sqrt(dx*dx + 144); tg = dg/vg; tf = df/vf; if(tg <= tf){ printf("S\n"); }else { printf("N\n"); } } return 0; }
true
39fbef5ed2f96b3473ffdcd6465c5275debea659
C++
optozorax/olymp
/contests/icpc/acm2018/3.cpp
UTF-8
556
2.796875
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <map> #include <fstream> using namespace std; int main() { string line; cin >> line; long long max = 0; string letters; int k = 0; for (int i = 0; i < line.size(); ++i) { if (letters.find(line[i]) != string::npos) { if (letters.size() >= max) max = letters.size(); k++; i = k; letters.clear(); } else { letters += line[i]; if (i == line.size() - 1 && letters.size() >= max) max = letters.size(); } } cout << max; return 0; }
true
7fac88424cc6ccb785aabf40bf7171244cb42d43
C++
wanglg007/Cplusplus17
/02_concurrency/example01/Ex01_08.cpp
UTF-8
3,328
3.609375
4
[]
no_license
//(1.8)简单的层级互斥量实现 #include <mutex> #include <stdexcept> class hierarchical_mutex { std::mutex internal_mutex; unsigned long const hierarchy_value; unsigned long previous_hierarchy_value; static thread_local unsigned long this_thread_hierarchy_value; // 1 void check_for_hierarchy_violation() { if (this_thread_hierarchy_value <= hierarchy_value) { // 2 throw std::logic_error("mutex hierarchy violated"); } } void update_hierarchy_value() { previous_hierarchy_value = this_thread_hierarchy_value; // 3 this_thread_hierarchy_value = hierarchy_value; } public: explicit hierarchical_mutex(unsigned long value) : hierarchy_value(value), previous_hierarchy_value(0) {} void lock() { check_for_hierarchy_violation(); internal_mutex.lock(); // 4 update_hierarchy_value(); // 5 } void unlock() { this_thread_hierarchy_value = previous_hierarchy_value; // 6 internal_mutex.unlock(); } bool try_lock() { check_for_hierarchy_violation(); if (!internal_mutex.try_lock()) // 7 return false; update_hierarchy_value(); return true; } }; thread_local unsigned long hierarchical_mutex::this_thread_hierarchy_value(ULLONG_MAX); // 8 int main() { hierarchical_mutex m1(42); hierarchical_mutex m2(2000); } /** * 这里重点使用thread_local的值来代表当前线程的层级值:this_thread_hierarchy_value①。它被初始化为最大值⑧,所以最初所有线程都能被锁住。因 * 为其声明中有thread_local,所以每个线程都有其拷贝副本,这样线程中变量状态完全独立,当从另一个线程进行读取时,变量的状态也完全独立。 * * 所以,第一次线程锁住一个hierarchical_mutex时,this_thread_hierarchy_value的值是ULONG_MAX。由于其本身的性质,这个值会大于其他任何值,所以会通过 * check_for_hierarchy_vilation()②的检查。在这种检查方式下,lock()代表内部互斥锁已被锁住④。一旦成功锁住,你可以更新层级值了⑤。 * * 当你现在锁住另一个hierarchical_mutex时,还持有第一个锁,this_thread_hierarchy_value的值将会显示第一个互斥量的层级值。第二个互斥量的层级值必须小于 * 已经持有互斥量检查函数②才能通过。 * * 最重要的是为当前线程存储之前的层级值,所以你可以调用unlock()⑥对层级值进行保存;否则,就锁不住任何互斥量(第二个互斥量的层级数高于第一个互斥量), * 即使线程没有持有任何锁。因为保存了之前的层级值,只有当持有internal_mutex③,且在解锁内部互斥量⑥之前存储它的层级值,才能安全的将hierarchical_mutex自身 * 进行存储。这是因为hierarchical_mutex被内部互斥量的锁所保护着。 * * try_lock()与lock()的功能相似,除了在调用internal_mutex的try_lock()⑦失败时,不能持有对应锁,所以不必更新层级值,并直接返回false。 */
true
518b85c781a8a0ac98855f6c575b5edec5df1de7
C++
beckrpgirl/Murder-Magic
/MurderMagic/Source/MurderMagic/Private/Objects/Door.cpp
UTF-8
2,056
2.515625
3
[]
no_license
// Fill out your copyright notice in the Description page of Project Settings. #include "Door.h" // Sets default values ADoor::ADoor(const FObjectInitializer& OI) : Super(OI) { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; //Parameters for the collision box CollisionBox = OI.CreateDefaultSubobject<UBoxComponent>(this, TEXT("SphereComponent")); CollisionBox->GetCollisionResponseToChannel(ECC_WorldStatic); CollisionBox->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); CollisionBox->SetGenerateOverlapEvents(true); CollisionBox->OnComponentBeginOverlap.AddDynamic(this, &ADoor::OnOverlapBegin); SetRootComponent(CollisionBox); //Parameters for the static mesh Mesh = OI.CreateDefaultSubobject<UStaticMeshComponent>(this, TEXT("MeshComponent")); Mesh->SetupAttachment(CollisionBox); Mesh->AttachToComponent(this->RootComponent, FAttachmentTransformRules::KeepRelativeTransform); } // Called when the game starts or when spawned void ADoor::BeginPlay() { Super::BeginPlay(); } // Called every frame void ADoor::Tick(float DeltaTime) { Super::Tick(DeltaTime); this->Transition(DeltaTime); } //Begin overlap function for door void ADoor::OnOverlapBegin(UPrimitiveComponent* OverlapComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& Hit) { } //Function Definition of Open void ADoor::Open() { //Calls Transition function if the prequisites are completed and is returned true this->isTransitioning = true; } //Function Definition of Transition void ADoor::Transition(float DeltaTime) { //calls If statement if (this->isTransitioning) { //Updates position via float value and slides door along Y axis thus moving the door and opening it float UpdatedYPosition = FMath::FInterpConstantTo(this->Mesh->RelativeLocation.Y, this->SlideDistance, DeltaTime, 100.f); this->Mesh->SetRelativeLocation(FVector{ 0.f,UpdatedYPosition, 0.f }); } }
true
1e1c7e4e4ebd5d63aa63884e5db3be5c9cb03224
C++
VictorTagayun/Arduino
/due/Oscilloscope/Graphs/GraphStar.cpp
UTF-8
406
2.515625
3
[ "MIT" ]
permissive
// // // #include "GraphStar.h" #include "OsciCanvasInt.h" void GraphStar::init() { CanvasInt.init(0, 200); // delay 200 microseconds on drawing lines } void GraphStar::draw() { for (int i = 0; i < 20; i++) { CanvasInt.line(128,32, 256, 480 ); CanvasInt.line(256,480, 384,32 ); CanvasInt.line(384,32, 32,320 ); CanvasInt.line(32,320, 480,320 ); CanvasInt.line(480,320, 128,32 ); } }
true
4068ad489b3dc8e737536b2554f450874b1eb93a
C++
aaryan6789/cppSpace
/Pointers/custom_smart/my_smartPtr.cpp
UTF-8
1,699
3.890625
4
[]
no_license
// Smart Pointer Implementation // Requirements // 1. Template implementation // 2. Reference Count variable // The reference count variable is incremented when we add a new reference // to the object and decremented when the reference is removed. #include <iostream> using namespace std; // SmartPtr class needs pointers to both the Object that it would be pointing to // and to the refCount. These have to be the pointers rather than the actual // object or the ref count value, as the goal of a smart pointer is that the // reference count is tracked across multiple smart pointers to one object. template <class T> class smartPtr { private: T* obj; unsigned* ref_count; public: smartPtr(T* ptr){ obj = ptr; ref_count = (unsigned*)malloc(sizeof(unsigned)); *ref_count = 1; } }; // 2 Constructors and Destructor smartPtr(T * object){ // Set the value of T* obj // Set the ref count to 1 } // Contructor that will create a new Smart Pointer that points to an existing // object. We will need to first set obj and ref count to pointer to sptr's obj // and ref_count. // Because we created a new reference to obj, we need to increment ref_count. smartPtr(smartPtr<T>& sptr){ } // Destructor // We have to destroy a reference to the object. // Decrement the ref_count. If ref_count is 0 then free the memory created by // the integer and destroy the object ~smartPtr(smartPtr<T> sptr){ } // There is one additional way that references can be created. // By setting one smartPtr equal to another . // So for this we would have to override the equal operator to handle this.
true
cf65a1772fd7a768de6b3731dd90194b8ea92f02
C++
fabalcu97/2016-2-p1
/c_BSTree.h
UTF-8
3,596
3.078125
3
[]
no_license
#ifndef C_BSTREE_H #define C_BSTREE_H #include <iostream> #include <queue> #include"node.h" using namespace std; struct arg_struct { void* arg1; void* arg2; }; template <class T> class c_BSTree{ public: c_BSTree(){ root=nullptr; } c_Node<T>* root; pthread_mutex_t mMutex; void* my_insert(void* mdata); static void* insert_helper(void* context); void* my_delete(void* mdata); static void* delete_helper(void* context); void print(c_Node<T>* it); void print_bfs(); void transform(); c_Node<T>** my_find(T data, c_Node<T>*&ant); }; template <class T> c_Node<T>** c_BSTree<T>::my_find(T data, c_Node<T>*&ant){ c_Node<T>** it=&root; // cout<<"Buscando"<<data<<endl; for(; *it!=nullptr && (*it)->data!=data; it=&(*it)->hijos[(*it)->data < data]){ if(ant){ ant->lock=0; } while((*it)->lock); if( *it != nullptr && (*it)->data != data ){ ant=*it; (*it)->lock=1; } } return it; } template <class T> void* c_BSTree<T>::my_insert(void *mdata){ int a = *((int*) mdata); cout<<"Inserto: "<<a<<endl; T data; data= *((T *)mdata); // cout<<"Insertando "<<(data)<<endl; c_Node<T>* ant = nullptr; c_Node<T>** it; it=my_find(data, ant); while(it!=nullptr && (*it)->data!=data){ it=my_find(data, ant); } cout<<"entro"<<endl; if(ant){ ant->lock=1; } again: pthread_mutex_lock(&mMutex); if(!(*it)){ *it = new c_Node<T> (data); } pthread_mutex_unlock(&mMutex); if ( (*it) && (*it)->data != data ){ it = my_find(data, ant); goto again; } //if(ant) { // ant->lock=0; // cout<<"Desbloqueo"<<endl; //} } /* template <class T> void c_BSTree<T>::parallel_insert(int elementos[], int tam){ pthread_t* threads; threads = (pthread_t*) malloc( tam * sizeof(pthread_t) ); void* u[2]; u[0]=this; for (int i = 0; i < tam; ++i) { u[1]=(void*) elementos[i]; pthread_create( &threads[i], NULL, c_BSTree<T>::insert_helper,u); } for (int i = 0; i < tam; ++i) { pthread_join( threads[i], NULL); } }*/ template <class T> void* c_BSTree<T>::insert_helper(void* context){ struct arg_struct *args = (struct arg_struct *)context; //int el=args->arg1; return ((c_BSTree<T> *)args->arg1)->my_insert(args->arg2); } template <class T> void c_BSTree<T>::print(c_Node<T>* it){ if(!it) return; print(it->hijos[0]); cout<<it->data<<endl; print(it->hijos[1]); } template <class T> void c_BSTree<T>::print_bfs(){ int nivel; queue<pair<c_Node<T>* ,int> > cola; c_Node<T>* aux; cola.push(make_pair(root,0)); while(!cola.empty()){ aux=cola.front().first; nivel=cola.front().second; cout<<aux->data<<" en nivel "<<nivel<<endl; cola.pop(); if(aux->hijos[0]!=nullptr) cola.push(make_pair(aux->hijos[0],nivel+1)); if(aux->hijos[1]!=nullptr) cola.push(make_pair(aux->hijos[1],nivel+1)); } cout<<endl; } template<class T> void* c_BSTree<T>::my_delete(void* mdata) { c_Node<T>** p; c_Node<T>* temp; c_Node<T>* ant=nullptr; T data; data= *((T *)mdata); p=my_find(data, ant); pthread_mutex_lock(&mMutex); if(!(*p)) return 0; cout<<"Elimino "<<data<<endl; temp=(*p); if((*p)->hijos[0] && (*p)->hijos[1]){ for(p=&((*p)->hijos[0]); (*p)->hijos[1]; p=&((*p)->hijos[1])); swap((*p)->data,temp->data); } temp=(*p); (*p)=(*p)->hijos[!!(*p)->hijos[1]]; pthread_mutex_unlock(&mMutex); //if(ant) { //ant->lock=0; cout<<"Desbloqueo"<<endl; //} } template <class T> void* c_BSTree<T>::delete_helper(void* context){ struct arg_struct *args = (struct arg_struct *)context; //int el=args->arg1; return ((c_BSTree<T> *)args->arg1)->my_delete(args->arg2); } #endif // C_BSTREE_H
true
fdc2d0b986621c46c70b295bd3afe8fe5925bcb5
C++
Moon-ChangHyun/BOJ
/2133/source.cpp
UTF-8
254
2.734375
3
[]
no_license
#include <cstdio> int main() { int A[31], B[31]; A[0] = B[1] = 1; A[1] = B[0] = 0; int n; scanf("%d", &n); if (n > 1) { for (int i = 2; i <= n; ++i) { A[i] = A[i - 2] + 2 * B[i - 1]; B[i] = A[i - 1] + B[i - 2]; } } printf("%d", A[n]); }
true
a44569beffef4fe1365f5b2e87eacfbba382f647
C++
aashreyj/oops-lab
/basic_classes/linked_list.cpp
UTF-8
2,961
4.03125
4
[]
no_license
#include<iostream> #include<bits/stdc++.h> using namespace std; class node { public: int data; node *link; node() //default constructor {} node(int x, node* next) //constructor with data input { data = x; link = next; } ~node() //destructor {} }; class linked_list { public: node *head; linked_list() //linked list constructor { head = NULL; } void list_add(int); void list_del(void); int search(int); void display(void); ~linked_list() //linked list destructor { while(head != NULL) { node* temp = head; head = head -> link; delete temp; } } }; void linked_list::list_add(int data) { head = new node(data, head); } void linked_list::list_del() { if(head == NULL) { cout<<"Empty list."<<endl; return; } node* temp = head; head = head -> link; delete temp; cout<<"Node deleted."<<endl<<endl; } void linked_list::display() { node *temp = head; cout<<"The current linked list is: "; while(temp != NULL) { cout<<temp -> data<<" "; temp = temp -> link; } cout<<endl<<endl; } int linked_list::search(int key) { int index = 1; node *temp = head; while(temp != NULL) { if(temp -> data == key) return index; temp = temp -> link; index++; } return -1; } int main() { int index, data, size, choice, cont; linked_list a; do { cout<<"1. Enter new list. \n2. Delete first node. \n3. Search node \n4. Display node\n\n"; cout<<"Enter choice: "; cin>>choice; switch(choice) { case 1: { cout<<"Enter the size of the linked list: "; cin>>size; for(index = 0; index < size; index++) { cout<<"Enter the data: "; cin>>data; a.list_add(data); } cout<<"List Created."<<endl<<endl; break; } case 2: { a.list_del(); a.display(); break; } case 3: { int key, index; cout<<"Enter element to be searched: "; cin>>key; index = a.search(key); if(index == -1) cout<<"Node not found."<<endl<<endl; else cout<<"Node found in the list at index "<<index<<"."<<endl<<endl; break; } case 4: { a.display(); break; } } cout<<"Do you want to continue (1/0)? "; cin>>cont; cout<<endl<<endl; } while(cont); cout<<"List will be deleted..."<<endl; return 0; }
true
2d1e711cc33c710672714c63743cc793de4aa0bc
C++
luk2010/gangtella
/serializer.cpp
UTF-8
7,770
2.53125
3
[]
no_license
/* This file is part of the GangTella project */ #include "serializer.h" GBEGIN_DECL typedef union { uint8_t data; byte_t bytes[1]; } uint8_nt; typedef union { uint16_t data; byte_t bytes[2]; } uint16_nt; typedef union { uint32_t data; byte_t bytes[4]; } uint32_nt; typedef union { size_t data; byte_t bytes[sizeof(size_t)]; } size_nt; typedef union { float data; uint32_t i; byte_t bytes[4]; struct { uint32_t mantissa : 23; uint32_t exponent : 8; uint32_t sign : 1; } parts; } float_nt; typedef union { uint64_t data; uint32_nt parts[2]; } uint64_nt; template <> uint8_nt serialize(const uint8_nt& ); template <> uint16_nt serialize(const uint16_nt&); template <> uint32_nt serialize(const uint32_nt&); template <> float_nt serialize(const float_nt& ); template <> size_nt serialize(const size_nt&); template <> uint64_nt serialize(const uint64_nt&); template <> uint8_nt deserialize(const uint8_nt&); template <> uint16_nt deserialize(const uint16_nt&); template <> uint32_nt deserialize(const uint32_nt&); template <> float_nt deserialize(const float_nt& ); template <> size_nt deserialize(const size_nt&); template <> uint64_nt deserialize(const uint64_nt&); /* ========================= uint8 =============================== */ template <> uint8_nt serialize(const uint8_nt& src) { return src; } template <> uint8_t serialize(const uint8_t& rhs) { return rhs; } template <> uint8_nt deserialize(const uint8_nt& src) { return src; } template <> uint8_t deserialize(const uint8_t& rhs) { return rhs; } /* ========================= uint16 =============================== */ template <> uint16_nt serialize(const uint16_nt& rhs) { #if __BYTE_ORDER == __LITTLE_ENDIAN uint16_nt ret; ret.bytes[1] = rhs.bytes[0]; ret.bytes[0] = rhs.bytes[1]; return ret; #else return rhs; #endif } template <> uint16_t serialize(const uint16_t& rhs) { #if __BYTE_ORDER == __LITTLE_ENDIAN return (rhs<<8) | (rhs>>8); #else return rhs; #endif } template <> uint16_nt deserialize(const uint16_nt& rhs) { #if __BYTE_ORDER == __LITTLE_ENDIAN uint16_nt ret; ret.bytes[1] = rhs.bytes[0]; ret.bytes[0] = rhs.bytes[1]; return ret; #else return rhs; #endif } template <> uint16_t deserialize(const uint16_t& rhs) { #if __BYTE_ORDER == __LITTLE_ENDIAN return (rhs<<8) | (rhs>>8); #else return rhs; #endif } /* ========================= uint32 =============================== */ template <> uint32_nt serialize(const uint32_nt& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN uint32_nt ret; ret.bytes[0] = src.bytes[3]; ret.bytes[1] = src.bytes[2]; ret.bytes[2] = src.bytes[1]; ret.bytes[3] = src.bytes[0]; return ret; #else return src; #endif // __BYTE_ORDER } template <> uint32_t serialize(const uint32_t& val) { #if __BYTE_ORDER == __LITTLE_ENDIAN return (val<<24) | ((val<<8) & 0x00ff0000) | ((val>>8) & 0x0000ff00) | (val>>24); #else return val; #endif // __BYTE_ORDER } template <> uint32_nt deserialize(const uint32_nt& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN uint32_nt ret; ret.bytes[0] = src.bytes[3]; ret.bytes[1] = src.bytes[2]; ret.bytes[2] = src.bytes[1]; ret.bytes[3] = src.bytes[0]; return ret; #else return src; #endif // __BYTE_ORDER } template <> uint32_t deserialize(const uint32_t& val) { #if __BYTE_ORDER == __LITTLE_ENDIAN return (val<<24) | ((val<<8) & 0x00ff0000) | ((val>>8) & 0x0000ff00) | (val>>24); #else return val; #endif // __BYTE_ORDER } /* ========================= uint64 =============================== */ template <> uint64_nt serialize(const uint64_nt& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN uint64_nt ret; ret.parts[0] = serialize<uint32_nt>(src.parts[1]); ret.parts[1] = serialize<uint32_nt>(src.parts[0]); return ret; #else return src; #endif // __BYTE_ORDER } template <> uint64_t serialize(const uint64_t& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN uint64_nt tmp; tmp.data = src; uint64_nt ret; ret.parts[0] = serialize<uint32_nt>(tmp.parts[1]); ret.parts[1] = serialize<uint32_nt>(tmp.parts[0]); return ret.data; #else return src; #endif // __BYTE_ORDER } template <> uint64_nt deserialize(const uint64_nt& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN uint64_nt ret; ret.parts[0] = serialize<uint32_nt>(src.parts[1]); ret.parts[1] = serialize<uint32_nt>(src.parts[0]); return ret; #else return src; #endif // __BYTE_ORDER } template <> uint64_t deserialize(const uint64_t& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN uint64_nt tmp; tmp.data = src; uint64_nt ret; ret.parts[0] = serialize<uint32_nt>(tmp.parts[1]); ret.parts[1] = serialize<uint32_nt>(tmp.parts[0]); return ret.data; #else return src; #endif // __BYTE_ORDER } /* ========================= float =============================== */ template <> float_nt serialize(const float_nt& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN float_nt ret; ret.bytes[0] = src.bytes[3]; ret.bytes[1] = src.bytes[2]; ret.bytes[2] = src.bytes[1]; ret.bytes[3] = src.bytes[0]; return ret; #else return src; #endif // __BYTE_ORDER } template <> float serialize(const float& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN float_nt tmp; tmp.data = src; float_nt ret; ret.bytes[0] = tmp.bytes[3]; ret.bytes[1] = tmp.bytes[2]; ret.bytes[2] = tmp.bytes[1]; ret.bytes[3] = tmp.bytes[0]; return ret.data; #else return src; #endif // __BYTE_ORDER } template <> float_nt deserialize(const float_nt& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN float_nt ret; ret.bytes[0] = src.bytes[3]; ret.bytes[1] = src.bytes[2]; ret.bytes[2] = src.bytes[1]; ret.bytes[3] = src.bytes[0]; return ret; #else return src; #endif // __BYTE_ORDER } template <> float deserialize(const float& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN float_nt tmp; tmp.data = src; float_nt ret; ret.bytes[0] = tmp.bytes[3]; ret.bytes[1] = tmp.bytes[2]; ret.bytes[2] = tmp.bytes[1]; ret.bytes[3] = tmp.bytes[0]; return ret.data; #else return src; #endif // __BYTE_ORDER } /* ========================= size_t =============================== */ #ifndef size_t template <> size_nt serialize(const size_nt& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN size_nt ret; for(unsigned int i = 0; i < sizeof(size_t); ++i) ret.bytes[i] = src.bytes[sizeof(size_t) - (i+1)]; return ret; #else return src; #endif // __BYTE_ORDER } template <> size_t serialize(const size_t& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN size_nt tmp; tmp.data = src; size_nt ret; for(unsigned int i = 0; i < sizeof(size_t); ++i) ret.bytes[i] = tmp.bytes[sizeof(size_t) - (i+1)]; return ret.data; #else return src; #endif // __BYTE_ORDER } template <> size_nt deserialize(const size_nt& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN size_nt ret; ret.bytes[0] = src.bytes[7]; ret.bytes[1] = src.bytes[6]; ret.bytes[2] = src.bytes[5]; ret.bytes[3] = src.bytes[4]; ret.bytes[4] = src.bytes[3]; ret.bytes[5] = src.bytes[2]; ret.bytes[6] = src.bytes[1]; ret.bytes[7] = src.bytes[0]; return ret; #else return src; #endif // __BYTE_ORDER } template <> size_t deserialize(const size_t& src) { #if __BYTE_ORDER == __LITTLE_ENDIAN size_nt tmp; tmp.data = src; size_nt ret; for(unsigned int i = 0; i < sizeof(size_t); ++i) ret.bytes[i] = tmp.bytes[sizeof(size_t) - (i+1)]; return ret.data; #else return src; #endif // __BYTE_ORDER } #endif GEND_DECL
true
aa388b649092b120fb2483785e24fb051316cb8f
C++
phyzhenli/Accelerated_Cpp
/Chapter 7/sentence/Grammar.cpp
UTF-8
444
2.828125
3
[]
no_license
#include "Grammar.h" #include "split.h" using std::vector; using std::string; using std::istream; using std::map; Grammar read_grammar(istream& in) { Grammar ret; string line; while (getline(in, line)) { vector<string> entry = split(line); if (!entry.empty()) ret[entry[0]].push_back( Rule(entry.begin() + 1, entry.end()) ); } return ret; }
true
950d5dc8c6ddc58c756d91481d2233ea01fd198f
C++
Ioni14/quoridor
/src/MainMenuState.cpp
UTF-8
4,528
2.71875
3
[]
no_license
#include "MainMenuState.h" #include <iostream> #include <memory> #include "Quoridor.h" #include "QuitState.h" #include "GameState.h" #include "GameView.h" namespace G36631 { MainMenuState::MainMenuState(Quoridor& app) : State(app), m_subState(SUB_STATE::TITLE), m_error(), m_titleEnded(false), m_waitingChoiceMenu(false), m_waitingChoicePlay(false), m_waitingChoicePlayers(false), m_waitingChoiceBoardSize(false), m_waitingChoiceSummary(false), m_nbPlayers(0), m_boardSize(0), m_playerActual(0), m_players(0) { } void MainMenuState::render() { notifyObservers(); } void MainMenuState::update() { if (m_titleEnded) { m_titleEnded = false; m_subState = SUB_STATE::MENU; } } void MainMenuState::makeChoiceMenu() { int choice = State::promptInteger(); switch (choice) { case 1: m_subState = SUB_STATE::PLAY; break; case 2: { StatePtr newState = std::make_unique<QuitState>(m_app); m_app.setState(std::move(newState)); m_app.applyNewState(); return; } break; case -1: default: m_error << "Veuillez taper 1 ou 2."; } } void MainMenuState::makeChoicePlay() { int choice = State::promptInteger(); switch (choice) { case 1: m_subState = SUB_STATE::PLAYERS; m_nbPlayers = 2; m_playerActual = 1; break; case 2: m_subState = SUB_STATE::PLAYERS; m_nbPlayers = 4; m_playerActual = 1; break; case 3: m_subState = SUB_STATE::MENU; break; default: m_error << "Veuillez taper 1, 2 ou 3."; } } void MainMenuState::makeChoicePlayers() { int choice = State::promptInteger(); switch (choice) { case 1: m_players.push_back(Player(m_playerActual++)); if (m_playerActual > m_nbPlayers) { // On a entré tous les joueurs m_subState = SUB_STATE::BOARD_SIZE; } break; case 2: m_error << "Desole, mais l'IA n'est pas encore implementee."; break; case 3: if (m_playerActual == 1) { m_subState = SUB_STATE::PLAY; } else { m_playerActual--; m_players.pop_back(); } break; case -1: default: m_error << "Veuillez taper 1, 2 ou 3."; } } void MainMenuState::makeChoiceBoardSize() { int choice = State::promptInteger(); if (choice == 0) { m_playerActual--; m_players.pop_back(); m_subState = SUB_STATE::PLAYERS; } else if (choice >= 5 && choice <= 19) { if (choice % 2 == 0) { m_error << "Veuillez entrer une taille impaire comprise entre 5 et 19."; } else { m_boardSize = choice; m_subState = SUB_STATE::SUMMARY; } } else { m_error << "Veuillez taper une valeur entre 5 et 19 ou 0."; } } void MainMenuState::makeChoiceSummary() { int choice = State::promptInteger(); switch (choice) { case 1: { auto newState = std::make_unique<GameState>(m_app, std::move(m_players), m_boardSize); auto newView = std::make_shared<GameView>(*newState); newState->addObserver(newView); m_app.setState(std::move(newState)); m_app.setView(newView); m_app.applyNewState(); return; } break; case 2: m_subState = SUB_STATE::BOARD_SIZE; break; case -1: default: m_error << "Veuillez taper 1 ou 2."; } } void MainMenuState::handleEvents() { m_error.str(""); // On vide la précédente erreur if (m_waitingChoiceMenu) { m_waitingChoiceMenu = false; makeChoiceMenu(); } else if (m_waitingChoicePlay) { m_waitingChoicePlay = false; makeChoicePlay(); } else if (m_waitingChoicePlayers) { m_waitingChoicePlayers = false; makeChoicePlayers(); } else if (m_waitingChoiceBoardSize) { m_waitingChoiceBoardSize = false; makeChoiceBoardSize(); } else if (m_waitingChoiceSummary) { m_waitingChoiceSummary = false; makeChoiceSummary(); } } }
true
e27f25224de2310703b538241f791fc2012853e9
C++
saleph/turing_machine
/include/TMStateWatcher.h
UTF-8
1,194
2.875
3
[ "MIT" ]
permissive
#ifndef TMSTATEWATCHER_H #define TMSTATEWATCHER_H #include "LazyInitializator.h" #include <memory> #include <vector> struct TMStateWatcher { TMStateWatcher() = delete; static std::shared_ptr<LazyInitializator<std::string>> alphabetAsString; static std::shared_ptr<LazyInitializator<size_t>> headPosition; static std::shared_ptr<LazyInitializator<size_t>> tapeLength; static std::shared_ptr<LazyInitializator<size_t>> tapeContentPosition; static std::shared_ptr<LazyInitializator<std::string>> tapeContent; static std::shared_ptr<LazyInitializator<std::vector<std::string>>> graphAsText; static bool prepared() { // dereference because shared_ptr contains unique_ptr with content return (*alphabetAsString && *headPosition && *tapeLength && *tapeContentPosition && *tapeContent && *graphAsText); } static void reset() { // members of StateWatcher are only pointers to unique_ptr, so -> is neccessary alphabetAsString->reset(); graphAsText->reset(); headPosition->reset(); tapeContent->reset(); tapeContentPosition->reset(); tapeLength->reset(); } }; #endif // TMSTATEWATCHER_H
true
c0c7c872695073501b402e1b6cb839efd9241601
C++
weidagang/coding
/algorithms/kth-smallest-in-tree/kth-smallest-in-tree.cpp
UTF-8
2,357
3.8125
4
[]
no_license
#include <cstdio> #include <stack> #include <queue> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; int kth_smallest_in_tree(TreeNode *root, int k) { if (NULL == root || k < 1) { return -1; } int i = 0; std::stack<TreeNode*> s; bool go_left = true; s.push(root); while (!s.empty()) { TreeNode *top = s.top(); if (go_left) { // down to the left most child TreeNode *node = top->left; while (NULL != node) { s.push(node); node = node->left; } go_left = false; } else { s.pop(); if (++i == k) { return top->val; } // visit the right branch if (NULL != top->right) { go_left = true; s.push(top->right); } } } return -1; } TreeNode* make_tree(int nodes[], int n) { if (0 == n) { return NULL; } TreeNode *root = new TreeNode(nodes[0]); std::queue<TreeNode*> q; q.push(root); int i = 1; while (!q.empty()) { TreeNode *front = q.front(); q.pop(); if (i < n && -1 != nodes[i]) { front->left = new TreeNode(nodes[i]); q.push(front->left); } ++i; if (i < n && -1 != nodes[i]) { front->right = new TreeNode(nodes[i]); q.push(front->right); } ++i; } return root; } void test(int nodes[], int n) { TreeNode *root = make_tree(nodes, n); for (int i = 0; i < n; ++i) { int val = kth_smallest_in_tree(root, i + 1); printf("%d ", val); } printf("\n"); } int main() { { int nodes[] = { 3 }; int n = sizeof(nodes)/sizeof(nodes[0]); test(nodes, n); } { int nodes[] = { 2, 1, 3 }; int n = sizeof(nodes)/sizeof(nodes[0]); test(nodes, n); } { int nodes[] = { 4, 2, 6, 1, 3, 5, 7 }; int n = sizeof(nodes)/sizeof(nodes[0]); test(nodes, n); } { int nodes[] = { 4, 2, 6, -1, 3, 5, -1 }; int n = sizeof(nodes)/sizeof(nodes[0]); test(nodes, n); } return 0; }
true
06e3712b7456af485fc6b659c44a8aac9e61cf3a
C++
marcellodash/psmame
/frontend/system/src/utility/GUI/Summerface/Summerface.cpp
UTF-8
2,797
2.578125
3
[]
no_license
#include <es_system.h> #include "Summerface.h" Summerface_Ptr Summerface::Create () { return boost::make_shared<Summerface>(); } Summerface_Ptr Summerface::Create (const std::string& aName, SummerfaceWindow_Ptr aWindow) { Summerface_Ptr sface = boost::make_shared<Summerface>(); sface->AddWindow(aName, aWindow); return sface; } bool Summerface::Draw () { uint32_t screenW = ESVideo::GetScreenWidth(); uint32_t screenH = ESVideo::GetScreenHeight(); ESVideo::SetClip(Area(0, 0, screenW, screenH)); if(BackgroundCallback && BackgroundCallback()) { Texture* tex = ImageManager::GetImage("GUIOverlay"); if(!tex) { ESVideo::FillRectangle(Area(0, 0, screenW, screenH), 0x00000080); } else { ESVideo::PlaceTexture(tex, Area(0, 0, screenW, screenH), Area(0, 0, tex->GetWidth(), tex->GetHeight()), 0xFFFFFF80); } } else { Texture* tex = ImageManager::GetImage("GUIBackground"); if(!tex) { ESVideo::FillRectangle(Area(0, 0, screenW, screenH), Colors::Border); } else { ESVideo::PlaceTexture(tex, Area(0, 0, screenW, screenH), Area(0, 0, tex->GetWidth(), tex->GetHeight()), 0xFFFFFFFF); } } for(std::map<std::string, SummerfaceWindow_Ptr>::iterator i = Windows.begin(); i != Windows.end(); i ++) { if(i->second && i->second->PrepareDraw()) { return true; } } return false; } bool Summerface::Input () { if(Windows.find(ActiveWindow) != Windows.end()) { return Windows[ActiveWindow]->Input(); } return false; } void Summerface::AddWindow (const std::string& aName, SummerfaceWindow_Ptr aWindow) { ErrorCheck(aWindow, "Summerface::AddWindow: Window is not a valid pointer. [Name: %s]", aName.c_str()); ErrorCheck(Windows.find(aName) == Windows.end(), "Summerface::AddWindow: Window with name is already present. [Name: %s]", aName.c_str()); Windows[aName] = aWindow; aWindow->SetInterface(shared_from_this(), aName); ActiveWindow = aName; } void Summerface::RemoveWindow (const std::string& aName) { ErrorCheck(Windows.find(aName) != Windows.end(), "Summerface::RemoveWindow: Window with name is not present. [Name: %s]", aName.c_str()); Windows.erase(aName); } SummerfaceWindow_Ptr Summerface::GetWindow (const std::string& aName) { ErrorCheck(Windows.find(aName) != Windows.end(), "Summerface::GetWindow: Window with name is not present. [Name: %s]", aName.c_str()); return Windows[aName]; } void Summerface::SetActiveWindow (const std::string& aName) { ErrorCheck(Windows.find(aName) != Windows.end(), "Summerface::SetActiveWindow: Window with name is not present. [Name: %s]", aName.c_str()); ActiveWindow = aName; } bool (*Summerface::BackgroundCallback) () = 0;
true
8baacc228fb271912cfc775eacb11a9bf5bdb21a
C++
namanadlakha3/30-Day-LeetCoding-Challenge
/maximized_distance_to_closest_person.cpp
UTF-8
831
2.609375
3
[]
no_license
class Solution { public: int maxDistToClosest(vector<int>& seats) { int ans=0; int flag=0; int max=0; int first=0; bool f=true; int check=0; for(int i=0;i<seats.size();i++) { if(seats[i]==1) { f=false; } if(seats[i]==0) { if(f) check++; flag++; } else { if(max<flag) { max=flag; } flag=0; } } if(flag*2-1>=max) max=flag*2-1; max=max%2==1?max/2+1:max/2; return max>check?max:check; } };
true
d5af1b70da66500fcac757201e03e757e7a5665a
C++
jmbarzee/byu-236
/lab5/Rule.h
UTF-8
750
2.75
3
[]
no_license
/* * Rule.h * * Created on: May 14, 2015 * Author: jacobmb */ #ifndef RULE_H_ #define RULE_H_ #include <string> #include <vector> #include "RefinedRule.h" #include "Predicate.h" using namespace std; class Rule { public: Rule(Predicate predicate) { this->predicate = predicate; } ~Rule() { } Predicate getHeadPredicate() { return predicate; } vector<Predicate> getPredicateList() { return predicateList; } void setPredicateList(vector<Predicate> predicateList) { this->predicateList = predicateList; } string toString(); bool isSelfDependant(); RefinedRule refine(); static vector<RefinedRule> refine(vector <Rule> rules); private: Predicate predicate; vector<Predicate> predicateList; }; #endif /* RULE_H_ */
true
5eab7130d984a1acc8c53d77480ec981631b9a57
C++
chen-assert/algorithm-code-library
/Test1/p1914.cpp
WINDOWS-1252
344
2.703125
3
[]
no_license
#include<stdio.h> #include<string.h> int a = 0; char c(char w) { int q = w; q = q + a; if (q > 'z')q -= 26; w = q; return w; } int main() { scanf("%d", &a); a = a % 26; char q[10000] = { 0 }; int p = 0; //getchar();///n scanf("%s", q); p = strlen(q); for (int i = 0; i < p; i++) { q[i] = c(q[i]); } printf("%s", q); }
true
a587c2ac8ccf59ad46bc95db97a5a93d3fb302a9
C++
habib-e/All-Problem-Solving-code-with-name
/linearSearch.cpp
UTF-8
406
2.953125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int sarch(int arr[],int m,int y) { int j; for(j=0;j<m;j++) { if(arr[j]==y) return j; } return -1; } int main() { int ar[100],n,x; scanf("%d",&n); scanf("%d",&x); for(int i=0;i<n;i++) { scanf("%d",&ar[i]); } cout<<x<<" is present at index "<<sarch(ar,n,x); }
true
9e4d3169a6bed3ae926e79c749c76f470cfcf165
C++
aktiger/C-CPP
/listreverse.cpp
UTF-8
2,582
3.671875
4
[]
no_license
/* *about: 腾讯面试,将一个单向链表逆序 *author:justinzhang *email:uestczhangchao@gmail.com *estblished:2011年4月24日16:40:25 *revised:2011年5月10日15:00:26 */ #include <iostream> using namespace std; class node { public: node * next; int data; }; node *test = NULL; node *nodereverse(node *head) { //如果一个函数的输入参数有指针,一定要记住判断指针时候为空 //1>:在使用一个指针之前一定要判断它是否为空; //2>:使用完后要释放由指针指向的存储单元 //3>:释放完存储单元后要将指针赋值为NULL; if(head->next==NULL || head==NULL) return head; node* temp1=head; node* temp2=NULL; node* temp3=head->next; temp1->next = NULL; //要注意这里面的顺序,先将temp3保存在temp2中, //然后再将temp3移动到下一个元素,然后才能改动temp2 // while(temp3->next!=NULL) { temp2 = temp3; temp3 = temp3->next; temp2->next = temp1;//不能再temp3= temp3->next;之前执行 temp1 = temp2; } temp3->next = temp2; return temp3; } void initnode() { node * tmp = NULL; for(int i=0; i<4; i++) { tmp = new node; tmp->data = i; tmp->next = test; test = tmp; } } void display(node *nn) { if(nn==NULL) { cout << "no data to display\n"; return ; } node *dis = nn; while(dis!=NULL) { cout << dis->data << endl; dis = dis->next; } } //释放动态申请的空间 void distroy(node *nn) { if (nn==NULL) { return ; } while (nn!=NULL) { node *tmp = nn; nn = nn->next; delete tmp; } } int main() { initnode(); display(test); cout << "**************" << endl; node *tmp = nodereverse(test); if(test==NULL) exit(0); display(tmp); //tmp和test指向的存储空间已经使用完毕,应该释放掉他们申请的空间! //并且,要将他们赋值为NULL,否则他们将成为野指针!!!!,一定要注意了~~ distroy(tmp);//释放动态申请的内存 tmp = NULL;//将他们重新赋值为NULL,不然就会成为野指针~~~~~ test = NULL; cout << "tmp= " << tmp << endl; //如果上面没有tmp = NULL;test = NULL;,display将会出错, //因为在display开始的时候判断传入的参数是否为NULL,如果不把野指针赋值为NULL, //那么判断就没有效果,会继续指向display中的while语句,而此时指针所指向的存储空间已经被释放掉了, //这样就会出现异常. display(test); system("pause"); return 0; }
true
bc7bb6e373b0a2ca88834e72a4d6d619723bc993
C++
alexey3nemckovich/ObjectsDetector
/ObjectsDetecter/ImageProcesser.h
UTF-8
729
2.546875
3
[]
no_license
#pragma once #include <map> #include "cvUtilities.h" using namespace cvutils; class ImageProcesser { public: static ImageProcesser& GetInstance(); enum class ObjectsClassifyingAlgorithmName { Alg1, Alg2, Alg3 }; public: ImageProcesser(); public: const ImageProcessResult& ProcessImage(cv::Mat&); void SetImageProcessingAlgorithm(ObjectsClassifyingAlgorithmName); public: const ImageProcessResult& GetLastImageProcessResult() const; private: ImageProcessResult _lastImageProcessingResult; ObjectsClassifyingAlgorithm _objectsClassifyingAlgorithm; std::map<ObjectsClassifyingAlgorithmName, ObjectsClassifyingAlgorithm> _objectsClassifyingAlgorithmsMap; };
true
e3c7978e3b97e6b539dfa5914f2c18897a34382c
C++
jianmingwu/leetcode
/countAndSay/countAndSay.cpp
UTF-8
951
3.421875
3
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; class Solution { public: string countAndSay(int n) { vector<string> vs(2); int i, j; vs[0] = "1"; for (i = 1; i < n; ++i) { int pidx = (i - 1) & 1; for (j = 0; j < vs[pidx].size(); ++j) { int cnt = 1; while (j + 1 < vs[pidx].size() && vs[pidx][j] == vs[pidx][j + 1]) { ++j; ++cnt; } vs[1 - pidx].push_back('0' + cnt); vs[1 - pidx].push_back(vs[pidx][j]); } vs[pidx].clear(); } return vs[(n - 1) & 1]; } }; int main() { Solution s; cout << s.countAndSay(1) << endl; cout << s.countAndSay(2) << endl; cout << s.countAndSay(3) << endl; cout << s.countAndSay(4) << endl; cout << s.countAndSay(5) << endl; return 0; }
true
5749a70a3ac187ae4b97946c90b3139d37ed0b9f
C++
Vaskka/mysql_interface
/queryset.cpp
UTF-8
585
2.84375
3
[]
no_license
#include "queryset.h" #include <string> #include <sstream> using namespace std; QuerySet::QuerySet() { } string QuerySet::operator[](string key) { return this->dict[key]; } // 设置queryset void QuerySet::setValue(string key, string value) { this->dict[key] = value; } void QuerySet::setValue(string key, int value) { stringstream ss; string s; ss << value; ss >> s; this->dict[key] = s; } // 查找queryset string QuerySet::findValue(string key) { return this->dict[key]; } map<string, string> QuerySet::getDict() const { return dict; }
true
a225b5f58678da6a9b12cb8c4b565d98aaa36020
C++
kevinsala/HealthProject
/Arduino/main/libraries/Bluetooth/Bluetooth.cpp
UTF-8
2,746
3.015625
3
[]
no_license
/* Bluetooth.cpp - Library for Bluetooth device. Created by Kevin Sala & Oriol Torrillas. */ #include "Bluetooth.h" #include "Arduino.h" #include <string.h> #include <assert.h> Bluetooth::Bluetooth() : ss(RX_PIN, TX_PIN) {} void Bluetooth::setup() { ss.begin(9600); } int Bluetooth::getAction() { if (ss.available() >= 4 && ss.read() == 'M') { int functionality = ss.read() - '0'; int msgType = ss.read() - '0'; assert(ss.read() == 'X'); Serial.print("MSG: Func: "); Serial.print(functionality); Serial.print(", Type: "); Serial.println(msgType); if (msgType == END_MSG) return STOP_ACTION; else return functionality; } return CONTINUE_ACTION; } void Bluetooth::sendData(int functionality, double data, bool finished) { /* The message starts with an 'M' */ String msg = String('M'); /* Converts the data to string */ String strData = String(data, 3); /* Adds the size of the message (2 digits, max size: 99) */ int size = strData.length() + 4; if (size < 10) msg.concat("0"); msg.concat(size); /* Adds the functionality */ msg.concat(functionality); /* Adds the type of the message */ if (finished) msg.concat(DATA_END_MSG); else msg.concat(DATA_MSG); /* Adds the data field */ msg.concat(strData); /* Adds a separator */ msg.concat('!'); /* Adds the final mark of the message */ msg.concat('X'); /* Sends the message */ char msgCharArray[msg.length() + 1]; msg.toCharArray(msgCharArray, msg.length() + 1); Serial.println(msgCharArray); if (ss.write(msgCharArray) != msg.length()) Serial.println("Message sent not correctly"); } void Bluetooth::send2Data(int functionality, double data1, double data2, bool finished) { /* The message starts with an 'M' */ String msg = String('M'); /* Converts the data to string */ String strData1 = String(data1, 3); String strData2 = String(data2, 3); /* Adds the size of the message (2 digits, max size: 99) */ int size = strData1.length() + strData2.length() + 4; if (size < 10) msg.concat("0"); msg.concat(size); /* Adds the functionality */ msg.concat(functionality); /* Adds the type of the message */ if (finished) msg.concat(DATA_END_MSG); else msg.concat(DATA_MSG); /* Adds the data field */ msg.concat(strData1); /* Adds a separator */ msg.concat('!'); /* Adds the data field */ msg.concat(strData2); /* Adds the final mark of the message */ msg.concat('X'); /* Sends the message */ char msgCharArray[msg.length() + 1]; msg.toCharArray(msgCharArray, msg.length() + 1); Serial.println(msgCharArray); if (ss.write(msgCharArray) != msg.length()) Serial.println("Message sent not correctly"); } void Bluetooth::print(char * msg) { ss.println(msg); } void Bluetooth::print(int msg) { ss.println(msg); }
true
81e89c0d2878bfdb0264eb87e46717a2a4e2ade2
C++
Jassy930/leetcode_main
/500.键盘行.cpp
UTF-8
1,901
3.1875
3
[]
no_license
/* * @lc app=leetcode.cn id=500 lang=cpp * * [500] 键盘行 * * https://leetcode-cn.com/problems/keyboard-row/description/ * * algorithms * Easy (64.75%) * Total Accepted: 5.6K * Total Submissions: 8.6K * Testcase Example: '["Hello","Alaska","Dad","Peace"]' * * 给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。 * * * * * * * * 示例: * * 输入: ["Hello", "Alaska", "Dad", "Peace"] * 输出: ["Alaska", "Dad"] * * * * * 注意: * * * 你可以重复使用键盘上同一字符。 * 你可以假设输入的字符串将只包含字母。 * */ class Solution { public: vector<string> findWords(vector<string>& words) { vector<string> out; map<char,int> keymap; keymap['q']=0; keymap['w']=0; keymap['e']=0; keymap['r']=0; keymap['t']=0; keymap['y']=0; keymap['u']=0; keymap['i']=0; keymap['o']=0; keymap['p']=0; keymap['a']=1; keymap['s']=1; keymap['d']=1; keymap['f']=1; keymap['g']=1; keymap['h']=1; keymap['j']=1; keymap['k']=1; keymap['l']=1; keymap['z']=2; keymap['x']=2; keymap['c']=2; keymap['v']=2; keymap['b']=2; keymap['n']=2; keymap['m']=2; for(int i=0; i<words.size(); i++) { int m = keymap[(words.at(i).at(0)<'a'?words.at(i).at(0)+32:words.at(i).at(0))]; int n = 0; for(int k=0; k<words.at(i).size(); k++) { char q = words.at(i).at(k); if (q<'a') q+=32; cout<<keymap[q]; if(keymap[q] != m) n++; } if(n == 0) out.push_back(words.at(i)); } return out; } };
true
02532a68b920eb54c2689e0b47d3973ca8a96161
C++
fmidev/smartmet-library-calculator
/calculator/NullPeriodGenerator.cpp
WINDOWS-1252
2,749
2.984375
3
[ "MIT" ]
permissive
// ====================================================================== /*! * \file * \brief Implementation of class TextGen::NullPeriodGenerator */ // ====================================================================== /*! * \class TextGen::NullPeriodGenerator * * \brief Generates a sequence of periods * * This class always returns the main period as is. */ // ---------------------------------------------------------------------- // boost included laitettava ennen newbase:n NFmiGlobals-includea, // muuten MSVC:ss min max mrittelyt jo tehty #include "NullPeriodGenerator.h" #include "TextGenError.h" #include <macgyver/StringConversion.h> namespace TextGen { // ---------------------------------------------------------------------- /*! * \brief Constructor * * \param theMainPeriod The period to iterate */ // ---------------------------------------------------------------------- NullPeriodGenerator::NullPeriodGenerator(WeatherPeriod theMainPeriod) : itsMainPeriod(std::move(theMainPeriod)) { } // ---------------------------------------------------------------------- /*! * \brief Test if the period is undivided * * \return Always true, null period is the original one */ // ---------------------------------------------------------------------- bool NullPeriodGenerator::undivided() const { return true; } // ---------------------------------------------------------------------- /*! * \brief Return the number of subperiods * * \return The number of subperiods (always 1) */ // ---------------------------------------------------------------------- NullPeriodGenerator::size_type NullPeriodGenerator::size() const { return 1; } // ---------------------------------------------------------------------- /*! * \brief Return the minimal period covered by the generator * * \return The minimal period */ // ---------------------------------------------------------------------- WeatherPeriod NullPeriodGenerator::period() const { return itsMainPeriod; } // ---------------------------------------------------------------------- /*! *\brief Return the desired subperiod * * Throws if anything but the first period is requested, since by * definition there is always exactly 1 subperiod. * * \param thePeriod The index of the subperiod * \return The subperiod */ // ---------------------------------------------------------------------- WeatherPeriod NullPeriodGenerator::period(size_type thePeriod) const { if (thePeriod == 1) return itsMainPeriod; const std::string msg = ("NullPeriodGenerator cannot return period " + Fmi::to_string(thePeriod)); throw TextGenError(msg); } } // namespace TextGen // ======================================================================
true
9ef959a8b3fa63974c3dd66f8f7f183dc4aa82eb
C++
mathnogueira/mips
/include/mips/instructions/format_III/lcl.hpp
UTF-8
813
3.265625
3
[ "MIT" ]
permissive
/** * \file lcl.hpp * * Instrução que carrega uma constante com sinal no bit menos significativo * do registrador. */ #pragma once #include <mips/instructions/instruction_III.hpp> namespace MIPS { /** * Instrução utilizada para carregar 8 bits e carregá-los em um no bit menos * significativo do registrador definido pelo programador. * * \author Matheus Nogueira */ class LclInstruction : public InstructionIII { public: /** * Cria uma instrução de lhc. * * \param opcode código da operação * \param rd registrador de destino * \param offset offset de 11 bits */ LclInstruction(bit8_t opcode, Register *rd, bit8_t offset) : InstructionIII(opcode, rd, offset) {} /** * Executa a instrução. * * \return resultado da operação */ bit16_t execute(); }; } // namespace
true
832f294483e68f8596c3be833f2048acc2a74ac8
C++
robotology/idyntree
/src/core/src/SparseMatrix.cpp
UTF-8
30,812
2.578125
3
[ "BSD-3-Clause" ]
permissive
// SPDX-FileCopyrightText: Fondazione Istituto Italiano di Tecnologia (IIT) // SPDX-License-Identifier: BSD-3-Clause #include "SparseMatrix.h" #include "Triplets.h" #include <cassert> #include <sstream> #include <algorithm> #include <vector> #include <queue> #include <cstring> #include <iterator> #ifndef UNUSED #define UNUSED(x) (void)(sizeof((x), 0)) #endif namespace iDynTree { // MARK: - generic SparseMatrix implementation template <iDynTree::MatrixStorageOrdering ordering> SparseMatrix<ordering>::SparseMatrix() : SparseMatrix(0, 0) {} template <iDynTree::MatrixStorageOrdering ordering> SparseMatrix<ordering>::SparseMatrix(std::size_t rows, std::size_t cols) : SparseMatrix(rows, cols, iDynTree::VectorDynSize()) { } template <iDynTree::MatrixStorageOrdering ordering> void SparseMatrix<ordering>::initializeMatrix(std::size_t outerSize, const double* vector, std::size_t vectorSize) { m_outerStarts.assign(outerSize + 1, 0); for (std::size_t i = 0; i < vectorSize; ++i) { m_allocatedSize += vector[i]; } m_values.reserve(m_allocatedSize); // Inner indeces has same size of values m_innerIndices.reserve(m_allocatedSize); } template <iDynTree::MatrixStorageOrdering ordering> SparseMatrix<ordering>::~SparseMatrix() {} template <iDynTree::MatrixStorageOrdering ordering> template <iDynTree::MatrixStorageOrdering otherOrdering> SparseMatrix<ordering>::SparseMatrix(const SparseMatrix<otherOrdering>& other) : m_values(other.m_values) , m_innerIndices(other.m_innerIndices) , m_outerStarts(other.m_outerStarts) , m_allocatedSize(other.m_allocatedSize) , m_rows(other.m_rows) , m_columns(other.m_columns) {} template <iDynTree::MatrixStorageOrdering ordering> std::size_t SparseMatrix<ordering>::numberOfNonZeros() const { return m_values.size(); } template <iDynTree::MatrixStorageOrdering ordering> template <iDynTree::MatrixStorageOrdering otherOrdering> SparseMatrix<ordering>& SparseMatrix<ordering>::operator=(const SparseMatrix<otherOrdering>& other) { if (this == &other) return *this; m_values = other.m_values; m_innerIndices = other.m_innerIndices; m_outerStarts = other.m_outerStarts; m_allocatedSize = other.m_allocatedSize; m_rows = other.m_rows; m_columns = other.m_columns; return *this; } template <iDynTree::MatrixStorageOrdering ordering> void SparseMatrix<ordering>::resize(std::size_t rows, std::size_t columns) { VectorDynSize empty; //this does not allocate memory resize(rows, columns, empty); } template <iDynTree::MatrixStorageOrdering ordering> void SparseMatrix<ordering>::reserve(std::size_t nonZeroElements) { if (nonZeroElements <= m_allocatedSize) return; //do nothing m_values.reserve(nonZeroElements); m_innerIndices.reserve(nonZeroElements); m_allocatedSize = nonZeroElements; } template <iDynTree::MatrixStorageOrdering ordering> void SparseMatrix<ordering>::zero() { //zero: simply clear m_values.resize(0); m_innerIndices.resize(0); m_outerStarts.assign(m_outerStarts.size(), 0); } template <MatrixStorageOrdering ordering> bool SparseMatrix<ordering>::valueIndexForOuterAndInnerIndices(std::size_t outerIndex, std::size_t innerIndex, std::size_t& valueIndex) const { //We can use std::lower_bound to between rowNZIndex and rowNZIndex + rowNNZ //They are already sorted. The only critical point is if we have -1 in the matrix //Which right now it does not apply int outerBegin = m_outerStarts[outerIndex]; int outerEnd = m_outerStarts[outerIndex + 1]; std::vector<int>::const_iterator innerVectorBegin = m_innerIndices.begin(); //initialize the return value to be the first element of the row valueIndex = outerBegin; if (outerEnd - outerBegin == 0) { //empty block, avoid searching return false; } std::vector<int>::const_iterator foundIndex = std::lower_bound(innerVectorBegin + outerBegin, innerVectorBegin + outerEnd, innerIndex); //Compute the index of the first element next or equal to the one we //were looking for valueIndex = std::distance(innerVectorBegin, foundIndex); if (foundIndex == innerVectorBegin + outerEnd) { //not found //return the index of the last element of the row //as we have to put the element as last element return false; } if (*foundIndex >= 0 && static_cast<std::size_t>(*foundIndex) == innerIndex) { //found return true; } return false; } template <iDynTree::MatrixStorageOrdering ordering> std::size_t SparseMatrix<ordering>::insert(std::size_t outerIndex, std::size_t innerIndex, double value) { //first: check if there is space in the arrays if (m_allocatedSize <= m_values.size()) { reserve(m_values.size() + 10); } //find insertion position std::size_t insertionIndex = 0; if (valueIndexForOuterAndInnerIndices(outerIndex, innerIndex, insertionIndex)) { //???: what if the element exists alredy in the matrix? return insertionIndex; } //I found the index. Now I have to shift to the right the values and inner elements m_values.resize(m_values.size() + 1); m_innerIndices.resize(m_innerIndices.size() + 1); for (std::size_t i = m_values.size() - 1; i > insertionIndex && i > 0; --i) { m_values(i) = m_values(i - 1); m_innerIndices[i] = m_innerIndices[i - 1]; } m_values(insertionIndex) = value; m_innerIndices[insertionIndex] = innerIndex; //update row NNZ for (std::size_t nextOuterIndex = outerIndex; nextOuterIndex < m_outerStarts.size() - 1; ++nextOuterIndex) { m_outerStarts[nextOuterIndex + 1]++; } return insertionIndex; } template <iDynTree::MatrixStorageOrdering ordering> void SparseMatrix<ordering>::setFromConstTriplets(const iDynTree::Triplets& triplets) { iDynTree::Triplets copy(triplets); setFromTriplets(copy); } template <iDynTree::MatrixStorageOrdering ordering> SparseMatrix<ordering> SparseMatrix<ordering>::sparseMatrixFromTriplets(std::size_t rows, std::size_t cols, const iDynTree::Triplets& nonZeroElements) { SparseMatrix newMatrix(rows, cols); newMatrix.setFromConstTriplets(nonZeroElements); return newMatrix; } template <iDynTree::MatrixStorageOrdering ordering> std::size_t SparseMatrix<ordering>::rows() const { return m_rows; } template <iDynTree::MatrixStorageOrdering ordering> std::size_t SparseMatrix<ordering>::columns() const { return m_columns; } template <iDynTree::MatrixStorageOrdering ordering> double * SparseMatrix<ordering>::valuesBuffer() { return m_values.data(); } template <iDynTree::MatrixStorageOrdering ordering> double const * SparseMatrix<ordering>::valuesBuffer() const { return m_values.data(); } template <iDynTree::MatrixStorageOrdering ordering> int * SparseMatrix<ordering>::innerIndicesBuffer() { return m_innerIndices.data(); } template <iDynTree::MatrixStorageOrdering ordering> int const * SparseMatrix<ordering>::innerIndicesBuffer() const { return m_innerIndices.data(); } template <iDynTree::MatrixStorageOrdering ordering> int * SparseMatrix<ordering>::outerIndicesBuffer() { return m_outerStarts.data(); } template <iDynTree::MatrixStorageOrdering ordering> int const * SparseMatrix<ordering>::outerIndicesBuffer() const { return m_outerStarts.data(); } template <iDynTree::MatrixStorageOrdering ordering> std::string SparseMatrix<ordering>::description(bool fullMatrix) const { std::ostringstream stream; if (!fullMatrix) { for (const_iterator it = begin(); it != end(); ++it) { stream << it->value << "(" << it->row << ", " << it->column << ") "; } } else { for (std::size_t row = 0; row < rows(); ++row) { for (std::size_t col = 0; col < columns(); ++col) { stream << this->operator()(row, col) << " "; } stream << std::endl; } } return stream.str(); } #ifndef NDEBUG template <iDynTree::MatrixStorageOrdering ordering> std::string SparseMatrix<ordering>::internalDescription() const { std::ostringstream stream; stream << "Values: \n"; for (std::size_t i = 0; i < m_values.size(); ++i) { stream << m_values(i) << " "; } stream << "\nInner indices: \n"; for (std::size_t i = 0; i < m_values.size(); ++i) { stream << m_innerIndices[i] << " "; } stream << "\nOuter indices: \n"; for (std::size_t i = 0; i < m_rows + 1; ++i) { stream << m_outerStarts[i] << " "; } stream << "\n"; return stream.str(); } #endif template <iDynTree::MatrixStorageOrdering ordering> typename SparseMatrix<ordering>::iterator SparseMatrix<ordering>::begin() { return iterator(*this); } template <iDynTree::MatrixStorageOrdering ordering> typename SparseMatrix<ordering>::const_iterator SparseMatrix<ordering>::begin() const { return const_iterator(*this); } template <iDynTree::MatrixStorageOrdering ordering> typename SparseMatrix<ordering>::iterator SparseMatrix<ordering>::end() { iterator it(*this, false); (&it)->m_index = -1; return it; } template <iDynTree::MatrixStorageOrdering ordering> typename SparseMatrix<ordering>::const_iterator SparseMatrix<ordering>::end() const { const_iterator it(*this, false); (&it)->m_index = -1; return it; } // MARK: - Row-Major implementation template <> SparseMatrix<iDynTree::RowMajor>::SparseMatrix(std::size_t rows, std::size_t cols, const iDynTree::VectorDynSize& memoryReserveDescription) : m_allocatedSize(0) , m_rows(rows) , m_columns(cols) { initializeMatrix(rows, memoryReserveDescription.data(), memoryReserveDescription.size()); } template <> double SparseMatrix<iDynTree::RowMajor>::operator()(std::size_t row, std::size_t col) const { assert(row >= 0 && row < rows() && col >= 0 && col < columns()); std::size_t index = 0; double value = 0; if (valueIndexForOuterAndInnerIndices(row, col, index)) { value = m_values(index); } return value; } template <> double& SparseMatrix<iDynTree::RowMajor>::operator()(std::size_t row, std::size_t col) { assert(row >= 0 && row < rows() && col >= 0 && col < columns()); std::size_t index = 0; if (valueIndexForOuterAndInnerIndices(row, col, index)) { return m_values(index); } else { return m_values(insert(row, col, 0)); } } template <> void SparseMatrix<iDynTree::RowMajor>::resize(std::size_t rows, std::size_t columns, const iDynTree::VectorDynSize &columnNNZInformation) { //Avoid destroying the matrix if the size is the same if (m_rows == rows && m_columns == columns) return; m_rows = rows; m_columns = columns; initializeMatrix(rows, columnNNZInformation.data(), columnNNZInformation.size()); } template <> void SparseMatrix<iDynTree::RowMajor>::setFromTriplets(iDynTree::Triplets& triplets) { if (triplets.size() == 0) return; //Get number of NZ and reserve buffers O(1) : size of compressed vector //We can overestimate with the size of triplets reserve(triplets.size()); //Fastest way is to order by row and column N*log2(N) std::sort(triplets.begin(), triplets.end(), Triplet::rowMajorCompare); //now is a simple insert O(N) + //find to remove duplicates //Note: find is useless if array is sorted //Resize to maximum value. Will shrink at the end m_values.resize(triplets.size()); m_innerIndices.resize(triplets.size()); m_outerStarts.assign(m_rows + 1, 0); //reset vector std::size_t lastRow = 0; std::size_t lastColumn = 0; std::size_t innerIndex = 0; std::size_t lastIndex = innerIndex; m_values(0) = 0; //initialize the first element for (std::vector<Triplet>::const_iterator iterator(triplets.begin()); iterator != triplets.end(); ++iterator) { // As triplets are ordered, only subsequent elements can be equal if (lastRow == iterator->row && lastColumn == iterator->column) { //Adjust for the first element //this should happen only the first time m_values(lastIndex) += iterator->value; //innerIndex should point to the next element //If the next element is at the same position, innerIndex will be ignored, //otherwise it will point to the next (free) element innerIndex = lastIndex + 1; continue; } //if current row is different from lastRow //I have to update the outerStarts vector if (lastRow != iterator->row) { for (std::vector<int>::iterator outerIt(m_outerStarts.begin() + lastRow + 1); outerIt <= m_outerStarts.begin() + iterator->row; ++outerIt) { *outerIt = innerIndex; } lastRow = iterator->row; } m_values(innerIndex) = iterator->value; m_innerIndices[innerIndex] = iterator->column; lastIndex = innerIndex; //increment index as this should always point to the next element ++innerIndex; lastColumn = iterator->column; } if (lastRow < m_rows) { for (std::vector<int>::iterator outerIt(m_outerStarts.begin() + lastRow + 1); outerIt < m_outerStarts.end(); ++outerIt) { *outerIt = innerIndex; } } //Shrink containers m_values.resize(innerIndex); m_innerIndices.resize(innerIndex); } template <> template <> SparseMatrix<iDynTree::RowMajor>::SparseMatrix(const SparseMatrix<iDynTree::ColumnMajor>& other) : m_allocatedSize(0) , m_rows(other.rows()) , m_columns(other.columns()) { iDynTree::Triplets oldTriplets; oldTriplets.reserve(other.numberOfNonZeros()); oldTriplets.addSubMatrix(0, 0, other); setFromTriplets(oldTriplets); } template <> template <> SparseMatrix<iDynTree::RowMajor>& SparseMatrix<iDynTree::RowMajor>::operator=(const SparseMatrix<iDynTree::ColumnMajor>& other) { resize(other.rows(), other.columns()); iDynTree::Triplets oldTriplets; oldTriplets.reserve(other.numberOfNonZeros()); oldTriplets.addSubMatrix(0, 0, other); setFromTriplets(oldTriplets); return *this; } // MARK: - Column-Major implementation template <> SparseMatrix<iDynTree::ColumnMajor>::SparseMatrix(std::size_t rows, std::size_t cols, const iDynTree::VectorDynSize& memoryReserveDescription) : m_allocatedSize(0) , m_rows(rows) , m_columns(cols) { initializeMatrix(cols, memoryReserveDescription.data(), memoryReserveDescription.size()); } template <> double SparseMatrix<iDynTree::ColumnMajor>::operator()(std::size_t row, std::size_t col) const { assert(row >= 0 && row < rows() && col >= 0 && col < columns()); std::size_t index = 0; double value = 0; if (valueIndexForOuterAndInnerIndices(col, row, index)) { value = m_values(index); } return value; } template <> double& SparseMatrix<iDynTree::ColumnMajor>::operator()(std::size_t row, std::size_t col) { assert(row >= 0 && row < rows() && col >= 0 && col < columns()); std::size_t index = 0; if (valueIndexForOuterAndInnerIndices(col, row, index)) { return m_values(index); } else { return m_values(insert(col, row, 0)); } } template <> void SparseMatrix<iDynTree::ColumnMajor>::resize(std::size_t rows, std::size_t columns, const iDynTree::VectorDynSize &columnNNZInformation) { //Avoid destroying the matrix if the size is the same if (m_rows == rows && m_columns == columns) return; m_rows = rows; m_columns = columns; initializeMatrix(columns, columnNNZInformation.data(), columnNNZInformation.size()); } template <> void SparseMatrix<iDynTree::ColumnMajor>::setFromTriplets(iDynTree::Triplets& triplets) { if (triplets.size() == 0) return; //Get number of NZ and reserve buffers O(1) : size of compressed vector //We can overestimate with the size of triplets reserve(triplets.size()); //Fastest way is to order by row and column N*log2(N) std::sort(triplets.begin(), triplets.end(), Triplet::columnMajorCompare); //now is a simple insert O(N) + //find to remove duplicates //Note: find is useless if array is sorted //Resize to maximum value. Will shrink at the end m_values.resize(triplets.size()); m_innerIndices.resize(triplets.size()); m_outerStarts.assign(m_columns + 1, 0); //reset vector std::size_t lastRow = 0; std::size_t lastColumn = 0; std::size_t innerIndex = 0; std::size_t lastIndex = innerIndex; m_values(0) = 0; //initialize the first element for (std::vector<Triplet>::const_iterator iterator(triplets.begin()); iterator != triplets.end(); ++iterator) { // As triplets are ordered, only subsequent elements can be equal if (lastRow == iterator->row && lastColumn == iterator->column) { //Adjust for the first element //this should happen only the first time m_values(lastIndex) += iterator->value; //innerIndex should point to the next element //If the next element is at the same position, innerIndex will be ignored, //otherwise it will point to the next (free) element innerIndex = lastIndex + 1; continue; } //if current row is different from lastRow //I have to update the outerStarts vector if (lastColumn != iterator->column) { for (std::vector<int>::iterator outerIt(m_outerStarts.begin() + lastColumn + 1); outerIt <= m_outerStarts.begin() + iterator->column; ++outerIt) { *outerIt = innerIndex; } lastColumn = iterator->column; } m_values(innerIndex) = iterator->value; m_innerIndices[innerIndex] = iterator->row; lastIndex = innerIndex; //increment index as this should always point to the next element ++innerIndex; lastRow = iterator->row; } if (lastColumn < m_columns) { for (std::vector<int>::iterator outerIt(m_outerStarts.begin() + lastColumn + 1); outerIt < m_outerStarts.end(); ++outerIt) { *outerIt = innerIndex; } } //Shrink containers m_values.resize(innerIndex); m_innerIndices.resize(innerIndex); } template <> template <> SparseMatrix<iDynTree::ColumnMajor>::SparseMatrix(const SparseMatrix<iDynTree::RowMajor>& other) : m_allocatedSize(0) , m_rows(other.rows()) , m_columns(other.columns()) { iDynTree::Triplets oldTriplets; oldTriplets.reserve(other.numberOfNonZeros()); oldTriplets.addSubMatrix(0, 0, other); setFromTriplets(oldTriplets); } template <> template <> SparseMatrix<iDynTree::ColumnMajor>& SparseMatrix<iDynTree::ColumnMajor>::operator=(const SparseMatrix<iDynTree::RowMajor>& other) { resize(other.rows(), other.columns()); iDynTree::Triplets oldTriplets; oldTriplets.reserve(other.numberOfNonZeros()); oldTriplets.addSubMatrix(0, 0, other); setFromTriplets(oldTriplets); return *this; } // MARK: - Iterator implementation template <iDynTree::MatrixStorageOrdering ordering> SparseMatrix<ordering>::Iterator::TripletRef::TripletRef(std::size_t row, std::size_t column, double *value) : m_row(row) , m_column(column) , m_value(value) {} template <iDynTree::MatrixStorageOrdering ordering> SparseMatrix<ordering>::Iterator::Iterator(iDynTree::SparseMatrix<ordering> &matrix, bool valid) : m_matrix(matrix) , m_index(-1) , m_currentTriplet(-1, -1, 0) , m_nonZerosInOuterDirection(1) //to initialize the counter { if (matrix.m_values.size() == 0 || !valid) return; m_index = 0; updateTriplet(); } template <iDynTree::MatrixStorageOrdering ordering> void SparseMatrix<ordering>::Iterator::updateTriplet() { assert(false); } template <iDynTree::MatrixStorageOrdering ordering> typename SparseMatrix<ordering>::Iterator& SparseMatrix<ordering>::Iterator::operator++() { if (m_index < 0) { //Iterator is not valid. We do nothing return *this; } m_index++; if (static_cast<std::size_t>(m_index) >= m_matrix.m_values.size()) { //Out of range m_index = -1; } else { updateTriplet(); } return *this; } template <iDynTree::MatrixStorageOrdering ordering> typename SparseMatrix<ordering>::Iterator SparseMatrix<ordering>::Iterator::operator++(int) { if (m_index < 0) { //Iterator is not valid. We do nothing return *this; } Iterator newIterator(*this); ++newIterator; return newIterator; } template <iDynTree::MatrixStorageOrdering ordering> bool SparseMatrix<ordering>::Iterator::operator==(const Iterator &it) const { return &m_matrix == &((&it)->m_matrix) //check that we are pointing to the same matrix && m_index == it.m_index; } template <iDynTree::MatrixStorageOrdering ordering> bool SparseMatrix<ordering>::Iterator::operator==(const ConstIterator &it) const { return &m_matrix == &((&it)->m_matrix) //check that we are pointing to the same matrix && m_index == it.m_index; } template <iDynTree::MatrixStorageOrdering ordering> typename SparseMatrix<ordering>::Iterator::reference SparseMatrix<ordering>::Iterator::operator*() { return m_currentTriplet; } template <iDynTree::MatrixStorageOrdering ordering> typename SparseMatrix<ordering>::Iterator::pointer SparseMatrix<ordering>::Iterator::operator->() { return &m_currentTriplet; } template <iDynTree::MatrixStorageOrdering ordering> bool SparseMatrix<ordering>::Iterator::isValid() const { return m_index >= 0 && true; //TODO: check if we are < than end or >= begin } template <> void SparseMatrix<iDynTree::RowMajor>::Iterator::updateTriplet() { m_currentTriplet.m_value = &(m_matrix.m_values(m_index)); m_currentTriplet.m_column = m_matrix.m_innerIndices[m_index]; if (--m_nonZerosInOuterDirection <= 0) { //increment row m_currentTriplet.m_row++; while (static_cast<std::size_t>(m_currentTriplet.m_row) < m_matrix.rows()) { //compute row NNZ m_nonZerosInOuterDirection = m_matrix.m_outerStarts[m_currentTriplet.m_row + 1] - m_matrix.m_outerStarts[m_currentTriplet.m_row]; if (m_nonZerosInOuterDirection > 0) break; //increment row m_currentTriplet.m_row++; } } } template <> void SparseMatrix<iDynTree::ColumnMajor>::Iterator::updateTriplet() { m_currentTriplet.m_value = &(m_matrix.m_values(m_index)); m_currentTriplet.m_row = m_matrix.m_innerIndices[m_index]; if (--m_nonZerosInOuterDirection <= 0) { m_currentTriplet.m_column++; while (static_cast<std::size_t>(m_currentTriplet.m_column) < m_matrix.columns()) { //compute row NNZ m_nonZerosInOuterDirection = m_matrix.m_outerStarts[m_currentTriplet.m_column + 1] - m_matrix.m_outerStarts[m_currentTriplet.m_column]; if (m_nonZerosInOuterDirection > 0) break; //increment row m_currentTriplet.m_column++; } } } template <iDynTree::MatrixStorageOrdering ordering> SparseMatrix<ordering>::ConstIterator::ConstIterator(const iDynTree::SparseMatrix<ordering> &matrix, bool valid) : m_matrix(matrix) , m_index(-1) , m_currentTriplet(-1, -1, 0) , m_nonZerosInOuterDirection(1) //to initialize the counter { if (matrix.m_values.size() == 0 || !valid) return; m_index = 0; updateTriplet(); } template <iDynTree::MatrixStorageOrdering ordering> SparseMatrix<ordering>::ConstIterator::ConstIterator(const typename SparseMatrix<ordering>::Iterator& iterator) : m_matrix(iterator.m_matrix) , m_index(iterator.m_index) , m_currentTriplet(iterator.m_currentTriplet.row(), iterator.m_currentTriplet.column(), iterator.isValid() ? iterator.m_currentTriplet.value() : 0) , m_nonZerosInOuterDirection(iterator.m_nonZerosInOuterDirection) { } template <iDynTree::MatrixStorageOrdering ordering> void SparseMatrix<ordering>::ConstIterator::updateTriplet() { assert(false); } template <> void SparseMatrix<iDynTree::RowMajor>::ConstIterator::updateTriplet() { m_currentTriplet.value = m_matrix.m_values(m_index); m_currentTriplet.column = m_matrix.m_innerIndices[m_index]; if (--m_nonZerosInOuterDirection <= 0) { //increment row m_currentTriplet.row++; while (static_cast<std::size_t>(m_currentTriplet.row) < m_matrix.rows()) { //compute row NNZ m_nonZerosInOuterDirection = m_matrix.m_outerStarts[m_currentTriplet.row + 1] - m_matrix.m_outerStarts[m_currentTriplet.row]; if (m_nonZerosInOuterDirection > 0) break; //increment row m_currentTriplet.row++; } } } template <> void SparseMatrix<iDynTree::ColumnMajor>::ConstIterator::updateTriplet() { m_currentTriplet.value = m_matrix.m_values(m_index); m_currentTriplet.row = m_matrix.m_innerIndices[m_index]; if (--m_nonZerosInOuterDirection <= 0) { //increment row m_currentTriplet.column++; while (static_cast<std::size_t>(m_currentTriplet.column) < m_matrix.columns()) { //compute row NNZ m_nonZerosInOuterDirection = m_matrix.m_outerStarts[m_currentTriplet.column + 1] - m_matrix.m_outerStarts[m_currentTriplet.column]; if (m_nonZerosInOuterDirection > 0) break; //increment row m_currentTriplet.column++; } } } template <iDynTree::MatrixStorageOrdering ordering> typename SparseMatrix<ordering>::ConstIterator& SparseMatrix<ordering>::ConstIterator::operator++() { if (m_index < 0) { //Iterator is not valid. We do nothing return *this; } m_index++; if (static_cast<std::size_t>(m_index) >= m_matrix.m_values.size()) { //Out of range m_index = -1; } else { updateTriplet(); } return *this; } template <iDynTree::MatrixStorageOrdering ordering> typename SparseMatrix<ordering>::ConstIterator SparseMatrix<ordering>::ConstIterator::operator++(int) { if (m_index < 0) { //Iterator is not valid. We do nothing return *this; } ConstIterator newIterator(*this); ++newIterator; return newIterator; } template <iDynTree::MatrixStorageOrdering ordering> bool SparseMatrix<ordering>::ConstIterator::operator==(const ConstIterator &it) const { return &m_matrix == &((&it)->m_matrix) //check that we are pointing to the same matrix && m_index == it.m_index; } template <iDynTree::MatrixStorageOrdering ordering> bool SparseMatrix<ordering>::ConstIterator::operator==(const Iterator &it) const { return &m_matrix == &((&it)->m_matrix) //check that we are pointing to the same matrix && m_index == it.m_index; } template <iDynTree::MatrixStorageOrdering ordering> typename SparseMatrix<ordering>::ConstIterator::reference SparseMatrix<ordering>::ConstIterator::operator*() { return m_currentTriplet; } template <iDynTree::MatrixStorageOrdering ordering> typename SparseMatrix<ordering>::ConstIterator::pointer SparseMatrix<ordering>::ConstIterator::operator->() { return &m_currentTriplet; } template <iDynTree::MatrixStorageOrdering ordering> bool SparseMatrix<ordering>::ConstIterator::isValid() const { return m_index >= 0 && true; //TODO: check if we are < than end or >= begin } } // MARK: - Explicit instantiation of available templates template class iDynTree::SparseMatrix<iDynTree::RowMajor>; template class iDynTree::SparseMatrix<iDynTree::ColumnMajor>;
true
70b7a467e4175d3803e6fb822c8000e7aab94ce5
C++
AbiralBhattarai/random
/random6.cpp
UTF-8
209
2.734375
3
[]
no_license
#include<stdio.h> #include<conio.h> int main(){ int a; int n[10]; for(int i = 0;i < 10;i++){ printf("enter a number:"); scanf("%d",&a); n[i]=a; } for(int j=9;j>=0;j--){ printf("%d \n",n[j]); } }
true
a4da8982385dfc319cce061708e2fea4847f25a2
C++
Sookmyung-Algos/2021algos
/algos_assignment/team_pratice/ucpc/지져스/week1/10026.cpp
UTF-8
2,445
3.59375
4
[]
no_license
#include <iostream> #include <cstring> using namespace std; int N; int arr[100][100]; int visit[100][100]; // 0으로 초기화 int dx[] = { 1,-1,0,0 }; int dy[] = { 0,0,1,-1 }; //각 color에 대해 탐색 int dfs(int color, int x, int y) { visit[x][y] = 1; // 방문하면 1로 수정 for (int i = 0; i < 4; i++) { int movex, movey; movex= x + dx[i]; // x기준 상하좌우 movey = y + dy[i]; // y기준 상하좌우 if (movex >= 0 && movey >= 0 && movex < N && movey < N && arr[movex][movey] == color && !visit[movex][movey]) { dfs(color, movex, movey); } } return 0; } //Red-Green 영역 int RedGreen(int x, int y) { visit[x][y] = 1; for (int i = 0; i < 4; i++) { int movex, movey; movex = x + dx[i]; // x기준 상하좌우 movey = y + dy[i]; // y기준 상하좌우 if (movex >= 0 && movey >= 0 && movex < N && movey < N && (arr[movex][movey] == 1 || arr[movex][movey] == 2) && !visit[movex][movey]) { RedGreen(movex, movey); } } return 0; } int main() { cin >> N; char color[101]; for (int i = 0; i < N; i++) { cin >> color; // 숫자로 바꿔서 저장 for (int j = 0; j < N; j++) { if (color[j] == 'R') arr[i][j] = 1; else if (color[j] == 'G') arr[i][j] = 2; else arr[i][j] = 3; } } int red = 0, green = 0, blue = 0, red_green = 0; //빨초파 영역 개수 구하기 for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (arr[i][j] == 1 && !visit[i][j]) { dfs(1, i, j); red++; } if (arr[i][j] == 2 && !visit[i][j]) { dfs(2, i, j); green++; } if (arr[i][j] == 3 && !visit[i][j]) { dfs(3, i, j); blue++; } } } //방문기록 초기화하고 빨-초 영역 구하기 memset(visit, 0, sizeof(visit)); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if ((arr[i][j] == 1 || arr[i][j] == 2) && !visit[i][j]) { RedGreen(i, j); red_green++; } } } //결과 int result1 = red + green + blue; int result2 = red_green + blue; printf("%d %d\n", result1, result2); return 0; }
true
e0873f69f2ff552d3641340174764fab941bb190
C++
lb2616/all_descriptions_of_pdfs
/各种pdf/上嵌/C++上课内容/c++第4天/717下午/虚函数.cc
UTF-8
587
3.296875
3
[]
no_license
#include<iostream> using namespace std; class B0 { public: virtual void display()//加在基类上,可以使得其他子类调用自己的成员函数 { cout <<"B0 ::display()"<<endl; } }; class B1:public B0 { public: void display() { cout <<"B1:: display()"<<endl; } }; class D1:public B1 { public: void display() { cout<<"D1::display()"<<endl; } }; void fun(B0 *ptr) { ptr->display(); } int main(int argc,char **argv) { B0 b0,*p; B1 b1; D1 d1; p = &b0;//编译器此时只按照定义的指针来调用 fun(p); p = &b1; fun(p); p = &d1; fun(p); }
true
0ebdf52006baae63aff1593910506d6024760079
C++
layetri/trees
/src/Header/Buffer.h
UTF-8
985
2.796875
3
[]
no_license
// // Created by Daniël Kamp on 17/02/2021. // #ifndef SNOWSTORM_BUFFER_H #define SNOWSTORM_BUFFER_H #include <string> #include "Global.h" #if defined(PLATFORM_TEENSY_40) #include <Arduino.h> #elif defined(PLATFORM_DARWIN_X86) #include <cmath> #include <cstdint> #endif class Buffer { public: Buffer(int length, std::string name="Generic Buffer"); ~Buffer(); void write(sample_t sample); void writeAhead(sample_t sample, int places); void writeAddition(sample_t sample); void tick(); void flush(); void wipe(); int getPosition(); int getSize(); std::string getName(); sample_t getSample(int sample_position); sample_t getCurrentSample(); sample_t readAhead(int places); sample_t readBack(int places); sample_t& operator[] (int index) { return data[index]; } private: sample_t *data; int size; int position; std::string name; bool full_cycle_flag; }; #endif //SNOWSTORM_BUFFER_H
true
44cbfd4e23fd196707501b752751ee002804f152
C++
xhz636/PAT
/Advanced Level/1080.cpp
UTF-8
1,757
2.8125
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <vector> using namespace std; typedef struct { int ID; int GE; int GI; vector<int> order; } App; bool cmp(App a, App b) { if (a.GE + a.GI != b.GE + b.GI) return a.GE + a.GI > b.GE + b.GI; else return a.GE > b.GE; } int main(void) { int N, M, K; cin >> N >> M >> K; int Quota[M]; int Rank[M]; vector<int> School[M]; for (int i = 0; i < M; i++) { scanf("%d", &Quota[i]); Rank[i] = 0; } App A[N]; for (int i = 0; i < N; i++) { scanf("%d %d", &A[i].GE, &A[i].GI); A[i].ID = i; for (int j = 0; j < K; j++) { int num; scanf("%d", &num); A[i].order.push_back(num); } } sort(A, A + N, cmp); int nowrank = 0; int laste = A[0].GE, lasti = A[0].GI; for (int i = 0; i < N; i++) { if (A[i].GE + A[i].GI != laste + lasti || A[i].GE != laste) { nowrank++; laste = A[i].GE; lasti = A[i].GI; } for (int j = 0; j < K; j++) { int want = A[i].order[j]; if (Rank[want] == nowrank || School[want].size() < Quota[want]) { School[want].push_back(A[i].ID); Rank[want] = nowrank; break; } } } for (int i = 0; i < M; i++) { sort(School[i].begin(), School[i].end()); for (int j = 0; j < School[i].size(); j++) { if (j != 0) putchar(' '); printf("%d", School[i][j]); } putchar('\n'); } return 0; }
true
07298bb9ddd223eee51fc406e7ab796086239ef6
C++
c437yuyang/DayliExcercise_Old
/2016校招真题/百度_03_钓鱼比赛.cpp
UTF-8
1,889
3.296875
3
[]
no_license
/* ss请cc来家里钓鱼,鱼塘可划分为n*m的格子,每个格子有不同的概率钓上鱼,cc一直在坐标(x,y)的格子钓鱼,而ss每分钟随机钓一个格子。问t分钟后他们谁至少钓到一条鱼的概率大?为多少? 输入描述: 第一行五个整数n,m,x,y,t(1≤n,m,t≤1000,1≤x≤n,1≤y≤m); 接下来为一个n*m的矩阵,每行m个一位小数,共n行,第i行第j个数代表坐标为(i,j)的格子钓到鱼的概率为p(0≤p≤1) 输出描述: 输出两行。第一行为概率大的人的名字(cc/ss/equal),第二行为这个概率(保留2位小数) 示例1 输入 2 2 1 1 1 0.2 0.1 0.1 0.4 输出 equal 0.20 */ #include <iostream> #include <algorithm> #include <vector> #include <string> #include <climits> #include <cassert> #include <map> #include <set> #include <unordered_map> using namespace std; double removeFraction(double num, int digit) { int factor = pow(10, digit); num *= factor; return (num - floor(num)) / factor; } void solve(vector<vector<double>> &pools, int x, int y, int t) { int m = pools.size(); int n = pools[0].size(); double p = 0.0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { p += 1.0 - pools[i][j]; } } p /= (m*n); double ss = 1 - pow(p, t); double cc = 1 - pow((1.0 - pools[x - 1][y - 1]), t); //这里的x,y是反的 if (abs(ss - cc) < 1e-13) { cout << "equal" << endl; printf("%.2f\n", ss); } else if (ss > cc) { printf("ss\n%.2f\n", ss); } else { printf("cc\n%.2f\n", cc); } } int main() { int m; int n; int x; int y; int t; while (cin >> m >> n >> x >> y >> t) { vector<vector<double>> pools(m, vector<double>(n)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { cin >> pools[i][j]; } } solve(pools, x, y, t); } return 0; }
true
2e05730ebe7cb1468e4ac10cc9f2a003551a0ae5
C++
lilmonk3y/aed3-2019-1c-tp3
/src/trabajo/src/entities/Individuo.cpp
UTF-8
2,270
2.703125
3
[]
no_license
#include "Individuo.h" Individuo::Individuo(int pesoGenes,int eval) { this->evaluacion = eval; this->seleccionado = false; // genoma/genotipo: (conjunto de genes) this->horizontal_defensivo = pesoGenes; this->horizontal_ofensivo = pesoGenes; this->vertical_defensivo = pesoGenes; this->vertical_ofensivo = pesoGenes; this->diagonal_45_defensivo = pesoGenes; this->diagonal_45_ofensivo = pesoGenes; this->diagonal_315_defensivo = pesoGenes; this->diagonal_315_ofensivo = pesoGenes; this->jugada_aleatoria = pesoGenes; } Individuo::Individuo(PESO gen1,PESO gen2,PESO gen3,PESO gen4,PESO gen5,PESO gen6,PESO gen7,PESO gen8,PESO gen9,int eval) { this->evaluacion = eval; this->seleccionado = false; // genoma/genotipo: (conjunto de genes) this->horizontal_defensivo = gen1; this->horizontal_ofensivo = gen2; this->vertical_defensivo = gen3; this->vertical_ofensivo = gen4; this->diagonal_45_defensivo = gen5; this->diagonal_45_ofensivo = gen6; this->diagonal_315_defensivo = gen7; this->diagonal_315_ofensivo = gen8; this->jugada_aleatoria = gen9; } int Individuo::getEvaluacion() { return this->evaluacion; } void Individuo::setEvaluacion(int fitness ) { this->evaluacion = fitness; } bool Individuo::fueSeleccionado() { return this->seleccionado; } void Individuo::seleccionar() { this->seleccionado = true; } Individuo::Individuo(Individuo &anotherIndividuo) { this->evaluacion = anotherIndividuo.evaluacion; this->seleccionado = anotherIndividuo.seleccionado; // genoma/genotipo: (conjunto de genes) this->horizontal_defensivo = anotherIndividuo.horizontal_defensivo; this->horizontal_ofensivo = anotherIndividuo.horizontal_ofensivo; this->vertical_defensivo = anotherIndividuo.vertical_defensivo; this->vertical_ofensivo = anotherIndividuo.vertical_ofensivo; this->diagonal_45_defensivo = anotherIndividuo.diagonal_45_defensivo; this->diagonal_45_ofensivo = anotherIndividuo.diagonal_45_ofensivo; this->diagonal_315_defensivo = anotherIndividuo.diagonal_315_defensivo; this->diagonal_315_ofensivo = anotherIndividuo.diagonal_315_ofensivo; this->jugada_aleatoria = anotherIndividuo.jugada_aleatoria; }
true
8b44837c63fba705dd4178e733d92d440fd11f6b
C++
hongthepotato/CS106b-code
/Book_Exercise/Chapter2/Celsius_to_Fahrenheit.cpp
UTF-8
419
4
4
[]
no_license
#include<iostream> using namespace std; double celsius_to_fahrenheit(double cel){ double fahren = cel * 9 / 5 + 32; return fahren; } int main(){ cout << "Enter a temperature in celsius degrees: " << endl; double cel; cin >> cel; double fahren = celsius_to_fahrenheit(cel); cout << cel << " degrees in celsius equals " << fahren << " in fahrenheit" << endl; return 0; }
true